Coverage for scripts/v643_research.py: 100%

337 statements  

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

1"""V6.4.3 research chain: rule R-MODEL11's fixed grid (ml/evaluation/v643/r_model11_rule.json, written before any score), 

2the as-of label leak measurement and the leakage audit. Scoring is V6.4.0's: the calibrated as-live simulator 

3(lean_calibration.calibrated_overrides + the V6.1.0 mechanisms without the legacy signal, learned-topology sizing at the 

4mid bracket), rolling-IC gate on, T-bill sweep off, the median over --max-phases evenly spaced rebalance phases. 

5 

6Stages (each resumable from the memo next to --out): 

7 labels as-of beta labels (features/asof_beta_labels.py) -> --asof-labels parquet, and the leak: the installed 

8 multitask residual / beta-neutral heads' IC against the whole-history labels and against the as-of ones 

9 leakage evaluation/leakage_audit.audit_leakage on the 50 scaled features 

10 grid F1-F6, L1-L3, G1-G3, B1-B3, R1: IC report (evaluation/research_harness) + as-live phases on both splits 

11 pbo CSCV over the grid's phase-0 daily as-live returns (validation + backtest) 

12 spanning probes' long/short returns against F1-F5's on backtest 

13 verdict R-MODEL11's six clauses; the holdout is read once, for finalists only 

14 

15 python scripts/v643_research.py [--dataset ml/datasets/full_dataset.csv] [--stages labels leakage grid pbo spanning verdict] 

16 [--max-phases 10] [--out ml/evaluation/v643/research.json] 

17""" 

18 

19from __future__ import annotations 

20 

21import argparse 

22import contextlib 

23import hashlib 

24import json 

25import sys 

26from pathlib import Path 

27 

28import numpy as np 

29import pandas as pd 

30 

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

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

33sys.path.insert(0, str(ROOT_DIR / "scripts")) 

34 

35SPLITS = ("validation", "backtest") 

36YARDSTICK = 0.034 

37RAW_FACTOR_INPUTS = ("close_to_close_return_1d", "close_to_close_return_5d", "momentum_20d", "rolling_volatility_20d", "dist_52w_high") 

38TARGETS = ("target_rank_20d", "target_rank_5d", "target_return_1d", "target_return_5d", "target_return_20d", 

39 "target_residual_rank_20d", "target_residual_rank_5d", "target_beta_neutral_rank_20d", "target_beta_neutral_rank_5d") 

40CLASS_COLUMNS = ("asset_class_equity", "asset_class_crypto", "asset_class_bond", "asset_class_future", "asset_class_option", "asset_class_forex") 

41FACTOR_TRIALS = {"F1": "f_mom_12_1", "F2": "f_mom_20", "F3": "f_rev_5", "F4": "f_lowvol", "F5": "f_high52", "F6": "f_composite"} 

42OVERLAY_TRIALS = ("F1", "F2", "F3", "F4", "F5", "F6", "B1", "B2", "B3", "R1", "S1") 

43S1_HEADS = {"sector_neutral_rank_20d": 1.0} 

44HGB_PARAMS = dict(max_depth=3, learning_rate=0.05, max_iter=200, min_samples_leaf=500, l2_regularization=1.0, early_stopping=False, 

45 random_state=7) 

46 

47 

48def _json(path: Path, default): 

49 return json.loads(path.read_text(encoding="utf-8")) if path.exists() else default 

50 

51 

52def _save(path: Path, payload) -> None: 

53 from json_safety import atomic_write_json 

54 

55 atomic_write_json(path, payload, indent=1) 

56 

57 

58def per_date_rank(frame: pd.DataFrame, column: str) -> pd.Series: 

59 return frame.groupby("date")[column].rank(pct=True) 

60 

61 

62class Chain: 

63 def __init__(self, args): 

64 self.args = args 

65 self.out = Path(args.out) 

66 self.report = _json(self.out, {}) 

67 self.report.setdefault("holdout_reads", []) 

68 self.memo_path = self.out.with_suffix(".memo.json") 

69 self.memo = _json(self.memo_path, {}) 

70 self.config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8")) 

71 self.harnesses: dict = {} 

72 self._frame = None 

73 

74 def save(self) -> None: 

75 _save(self.out, self.report) 

76 _save(self.memo_path, self.memo) 

77 

78 # -- data 

79 def frame(self) -> pd.DataFrame: 

80 if self._frame is None: 

81 from evaluation.research_probes import load_research_frame 

82 

83 schema = json.loads((ROOT_DIR / "ml" / "feature_schema.json").read_text(encoding="utf-8")) 

84 mt_schema = json.loads((ROOT_DIR / "ml" / "multitask_feature_schema.json").read_text(encoding="utf-8")) 

85 self.scaled = list(schema["scaled_feature_names"]) 

86 self.model_inputs = list(mt_schema["model_input_names"]) 

87 columns = [*self.model_inputs, *RAW_FACTOR_INPUTS, *TARGETS, "regime_signal_risk_score", "liquidity_log_dollar_volume"] 

88 frame = load_research_frame(self.args.dataset, columns=columns) 

89 labels_path = Path(self.args.asof_labels) 

90 if labels_path.exists(): 

91 labels = pd.read_parquet(labels_path) 

92 frame = frame.merge(labels, on=["date", "ticker"], how="left") 

93 frame = frame.sort_values(["date", "ticker"]).reset_index(drop=True) 

94 self._frame = frame 

95 print(f"research frame {frame.shape}, {frame.memory_usage(deep=False).sum() / 1e6:.0f} MB", flush=True) 

96 return self._frame 

97 

98 def harness(self, split: str): 

99 if split not in self.harnesses: 

100 from as_live_levers import AsLiveHarness 

101 from lean_calibration import topology_inputs_fn_for 

102 

103 harness = AsLiveHarness(split, dataset_path=self.args.dataset, config=self.config) 

104 harness.topology_inputs_fn = topology_inputs_fn_for(harness, self.config) 

105 harness.original_scores = harness.frame["live_rank_score"].to_numpy().copy() 

106 self.harnesses[split] = harness 

107 return self.harnesses[split] 

108 

109 def installed_scores(self) -> pd.Series: 

110 """live_rank_score of every validation / backtest / holdout row, aligned to the research frame.""" 

111 frame = self.frame() 

112 if "installed" not in frame: 

113 parts = [] 

114 for split in (*SPLITS, "holdout"): 

115 harness = self.harness(split) 

116 parts.append(pd.DataFrame({"date": harness.frame["date"].astype(str).str[:10], "ticker": harness.frame["ticker"].astype(str), 

117 "installed": harness.original_scores})) 

118 scores = pd.concat(parts, ignore_index=True).drop_duplicates(["date", "ticker"]) 

119 self._frame = frame.merge(scores, on=["date", "ticker"], how="left") 

120 return self._frame["installed"] 

121 

122 def s1_scores(self, splits=(*SPLITS, "holdout")) -> pd.Series: 

123 """S1: the live rank score the installed models give with rank_signal.heads = S1_HEADS, aligned to the frame.""" 

124 import copy 

125 

126 from as_live_levers import AsLiveHarness 

127 

128 config = copy.deepcopy(self.config) 

129 config["phase_v2"]["rank_signal"]["heads"] = dict(S1_HEADS) 

130 parts = [] 

131 for split in splits: 

132 harness = AsLiveHarness(split, dataset_path=self.args.dataset, config=config) 

133 parts.append(pd.DataFrame({"date": harness.frame["date"].astype(str).str[:10], "ticker": harness.frame["ticker"].astype(str), 

134 "s1": harness.frame["live_rank_score"].to_numpy()})) 

135 del harness 

136 scores = pd.concat(parts, ignore_index=True).drop_duplicates(["date", "ticker"]) 

137 merged = self.frame()[["date", "ticker"]].merge(scores, on=["date", "ticker"], how="left") 

138 return pd.Series(merged["s1"].to_numpy(), index=self.frame().index) 

139 

140 @contextlib.contextmanager 

141 def score_override(self, harness, scores: pd.Series): 

142 """Swap the harness' live score for `scores` (indexed like the research frame) while the block runs.""" 

143 from evaluation.live_parity import lag_predictions_for_tickers 

144 

145 frame = self.frame() 

146 lookup = dict(zip(zip(frame["date"], frame["ticker"], strict=False), scores.to_numpy(), strict=False)) 

147 keys = zip(harness.frame["date"].astype(str).str[:10], harness.frame["ticker"].astype(str), strict=False) 

148 replaced = np.array([lookup.get(key, np.nan) for key in keys], dtype=float) 

149 try: 

150 harness.frame["live_rank_score"] = replaced 

151 harness.lagged_frame = lag_predictions_for_tickers(harness.frame, prediction_column="live_rank_score", 

152 tickers=harness.late_bar_tickers) 

153 harness._states.clear() 

154 harness._gates.clear() 

155 harness._mechanisms.clear() 

156 yield 

157 finally: 

158 harness.frame["live_rank_score"] = harness.original_scores 

159 harness.lagged_frame = lag_predictions_for_tickers(harness.frame, prediction_column="live_rank_score", 

160 tickers=harness.late_bar_tickers) 

161 harness._states.clear() 

162 harness._gates.clear() 

163 harness._mechanisms.clear() 

164 

165 # -- scoring 

166 def phases(self) -> list[int]: 

167 every = int(self.config["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 20)) 

168 count = min(self.args.max_phases, every) 

169 return sorted({int(round(i * every / count)) % every for i in range(count)}) 

170 

171 def as_live(self, trial: str, split: str, scores: pd.Series | None) -> dict: 

172 """{"summary": extended_summary, "daily": phase-0 {date: net return}} for one trial on one split (memoised).""" 

173 from as_live_levers import summarize 

174 from lean_calibration import ANALYZER_INCLUDE, calibrated_overrides 

175 from v640_research import extended_summary 

176 

177 digest = hashlib.sha1(np.nan_to_num(scores.to_numpy(dtype=float), nan=-9.0).tobytes()).hexdigest() if scores is not None else "base" 

178 key = f"{trial}|{split}|{digest}|{self.args.max_phases}" 

179 if key in self.memo: 

180 return self.memo[key] 

181 harness = self.harness(split) 

182 mechanisms = harness.v610_mechanisms(self.config, legacy=False) 

183 per_phase, daily = [], {} 

184 context = self.score_override(harness, scores) if scores is not None else contextlib.nullcontext() 

185 with context: 

186 for phase in self.phases(): 

187 result = harness.as_live(**dict(calibrated_overrides(harness, phase=phase), **mechanisms), include=ANALYZER_INCLUDE) 

188 per_phase.append(summarize(result)) 

189 if not daily: 

190 daily = {str(d)[:10]: float(r) for d, r in zip(result.per_date, result.per_date_net_return, strict=False)} 

191 entry = {"summary": extended_summary(per_phase), "daily": daily} 

192 self.memo[key] = entry 

193 self.save() 

194 print(f" {trial:4s} {split:10s} median as-live Sharpe {entry['summary']['median_net_sharpe']:+.3f}", flush=True) 

195 return entry 

196 

197 def ic(self, scores: pd.Series, splits=SPLITS) -> dict: 

198 from evaluation.research_harness import evaluate_signal 

199 

200 frame = self.frame().assign(_score=scores.to_numpy()) 

201 return evaluate_signal(frame, score_column="_score", splits=splits, horizons=(5, 20), min_names_per_date=20, 

202 bootstrap_draws=500)["splits"] 

203 

204 

205# -- stages ----------------------------------------------------------------------------------------------------------- 

206 

207def stage_labels(chain: Chain) -> None: 

208 from features import load_sector_mapping 

209 from features.asof_beta_labels import build_asof_rank_labels 

210 

211 frame = chain.frame() 

212 labels_path = Path(chain.args.asof_labels) 

213 if "target_residual_rank_20d_asof" not in frame: 

214 ranking = chain.config["phase1"]["target"]["ranking"] 

215 residual = ranking.get("residual_neutral", {}) 

216 labels = build_asof_rank_labels( 

217 frame[["date", "ticker", "close_to_close_return_1d", "target_return_5d", "target_return_20d", "liquidity_log_dollar_volume"]], 

218 market_ticker=residual.get("market_ticker", "SPY"), sector_by_ticker=load_sector_mapping(chain.config), 

219 min_universe_size=int(residual.get("min_universe_size", ranking.get("min_universe_size", 20))), 

220 ) 

221 out = pd.concat([frame[["date", "ticker"]], labels], axis=1) 

222 labels_path.parent.mkdir(parents=True, exist_ok=True) 

223 out.to_parquet(labels_path, index=False) 

224 chain._frame = pd.concat([frame, labels], axis=1) 

225 frame = chain._frame 

226 print(f"as-of labels -> {labels_path}", flush=True) 

227 

228 from evaluation.gate_audit import daily_rank_ic 

229 from evaluation.model_predictions import predict_heads 

230 

231 export = json.loads((ROOT_DIR / "ml" / "multitask_model.json").read_text(encoding="utf-8")) 

232 heads = ["residual_rank_20d", "beta_neutral_rank_20d"] 

233 report: dict = {} 

234 for split in SPLITS: 

235 part = frame[frame["split"] == split].reset_index(drop=True) 

236 predictions = predict_heads(part, export, chain.model_inputs, heads, model_kind="multitask", batched=True) 

237 split_report = {} 

238 for head in heads: 

239 scored = part.assign(_p=predictions[head]) 

240 row = {} 

241 for label in (f"target_{head}", f"target_{head}_asof"): 

242 ic = daily_rank_ic(scored, score_column="_p", target_column=label, min_names_per_date=20) 

243 row[label] = float(np.mean(list(ic.values()))) if ic else None 

244 agreement = daily_rank_ic(part, score_column=f"target_{head}", target_column=f"target_{head}_asof", min_names_per_date=20) 

245 row["label_agreement_spearman"] = float(np.mean(list(agreement.values()))) if agreement else None 

246 if row[f"target_{head}"] is not None and row[f"target_{head}_asof"] is not None: 

247 row["ic_inflation"] = row[f"target_{head}"] - row[f"target_{head}_asof"] 

248 split_report[head] = row 

249 report[split] = split_report 

250 chain.report["label_leak"] = report 

251 chain.save() 

252 print("label leak:", json.dumps(report, indent=1), flush=True) 

253 

254 

255def stage_leakage(chain: Chain) -> None: 

256 from evaluation.leakage_audit import audit_leakage 

257 

258 frame = chain.frame() 

259 chain.installed_scores() 

260 report = audit_leakage(chain._frame, feature_columns=chain.scaled, target_column="target_rank_20d", class_columns=CLASS_COLUMNS, 

261 model_score_column="installed") 

262 chain.report["leakage_audit"] = report 

263 _save(chain.out.parent / "leakage_audit.json", report) 

264 chain.save() 

265 print("leakage flagged:", report["flagged"], "identity:", report["identity"], flush=True) 

266 del frame 

267 

268 

269def build_trial_scores(chain: Chain) -> dict[str, pd.Series]: 

270 from evaluation.factor_spanning import build_factor_scores 

271 from evaluation.research_probes import fit_hgb_rank, fit_ridge_rank, predict_scores 

272 from features.cross_sectional_norm import cross_sectional_rank 

273 

274 frame = chain.frame() 

275 installed = chain.installed_scores() 

276 frame = chain._frame 

277 factors = build_factor_scores(frame) 

278 scores: dict[str, pd.Series] = {trial: factors[column] for trial, column in FACTOR_TRIALS.items()} 

279 

280 ranked = cross_sectional_rank(frame, chain.scaled) 

281 flagged = set((chain.report.get("leakage_audit") or {}).get("flagged", [])) 

282 identity_like = {column for column, row in ((chain.report.get("leakage_audit") or {}).get("single_feature_ic") or {}).items() 

283 if row.get("flag")} 

284 train = (frame["split"] == "train").to_numpy() 

285 inputs = {"L1": chain.scaled, "L2": chain.scaled, "L3": [c for c in chain.scaled if c not in flagged | identity_like 

286 and c != "dist_52w_high_scaled"]} 

287 for name, columns in inputs.items(): 

288 x = ranked[columns].to_numpy(dtype=np.float64) 

289 if name == "L2": 

290 x = np.column_stack([x, frame[list(CLASS_COLUMNS)].to_numpy(dtype=np.float64)]) 

291 model = fit_ridge_rank(x[train], frame.loc[train, "target_rank_20d"].to_numpy(), alpha=10.0) 

292 scores[name] = pd.Series(predict_scores(model, x), index=frame.index) 

293 print(f" {name} ridge on {model['rows']} rows, {x.shape[1]} inputs", flush=True) 

294 x = ranked[chain.scaled].to_numpy(dtype=np.float32) 

295 for name, depth, target in (("G1", 3, "target_rank_20d"), ("G2", 4, "target_rank_20d"), ("G3", 3, "target_residual_rank_20d_asof")): 

296 model = fit_hgb_rank(x[train], frame.loc[train, target].to_numpy(), **dict(HGB_PARAMS, max_depth=depth)) 

297 scores[name] = pd.Series(predict_scores(model, x), index=frame.index) 

298 print(f" {name} HGB depth {depth} on {target}", flush=True) 

299 del model 

300 

301 installed_rank = per_date_rank(frame.assign(_s=installed), "_s") 

302 composite_rank = per_date_rank(frame.assign(_s=scores["F6"]), "_s") 

303 for name, weight in (("B1", 0.25), ("B2", 0.5), ("B3", 0.75)): 

304 scores[name] = (1.0 - weight) * installed_rank + weight * composite_rank.fillna(0.5) 

305 

306 risk = frame["regime_signal_risk_score"] 

307 edges = risk[train].quantile([1 / 3, 2 / 3]).to_numpy() 

308 tercile = np.digitize(risk.to_numpy(), edges) 

309 weights = {} 

310 from evaluation.gate_audit import daily_rank_ic 

311 

312 ranks = {trial: per_date_rank(frame.assign(_s=scores[trial]), "_s") for trial in ("F1", "F3", "F4", "F5")} 

313 for bucket in range(3): 

314 mask = train & (tercile == bucket) 

315 ics = {} 

316 for trial in ranks: 

317 ic = daily_rank_ic(frame[mask].assign(_s=scores[trial][mask]), score_column="_s", target_column="target_rank_20d", 

318 min_names_per_date=20) 

319 ics[trial] = max(0.0, float(np.mean(list(ic.values())))) if ic else 0.0 

320 total = sum(ics.values()) 

321 weights[bucket] = {trial: (value / total if total > 0 else 0.25) for trial, value in ics.items()} 

322 chain.report["r1_weights"] = {str(k): v for k, v in weights.items()} 

323 r1 = pd.Series(0.0, index=frame.index) 

324 for bucket, w in weights.items(): 

325 mask = tercile == bucket 

326 r1[mask] = sum(w[trial] * ranks[trial][mask].fillna(0.5) for trial in w) 

327 scores["R1"] = r1.where(risk.notna()) 

328 scores["S1"] = chain.s1_scores() 

329 return scores 

330 

331 

332def stage_grid(chain: Chain) -> dict[str, pd.Series]: 

333 scores = build_trial_scores(chain) 

334 installed = chain.installed_scores() 

335 grid = chain.report.setdefault("grid", {}) 

336 base = {"ic": chain.ic(installed), "as_live": {split: chain.as_live("base", split, None)["summary"] for split in SPLITS}} 

337 chain.report["baseline"] = base 

338 for trial, series in scores.items(): 

339 entry = grid.setdefault(trial, {}) 

340 entry["ic"] = chain.ic(series) 

341 entry["as_live"] = {split: chain.as_live(trial, split, series)["summary"] for split in SPLITS} 

342 # build_trial_registry reads <trial>/backtest/median_net_sharpe 

343 entry["registry"] = {split: {"median_net_sharpe": entry["as_live"][split]["median_net_sharpe"], 

344 "phases": entry["as_live"][split]["phases"]} for split in SPLITS} 

345 chain.save() 

346 return scores 

347 

348 

349def stage_pbo(chain: Chain, scores: dict[str, pd.Series]) -> None: 

350 from evaluation.pbo import probability_of_backtest_overfitting 

351 

352 trials = list(scores) 

353 series = [] 

354 for trial in trials: 

355 daily: dict = {} 

356 for split in SPLITS: 

357 daily.update(chain.as_live(trial, split, scores[trial])["daily"]) 

358 series.append(pd.Series(daily)) 

359 matrix = pd.concat(series, axis=1, keys=trials).sort_index().fillna(0.0) 

360 matrix.to_parquet(chain.out.parent / "trial_returns.parquet") 

361 chain.report["pbo"] = probability_of_backtest_overfitting(matrix.to_numpy(), blocks=16) 

362 chain.save() 

363 print("PBO:", chain.report["pbo"]["pbo"], flush=True) 

364 

365 

366def stage_spanning(chain: Chain, scores: dict[str, pd.Series]) -> None: 

367 from evaluation.factor_spanning import build_factor_returns, factor_spanning 

368 

369 frame = chain.frame() 

370 backtest = (frame["split"] == "backtest").to_numpy() 

371 part = frame.loc[backtest, ["date", "target_return_1d"]].copy() 

372 for trial, series in scores.items(): 

373 part[trial] = series[backtest].to_numpy() 

374 factor_returns = build_factor_returns(part, ["F1", "F2", "F3", "F4", "F5"]) 

375 result = {} 

376 for trial in ("L1", "L2", "L3", "G1", "G2", "G3"): 

377 signal = build_factor_returns(part, [trial])[trial] 

378 result[trial] = factor_spanning(signal, factor_returns) 

379 chain.report["spanning"] = result 

380 chain.save() 

381 print("spanning alpha t:", {k: v.get("alpha_t") for k, v in result.items()}, flush=True) 

382 

383 

384def clause_checks(chain: Chain, trial: str) -> dict: 

385 from v640_research import verdict_as_live 

386 

387 base, entry = chain.report["baseline"], chain.report["grid"][trial] 

388 base_ic = base["ic"]["validation"]["h20"]["nonoverlap_mean_ic"] 

389 checks = { 

390 "1_validation_ic_beats_base_by_0.034": entry["ic"]["validation"]["h20"]["nonoverlap_mean_ic"] - base_ic >= YARDSTICK, 

391 "2_backtest_hac_t_ge_2": entry["ic"]["backtest"]["h20"]["hac_t"] >= 2.0, 

392 "3_verdict_as_live": verdict_as_live(base["as_live"], entry["as_live"])["passes"], 

393 "4_grid_pbo_below_0.5": (chain.report.get("pbo") or {}).get("pbo") is not None and chain.report["pbo"]["pbo"] < 0.5, 

394 } 

395 if trial[0] in "LG": 

396 checks["5_spanning_alpha_t_ge_2"] = ((chain.report.get("spanning") or {}).get(trial) or {}).get("alpha_t") is not None and \ 

397 chain.report["spanning"][trial]["alpha_t"] >= 2.0 

398 return checks 

399 

400 

401def stage_verdict(chain: Chain, scores: dict[str, pd.Series]) -> None: 

402 verdicts = {trial: clause_checks(chain, trial) for trial in chain.report["grid"]} 

403 finalists = [trial for trial, checks in verdicts.items() if all(checks.values())] 

404 holdout = {} 

405 if finalists: 

406 base = chain.as_live("base", "holdout", None)["summary"]["median_net_sharpe"] 

407 for trial in finalists: 

408 chain.report["holdout_reads"].append({"trial": trial, "what": "rank_20d IC and as-live Sharpe on the holdout"}) 

409 ic = chain.ic(scores[trial], splits=("holdout",))["holdout"]["h20"]["mean_ic"] 

410 sharpe = chain.as_live(trial, "holdout", scores[trial])["summary"]["median_net_sharpe"] 

411 holdout[trial] = {"ic": ic, "median_net_sharpe": sharpe, "baseline_median_net_sharpe": base, 

412 "passes": ic > 0 and sharpe >= base - 0.10} 

413 verdicts[trial]["6_holdout"] = holdout[trial]["passes"] 

414 qualifiers = [trial for trial in finalists if all(verdicts[trial].values())] 

415 winner = max(qualifiers, key=lambda t: chain.report["grid"][t]["as_live"]["backtest"]["median_net_sharpe"]) if qualifiers else None 

416 chain.report["verdict"] = {"rule": "R-MODEL11", "checks": verdicts, "finalists": finalists, "holdout": holdout, 

417 "qualifiers": qualifiers, "winner": winner, 

418 "winner_type": None if winner is None else ("overlay" if winner in OVERLAY_TRIALS else "probe")} 

419 chain.save() 

420 print("R-MODEL11:", json.dumps(chain.report["verdict"], indent=1, default=str), flush=True) 

421 

422 

423def main() -> int: 

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

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

426 parser.add_argument("--asof-labels", default=str(ROOT_DIR / "ml" / "datasets" / "v643_asof_labels.parquet")) 

427 parser.add_argument("--stages", nargs="*", default=["labels", "leakage", "grid", "pbo", "spanning", "verdict"]) 

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

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

430 args = parser.parse_args() 

431 chain = Chain(args) 

432 if "labels" in args.stages: 

433 stage_labels(chain) 

434 if "leakage" in args.stages: 

435 stage_leakage(chain) 

436 scores = None 

437 if any(stage in args.stages for stage in ("grid", "pbo", "spanning", "verdict")): 

438 scores = stage_grid(chain) 

439 if "pbo" in args.stages: 

440 stage_pbo(chain, scores) 

441 if "spanning" in args.stages: 

442 stage_spanning(chain, scores) 

443 if "verdict" in args.stages: 

444 stage_verdict(chain, scores) 

445 chain.report["phases"] = chain.phases() 

446 chain.save() 

447 return 0 

448 

449 

450if __name__ == "__main__": 

451 raise SystemExit(main())