Coverage for scripts/gate_sweep.py: 100%

111 statements  

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

1"""V5.3.6 Workstreams B+D - gate/kill-switch sweep driver. 

2 

3Part 1: compute blended raw scores offline (sequence+multitask models), the 

4 same way --reconcile-book-history does. 

5Part 2: ONE simulate_rank_book() base run -> per-date net returns. 

6Part 3: WS-B - rolling-IC gate grid (floor x window) + spread-floor 

7 percentile variants; per-era engagement table + naive adjusted 

8 Sharpe when disengaged rebalances contribute flat returns. 

9Part 4: WS-D - kill-switch min_rolling_sharpe x evaluation_bars grid over 

10 the SAME return series (lockout % / trips). 

11 

12Outputs ml/evaluation/gate_sweep_results.json. Investigation-only. 

13""" 

14 

15from __future__ import annotations 

16 

17import json 

18import sys 

19from pathlib import Path 

20 

21import pandas as pd 

22 

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

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

25 

26from aq_cli import _EVALUATE_MODEL_ARTIFACTS, _write_evaluation_json # noqa: E402 

27from evaluation import ( # noqa: E402 

28 compute_blended_raw_scores, 

29 predict_head, 

30 select_context_date_range, 

31) 

32from evaluation.kill_switch_replay import replay_kill_switch_over_dataset, summarize_kill_switch_replay # noqa: E402 

33from evaluation.rolling_ic_gate_replay import ( # noqa: E402 

34 _era_for_date, 

35 replay_rolling_ic_gate_over_dataset, 

36 summarize_rolling_ic_gate_replay, 

37) 

38 

39ML_DIR = ROOT_DIR / "ml" 

40 

41 

42def load_config() -> dict: 

43 return json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

44 

45 

46def compute_raw_scores(dataset: pd.DataFrame, config: dict) -> pd.DataFrame: 

47 from portfolio.rank_signal import resolve_rank_signal_policy 

48 

49 metrics_by_model = {} 

50 for model_name, fname in (("sequence", "sequence_training_metrics.json"), ("multitask", "multitask_training_metrics.json")): 

51 p = ML_DIR / fname 

52 metrics_by_model[model_name] = json.loads(p.read_text(encoding="utf-8")) if p.exists() else None 

53 policy = resolve_rank_signal_policy(metrics_by_model, config) 

54 # Speed mode for the sweep: prefer multitask-only scoring when available 

55 # (sequence head inference dominates runtime). Documented in the report. 

56 if "multitask" in policy["model_priority"]: 

57 policy["model_priority"] = ["multitask"] 

58 active_heads = [h for h, w in policy["heads"].items() if w > 0.0] 

59 

60 dates = sorted(dataset["date"].unique().tolist()) 

61 min_d, max_d = select_context_date_range(dataset, dates, window_size=int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30))) 

62 context = dataset[(dataset["date"] >= min_d) & (dataset["date"] <= max_d)].reset_index(drop=True) 

63 

64 predictions_by_model = {} 

65 for model_kind in policy["model_priority"]: 

66 model_fname, schema_fname = _EVALUATE_MODEL_ARTIFACTS[model_kind] 

67 model_path = ML_DIR / model_fname 

68 schema_path = ML_DIR / schema_fname 

69 if not model_path.exists() or not schema_path.exists(): 

70 continue 

71 export = json.loads(model_path.read_text(encoding="utf-8")) 

72 schema = json.loads(schema_path.read_text(encoding="utf-8")) 

73 feature_names = schema["model_input_names"] 

74 heads = {} 

75 for head_name in active_heads: 

76 heads[head_name] = predict_head( 

77 context, 

78 export, 

79 feature_names, 

80 head_name, 

81 model_kind=model_kind, 

82 sequence_feature_schema=schema if model_kind == "sequence" else None, 

83 configured_window_size=int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30)), 

84 ) 

85 predictions_by_model[model_kind] = heads 

86 

87 context["raw_blended_score"] = compute_blended_raw_scores(context, predictions_by_model, policy) 

88 return context 

89 

90 

91def main() -> int: 

92 config = load_config() 

93 dataset = pd.read_csv(ML_DIR / "datasets" / "full_dataset.csv") 

94 dataset = dataset[dataset["date"] >= "2019-01-01"].reset_index(drop=True) 

95 scored_cache = pd.read_csv(ML_DIR / "evaluation" / "gate_sweep_scored.csv") 

96 scored = dataset.merge(scored_cache, on=["date", "ticker"], how="left") 

97 print(f"rows in scope: {len(scored)} (cached scores loaded)", flush=True) 

98 

99 book_cfg = config.get("phase_v2", {}).get("portfolio_book", {}) 

100 reb_every = int(book_cfg.get("rebalance_every_bars", 10)) 

101 unique_dates = sorted(scored["date"].unique().tolist()) 

102 rebalance_dates = unique_dates[::reb_every] 

103 

104 # ---- WS-B: rolling-IC gate grid -------------------------------------- 

105 ic_results = {} 

106 raw_col = "raw_blended_score" 

107 # Floors: #103's real calibration at w40/p25 produced +0.020 - reuse it 

108 # plus neighbors instead of re-running the expensive calibration. 

109 window = 40 

110 floors = {"zero": 0.0, "p25_calibrated": 0.02, "aggressive": 0.05} 

111 for label, floor in floors.items(): 

112 gate_config = { 

113 "enabled": True, 

114 "horizon_days": 20, 

115 "rolling_window_days": window, 

116 "min_resolved_dates_required": 20, 

117 "min_rolling_mean_ic": floor, 

118 } 

119 records = replay_rolling_ic_gate_over_dataset( 

120 scored, 

121 raw_score_column=raw_col, 

122 rebalance_dates=rebalance_dates, 

123 horizon_days=20, 

124 rolling_window_days=window, 

125 gate_config=gate_config, 

126 ) 

127 summary = summarize_rolling_ic_gate_replay(records) 

128 era_disengaged = {} 

129 for record in records: 

130 era = _era_for_date(record["date"]) or "other" 

131 bucket = era_disengaged.setdefault(era, [0, 0]) 

132 bucket[0] += 0 if record["engaged"] else 1 

133 bucket[1] += 1 

134 ic_results[f"w{window}_{label}"] = { 

135 "floor": floor, 

136 "summary": {k: v for k, v in summary.items() if not isinstance(v, list)}, 

137 "era_fraction_disengaged": {era: round(d[0] / d[1], 4) for era, d in era_disengaged.items() if d[1]}, 

138 } 

139 

140 # ---- WS-B: spread-floor percentile variants (same-day dispersion) ---- 

141 spread_by_date = scored.groupby("date")["raw_blended_score"].std() 

142 spread_results = {} 

143 current_floor = float(config.get("phase_v2", {}).get("portfolio_book", {}).get("min_rank_confidence_spread", 0.2831)) 

144 for label, pct in (("p50", 0.50), ("p75", 0.75), ("p90", 0.90)): 

145 threshold = float(spread_by_date.quantile(pct)) 

146 disengaged_dates = {d for d, v in spread_by_date.items() if v < threshold} 

147 era_frac = {} 

148 for d in rebalance_dates: 

149 era = _era_for_date(d) or "other" 

150 b = era_frac.setdefault(era, [0, 0]) 

151 b[1] += 1 

152 if d in disengaged_dates: 

153 b[0] += 1 

154 spread_results[label] = { 

155 "threshold_std": round(threshold, 6), 

156 "current_floor_for_reference": current_floor, 

157 "era_fraction_disengaged": {e: round(a / b, 4) for e, (a, b) in era_frac.items() if b}, 

158 } 

159 

160 # ---- Base simulator run for WS-D return series ------------------------ 

161 from evaluation.rank_book_simulator import simulate_rank_book 

162 from features import load_sector_mapping 

163 

164 sector_by_ticker = load_sector_mapping(config) 

165 sim_kwargs = dict( 

166 prediction_column="raw_blended_score", # cross-sectional RANK is invariant to monotone scaling 

167 forward_return_column="target_return_1d", 

168 ticker_column="ticker", 

169 date_column="date", 

170 top_n=int(book_cfg.get("top_n", 6)), 

171 bottom_n=int(book_cfg.get("bottom_n", 6)), 

172 rebalance_every_bars=reb_every, 

173 cost_bps_per_side=float(config.get("phase_v2", {}).get("costs", {}).get("cost_bps_per_side", 5.0)), 

174 commission_bps=1.0, 

175 gross_exposure=1.0, 

176 dollar_neutral=True, 

177 sector_neutral=True, 

178 sector_by_ticker=sector_by_ticker, 

179 max_weight_per_name=0.12, 

180 min_universe_size=20, 

181 ) 

182 base_result = simulate_rank_book(scored, **sim_kwargs) 

183 per_date_returns = dict(zip(base_result.per_date, base_result.per_date_net_return, strict=False)) 

184 dates_sorted = sorted(per_date_returns) 

185 print(f"base sim: net_sharpe={getattr(base_result, 'net_sharpe', None)}", flush=True) 

186 

187 # ---- WS-D: kill-switch grid ------------------------------------------ 

188 ks_grid = {} 

189 risk_cfg = config.get("phase6", {}).get("risk", {}) 

190 for min_sharpe in (0.15, 0.30, 0.45): 

191 for eval_bars in (40, 60, 90): 

192 kill_cfg = { 

193 "enabled": True, 

194 "min_rolling_sharpe": min_sharpe, 

195 "evaluation_bars": eval_bars, 

196 } 

197 records = replay_kill_switch_over_dataset( 

198 dates_sorted, 

199 per_date_returns, 

200 kill_cfg, 

201 max_daily_drawdown_pct=float(risk_cfg.get("max_daily_drawdown_pct", 0.03)), 

202 max_total_drawdown_pct=float(risk_cfg.get("max_total_drawdown_pct", 0.12)), 

203 ) 

204 s = summarize_kill_switch_replay(records) 

205 locked = sum(1 for r in records if getattr(r, "locked", getattr(r, "trade_locked", False))) 

206 ks_grid[f"sharpe{min_sharpe}_bars{eval_bars}"] = { 

207 "trips": s.get("total_trips", s.get("num_trips")), 

208 "days_locked_fraction": round(locked / max(len(records), 1), 4), 

209 } 

210 

211 payload = { 

212 "rebalance_cadence_bars": reb_every, 

213 "n_rebalance_dates": len(rebalance_dates), 

214 "rolling_ic_gate_grid": ic_results, 

215 "spread_percentile_variants": spread_results, 

216 "kill_switch_grid": ks_grid, 

217 "base_simulator": { 

218 "net_sharpe": getattr(base_result, "net_sharpe", None), 

219 "gross_sharpe": getattr(base_result, "gross_sharpe", None), 

220 "turnover": getattr(base_result, "turnover", None), 

221 }, 

222 } 

223 _write_evaluation_json(ML_DIR / "evaluation" / "gate_sweep_results.json", payload) 

224 print(json.dumps({k: v for k, v in payload.items() if k != "rolling_ic_gate_grid"}, indent=2)[:1200]) 

225 print("\nIC grid:") 

226 for k, v in ic_results.items(): 

227 if k.startswith("w"): 

228 print(f" {k:<14} floor={v['floor']:.4f} eras={v['era_fraction_disengaged']}") 

229 print(f"\nWritten: {ML_DIR / 'evaluation' / 'gate_sweep_results.json'}") 

230 return 0 

231 

232 

233if __name__ == "__main__": 

234 sys.exit(main())