Coverage for scripts/v640_research.py: 100%
663 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""V6.4.0 research chain (pre-registered rules for todo leads L1-L10 and R-DEDUPE2; plan V6.4.0). Written before any score.
3Scoring is V6.2/V6.3's (scripts/v620_research.py, v630_research.py): the modelled portfolio (main book + legacy signal) on the
4calibrated simulator, every rebalance phase (up to --max-phases evenly spaced ones) of both splits, the T-bill sweep off,
5statistics = the median across phases (plus p10 / p25 / interquartile range). Two modes: AS-LIVE (rolling-IC gate on, the shipped
6mechanisms) and UNGATED (gate and spread veto off; the gate is a safety control the offline simulator does not calibrate, R-CAL3
7branch B). `verdict_ungated` = `rule_verdict` (backtest median gain >= +0.10, validation not worse than -0.02, >= 60% of phases
8beating the base median on both splits, positive median on both splits, median drawdown within 1 pp). `verdict_as_live` = the
9same without the positive-median clause (the gated book's median is near zero). Each stage scores on top of what the earlier
10ones adopted. The holdout is never used to choose between variants; every read of it is logged in `report["holdout_reads"]`.
12 dedupe R-DEDUPE2 (Problems #201's second look, on the longer span): `rolling_ic_gate.late_bar_event_count` "once" against
13 "per_tick", AS-LIVE, with validation and the pooled post-validation span (backtest + holdout) as the two splits.
14 Adopted iff `verdict_as_live` passes. Either way #201 closes.
15 l1 Engaged-day skill (a report and a precondition, no config change). On validation and backtest (holdout report only)
16 the gate's per-date verdict splits the dates; rank IC (daily mean, non-overlapping, HAC t), the top-6/bottom-6 spread
17 and the as-live Sharpe over the days whose latest rebalance was engaged are compared with all days. Bar (owner): on
18 BOTH splits engaged - all >= +0.02 IC and >= +0.15 Sharpe (median over phases) -> "the gate protects capital";
19 otherwise "the gate hides weakness" and L6 / L7 cannot ship.
20 l8 Expert contribution to the legacy signal. contribution(e) = IC(legacy score) - IC(legacy score without expert e) on
21 the engaged equity dates, both splits. Experts with contribution <= 0 on BOTH splits are disabled together
22 (`gating_network.disabled_experts`) iff the book with them disabled is non-inferior as-live (median Sharpe change
23 >= -0.02 on both splits).
24 l2 Direction calibration. Heads: multitask / sequence direction_20d; temperature or isotonic fitted on VALIDATION only
25 (cross-fitted for the honest validation loss), the method with the lower cross-fitted log-loss and the head with the
26 lower raw log-loss are used. Overlays on the percentile ranks (portfolio.direction_overlay): C1 blend w=0.25,
27 C2 blend w=0.5, C3 agree_filter margin 0.05. Adopted (best backtest median) iff `verdict_as_live` passes AND the
28 median annualised turnover rises <= 20%. Otherwise "direction = diagnostic only".
29 l3 Legacy vs the main book. (a) budgets, AS-LIVE: LG-off (legacy sleeve disabled), LG-half (0.025 gross / 0.01 per name),
30 LG-double (0.10 / 0.04, with `legacy_clause`: the legacy component earns a positive median on both splits);
31 adopted iff `verdict_as_live` passes AND the validation change is > 0. (b) the multitask model retrained with the
32 previous day's legacy probability as an input (candidate v640_leg): adopted iff R-MODEL10's IC clauses pass with the
33 yardstick fixed at the owner's 0.034, `verdict_as_live` passes, validation improves and latency <= 1.5x. (c) report:
34 the legacy score's IC against rank_20d's by class and regime bucket.
35 l4 Within-class equity ranking. W1: crypto leaves the main rank group (`separate_rank_groups.crypto`); W2:
36 `rank_signal.normalization` "sector_relative"; W3: both. Adopted (best backtest median) iff the whole-book
37 `verdict_as_live` is non-inferior (>= -0.02 on both splits), the engaged equity IC rises on both splits, the equity
38 sleeve's gross Sharpe (from the logged weights) rises on both splits, and the holdout Sharpe falls by <= 0.10.
39 l5 Turnover vs IC: rebalance_every_bars {10, 20, 40} x exits.max_holding_bars {20, 40, 60} against 20/40, AS-LIVE.
40 Adopted (best backtest median) iff `verdict_as_live` passes and the median AND p25 phase Sharpe are >= the base's on
41 both splits.
42 l6 (skipped, closed by its precondition, unless L1 passed or --score-blocked-stages) Staggered book: T2 (2 tranches), T2h (2, half-way adjustment), T3, T3h, UNGATED (and AS-LIVE reported). Adopted iff
43 the median >= base on both splits, the validation IQR <= base, p10 >= base on both splits, the cost drag rises <= 30%,
44 and the L1 precondition holds.
45 l7 (same precondition as L6) Kill-switch design: KD1 trip_confirm_bars 3, KD2 120 bars + confirm 3, KD3 release band -0.5 + confirm 3, KD4 floor
46 -1.5, AS-LIVE. Adopted (lowest false-lock share) iff false-lock share < KS0's on both splits, the p95 phase max
47 drawdown <= KS0's + 0.5 pp, the lock-path stability (Jaccard under N(0, 0.5 bp) noise) >= KS0's, the median Sharpe
48 change >= -0.02 on both splits, and the L1 precondition holds. A false lock = a locked date after which the UNLOCKED
49 book's next-20-day return is in its split's top third.
50 l9 Crypto core vs graduates: bootstrap by trade on BT4's closed trades, leave-one-name-out (as-live), crypto-only IC.
51 G0 (graduates ineligible) against graduates on: kept iff graduates beat G0 on the median Sharpe of BOTH splits.
52 l10 Residual head: R1 (0.4 / 0.4 / 0.2), R2 (0.35 / 0.35 / 0.3), R3 (0.5 / 0 / 0.5) over rank_20d / rank_5d /
53 residual_rank_20d, AS-LIVE. Adopted (best backtest median) iff `verdict_as_live` passes and |change in the market loading|
54 and |change in the momentum loading| (evaluation.factor_neutralization_check) are both <= 0.10.
56 python scripts/v640_research.py --dataset ml/datasets/v640_full_dataset.csv --legacy-probability ml/datasets/legacy_probability.csv
57 --legacy-components ml/datasets/legacy_components.csv [--candidates ml/evaluation/v640/candidates.json]
58 [--model-ic ml/evaluation/v640/model_ic.json] [--lean-run backtests/2026-10-18_12-55-00]
59 [--stages dedupe l1 l8 l2 l3 l4 l5 l6 l7 l9 l10] [--max-phases 10] [--workers 2]
60 [--out ml/evaluation/v640/research.json] [--adopted-config-out ml/evaluation/v640/adopted_changes.json]
61"""
63from __future__ import annotations
65import argparse
66import contextlib
67import copy
68import hashlib
69import json
70import statistics
71import sys
72from pathlib import Path
74ROOT_DIR = Path(__file__).resolve().parents[1]
75sys.path.insert(0, str(ROOT_DIR))
76sys.path.insert(0, str(Path(__file__).resolve().parent))
78from v610_research import MAX_LATENCY_RATIO, SPLITS, apply_dotted, legacy_clause, phases_for, rule_verdict # noqa: E402
79from v620_research import model10_checks # noqa: E402
80from v630_research import interquartile_range, jaccard, perturbation # noqa: E402
82# ---------------------------------------------------------------- pre-registered variants and margins
84DEDUPE_VARIANT = {"rolling_ic_gate.late_bar_event_count": "once"}
85DEDUPE_SPECS = {"validation": "validation", "backtest": ("backtest", "holdout")}
86L2_VARIANTS = {
87 "C1": {"mode": "blend", "weight": 0.25},
88 "C2": {"mode": "blend", "weight": 0.5},
89 "C3": {"mode": "agree_filter", "margin": 0.05},
90}
91MAX_TURNOVER_RISE = 0.20
92LEGACY_VARIANTS = {
93 "LG-off": {"legacy_sleeve.enabled": False},
94 "LG-half": {"legacy_sleeve.max_gross_exposure": 0.025, "legacy_sleeve.max_weight_per_name": 0.01},
95 "LG-double": {"legacy_sleeve.max_gross_exposure": 0.10, "legacy_sleeve.max_weight_per_name": 0.04},
96}
97MODEL_YARDSTICK = 0.034
98SEPARATE_GROUPS_WITH_CRYPTO = {"forex": ["forex"], "bond": ["bond"], "crypto": ["crypto"]}
99L4_VARIANTS = {
100 "W1": {"patch": {"phase1.target.ranking.separate_rank_groups": SEPARATE_GROUPS_WITH_CRYPTO}, "changes": {}},
101 "W2": {"patch": {}, "changes": {"rank_signal.normalization": "sector_relative"}},
102 "W3": {"patch": {"phase1.target.ranking.separate_rank_groups": SEPARATE_GROUPS_WITH_CRYPTO},
103 "changes": {"rank_signal.normalization": "sector_relative"}},
104}
105L4_HOLDOUT_MAX_LOSS = 0.10
106L4_NON_INFERIOR = -0.02
107L5_VARIANTS = {
108 f"R{rebalance}/H{hold}": {"portfolio_book.rebalance_every_bars": rebalance, "exits.max_holding_bars": hold}
109 for rebalance in (10, 20, 40) for hold in (20, 40, 60) if (rebalance, hold) != (20, 40)
110}
111L6_VARIANTS = {
112 "T2": {"tranches": 2, "adjust": 1.0}, "T2h": {"tranches": 2, "adjust": 0.5},
113 "T3": {"tranches": 3, "adjust": 1.0}, "T3h": {"tranches": 3, "adjust": 0.5},
114}
115MAX_COST_RISE = 0.30
116L7_VARIANTS = {
117 "KD1": {"risk.kill_switch.trip_confirm_bars": 3},
118 "KD2": {"risk.kill_switch.evaluation_bars": 120, "risk.kill_switch.trip_confirm_bars": 3},
119 "KD3": {"risk.kill_switch.release_rolling_sharpe": -0.5, "risk.kill_switch.trip_confirm_bars": 3},
120 "KD4": {"risk.kill_switch.min_rolling_sharpe": -1.5},
121}
122L7_DRAWDOWN_CAP = 0.005
123L7_NON_INFERIOR = -0.02
124NOISE_SEEDS = (1, 2, 3)
125STABILITY_PHASES = 5
126L10_VARIANTS = {
127 "R1": {"rank_20d": 0.4, "rank_5d": 0.4, "residual_rank_20d": 0.2},
128 "R2": {"rank_20d": 0.35, "rank_5d": 0.35, "residual_rank_20d": 0.3},
129 "R3": {"rank_20d": 0.5, "rank_5d": 0.0, "residual_rank_20d": 0.5},
130}
131L10_MAX_FACTOR_SHIFT = 0.10
132EXPERTS = ("bullish", "bearish", "sideways", "volatility")
133LOO_PHASES = 5
136# ---------------------------------------------------------------- pure clause functions (unit-tested)
139def quantile(values, q: float) -> float:
140 ordered = sorted(float(value) for value in values)
141 position = q * (len(ordered) - 1)
142 low, high = int(position // 1), min(int(-(-position // 1)), len(ordered) - 1)
143 return ordered[low] + (ordered[high] - ordered[low]) * (position - low)
146def extended_summary(per_phase: list[dict]) -> dict:
147 """`v610_research.phase_summary` plus the figures this chain's clauses read (all lists are by phase)."""
148 from v610_research import phase_summary
150 summary = phase_summary(per_phase)
151 sharpes = summary["net_sharpe_by_phase"]
152 summary.update(
153 p10_net_sharpe=quantile(sharpes, 0.10), p25_net_sharpe=quantile(sharpes, 0.25), iqr_net_sharpe=interquartile_range(sharpes),
154 net_max_drawdown_by_phase=[row["net_max_drawdown"] for row in per_phase],
155 p05_net_max_drawdown=quantile([row["net_max_drawdown"] for row in per_phase], 0.05),
156 cost_drag_by_phase=[row["cost_drag_annual_bps"] for row in per_phase],
157 median_turnover=statistics.median(row["annualized_turnover"] for row in per_phase),
158 locked_dates_by_phase=[len(row.get("locked_dates", [])) for row in per_phase],
159 legacy_net_return_median=statistics.median(row.get("legacy_net_return", 0.0) for row in per_phase),
160 )
161 for name in ("engaged_sharpe", "all_sharpe", "equity_sharpe", "false_lock_share"):
162 values = [row[name] for row in per_phase if row.get(name) is not None]
163 if values:
164 summary[f"{name}_by_phase"] = values
165 summary[f"{name}_median"] = statistics.median(values)
166 return summary
169def verdict_as_live(base: dict, variant: dict) -> dict:
170 """`rule_verdict` on AS-LIVE scores: the gated book's median Sharpe sits near zero, so the positive-median clause goes."""
171 verdict = rule_verdict(base, variant)
172 verdict["checks"].pop("positive_median_on_both_splits", None)
173 verdict["passes"] = all(verdict["checks"].values())
174 return verdict
177def best_by_backtest(names, scores: dict) -> str | None:
178 names = list(names)
179 return max(names, key=lambda name: scores[name]["backtest"]["median_net_sharpe"]) if names else None
182def l1_margins(skill: dict, base_summary: dict) -> dict:
183 """{"ic_margin", "sharpe_margin"} of one split: engaged - all IC, and the median over phases of (engaged - all) Sharpe."""
184 engaged = base_summary.get("engaged_sharpe_by_phase") or []
185 everything = base_summary.get("all_sharpe_by_phase") or []
186 margins = [a - b for a, b in zip(engaged, everything, strict=False)]
187 return {"ic_margin": skill.get("ic_margin"), "sharpe_margin": statistics.median(margins) if margins else None}
190def l2_checks(base: dict, variant: dict) -> dict:
191 base_turnover = statistics.median([base[s]["median_turnover"] for s in SPLITS])
192 variant_turnover = statistics.median([variant[s]["median_turnover"] for s in SPLITS])
193 return {"turnover_rise_le_20pct": variant_turnover <= (1.0 + MAX_TURNOVER_RISE) * max(base_turnover, 1e-9)}
196def l3_budget_checks(verdict: dict, scores: dict, variant_name: str) -> dict:
197 checks = {"validation_improves": verdict["validation_change"] > 0.0}
198 if variant_name == "LG-double":
199 checks.update(legacy_clause({"ungated": scores}))
200 return checks
203def l3_model_checks(model_ic_checks: dict, verdict: dict, latency_ratio: float | None) -> dict:
204 return {
205 "validation_beats_installed_by_0.034": model_ic_checks["validation_beats_installed_by_yardstick"],
206 "backtest_ic_not_below_installed_minus_0.034": model_ic_checks["backtest_ic_not_below_installed_minus_yardstick"],
207 "backtest_hac_t_ge_2": model_ic_checks["backtest_hac_t_ge_2"],
208 "book_verdict_as_live_passes": verdict["passes"],
209 "validation_book_improves": verdict["validation_change"] > 0.0,
210 "latency_le_1.5x": latency_ratio is not None and latency_ratio <= MAX_LATENCY_RATIO,
211 }
214def l4_checks(base: dict, variant: dict, verdict: dict, ic_by_split: dict, holdout_loss: float | None) -> dict:
215 """`ic_by_split` = {split: {"base": engaged equity IC, "variant": ...}}; `holdout_loss` = base - variant holdout Sharpe."""
216 return {
217 "whole_book_non_inferior": verdict["backtest_gain"] >= L4_NON_INFERIOR and verdict["validation_change"] >= L4_NON_INFERIOR,
218 "engaged_equity_ic_up_on_both_splits": all(
219 ic_by_split[s]["variant"] is not None and ic_by_split[s]["base"] is not None and ic_by_split[s]["variant"] > ic_by_split[s]["base"]
220 for s in SPLITS
221 ),
222 "equity_sharpe_up_on_both_splits": all(
223 variant[s].get("equity_sharpe_median") is not None and base[s].get("equity_sharpe_median") is not None
224 and variant[s]["equity_sharpe_median"] > base[s]["equity_sharpe_median"] for s in SPLITS
225 ),
226 "holdout_loss_le_0.10": holdout_loss is not None and holdout_loss <= L4_HOLDOUT_MAX_LOSS,
227 }
230def l5_checks(base: dict, variant: dict) -> dict:
231 return {
232 "median_not_below_base_on_both_splits": all(variant[s]["median_net_sharpe"] >= base[s]["median_net_sharpe"] for s in SPLITS),
233 "p25_not_below_base_on_both_splits": all(variant[s]["p25_net_sharpe"] >= base[s]["p25_net_sharpe"] for s in SPLITS),
234 }
237def l6_checks(base: dict, variant: dict, l1_pass: bool) -> dict:
238 base_cost = statistics.median(base["validation"]["cost_drag_by_phase"] + base["backtest"]["cost_drag_by_phase"])
239 variant_cost = statistics.median(variant["validation"]["cost_drag_by_phase"] + variant["backtest"]["cost_drag_by_phase"])
240 return {
241 "median_not_below_base_on_both_splits": all(variant[s]["median_net_sharpe"] >= base[s]["median_net_sharpe"] for s in SPLITS),
242 "validation_iqr_not_wider": variant["validation"]["iqr_net_sharpe"] <= base["validation"]["iqr_net_sharpe"],
243 "p10_not_below_base_on_both_splits": all(variant[s]["p10_net_sharpe"] >= base[s]["p10_net_sharpe"] for s in SPLITS),
244 "cost_drag_rise_le_30pct": variant_cost <= (1.0 + MAX_COST_RISE) * max(base_cost, 1e-9),
245 "l1_precondition": bool(l1_pass),
246 }
249def l7_checks(base: dict, variant: dict, base_stability: float, variant_stability: float, l1_pass: bool) -> dict:
250 def share(scores, split):
251 values = scores[split].get("false_lock_share_by_phase") or []
252 return statistics.median(values) if values else None
254 lower_false_locks = all(
255 share(variant, s) is not None and share(base, s) is not None and share(variant, s) < share(base, s) for s in SPLITS
256 )
257 return {
258 "false_lock_share_below_base_on_both_splits": lower_false_locks,
259 "p95_drawdown_within_0.5pp": all(
260 variant[s]["p05_net_max_drawdown"] - base[s]["p05_net_max_drawdown"] >= -L7_DRAWDOWN_CAP for s in SPLITS
261 ),
262 "stability_not_below_base": variant_stability >= base_stability,
263 "median_sharpe_non_inferior": all(
264 variant[s]["median_net_sharpe"] - base[s]["median_net_sharpe"] >= L7_NON_INFERIOR for s in SPLITS
265 ),
266 "l1_precondition": bool(l1_pass),
267 }
270def l8_decision(contributions: dict[str, dict[str, float | None]], ablated_verdict: dict | None) -> dict:
271 """`contributions` = {expert: {split: IC(full) - IC(without expert)}}. The experts with contribution <= 0 on both splits,
272 and whether disabling them together is non-inferior."""
273 useless = sorted(
274 expert for expert, by_split in contributions.items()
275 if all(by_split.get(s) is not None and by_split[s] <= 0.0 for s in SPLITS)
276 )
277 non_inferior = (
278 ablated_verdict is not None and ablated_verdict["backtest_gain"] >= -0.02 and ablated_verdict["validation_change"] >= -0.02
279 )
280 return {"disable": useless if non_inferior else [], "candidates_with_no_contribution": useless, "non_inferior": non_inferior}
283def l9_decision(graduates_on: dict, graduates_off: dict) -> dict:
284 wins = {s: graduates_on[s]["median_net_sharpe"] > graduates_off[s]["median_net_sharpe"] for s in SPLITS}
285 return {"graduates_beat_core_only_on": wins, "keep_graduates": all(wins.values())}
288def l10_checks(verdict: dict, shift: dict) -> dict:
289 """`shift` = {"market": change in the book's market loading, "momentum": change in its momentum loading}."""
290 return {
291 "market_loading_shift_le_0.10": abs(shift.get("market", 0.0)) <= L10_MAX_FACTOR_SHIFT,
292 "momentum_loading_shift_le_0.10": abs(shift.get("momentum", 0.0)) <= L10_MAX_FACTOR_SHIFT,
293 "verdict_as_live_passes": verdict["passes"],
294 }
297def all_pass(checks: dict) -> bool:
298 return all(bool(value) for value in checks.values())
301def patch_config(config: dict, patches: dict) -> dict:
302 """A deep copy of `config` with `{full.dotted.path: value}` set (paths from the config root, unlike `apply_dotted`)."""
303 result = copy.deepcopy(config)
304 for dotted, value in (patches or {}).items():
305 node = result
306 *parents, leaf = dotted.split(".")
307 for part in parents:
308 node = node.setdefault(part, {})
309 node[leaf] = value
310 return result
313# ---------------------------------------------------------------- the scoring layer (runs on the Codespace)
315_JOB: dict = {}
318def _phase_worker(task: tuple[int, int | None]) -> dict:
319 from as_live_levers import summarize
320 from lean_calibration import ANALYZER_INCLUDE, calibrated_overrides
322 from evaluation.engaged_day_skill import engaged_window_returns, sharpe
324 phase, seed = task
325 job = _JOB
326 harness = job["harness"]
327 kwargs = dict(calibrated_overrides(harness, phase=phase), **job["mechanisms"], include=ANALYZER_INCLUDE)
328 if job["mode"] == "ungated":
329 kwargs.update(gate="off", min_rank_confidence_spread=0.0)
330 if seed is not None:
331 kwargs["kill_switch_extra_returns"] = perturbation(job["dates"], seed, kwargs.get("kill_switch_extra_returns"))
332 if job.get("overlay_fn") is not None:
333 kwargs["rank_overlay_fn"] = job["overlay_fn"]
334 if job.get("candidate_metadata") is not None:
335 kwargs["candidate_metadata_by_ticker"] = job["candidate_metadata"]
336 if "equity" in job["extras"]:
337 kwargs["log_weights"] = True
338 result = harness.as_live(config_overrides=job["resolved"] or None, tranches=job.get("tranches", 1), **kwargs)
339 summary = summarize(result)
340 components = result.per_date_component_returns or {}
341 summary["legacy_net_return"] = sum(components.get("legacy", {}).values())
342 summary["locked_dates"] = list(result.kill_switch_locked_date_list or [])
343 returns = dict(zip(result.per_date, result.per_date_net_return, strict=False))
344 if "returns" in job["extras"]:
345 summary["returns"] = returns
346 if "engaged" in job["extras"]:
347 engaged, everything = engaged_window_returns(returns, result.rebalance_log or [])
348 summary["engaged_sharpe"], summary["all_sharpe"] = sharpe(engaged), sharpe(everything)
349 if "equity" in job["extras"]:
350 summary["equity_sharpe"] = equity_gross_sharpe(result, job["frame_returns"], job["equity_tickers"])
351 return summary
354def equity_gross_sharpe(result, frame_returns: dict, equity_tickers: set) -> float | None:
355 """Sharpe of the equity part of the book alone, from the logged held weights x the dated next-day returns (gross of costs;
356 the effective-weight lag of the calibrated simulator is ignored, identically for every variant)."""
357 from evaluation.engaged_day_skill import sharpe
359 series = []
360 for day, weights in zip(result.per_date, result.weights_log or [], strict=False):
361 returns = frame_returns.get(day, {})
362 series.append(sum(weight * returns.get(ticker, 0.0) for ticker, weight in weights.items() if ticker in equity_tickers))
363 return sharpe(series)
366def map_tasks(tasks: list, workers: int) -> list[dict]:
367 import multiprocessing
369 if workers > 1 and len(tasks) > 1 and sys.platform.startswith("linux"):
370 with multiprocessing.get_context("fork").Pool(min(workers, len(tasks))) as pool:
371 return pool.map(_phase_worker, tasks)
372 return [_phase_worker(task) for task in tasks]
375class Research:
376 """Harness pool, memoised scoring and the report; stages talk to it through `score`, `harness`, `labels`."""
378 def __init__(self, args, base_config: dict, report: dict, out_path: Path):
379 self.args = args
380 self.base_config = base_config
381 self.report = report
382 self.out_path = out_path
383 self.pool: dict = {}
384 self.memo_path = out_path.with_suffix(".memo.json")
385 self.memo: dict = json.loads(self.memo_path.read_text(encoding="utf-8")) if self.memo_path.exists() else {}
386 # a resumed run replays every stage from the memo and re-adopts in order: the previous run's adoptions must not leak
387 # into the earlier stages' base config (memo keys include it), so the chain always starts from the shipped config
388 self.adopted = report["adopted"] = {"config": {}, "tranches": 1, "adjust_fraction": 1.0, "patch": {}, "model": None,
389 "direction_overlay": None, "needs_live_path": []}
390 report.pop("l1_pass", None)
391 self.report.setdefault("holdout_reads", [])
393 # -- persistence
394 def save(self) -> None:
395 self.out_path.parent.mkdir(parents=True, exist_ok=True)
396 self.out_path.write_text(json.dumps(self.report, indent=1, default=float), encoding="utf-8")
397 self.memo_path.write_text(json.dumps(self.memo, default=float), encoding="utf-8")
399 def log_holdout_read(self, stage: str, what: str) -> None:
400 entry = {"stage": stage, "what": what}
401 if entry not in self.report["holdout_reads"]: # a resumed run replays the stage: one read, one entry
402 self.report["holdout_reads"].append(entry)
404 # -- harnesses
405 def harness(self, split, *, patch: dict | None = None, model: str | None = None):
406 from as_live_levers import AsLiveHarness
407 from lean_calibration import topology_inputs_fn_for
409 spec = (self.args.candidates_spec or {}).get(model, {}) if model else {}
410 key = json.dumps([list(split) if isinstance(split, tuple) else split, patch or {}, model], sort_keys=True, default=str)
411 if key not in self.pool:
412 while len(self.pool) >= 4:
413 self.pool.pop(next(iter(self.pool)))
414 config = patch_config(self.base_config, patch or {})
415 if spec.get("ensemble"):
416 config["phase_v2"]["model_ensemble"]["enabled"] = True
417 harness = AsLiveHarness(
418 split, dataset_path=spec.get("dataset") or self.args.dataset, config=config,
419 ml_dir=(ROOT_DIR / spec["ml_dir"]) if spec.get("ml_dir") else None,
420 legacy_probability_path=spec.get("legacy_probability") or self.args.legacy_probability,
421 gate_warmup_days=self.args.gate_warmup_days,
422 )
423 self.pool[key] = (harness, topology_inputs_fn_for(harness, config), config)
424 return self.pool[key]
426 @contextlib.contextmanager
427 def legacy_override(self, harness, probabilities: dict):
428 """Swap the legacy probability column of a harness' frames for `{(date, ticker): p}` while the block runs."""
429 from as_live_levers import LEGACY_PROBABILITY_COLUMN
431 saved = {name: getattr(harness, name)[LEGACY_PROBABILITY_COLUMN].copy() for name in ("frame", "lagged_frame")}
432 try:
433 for name in saved:
434 frame = getattr(harness, name)
435 keys = list(zip(frame["date"].astype(str).str[:10], frame["ticker"].astype(str), strict=False))
436 frame[LEGACY_PROBABILITY_COLUMN] = [probabilities.get(key, value) for key, value in zip(keys, saved[name], strict=False)]
437 yield
438 finally:
439 for name, column in saved.items():
440 getattr(harness, name)[LEGACY_PROBABILITY_COLUMN] = column
442 # -- scoring
443 def score(self, changes: dict, *, patch: dict | None = None, specs: dict | None = None, tranches: int = 1, mode: str = "ungated",
444 model: str | None = None, overlay: dict | None = None, extras: tuple = (), stability: bool = False,
445 eligible_override: set | None = None, legacy_probabilities: dict | None = None, phases: int | None = None,
446 memo_tag: str = "") -> dict:
447 from lean_calibration import use_topology
449 specs = specs or {split: split for split in SPLITS}
450 overlay_key = {k: v for k, v in (overlay or {}).items() if k != "probabilities"} or None
451 key = hashlib.sha1(json.dumps([changes, patch, sorted(map(str, specs.items())), tranches, mode, model, overlay_key, list(extras),
452 stability, sorted(eligible_override) if eligible_override is not None else None,
453 legacy_probabilities is not None, phases, memo_tag], sort_keys=True, default=str).encode()).hexdigest()
454 if key in self.memo:
455 return self.memo[key]
456 out: dict = {}
457 for name, split in specs.items():
458 harness, topology_fn, config = self.harness(split, patch=patch, model=model)
459 merged = apply_dotted(config, changes)
460 use_topology(harness, topology_fn)
461 cadence = int(merged["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 20))
462 candidate_metadata = None
463 if eligible_override is not None:
464 candidate_metadata = {t: dict(v) for t, v in harness.metadata.items()}
465 for ticker, kind in harness.asset_class_by_ticker.items():
466 if kind == "crypto":
467 candidate_metadata[ticker]["trading_eligible"] = ticker in eligible_override
468 frame_returns = None
469 equity_tickers = {t for t, kind in harness.asset_class_by_ticker.items() if kind == "equity"}
470 if "equity" in extras:
471 frame_returns = {}
472 for row in harness.lagged_frame[["date", "ticker", "target_return_1d"]].itertuples(index=False):
473 frame_returns.setdefault(str(row[0])[:10], {})[str(row[1])] = float(row[2]) if row[2] == row[2] else 0.0
474 overlay_fn = self.overlay_fn(harness, overlay) if overlay else None
475 context = self.legacy_override(harness, legacy_probabilities) if legacy_probabilities else contextlib.nullcontext()
476 with context:
477 _JOB.update(harness=harness, mechanisms=harness.v610_mechanisms(merged), resolved=dict(changes), mode=mode,
478 tranches=tranches, dates=sorted(map(str, harness.frame["date"].unique())), extras=tuple(extras),
479 overlay_fn=overlay_fn, candidate_metadata=candidate_metadata, frame_returns=frame_returns,
480 equity_tickers=equity_tickers)
481 phase_list = phases_for(cadence, phases or self.args.max_phases)
482 per_phase = map_tasks([(phase, None) for phase in phase_list], self.args.workers)
483 summary = extended_summary(per_phase)
484 if "returns" in extras:
485 summary["returns_by_phase"] = [row["returns"] for row in per_phase]
486 summary["locked_dates_lists"] = [row["locked_dates"] for row in per_phase]
487 if stability and name == "backtest":
488 picked = phase_list[:: max(1, len(phase_list) // STABILITY_PHASES)][:STABILITY_PHASES]
489 locked = {phase: row["locked_dates"] for phase, row in zip(phase_list, per_phase, strict=False)}
490 tasks = [(phase, seed) for phase in picked for seed in NOISE_SEEDS]
491 perturbed = map_tasks(tasks, self.args.workers)
492 overlaps = [jaccard(locked[phase], row["locked_dates"]) for (phase, _seed), row in zip(tasks, perturbed, strict=False)]
493 summary["stability_jaccard_median"] = statistics.median(overlaps)
494 out[name] = summary
495 self.memo[key] = out
496 self.save()
497 return out
499 def overlay_fn(self, harness, overlay: dict):
500 """rank_overlay_fn(date, ranks) running portfolio.direction_overlay with a calibrated head probability per row."""
501 from portfolio.direction_overlay import apply_direction_overlay, resolve_direction_overlay
503 params = resolve_direction_overlay({"enabled": True, **{k: v for k, v in overlay.items() if k not in ("probabilities",)}})
504 probabilities = overlay["probabilities"]
505 groups = harness.rank_groups
507 def apply(date, ranks):
508 return apply_direction_overlay(ranks, {t: probabilities.get((date, t)) for t in ranks}, params, groups)
510 return apply
513# ---------------------------------------------------------------- stages
516def stage_dedupe(ctx: Research) -> dict:
517 base = ctx.score(ctx.adopted["config"], specs=DEDUPE_SPECS, mode="as_live", memo_tag="dedupe")
518 variant = ctx.score({**ctx.adopted["config"], **DEDUPE_VARIANT}, specs=DEDUPE_SPECS, mode="as_live", memo_tag="dedupe")
519 verdict = verdict_as_live(base, variant)
520 ctx.log_holdout_read("dedupe", "backtest+holdout pooled span, as-live, base and 'once'")
521 if verdict["passes"]:
522 ctx.adopted["config"].update(DEDUPE_VARIANT)
523 return {"base": base, "variant": variant, "verdict": verdict, "adopted": verdict["passes"]}
526def main_group_frame(harness):
527 from evaluation.live_parity import main_group_tickers
529 frame = harness.lagged_frame
530 tickers = main_group_tickers(harness.rank_groups, frame["ticker"].unique())
531 if tickers is not None:
532 frame = frame[frame["ticker"].astype(str).isin(tickers)]
533 return frame[frame["target_rank_20d"].notna()] if "target_rank_20d" in frame.columns else frame
536def engaged_labels(ctx: Research, harness, config: dict) -> dict:
537 from evaluation.engaged_day_skill import gate_labels
539 cfg = config["phase_v2"].get("rolling_ic_gate", {}) or {}
540 gate_fn = harness.gate_for(harness.lagged_frame, ic_floor=cfg.get("min_rolling_mean_ic"),
541 late_bar_event_count=cfg.get("late_bar_event_count"))
542 return gate_labels(gate_fn, sorted(set(harness.lagged_frame["date"].astype(str).str[:10])))
545def stage_l1(ctx: Research) -> dict:
546 from evaluation.engaged_day_skill import engaged_vs_all, l1_verdict
548 skills, margins, summaries = {}, {}, {}
549 for split in (*SPLITS, "holdout"):
550 harness, _topology, config = ctx.harness(split)
551 merged = apply_dotted(config, ctx.adopted["config"])
552 labels = engaged_labels(ctx, harness, merged)
553 skills[split] = engaged_vs_all(main_group_frame(harness), labels)
554 summaries[split] = ctx.score(ctx.adopted["config"], specs={split: split}, mode="as_live", extras=("engaged",),
555 memo_tag="l1")[split]
556 margins[split] = l1_margins(skills[split], summaries[split])
557 ctx.log_holdout_read("l1", "holdout engaged-vs-all skill and gated Sharpe (report only)")
558 verdict = l1_verdict({s: margins[s] for s in SPLITS})
559 stage = {"skill": skills, "margins": margins, "verdict": verdict, "gate_protects_capital": verdict["gate_protects_capital"]}
560 ctx.report["l1_pass"] = verdict["gate_protects_capital"]
561 return stage
564def equity_engaged_ic(ctx: Research, split, config_changes: dict, patch: dict | None, probabilities: dict | None = None) -> float | None:
565 """Daily mean rank IC of the live rank score (or of `probabilities`, a legacy score) on the ENGAGED equity dates of a split."""
566 from evaluation.engaged_day_skill import engaged_vs_all
568 harness, _t, config = ctx.harness(split, patch=patch)
569 frame = main_group_frame(harness)
570 equity = {t for t, kind in harness.asset_class_by_ticker.items() if kind == "equity"}
571 frame = frame[frame["ticker"].astype(str).isin(equity)]
572 score_column = "live_rank_score"
573 if probabilities is not None:
574 frame = frame.copy()
575 keys = zip(frame["date"].astype(str).str[:10], frame["ticker"].astype(str), strict=False)
576 frame["legacy_score"] = [probabilities.get(key) for key in keys]
577 score_column = "legacy_score"
578 labels = engaged_labels(ctx, harness, apply_dotted(config, config_changes))
579 return (engaged_vs_all(frame, labels, score_column=score_column).get("engaged") or {}).get("daily_mean_ic")
582def stage_l8(ctx: Research) -> dict:
583 import pandas as pd
584 from build_legacy_probability import legacy_probability_from_components
586 components = pd.read_csv(ctx.args.legacy_components)
587 components["date"] = components["date"].astype(str).str[:10]
588 config = ctx.base_config
589 metrics_path = ROOT_DIR / "ml" / "expert_training_metrics.json"
590 expert_metrics = json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else {}
591 keys = list(zip(components["date"], components["ticker"].astype(str), strict=False))
592 rows = components.to_dict("records")
594 def probabilities(excluded=()):
595 return {key: legacy_probability_from_components(row, expert_metrics, config, tuple(excluded)) for key, row in zip(keys, rows, strict=False)}
597 full = probabilities()
598 contributions: dict = {expert: {} for expert in EXPERTS}
599 ablated = {expert: probabilities((expert,)) for expert in EXPERTS}
600 for split in SPLITS:
601 ic_full = equity_engaged_ic(ctx, split, ctx.adopted["config"], None, full)
602 for expert in EXPERTS:
603 without = equity_engaged_ic(ctx, split, ctx.adopted["config"], None, ablated[expert])
604 contributions[expert][split] = None if ic_full is None or without is None else ic_full - without
605 base = ctx.score(ctx.adopted["config"], mode="as_live", memo_tag="l8")
606 scores = {}
607 for expert in EXPERTS:
608 scores[expert] = ctx.score(ctx.adopted["config"], mode="as_live", legacy_probabilities=ablated[expert], memo_tag=f"l8-{expert}")
609 useless = sorted(e for e, by in contributions.items() if all(by.get(s) is not None and by[s] <= 0.0 for s in SPLITS))
610 combined_verdict = None
611 if useless:
612 combined = probabilities(useless)
613 combined_scores = ctx.score(ctx.adopted["config"], mode="as_live", legacy_probabilities=combined, memo_tag="l8-" + "+".join(useless))
614 combined_verdict = verdict_as_live(base, combined_scores)
615 decision = l8_decision(contributions, combined_verdict)
616 if decision["disable"]:
617 ctx.adopted["config"]["gating_network.disabled_experts"] = decision["disable"]
618 ctx.adopted["legacy_experts_disabled"] = decision["disable"]
619 return {"contributions": contributions, "ablated_scores": scores, "base": base, "combined_verdict": combined_verdict,
620 "decision": decision}
623def calibration_for_head(frame, head_column: str):
624 """Fit on the validation frame, return the report and the chosen map {"method", ...}."""
625 from evaluation.probability_calibration import calibration_report
627 report = calibration_report(frame[head_column].to_numpy(), frame["target_direction_20d"].to_numpy())
628 cross = report["cross_fitted_log_loss"]
629 methods = {m: v for m, v in cross.items() if v is not None and m != "raw"}
630 if not methods:
631 return report, None
632 method = min(methods, key=methods.get)
633 if method == "temperature" and report["temperature"]:
634 return report, {"method": "temperature", "temperature": report["temperature"]}
635 if method == "isotonic" and report["isotonic"]:
636 return report, {"method": "isotonic", **report["isotonic"]}
637 return report, None
640def stage_l2(ctx: Research) -> dict:
641 import numpy as np
643 from evaluation.live_parity import lag_predictions_for_tickers
644 from evaluation.model_predictions import predict_head
646 heads = {}
647 probabilities_by_head = {}
648 for kind, model_file, schema_file in (("multitask", "multitask_model.json", "multitask_feature_schema.json"),
649 ("sequence", "sequence_model.json", "sequence_feature_schema.json")):
650 export = json.loads((ROOT_DIR / "ml" / model_file).read_text(encoding="utf-8"))
651 schema = json.loads((ROOT_DIR / "ml" / schema_file).read_text(encoding="utf-8"))
652 window = int(ctx.base_config["phase_v2"].get("sequence_model", {}).get("window_size", 30))
653 per_split = {}
654 for split in SPLITS:
655 harness, _t, _c = ctx.harness(split)
656 frame = harness.lagged_frame
657 main = main_group_frame(harness)
658 values = predict_head(frame, export, schema["model_input_names"], "direction_20d", model_kind=kind,
659 sequence_feature_schema=schema if kind == "sequence" else None, configured_window_size=window)
660 scored = lag_predictions_for_tickers(frame.assign(head=values), prediction_column="head", tickers=harness.late_bar_tickers)
661 per_split[split] = (scored, scored[scored["ticker"].isin(set(main["ticker"]))])
662 validation_frame = per_split["validation"][1].dropna(subset=["head", "target_direction_20d"])
663 report, calibration = calibration_for_head(validation_frame, "head")
664 backtest_frame = per_split["backtest"][1].dropna(subset=["head", "target_direction_20d"])
665 from evaluation.probability_calibration import apply_isotonic, apply_temperature, balanced_accuracy, log_loss
667 raw_backtest = log_loss(backtest_frame["head"], backtest_frame["target_direction_20d"])
668 calibrated_backtest = None
669 if calibration:
670 mapped = (apply_temperature(backtest_frame["head"], calibration["temperature"]) if calibration["method"] == "temperature"
671 else np.clip(apply_isotonic(backtest_frame["head"], calibration), 1e-6, 1 - 1e-6))
672 calibrated_backtest = log_loss(mapped, backtest_frame["target_direction_20d"])
673 heads[kind] = {"validation": report, "calibration": calibration, "backtest_raw_log_loss": raw_backtest,
674 "backtest_calibrated_log_loss": calibrated_backtest,
675 "backtest_balanced_accuracy": balanced_accuracy(backtest_frame["head"], backtest_frame["target_direction_20d"])}
676 probabilities_by_head[kind] = per_split
677 chosen = min(heads, key=lambda k: heads[k]["validation"]["log_loss"] if heads[k]["validation"]["log_loss"] is not None else 9.9)
678 calibration = heads[chosen]["calibration"]
680 def probability_map(split_key):
681 from portfolio.direction_overlay import calibrate_probability
683 scored = probabilities_by_head[chosen][split_key][0]
684 return {(str(d)[:10], str(t)): calibrate_probability(p, calibration) for d, t, p in zip(scored["date"], scored["ticker"], scored["head"], strict=False)
685 if p == p}
687 base = ctx.score(ctx.adopted["config"], mode="as_live", memo_tag="l2")
688 merged_map = {**probability_map("validation"), **probability_map("backtest")}
689 stage = {"heads": heads, "chosen_head": chosen, "variants": {}}
690 for name, params in L2_VARIANTS.items():
691 # the overlay reads (date, ticker) -> calibrated probability; one map per split is merged (dates never overlap)
692 overlay = {**params, "calibration": None, "probabilities": merged_map}
693 result = ctx.score(ctx.adopted["config"], mode="as_live", overlay=overlay, memo_tag=f"l2-{name}-{chosen}")
694 verdict = verdict_as_live(base, result)
695 checks = l2_checks(base, result)
696 stage["variants"][name] = {"params": params, "scores": result, "verdict": verdict, "extra_checks": checks,
697 "passes": verdict["passes"] and all_pass(checks)}
698 winners = [n for n, v in stage["variants"].items() if v["passes"]]
699 stage["adopted"] = best_by_backtest(winners, {n: stage["variants"][n]["scores"] for n in winners})
700 if stage["adopted"]:
701 ctx.adopted["direction_overlay"] = {"head": chosen, "calibration": calibration, **L2_VARIANTS[stage["adopted"]]}
702 ctx.adopted["needs_live_path"].append("direction_overlay")
703 stage["base"] = base
704 return stage
707def stage_l3(ctx: Research) -> dict:
708 base = ctx.score(ctx.adopted["config"], mode="as_live", memo_tag="l3")
709 stage = {"base": base, "budgets": {}}
710 for name, changes in LEGACY_VARIANTS.items():
711 merged = {**ctx.adopted["config"], **changes}
712 result = ctx.score(merged, mode="as_live", memo_tag="l3")
713 verdict = verdict_as_live(base, result)
714 extra = l3_budget_checks(verdict, result, name)
715 stage["budgets"][name] = {"changes": changes, "scores": result, "verdict": verdict, "extra_checks": extra,
716 "passes": verdict["passes"] and all_pass(extra)}
717 winners = [n for n, v in stage["budgets"].items() if v["passes"]]
718 stage["budget_adopted"] = best_by_backtest(winners, {n: stage["budgets"][n]["scores"] for n in winners})
719 if stage["budget_adopted"]:
720 ctx.adopted["config"].update(LEGACY_VARIANTS[stage["budget_adopted"]])
721 stage["ic_by_class_and_regime"] = legacy_ic_report(ctx)
722 stage["model"] = model_stage(ctx, base)
723 return stage
726def legacy_ic_report(ctx: Research) -> dict:
727 """(c) IC of the legacy score against rank_20d's by asset class and by regime bucket, both splits."""
728 from as_live_levers import LEGACY_PROBABILITY_COLUMN
730 from evaluation.gate_audit import daily_rank_ic
732 out = {}
733 for split in SPLITS:
734 harness, _t, _c = ctx.harness(split)
735 frame = main_group_frame(harness)
736 frame = frame.assign(cls=[harness.asset_class_by_ticker.get(str(t), "other") for t in frame["ticker"]])
737 regime_columns = [c for c in frame.columns if c.startswith("regime_trend_")]
738 if regime_columns:
739 frame = frame.assign(regime=frame[regime_columns].idxmax(axis=1).str.replace("regime_trend_", "", regex=False))
740 rows = {}
741 for group_column in ("cls", "regime"):
742 if group_column not in frame.columns:
743 continue
744 for name, part in frame.groupby(group_column):
745 legacy = daily_rank_ic(part, score_column=LEGACY_PROBABILITY_COLUMN, target_column="target_rank_20d")
746 rank = daily_rank_ic(part, score_column="live_rank_score", target_column="target_rank_20d")
747 rows[f"{group_column}:{name}"] = {
748 "legacy_ic": statistics.fmean(legacy.values()) if legacy else None,
749 "rank_20d_ic": statistics.fmean(rank.values()) if rank else None, "dates": len(rank)}
750 out[split] = rows
751 return out
754def model_stage(ctx: Research, base: dict) -> dict:
755 """(b) the legacy-as-input candidate, scored against the installed models with the yardstick fixed at 0.034."""
756 candidates = ctx.args.candidates_spec or {}
757 name = "v640_leg"
758 if name not in candidates or not ctx.args.model_ic_data:
759 return {"skipped": "no candidate / model_ic supplied"}
760 model_ic = copy.deepcopy(ctx.args.model_ic_data)
761 model_ic["bootstrap"] = {key: {"yardstick": MODEL_YARDSTICK} for key in ("decision_rank_20d", "decision_rank_20d_swapped_priority")}
762 ic_checks = model10_checks(model_ic, name)
763 if not candidates[name].get("ml_dir"):
764 return {"ic_checks": ic_checks, "adopted": False, "reason": "the IC clauses failed, so no candidate directory was built"}
765 result = ctx.score(ctx.adopted["config"], mode="as_live", model=name, memo_tag="l3-model")
766 verdict = verdict_as_live(base, result)
767 checks = l3_model_checks(ic_checks, verdict, candidates[name].get("latency_ratio"))
768 stage = {"ic_checks": ic_checks, "scores": result, "verdict": verdict, "checks": checks, "adopted": all_pass(checks)}
769 if stage["adopted"]:
770 ctx.adopted["model"] = name
771 ctx.adopted["needs_live_path"].append("legacy_input")
772 return stage
775def stage_l4(ctx: Research) -> dict:
776 base = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", extras=("equity",), memo_tag="l4")
777 stage = {"base": base, "variants": {}}
778 for name, variant in L4_VARIANTS.items():
779 changes = {**ctx.adopted["config"], **variant["changes"]}
780 patch = {**ctx.adopted["patch"], **variant["patch"]}
781 result = ctx.score(changes, patch=patch, mode="as_live", extras=("equity",), memo_tag="l4")
782 verdict = verdict_as_live(base, result)
783 ic = {s: {"base": equity_engaged_ic(ctx, s, ctx.adopted["config"], ctx.adopted["patch"]),
784 "variant": equity_engaged_ic(ctx, s, changes, patch)} for s in SPLITS}
785 stage["variants"][name] = {"changes": variant["changes"], "patch": variant["patch"], "scores": result, "verdict": verdict,
786 "engaged_equity_ic": ic}
787 # the holdout veto is read once, for the leading candidate only
788 screened = [n for n, v in stage["variants"].items()
789 if v["verdict"]["backtest_gain"] >= L4_NON_INFERIOR and v["verdict"]["validation_change"] >= L4_NON_INFERIOR]
790 leader = best_by_backtest(screened, {n: stage["variants"][n]["scores"] for n in screened})
791 holdout_loss = None
792 if leader:
793 variant = L4_VARIANTS[leader]
794 base_hold = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], specs={"holdout": "holdout"}, mode="as_live", memo_tag="l4h")
795 var_hold = ctx.score({**ctx.adopted["config"], **variant["changes"]}, patch={**ctx.adopted["patch"], **variant["patch"]},
796 specs={"holdout": "holdout"}, mode="as_live", memo_tag="l4h")
797 holdout_loss = base_hold["holdout"]["median_net_sharpe"] - var_hold["holdout"]["median_net_sharpe"]
798 ctx.log_holdout_read("l4", f"holdout as-live Sharpe of {leader} against the base (veto clause)")
799 for name, entry in stage["variants"].items():
800 entry["extra_checks"] = l4_checks(base, entry["scores"], entry["verdict"], entry["engaged_equity_ic"],
801 holdout_loss if name == leader else None)
802 entry["passes"] = all_pass(entry["extra_checks"])
803 winners = [n for n, v in stage["variants"].items() if v["passes"]]
804 stage["adopted"] = best_by_backtest(winners, {n: stage["variants"][n]["scores"] for n in winners})
805 stage["holdout_loss_of_leader"] = {"variant": leader, "loss": holdout_loss}
806 if stage["adopted"]:
807 chosen = L4_VARIANTS[stage["adopted"]]
808 ctx.adopted["config"].update(chosen["changes"])
809 ctx.adopted["patch"].update(chosen["patch"])
810 return stage
813def stage_l5(ctx: Research) -> dict:
814 base = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", memo_tag="l5")
815 stage = {"base": base, "variants": {}}
816 for name, changes in L5_VARIANTS.items():
817 result = ctx.score({**ctx.adopted["config"], **changes}, patch=ctx.adopted["patch"], mode="as_live", memo_tag="l5")
818 verdict = verdict_as_live(base, result)
819 checks = l5_checks(base, result)
820 stage["variants"][name] = {"changes": changes, "scores": result, "verdict": verdict, "extra_checks": checks,
821 "passes": verdict["passes"] and all_pass(checks)}
822 winners = [n for n, v in stage["variants"].items() if v["passes"]]
823 stage["adopted"] = best_by_backtest(winners, {n: stage["variants"][n]["scores"] for n in winners})
824 if stage["adopted"]:
825 ctx.adopted["config"].update(L5_VARIANTS[stage["adopted"]])
826 return stage
829def blocked_by_l1(ctx: Research, lead: str) -> dict | None:
830 """L6 / L7 ship only if L1 showed the gate protects capital (the owner: structure rules only if L1 shows enough conditional
831 edge). When it did not, no variant can ship, so scoring them (hours of Codespace time) cannot change the decision: the lead
832 closes by its precondition unless `--score-blocked-stages` asks for the report anyway."""
833 if bool(ctx.report.get("l1_pass", False)) or getattr(getattr(ctx, "args", None), "score_blocked", False):
834 return None
835 return {"skipped": f"{lead} closed by its precondition: L1 found the gate hides weakness (engaged-day IC margin "
836 f"{((ctx.report.get('l1') or {}).get('margins') or {}).get('backtest', {}).get('ic_margin')}), so no variant can ship",
837 "l1_precondition": False, "adopted": None}
840def stage_l6(ctx: Research) -> dict:
841 closed = blocked_by_l1(ctx, "L6")
842 if closed is not None:
843 return closed
844 l1_pass = bool(ctx.report.get("l1_pass", False))
845 base = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="ungated", memo_tag="l6")
846 stage = {"base": base, "l1_precondition": l1_pass, "variants": {}}
847 for name, variant in L6_VARIANTS.items():
848 changes = {**ctx.adopted["config"], "portfolio_book.tranche_adjust_fraction": variant["adjust"]}
849 result = ctx.score(changes, patch=ctx.adopted["patch"], tranches=variant["tranches"], mode="ungated", memo_tag="l6")
850 as_live = ctx.score(changes, patch=ctx.adopted["patch"], tranches=variant["tranches"], mode="as_live", memo_tag="l6")
851 checks = l6_checks(base, result, l1_pass)
852 stage["variants"][name] = {"params": variant, "scores": result, "as_live_scores": as_live, "extra_checks": checks,
853 "passes": all_pass(checks)}
854 winners = [n for n, v in stage["variants"].items() if v["passes"]]
855 stage["adopted"] = best_by_backtest(winners, {n: stage["variants"][n]["scores"] for n in winners})
856 if stage["adopted"]:
857 ctx.adopted["tranches"] = L6_VARIANTS[stage["adopted"]]["tranches"]
858 ctx.adopted["adjust_fraction"] = L6_VARIANTS[stage["adopted"]]["adjust"]
859 ctx.adopted["needs_live_path"].append("tranches")
860 return stage
863def false_lock_summary(summary: dict, unlocked: dict) -> dict:
864 """Attach per-phase false-lock shares to a score (needs `returns`-extras and the unlocked book's returns by split/phase)."""
865 from evaluation.kill_switch_replay import false_lock_share, forward_window_returns
867 for split, entry in summary.items():
868 shares = []
869 for locked, returns in zip(entry["locked_dates_lists"], unlocked[split], strict=False):
870 share = false_lock_share(locked, forward_window_returns(returns))
871 if share is not None:
872 shares.append(share)
873 entry["false_lock_share_by_phase"] = shares
874 if shares:
875 entry["false_lock_share_median"] = statistics.median(shares)
876 return summary
879def stage_l7(ctx: Research) -> dict:
880 closed = blocked_by_l1(ctx, "L7")
881 if closed is not None:
882 return closed
883 l1_pass = bool(ctx.report.get("l1_pass", False))
884 off = {**ctx.adopted["config"], "risk.kill_switch.enabled": False}
885 unlocked_scores = ctx.score(off, patch=ctx.adopted["patch"], mode="as_live", extras=("returns",), memo_tag="l7-unlocked")
886 unlocked = {split: entry["returns_by_phase"] for split, entry in unlocked_scores.items()}
887 base = false_lock_summary(ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", extras=("returns",),
888 stability=True, memo_tag="l7"), unlocked)
889 stage = {"base": {s: {k: v for k, v in e.items() if k not in ("returns_by_phase", "locked_dates_lists")} for s, e in base.items()},
890 "l1_precondition": l1_pass, "variants": {}}
891 base_stability = base["backtest"]["stability_jaccard_median"]
892 for name, changes in L7_VARIANTS.items():
893 result = false_lock_summary(
894 ctx.score({**ctx.adopted["config"], **changes}, patch=ctx.adopted["patch"], mode="as_live", extras=("returns",),
895 stability=True, memo_tag="l7"), unlocked)
896 stability = result["backtest"]["stability_jaccard_median"]
897 checks = l7_checks(base, result, base_stability, stability, l1_pass)
898 stage["variants"][name] = {"changes": changes, "stability": stability, "extra_checks": checks, "passes": all_pass(checks),
899 "scores": {s: {k: v for k, v in e.items() if k not in ("returns_by_phase", "locked_dates_lists")}
900 for s, e in result.items()}}
901 winners = [n for n, v in stage["variants"].items() if v["passes"]]
902 chosen = min(winners, key=lambda n: statistics.median(
903 [stage["variants"][n]["scores"][s]["false_lock_share_median"] for s in SPLITS])) if winners else None
904 stage["adopted"] = chosen
905 if chosen:
906 ctx.adopted["config"].update(L7_VARIANTS[chosen])
907 stage["base_stability"] = base_stability
908 return stage
911def stage_l9(ctx: Research) -> dict:
912 from evaluation.trade_bootstrap import bootstrap_mean_pnl, leave_one_name_out, pnl_by_name, repeatable, round_trips_from_closed_trades, top_k_share
914 harness, _t, _c = ctx.harness("backtest", patch=ctx.adopted["patch"])
915 core = {"BTCUSD", "LTCUSD"}
916 crypto = sorted(t for t, kind in harness.asset_class_by_ticker.items() if kind == "crypto")
917 eligible = {t for t in crypto if harness.metadata[t]["trading_eligible"]}
918 graduates = sorted(eligible - core)
919 stage: dict = {"graduates": graduates}
920 # (1) the Lean run's own crypto round trips
921 if ctx.args.lean_run:
922 from evaluation.backtest_audit import load_backtest_run
924 run = load_backtest_run(ROOT_DIR / ctx.args.lean_run)
925 groups = {"core": round_trips_from_closed_trades(run, core), "graduates": round_trips_from_closed_trades(run, set(graduates))}
926 stage["lean_trades"] = {
927 name: {"bootstrap": bootstrap_mean_pnl([t["pnl"] for t in trades]), "top1_share": top_k_share([t["pnl"] for t in trades], 1),
928 "top3_share": top_k_share([t["pnl"] for t in trades], 3), "pnl_by_name": pnl_by_name(trades),
929 "leave_one_name_out": leave_one_name_out(pnl_by_name(trades)), "n": len(trades)}
930 for name, trades in groups.items()
931 }
932 core_stats = stage["lean_trades"]["core"]
933 stage["core_repeatable"] = repeatable(core_stats["bootstrap"], core_stats["leave_one_name_out"])
934 # (2) graduates on vs off, as-live
935 on = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", memo_tag="l9")
936 off = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", eligible_override=core & eligible, memo_tag="l9-g0")
937 stage.update(graduates_on=on, graduates_off=off, decision=l9_decision(on, off))
938 # (3) leave-one-name-out over the crypto names, as-live (reduced phases)
939 stage["leave_one_out"] = {}
940 for ticker in sorted(eligible):
941 result = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", eligible_override=eligible - {ticker},
942 phases=LOO_PHASES, memo_tag=f"l9-loo-{ticker}")
943 stage["leave_one_out"][ticker] = {s: result[s]["median_net_sharpe"] for s in SPLITS}
944 if not stage["decision"]["keep_graduates"]:
945 ctx.adopted["graduates_off"] = True
946 ctx.adopted["config"]["class_weight_caps.crypto.core_only"] = True # live and offline: only the core names are candidates
947 return stage
950def stage_l10(ctx: Research) -> dict:
951 base = ctx.score(ctx.adopted["config"], patch=ctx.adopted["patch"], mode="as_live", memo_tag="l10")
952 stage = {"base": base, "variants": {}}
953 for name, heads in L10_VARIANTS.items():
954 patch = {**ctx.adopted["patch"], "phase_v2.rank_signal.heads": heads, "phase_v2.rank_signal.demoted": [],
955 "phase_v2.rank_signal.demote_not_promotable_heads": False}
956 result = ctx.score(ctx.adopted["config"], patch=patch, mode="as_live", memo_tag="l10")
957 verdict = verdict_as_live(base, result)
958 shift = factor_shift(ctx, patch)
959 checks = l10_checks(verdict, shift)
960 stage["variants"][name] = {"heads": heads, "scores": result, "verdict": verdict, "factor_shift": shift, "extra_checks": checks,
961 "passes": all_pass(checks)}
962 winners = [n for n, v in stage["variants"].items() if v["passes"]]
963 stage["adopted"] = best_by_backtest(winners, {n: stage["variants"][n]["scores"] for n in winners})
964 if stage["adopted"]:
965 ctx.adopted["patch"]["phase_v2.rank_signal.heads"] = L10_VARIANTS[stage["adopted"]]
966 ctx.adopted["patch"]["phase_v2.rank_signal.demoted"] = []
967 ctx.adopted["patch"]["phase_v2.rank_signal.demote_not_promotable_heads"] = False
968 return stage
971def factor_shift(ctx: Research, patch: dict) -> dict:
972 """Change in the book's market and momentum loadings (`compute_book_factor_exposure`: the daily net returns of one
973 as-live run, phase 0, regressed on SPY and a 20-day momentum factor) when the head blend changes."""
974 from lean_calibration import calibrated_overrides
976 from evaluation.benchmark_comparison import close_pivot_from_frame
977 from evaluation.factor_neutralization_check import compute_book_factor_exposure
979 loadings = {}
980 for label, patched in (("base", ctx.adopted["patch"]), ("variant", patch)):
981 harness, _topology, config = ctx.harness("backtest", patch=patched)
982 merged = apply_dotted(config, ctx.adopted["config"])
983 result = harness.as_live(config_overrides=ctx.adopted["config"] or None,
984 **{**calibrated_overrides(harness, phase=0), **harness.v610_mechanisms(merged)})
985 report = compute_book_factor_exposure(result.per_date, result.per_date_net_return, close_pivot_from_frame(harness.frame))
986 loadings[label] = (report.get("loadings") or {}) if report.get("status") == "OK" else {}
987 return {name: loadings["variant"].get(name, 0.0) - loadings["base"].get(name, 0.0) for name in ("market", "momentum")}
990STAGES = {
991 "dedupe": stage_dedupe, "l1": stage_l1, "l8": stage_l8, "l2": stage_l2, "l3": stage_l3, "l4": stage_l4, "l5": stage_l5,
992 "l6": stage_l6, "l7": stage_l7, "l9": stage_l9, "l10": stage_l10,
993}
996def apply_smoke() -> None:
997 """--smoke: one variant per stage and two phases, so every code path runs end to end in minutes before the real chain."""
998 for table in (L2_VARIANTS, LEGACY_VARIANTS, L4_VARIANTS, L5_VARIANTS, L6_VARIANTS, L7_VARIANTS, L10_VARIANTS):
999 for name in list(table)[1:]:
1000 del table[name]
1001 global LOO_PHASES
1002 LOO_PHASES = 2
1005def main() -> int:
1006 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1007 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
1008 parser.add_argument("--legacy-probability", required=True)
1009 parser.add_argument("--legacy-components", default=str(ROOT_DIR / "ml" / "datasets" / "legacy_components.csv"))
1010 parser.add_argument("--candidates", default=None)
1011 parser.add_argument("--model-ic", default=None)
1012 parser.add_argument("--lean-run", default=None, help="the Lean run whose closed trades L9 bootstraps (relative to the repo)")
1013 parser.add_argument("--stages", nargs="*", default=list(STAGES))
1014 parser.add_argument("--max-phases", type=int, default=10)
1015 parser.add_argument("--workers", type=int, default=1)
1016 parser.add_argument("--gate-warmup-days", type=int, default=400)
1017 parser.add_argument("--score-blocked-stages", dest="score_blocked", action="store_true",
1018 help="score L6 / L7 even when L1 failed (they cannot ship then; a report only)")
1019 parser.add_argument("--smoke", action="store_true", help="one variant per stage, 2 phases, 1 crypto leave-one-out: a code-path check")
1020 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v640" / "research.json"))
1021 parser.add_argument("--adopted-config-out", default=str(ROOT_DIR / "ml" / "evaluation" / "v640" / "adopted_changes.json"))
1022 args = parser.parse_args()
1023 if args.smoke:
1024 apply_smoke()
1025 args.max_phases = min(args.max_phases, 2)
1026 args.candidates_spec = json.loads(Path(args.candidates).read_text(encoding="utf-8")) if args.candidates and Path(args.candidates).exists() else {}
1027 args.model_ic_data = json.loads(Path(args.model_ic).read_text(encoding="utf-8")) if args.model_ic and Path(args.model_ic).exists() else None
1029 base_config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
1030 out_path = Path(args.out)
1031 report = json.loads(out_path.read_text(encoding="utf-8")) if out_path.exists() else {}
1032 report.update({"max_phases": args.max_phases, "sweep_in_rule_scores": False})
1033 ctx = Research(args, base_config, report, out_path)
1034 for name in args.stages:
1035 print(f"=== stage {name}", flush=True)
1036 stage = STAGES[name](ctx)
1037 report[name] = stage
1038 ctx.save()
1039 print(f" {name}: adopted={stage.get('adopted', stage.get('budget_adopted', stage.get('decision')))}", flush=True)
1040 Path(args.adopted_config_out).parent.mkdir(parents=True, exist_ok=True)
1041 Path(args.adopted_config_out).write_text(json.dumps(ctx.adopted, indent=1), encoding="utf-8")
1042 print("adopted:", json.dumps(ctx.adopted))
1043 print(f"written {out_path}")
1044 return 0
1047if __name__ == "__main__":
1048 raise SystemExit(main())