Coverage for scripts/v620_research.py: 100%

181 statements  

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

1"""V6.2.0 research chain (pre-registered rules R-DEDUPE -> R-STAGGER -> R-MODEL10; plan V6.2.0). 

2 

3The scoring is V6.1.0's (scripts/v610_research.py): the modelled portfolio (main book + legacy signal) on the calibrated 

4simulator, every rebalance phase, a statistic = the median across phases plus the share of phases beating the 

5comparator's median, margins from `rule_verdict` (backtest gain >= +0.10, validation not worse than -0.02, >= 60% of 

6phases on both splits, positive median on both splits, median drawdown within 1 pp). Alpha is judged ex-carry: the 

7T-bill sweep is off in every rule score and reported apart. 

8 

9 dedupe R-DEDUPE: `rolling_ic_gate.late_bar_event_count` "once" against "per_tick", scored GATED (as-live) because the 

10 gate is the mechanism under change; adopted iff `rule_verdict` passes on the as-live scores. 

11 stagger R-STAGGER: S2 (2 tranches) and S4 (4 tranches) against 1, UNGATED (R-CAL2 branch B); adopted iff 

12 `rule_verdict` passes AND the validation phase range (max - min Sharpe) shrinks by >= 25% AND the median 

13 annual cost drag rises by <= 30%; the passing variant with the highest validation median wins. 

14 model R-MODEL10: a 5-seed multitask (+3-seed sequence) ensemble candidate is installed iff 

15 1. validation decision IC - installed > the yardstick (2 x the std of resampled control ensembles, 

16 floored at 0.02; model_candidate_research --bootstrap) and > 0, 

17 2. backtest IC >= installed - yardstick and backtest HAC t >= 2, 

18 3. the ungated all-phase book passes `rule_verdict` against the installed models, 

19 4. inference latency <= 1.5x the installed models', and the decision heads pass R-HEAD. 

20 

21 python scripts/v620_research.py --dataset ml/datasets/v610_full_dataset.csv --legacy-probability ml/datasets/legacy_probability.csv 

22 [--candidates ml/evaluation/v620/candidates.json] [--model-ic ml/evaluation/v620/model_ic.json] 

23 [--stages dedupe stagger model] [--max-phases 10] [--workers 2] [--out ml/evaluation/v620/research.json] 

24""" 

25 

26from __future__ import annotations 

27 

28import argparse 

29import copy 

30import json 

31import statistics 

32import sys 

33from pathlib import Path 

34 

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

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

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

38 

39from v610_research import ( # noqa: E402 

40 MAX_LATENCY_RATIO, 

41 SPLITS, 

42 apply_dotted, 

43 best_decision_key, 

44 phase_summary, 

45 phases_for, 

46 rule_verdict, 

47) 

48 

49DEDUPE_VARIANT = {"rolling_ic_gate.late_bar_event_count": "once"} 

50STAGGER_VARIANTS = {"S2": 2, "S4": 4} 

51MIN_PHASE_RANGE_CUT = 0.25 

52MAX_COST_RISE = 0.30 

53 

54 

55def model10_checks(model_ic: dict, name: str, installed: str = "installed") -> dict: 

56 """R-MODEL10 clauses 1-2 from model_candidate_research's output (`bootstrap` = the control ensembles' spread). Each 

57 side uses its own best decision key, as R-MODEL9; the yardstick is the one of the candidate's key.""" 

58 candidates = model_ic["candidates"] 

59 candidate_key, installed_key = best_decision_key(candidates[name]), best_decision_key(candidates[installed]) 

60 yardstick = float(((model_ic.get("bootstrap") or {}).get(candidate_key) or {}).get("yardstick", 0.02)) 

61 decision = lambda entry, split, key: entry["ensemble"][split][key] # noqa: E731 

62 cand_val = decision(candidates[name], "validation", candidate_key)["non_overlapping_mean_ic"] or 0.0 

63 inst_val = decision(candidates[installed], "validation", installed_key)["non_overlapping_mean_ic"] or 0.0 

64 cand_bt = decision(candidates[name], "backtest", candidate_key) 

65 inst_bt = decision(candidates[installed], "backtest", installed_key) 

66 return { 

67 "validation_beats_installed_by_yardstick": cand_val - inst_val > yardstick and cand_val > 0.0, 

68 "backtest_ic_not_below_installed_minus_yardstick": (cand_bt["daily_mean_ic"] or 0.0) >= (inst_bt["daily_mean_ic"] or 0.0) - yardstick, 

69 "backtest_hac_t_ge_2": (cand_bt["hac_t"] or 0.0) >= 2.0, 

70 "decision_priority": "swapped" if candidate_key.endswith("swapped_priority") else "live", 

71 "yardstick": yardstick, 

72 } 

73 

74 

75def stagger_checks(base: dict, variant: dict) -> dict: 

76 """R-STAGGER's clauses beyond `rule_verdict` (ungated scores): the phase luck it exists to remove, at bounded cost.""" 

77 def spread(scores): 

78 return scores["validation"]["max_net_sharpe"] - scores["validation"]["min_net_sharpe"] 

79 

80 base_cost = statistics.median(base["validation"]["cost_drag_by_phase"] + base["backtest"]["cost_drag_by_phase"]) 

81 variant_cost = statistics.median(variant["validation"]["cost_drag_by_phase"] + variant["backtest"]["cost_drag_by_phase"]) 

82 return { 

83 "validation_phase_range_cut_ge_25pct": spread(variant) <= (1.0 - MIN_PHASE_RANGE_CUT) * spread(base), 

84 "cost_drag_rise_le_30pct": variant_cost <= (1.0 + MAX_COST_RISE) * max(base_cost, 1e-9), 

85 } 

86 

87 

88_JOB: dict = {} 

89 

90 

91def _phase_worker(phase: int) -> dict: 

92 from as_live_levers import summarize 

93 from lean_calibration import ANALYZER_INCLUDE, calibrated_overrides 

94 

95 job = _JOB 

96 harness = job["harness"] 

97 kwargs = dict(calibrated_overrides(harness, phase=phase), **job["mechanisms"], include=ANALYZER_INCLUDE) 

98 if job["mode"] == "ungated": 

99 kwargs.update(gate="off", min_rank_confidence_spread=0.0) 

100 result = harness.as_live(config_overrides=job["resolved"] or None, tranches=job.get("tranches", 1), 

101 cash_sweep=job.get("cash_sweep", False), **kwargs) 

102 summary = summarize(result) 

103 components = result.per_date_component_returns or {} 

104 summary["legacy_net_return"] = sum(components.get("legacy", {}).values()) 

105 summary["cash_sweep_return"] = sum(components.get("cash_sweep", {}).values()) 

106 return summary 

107 

108 

109def map_phases(phases: list[int], workers: int) -> list[dict]: 

110 import multiprocessing 

111 

112 if workers > 1 and len(phases) > 1 and sys.platform.startswith("linux"): 

113 with multiprocessing.get_context("fork").Pool(min(workers, len(phases))) as pool: 

114 return pool.map(_phase_worker, phases) 

115 return [_phase_worker(phase) for phase in phases] 

116 

117 

118def main() -> int: 

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

120 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv")) 

121 parser.add_argument("--legacy-probability", required=True) 

122 parser.add_argument("--candidates", default=None) 

123 parser.add_argument("--model-ic", default=str(ROOT_DIR / "ml" / "evaluation" / "v620" / "model_ic.json")) 

124 parser.add_argument("--stages", nargs="*", default=["dedupe", "stagger", "model"]) 

125 parser.add_argument("--max-phases", type=int, default=10) 

126 parser.add_argument("--workers", type=int, default=1) 

127 parser.add_argument("--gate-warmup-days", type=int, default=400) 

128 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v620" / "research.json")) 

129 args = parser.parse_args() 

130 

131 from as_live_levers import AsLiveHarness 

132 from lean_calibration import topology_inputs_fn_for, use_topology 

133 

134 base_config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

135 out_path = Path(args.out) 

136 report = json.loads(out_path.read_text(encoding="utf-8")) if out_path.exists() else {} 

137 report.update({"branch": "B", "max_phases": args.max_phases, "sweep_in_rule_scores": False}) 

138 adopted = report.setdefault("adopted", {"config": {}, "tranches": 1, "model": None, "rank_signal": None}) 

139 candidates = json.loads(Path(args.candidates).read_text(encoding="utf-8")) if args.candidates else {} 

140 cache: dict = {} 

141 memo: dict = {} 

142 

143 def harness_for(model: str | None, rank_signal: dict | None, split: str): 

144 spec = candidates.get(model, {}) if model else {} 

145 key = (model, json.dumps(rank_signal, sort_keys=True), split) 

146 if key not in cache: 

147 if len(cache) >= 2: 

148 cache.pop(next(iter(cache))) 

149 cfg = copy.deepcopy(base_config) 

150 if rank_signal: 

151 cfg["phase_v2"]["rank_signal"].update(rank_signal) 

152 cfg["phase_v2"]["rank_signal"]["demote_not_promotable_heads"] = False 

153 if spec.get("ensemble"): 

154 cfg["phase_v2"]["model_ensemble"]["enabled"] = True 

155 harness = AsLiveHarness( 

156 split, dataset_path=args.dataset, config=cfg, 

157 ml_dir=(ROOT_DIR / spec["ml_dir"]) if spec.get("ml_dir") else None, 

158 legacy_probability_path=spec.get("legacy_probability") or args.legacy_probability, 

159 gate_warmup_days=args.gate_warmup_days, 

160 ) 

161 cache[key] = (harness, topology_inputs_fn_for(harness, cfg), cfg) 

162 return cache[key] 

163 

164 def score(changes: dict, *, tranches: int = 1, model=None, rank_signal=None, splits=SPLITS, modes=("ungated",), 

165 cash_sweep: bool = False) -> dict: 

166 memo_key = json.dumps([changes, tranches, model, rank_signal, list(splits), list(modes), cash_sweep], sort_keys=True, default=str) 

167 if memo_key in memo: 

168 return memo[memo_key] 

169 out: dict = {mode: {} for mode in modes} 

170 for split in splits: 

171 harness, topology_fn, cfg = harness_for(model, rank_signal, split) 

172 merged = apply_dotted(cfg, changes) 

173 cadence = int(merged["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 20)) 

174 use_topology(harness, topology_fn) 

175 mechanisms = harness.v610_mechanisms(merged) 

176 for mode in modes: 

177 _JOB.update(harness=harness, mechanisms=mechanisms, resolved=dict(changes), mode=mode, tranches=tranches, 

178 cash_sweep=cash_sweep) 

179 per_phase = map_phases(phases_for(cadence, args.max_phases), args.workers) 

180 summary = phase_summary(per_phase) 

181 summary["legacy_net_return_median"] = statistics.median(row["legacy_net_return"] for row in per_phase) 

182 summary["cost_drag_by_phase"] = [row["cost_drag_annual_bps"] for row in per_phase] 

183 summary["cash_sweep_return_median"] = statistics.median(row["cash_sweep_return"] for row in per_phase) 

184 out[mode][split] = summary 

185 memo[memo_key] = out 

186 return out 

187 

188 def save(): 

189 out_path.parent.mkdir(parents=True, exist_ok=True) 

190 out_path.write_text(json.dumps(report, indent=1, default=float), encoding="utf-8") 

191 

192 current = lambda: adopted["config"] # noqa: E731 

193 

194 if "dedupe" in args.stages: 

195 print("=== stage dedupe (R-DEDUPE, as-live)", flush=True) 

196 base = score(current(), modes=("as_live",)) 

197 variant = score({**current(), **DEDUPE_VARIANT}, modes=("as_live",)) 

198 verdict = rule_verdict(base["as_live"], variant["as_live"]) 

199 if verdict["passes"]: 

200 adopted["config"].update(DEDUPE_VARIANT) 

201 report["dedupe"] = {"base": base, "variant": variant, "verdict": verdict, "adopted": verdict["passes"]} 

202 print(f" once: adopted={verdict['passes']} gain {verdict['backtest_gain']:+.3f} val {verdict['validation_change']:+.3f}", flush=True) 

203 save() 

204 

205 if "stagger" in args.stages: 

206 print("=== stage stagger (R-STAGGER, ungated)", flush=True) 

207 base = score(current()) 

208 stage = {"base": base, "variants": {}} 

209 for name, count in STAGGER_VARIANTS.items(): 

210 result = score(current(), tranches=count) 

211 verdict = rule_verdict(base["ungated"], result["ungated"]) 

212 extra = stagger_checks(base["ungated"], result["ungated"]) 

213 verdict["extra_checks"] = extra 

214 verdict["adopted"] = verdict["passes"] and all(extra.values()) 

215 stage["variants"][name] = {"tranches": count, "scores": result, "verdict": verdict} 

216 print(f" {name}: adopted={verdict['adopted']} gain {verdict['backtest_gain']:+.3f} val {verdict['validation_change']:+.3f} " 

217 f"extra {extra}", flush=True) 

218 save() 

219 winners = [name for name, entry in stage["variants"].items() if entry["verdict"]["adopted"]] 

220 chosen = max(winners, key=lambda n: stage["variants"][n]["scores"]["ungated"]["validation"]["median_net_sharpe"]) if winners else None 

221 adopted["tranches"] = STAGGER_VARIANTS[chosen] if chosen else 1 

222 stage["adopted"] = chosen 

223 report["stagger"] = stage 

224 save() 

225 

226 if "model" in args.stages and candidates: 

227 print("=== stage model (R-MODEL10, ungated)", flush=True) 

228 model_ic = json.loads(Path(args.model_ic).read_text(encoding="utf-8")) 

229 stage = {"variants": {}} 

230 for name, spec in candidates.items(): 

231 if name == "installed": 

232 continue 

233 ic = spec.get("ic_checks") or model10_checks(model_ic, name) 

234 if not spec.get("ic_pass"): 

235 stage["variants"][name] = {"skipped": "IC clauses failed", "ic_checks": ic} 

236 print(f" {name}: skipped, IC clauses {ic}", flush=True) 

237 continue 

238 signal = {"model_priority": ["multitask", "sequence"]} if ic.get("decision_priority") == "swapped" else None 

239 base = score(current(), tranches=adopted["tranches"], rank_signal=signal) 

240 result = score(current(), tranches=adopted["tranches"], model=name, rank_signal=signal) 

241 verdict = rule_verdict(base["ungated"], result["ungated"]) 

242 extra = {"decision_heads_pass_r_head": bool(spec.get("decision_heads_pass_r_head")), 

243 "latency_within_1.5x": float(spec.get("latency_ratio", 1.0)) <= MAX_LATENCY_RATIO} 

244 verdict["extra_checks"] = extra 

245 verdict["adopted"] = verdict["passes"] and all(extra.values()) 

246 stage["variants"][name] = {"ic_checks": ic, "scores": result, "base": base, "verdict": verdict, "rank_signal": signal} 

247 print(f" {name}: adopted={verdict['adopted']} gain {verdict['backtest_gain']:+.3f}", flush=True) 

248 save() 

249 winners = [name for name, entry in stage["variants"].items() if (entry.get("verdict") or {}).get("adopted")] 

250 if winners: 

251 adopted["model"] = max(winners, key=lambda n: stage["variants"][n]["scores"]["ungated"]["validation"]["median_net_sharpe"]) 

252 adopted["rank_signal"] = stage["variants"][adopted["model"]]["rank_signal"] 

253 stage["adopted"] = adopted["model"] 

254 report["model"] = stage 

255 save() 

256 

257 # informational: the adopted configuration with and without the T-bill sweep (as-live), and the seen holdout 

258 report["sweep_report"] = { 

259 "without": score(current(), tranches=adopted["tranches"], model=adopted["model"], rank_signal=adopted["rank_signal"], 

260 modes=("as_live",)), 

261 "with": score(current(), tranches=adopted["tranches"], model=adopted["model"], rank_signal=adopted["rank_signal"], 

262 modes=("as_live",), cash_sweep=True) if adopted["tranches"] == 1 else None, 

263 } 

264 save() 

265 report["final_holdout_seen"] = score(current(), tranches=adopted["tranches"], model=adopted["model"], 

266 rank_signal=adopted["rank_signal"], splits=("holdout",), modes=("ungated", "as_live")) 

267 save() 

268 print("adopted:", json.dumps(adopted)) 

269 print(f"written {out_path}") 

270 return 0 

271 

272 

273if __name__ == "__main__": 

274 raise SystemExit(main())