Coverage for scripts/gate_research.py: 100%

73 statements  

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

1"""V5.7.0 gate research: every gate / lever decision of todo.md findings 1-6 on BOTH splits with the full as-live 

2simulator (kill switch, member sizing chain, liquidity and net-edge gates, per-name impact). 

3 

4For each experiment the net Sharpe, return, drawdown and gate counts are reported on the backtest split (the window Lean 

5also tests: an upper estimate) and on the validation split (the only independent evidence), next to the config baseline. 

6The decision rule (R-GATE in the V5.7.0 plan) is applied by `decide()`: 

7 

8 flip only if backtest net Sharpe improves by >= 0.10, validation net Sharpe does not fall by more than 0.02, and the 

9 max drawdown is not worse by more than 1.0 pp on either split; among passing values take the best validation Sharpe. 

10 

11 python scripts/gate_research.py [--group kill_switch spread ic_gate hold hrp impact] [--no-cache] 

12 

13Writes ml/evaluation/v570_gate_research.json. 

14""" 

15 

16from __future__ import annotations 

17 

18import argparse 

19import json 

20import sys 

21from pathlib import Path 

22 

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

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

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

26 

27from as_live_levers import AsLiveHarness, summarize # noqa: E402 

28 

29MIN_BACKTEST_GAIN = 0.10 

30MAX_VALIDATION_LOSS = 0.02 

31MAX_DRAWDOWN_WORSENING = 0.01 # fraction: 1.0 pp 

32 

33 

34def decide(baseline: dict, candidate: dict) -> dict: 

35 """R-GATE on two {"backtest": summary, "validation": summary} dicts.""" 

36 backtest_gain = candidate["backtest"]["net_sharpe"] - baseline["backtest"]["net_sharpe"] 

37 validation_gain = candidate["validation"]["net_sharpe"] - baseline["validation"]["net_sharpe"] 

38 drawdown_worse = { 

39 split: baseline[split]["net_max_drawdown"] - candidate[split]["net_max_drawdown"] # drawdowns are negative 

40 for split in ("backtest", "validation") 

41 } 

42 passes = ( 

43 backtest_gain >= MIN_BACKTEST_GAIN 

44 and validation_gain >= -MAX_VALIDATION_LOSS 

45 and all(worse <= MAX_DRAWDOWN_WORSENING for worse in drawdown_worse.values()) 

46 ) 

47 return { 

48 "backtest_sharpe_gain": round(backtest_gain, 4), "validation_sharpe_gain": round(validation_gain, 4), 

49 "drawdown_worsening_pp": {split: round(100 * worse, 3) for split, worse in drawdown_worse.items()}, 

50 "passes_r_gate": bool(passes), 

51 } 

52 

53 

54def experiments(harnesses: dict[str, AsLiveHarness]) -> dict[str, dict[str, callable]]: 

55 """{group: {name: callable(harness) -> result}}.""" 

56 ks = "risk.kill_switch" 

57 groups: dict[str, dict[str, callable]] = {"baseline": {"as-live (config)": lambda h: h.as_live()}} 

58 

59 kill = {"kill switch off": lambda h: h.as_live(include=("member_sizing", "hrp", "impact"))} 

60 for floor in (-1.0, -1.5, -2.0): 

61 for bars in (60, 120): 

62 for std in (0.0005, 0.001): 

63 kill[f"ks sharpe<{floor} bars={bars} std>{std}"] = ( 

64 lambda h, floor=floor, bars=bars, std=std: h.as_live(config_overrides={ 

65 f"{ks}.min_rolling_sharpe": floor, f"{ks}.evaluation_bars": bars, f"{ks}.min_return_std_for_sharpe": std, 

66 }) 

67 ) 

68 groups["kill_switch"] = kill 

69 

70 spread = {} 

71 for floor in (0.0, 0.10, 0.15, 0.1985, 0.25, 0.2831): 

72 spread[f"spread floor {floor}"] = lambda h, floor=floor: h.as_live(min_rank_confidence_spread=floor) 

73 groups["spread"] = spread 

74 

75 ic = {"ic gate off": lambda h: h.as_live(gate="off")} 

76 for horizon, window in ((20, 40), (20, 80), (20, 120), (5, 40), (5, 80)): 

77 for floor in (-0.10, -0.05, -0.02, 0.0, 0.02, 0.05): 

78 ic[f"ic h={horizon} w={window} floor={floor}"] = ( 

79 lambda h, horizon=horizon, window=window, floor=floor: h.as_live( 

80 ic_floor=floor, gate_horizon=horizon, gate_window=window, 

81 config_overrides={"rolling_ic_gate.min_resolved_dates_required": min(window, 40)}, 

82 ) 

83 ) 

84 groups["ic_gate"] = ic 

85 

86 groups["hold"] = { 

87 "hold-on-veto off (anchor kept)": lambda h: h.as_live(hold_positions_on_veto=False), 

88 "hold-on-veto off (anchor off)": lambda h: h.as_live(hold_positions_on_veto=False, hysteresis_anchor_on_formed_book=False), 

89 } 

90 groups["hrp"] = {"hrp allocation": lambda h: h.as_live(config_overrides={"portfolio_book.allocation_method": "hrp"})} 

91 groups["impact"] = {"as-live with Almgren impact": lambda h: h.as_live( 

92 impact_model_config={"enabled": True, "eta": 0.5} 

93 )} 

94 return groups 

95 

96 

97def main() -> int: 

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

99 parser.add_argument("--group", nargs="*", default=None) 

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

101 parser.add_argument("--dataset-validation", default=None, help="V5.8.0: dataset CSV holding the validation split") 

102 parser.add_argument("--dataset-backtest", default=None, help="V5.8.0: dataset CSV holding the backtest split") 

103 parser.add_argument("--only", nargs="*", default=None, help="V5.8.0: run only experiments whose name contains one of these") 

104 parser.add_argument("--out", default=None, help="V5.8.0: result file (default ml/evaluation/v570_gate_research.json)") 

105 args = parser.parse_args() 

106 

107 dataset_by_split = {"validation": args.dataset_validation, "backtest": args.dataset_backtest} 

108 harnesses = { 

109 split: AsLiveHarness(split, use_cache=not args.no_cache, dataset_path=dataset_by_split[split]) 

110 for split in ("backtest", "validation") 

111 } 

112 groups = experiments(harnesses) 

113 selected = args.group or [name for name in groups if name != "baseline"] 

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

115 for group in ["baseline", *selected]: 

116 for name, run in groups[group].items(): 

117 if args.only and group != "baseline" and not any(token in name for token in args.only): 

118 continue 

119 per_split = {split: summarize(run(harness)) for split, harness in harnesses.items()} 

120 results[name] = {"group": group, **per_split} 

121 print( 

122 f"[{group}] {name:44s} " 

123 + " | ".join( 

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

125 f"dd {100 * per_split[split]['net_max_drawdown']:.2f}% ks {per_split[split]['kill_switch_locked_dates']}" 

126 for split in per_split 

127 ), 

128 flush=True, 

129 ) 

130 baseline = results["as-live (config)"] 

131 for name, entry in results.items(): 

132 if name != "as-live (config)": 

133 entry["decision"] = decide(baseline, entry) 

134 out = Path(args.out) if args.out else ROOT_DIR / "ml" / "evaluation" / "v570_gate_research.json" 

135 out.write_text(json.dumps(results, indent=2), encoding="utf-8") 

136 print(f"written {out}") 

137 # Switching a safety control off (kill switch, whole IC gate) is reported but never a candidate winner: R-GATE tunes 

138 # a control's value, it does not remove it. 

139 winners = sorted( 

140 ( 

141 (name, entry["decision"]) 

142 for name, entry in results.items() 

143 if entry.get("decision", {}).get("passes_r_gate") and not name.endswith(" off") 

144 ), 

145 key=lambda item: -results[item[0]]["validation"]["net_sharpe"], 

146 ) 

147 print("R-GATE passes:", [name for name, _ in winners] or "none") 

148 return 0 

149 

150 

151if __name__ == "__main__": 

152 raise SystemExit(main())