Coverage for scripts/crypto_graduation_research.py: 100%

76 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Crypto graduates: which of the extra crypto pairs trade, and at what cap? (V5.7.0 question, rebuilt for V5.8.0) 

2 

3V5.7.0 asked whether any observation-only pair should JOIN the two core names (BTCUSD, LTCUSD); none passed R-GATE 

4(Problems.md #149). With the data window extended to 2026 every pair has >= 1,400 train rows, so all twelve are 

5trading-eligible and the owner's decision is that they trade — capped when the evidence is not there. This measures, on 

6BOTH splits with the full as-live simulator, Coinbase fees and the venue listing guard (no order before a pair's Coinbase 

7listing, none while it is suspended or after a delisting): 

8 

9 core_only the V5.7.0 state: only BTCUSD/LTCUSD can be selected 

10 all_uncapped every eligible crypto pair, no class caps 

11 capped <per-name>/<class-gross> every eligible pair with `class_weight_caps` (core exempt) 

12 leave-one-out the best capped configuration without one graduate at a time 

13 

14R-SLEEVE: a capped configuration that passes R-GATE against `core_only` ships at its researched cap ("edge_pass"); 

15otherwise the graduates ship at the minimum cap (per-name 1%, class gross 5%) with the crypto-graduates loss guard 

16("trade_anyway_minimum_cap") and the numbers say which branch fired. 

17 

18 python scripts/crypto_graduation_research.py [--dataset-validation PATH --dataset-backtest PATH] [--no-cache] -> ml/evaluation/crypto_graduation_research.json 

19""" 

20 

21from __future__ import annotations 

22 

23import argparse 

24import json 

25import sys 

26from pathlib import Path 

27 

28ROOT_DIR = Path(__file__).resolve().parents[1] 

29sys.path.insert(0, str(ROOT_DIR)) 

30sys.path.insert(0, str(Path(__file__).resolve().parent)) 

31 

32from as_live_levers import AsLiveHarness, add_split_dataset_args, dataset_for_split, summarize # noqa: E402 

33from gate_research import decide as r_gate # noqa: E402 

34 

35from portfolio.book_construction import resolve_class_weight_caps # noqa: E402 

36from risk.asset_class_router import load_venue_listing_dates # noqa: E402 

37 

38CORE = ("BTCUSD", "LTCUSD") 

39CAP_GRID = ((0.01, 0.05), (0.02, 0.05), (0.02, 0.10), (0.04, 0.10)) 

40MINIMUM_CAP = (0.01, 0.05) 

41 

42 

43def caps_for(per_name: float, class_gross: float) -> dict: 

44 return resolve_class_weight_caps({"crypto": {"per_name_cap": per_name, "class_gross_cap": class_gross, "exempt": list(CORE)}}) 

45 

46 

47def run(harness: AsLiveHarness, *, eligible: set[str], caps: dict | None): 

48 """One as-live run where exactly `eligible` crypto names (plus every non-crypto name as configured) can be selected.""" 

49 metadata = {t: dict(v) for t, v in harness.metadata.items()} 

50 for ticker, kind in harness.asset_class_by_ticker.items(): 

51 if kind == "crypto": 

52 metadata[ticker]["trading_eligible"] = ticker in eligible 

53 harness.core_crypto = frozenset(harness.core_crypto) | frozenset(eligible) 

54 harness._mechanisms.clear() 

55 return harness.as_live(candidate_metadata_by_ticker=metadata, class_weight_caps=caps or None) 

56 

57 

58def main() -> int: 

59 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

60 add_split_dataset_args(parser) 

61 parser.add_argument("--no-cache", action="store_true") 

62 args = parser.parse_args() 

63 

64 listing = load_venue_listing_dates(ROOT_DIR / "data" / "reference" / "crypto_listing_dates.json") 

65 harnesses = {} 

66 for split in ("backtest", "validation"): 

67 harness = AsLiveHarness(split, use_cache=not args.no_cache, dataset_path=dataset_for_split(args, split)) 

68 harness.venue_listing_dates = listing or None # always on for this research, whatever the config says 

69 harnesses[split] = harness 

70 reference = harnesses["backtest"] 

71 all_crypto = sorted(t for t, kind in reference.asset_class_by_ticker.items() if kind == "crypto") 

72 manifest_eligible = {t for t in all_crypto if reference.metadata[t]["trading_eligible"]} 

73 present = set.intersection(*[set(h.frame["ticker"].unique()) for h in harnesses.values()]) 

74 graduates = sorted(t for t in manifest_eligible if t not in CORE and t in present) 

75 print("crypto graduates with rows on both splits:", graduates) 

76 

77 experiments: dict[str, tuple[set[str], dict | None]] = { 

78 "core_only": (set(CORE) & manifest_eligible, None), 

79 "all_uncapped": (set(CORE) | set(graduates), None), 

80 } 

81 for per_name, class_gross in CAP_GRID: 

82 experiments[f"capped {per_name}/{class_gross}"] = (set(CORE) | set(graduates), caps_for(per_name, class_gross)) 

83 results: dict[str, dict] = {} 

84 for name, (eligible, caps) in experiments.items(): 

85 results[name] = {split: summarize(run(h, eligible=eligible, caps=caps)) for split, h in harnesses.items()} 

86 print(name.ljust(24) + " | ".join( 

87 f"{split[:4]} sharpe {results[name][split]['net_sharpe']:+.3f} ret {100 * results[name][split]['net_total_return']:+.2f}% " 

88 f"dd {100 * results[name][split]['net_max_drawdown']:.2f}%" for split in results[name]), flush=True) 

89 for name in results: 

90 if name != "core_only": 

91 results[name]["r_gate_vs_core_only"] = r_gate(results["core_only"], results[name]) 

92 

93 passing = [n for n in results if n.startswith("capped") and results[n]["r_gate_vs_core_only"]["passes_r_gate"]] 

94 best_capped = max( 

95 (n for n in results if n.startswith("capped")), key=lambda n: results[n]["validation"]["net_sharpe"] + results[n]["backtest"]["net_sharpe"] 

96 ) 

97 chosen = max(passing, key=lambda n: results[n]["validation"]["net_sharpe"]) if passing else None 

98 reference_name = chosen or f"capped {MINIMUM_CAP[0]}/{MINIMUM_CAP[1]}" 

99 reference_caps = experiments[reference_name][1] 

100 leave_one_out = {} 

101 for ticker in graduates: 

102 eligible = (set(CORE) | set(graduates)) - {ticker} 

103 leave_one_out[ticker] = {split: summarize(run(h, eligible=eligible, caps=reference_caps)) for split, h in harnesses.items()} 

104 leave_one_out[ticker]["r_gate_vs_reference"] = r_gate(results[reference_name], leave_one_out[ticker]) 

105 print(f"without {ticker:8s} " + " | ".join( 

106 f"{split[:4]} sharpe {leave_one_out[ticker][split]['net_sharpe']:+.3f}" for split in ("backtest", "validation")), flush=True) 

107 if chosen: 

108 decision = {"branch": "edge_pass", "config": chosen, "per_name_cap": float(chosen.split()[1].split("/")[0]), 

109 "class_gross_cap": float(chosen.split("/")[1]), "passing": sorted(passing)} 

110 else: 

111 decision = {"branch": "trade_anyway_minimum_cap", "per_name_cap": MINIMUM_CAP[0], "class_gross_cap": MINIMUM_CAP[1], 

112 "loss_guard": True, "best_capped_config": best_capped, 

113 "reason": "no capped configuration passes R-GATE against the core-only book on both splits"} 

114 names_that_hurt = sorted(t for t, entry in leave_one_out.items() if entry["r_gate_vs_reference"]["passes_r_gate"]) 

115 print("decision:", json.dumps(decision), "| removing these would pass R-GATE (reported, not applied):", names_that_hurt or "none") 

116 out = ROOT_DIR / "ml" / "evaluation" / "crypto_graduation_research.json" 

117 out.write_text(json.dumps({"graduates": graduates, "results": results, "leave_one_out": leave_one_out, "decision": decision, 

118 "removal_would_pass_r_gate": names_that_hurt}, indent=2, default=float), encoding="utf-8") 

119 print(f"written {out}") 

120 

121 from evaluation.readme_research import refresh_readme_best_effort 

122 

123 refresh_readme_best_effort() 

124 return 0 

125 

126 

127if __name__ == "__main__": 

128 raise SystemExit(main())