Coverage for scripts/lean_calibration.py: 100%
270 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"""Is the offline as-live simulator a model of what Lean does? Rule R-CAL (V6.0.0, todo lead 2).
3For each calibration window (a finished Lean run, optionally a sub-period) this compares the Lean main book - the main
4book plus its crypto members, rebuilt day by day from the order events by `evaluation.lean_attribution` - with the
5offline simulator run over the same dates, as a ladder of increasingly live-like variants:
7 v580 the V5.8.0 as-live simulator (cadence counted on every date with enough rows)
8 (V6.1.0, --rcal2) v610_member_pass + live's daily member pass between rebalances
9 v610_mechanisms + weekend accrual, the position cap, the live analyzer's verdicts
10 v610 + the legacy signal (--legacy-probability) and the sleeves' P&L in the kill switch:
11 R-CAL2's calibrated variant (the harness's rolling-IC gate is warm with --gate-warmup-days)
12 v610_replay / v610_ungated diagnostics as below
13 phase + live's cadence: equity sessions only (no step on an equity holiday), on live's phase
14 next_open + an order decided at the close earns from the next open, not the next close
15 min_fee + the broker's per-order dollar floor at the live NAV
16 live_gates + live's resize threshold, entry cooldown and trailing stop
17 calibrated + the learned-topology sizing multiplier (mid peer bracket, scripts/topology_sizing_research.py)
18 replay the calibrated simulator with live's own gate decisions replayed (diagnostic only)
20and reports, per variant: the daily P&L correlation, the annualised return gap, and the share of live rebalance dates
21on which the offline book took the same decision (engaged / vetoed / kill-switch locked).
23R-CAL (pre-registered, plan V6.0.0): calibrated iff on EVERY window the calibrated variant has daily correlation >= 0.50,
24|annualised return gap| <= 2.0 percentage points and decision agreement >= 80%. Branch A (calibrated) lets R-GATE and
25R-BOOK use the as-live simulator; branch B freezes the gates and judges alpha on the ungated book.
27 python scripts/lean_calibration.py --dataset ml/datasets/full_dataset.csv \
28 --window bt1=backtests/2026-10-13_17-54-47@2023-07-01..2025-06-30:backtest \
29 --window bt2_backtest=backtests/2026-10-14_07-27-32@2023-07-01..2025-06-30:backtest+holdout \
30 --window bt2_holdout=backtests/2026-10-14_07-27-32@2025-07-01..2026-09-30:backtest+holdout
31 python scripts/lean_calibration.py --predict --dataset ... --window bt=@2023-07-01..2026-09-30:backtest+holdout
32 (no Lean run yet: writes the calibrated simulator's prediction for the window, R-CAL's out-of-sample check; since
33 V6.1.0 it also runs the `v610` rung, with --legacy-probability and --gate-warmup-days as for --rcal2)
34"""
36from __future__ import annotations
38import argparse
39import bisect
40import json
41import sys
42from pathlib import Path
44import numpy as np
46ROOT_DIR = Path(__file__).resolve().parents[1]
47sys.path.insert(0, str(ROOT_DIR))
48sys.path.insert(0, str(ROOT_DIR / "scripts"))
50BOOK_COMPONENTS = ("main_book", "crypto_core", "crypto_graduate")
51# V6.1.0 R-CAL2: the legacy signal is modelled too, so it joins the comparison.
52RCAL2_COMPONENTS = ("main_book", "crypto_core", "crypto_graduate", "legacy", "legacy_crypto")
53# offline component -> the Lean attribution components it models
54COMPONENT_GROUPS = {"main_book": BOOK_COMPONENTS, "legacy": ("legacy", "legacy_crypto")}
55# P&L the simulation does not model but live's whole-portfolio kill switch reads
56UNMODELLED_COMPONENTS = ("bond_sleeve", "forex_sleeve")
57RCAL2_VARIANT = "v610"
58# R-CAL2 windows (plan V6.1.0): the V6 BT2 stretches and the V5.8.0 BT2 backtest stretch (a different config).
59RCAL2_WINDOWS = (
60 "v6bt2_backtest=backtests/2026-10-15_17-29-50@2023-07-01..2025-06-30:backtest+holdout",
61 "v6bt2_holdout=backtests/2026-10-15_17-29-50@2025-07-01..2026-09-30:backtest+holdout",
62 "v580bt2_backtest=backtests/2026-10-14_07-27-32@2023-07-01..2025-06-30:backtest+holdout",
63)
64# R-CAL3 windows (plan V6.3.0): V6.2.0's BT2 (the shipped config, T-bill sweep on; the sweep is outside the compared book).
65RCAL3_WINDOWS = (
66 "v62bt2_backtest=backtests/2026-10-17_21-39-55@2023-07-01..2025-06-30:backtest+holdout",
67 "v62bt2_holdout=backtests/2026-10-17_21-39-55@2025-07-01..2026-09-30:backtest+holdout",
68)
69MIN_CORRELATION = 0.50
70MAX_ANNUAL_GAP = 0.02
71MIN_DECISION_AGREEMENT = 0.80
72CALIBRATED_VARIANT = "calibrated"
75def parse_window(text: str) -> dict:
76 """`name=<run dir>@START..END:split[+split]`; an empty run dir means "no Lean run" (prediction only)."""
77 name, _, rest = text.partition("=")
78 run_dir, _, rest = rest.partition("@")
79 period, _, splits = rest.partition(":")
80 start, _, end = period.partition("..")
81 if not (name and start and end and splits):
82 raise ValueError(f"bad --window {text!r}")
83 return {"name": name, "run_dir": run_dir or None, "start": start, "end": end, "splits": tuple(splits.split("+"))}
86def lean_book_returns(daily_components: dict, daily_equity: list, components: tuple[str, ...] = BOOK_COMPONENTS) -> dict[str, float]:
87 """{date: net P&L of `components` / previous NAV} (default: the main book and its crypto members)."""
88 nav_dates = [date for date, _ in daily_equity]
89 navs = [value for _, value in daily_equity]
90 out = {}
91 for date, day in daily_components.items():
92 position = bisect.bisect_left(nav_dates, date) - 1
93 nav = navs[position] if position >= 0 else (navs[0] if navs else 0.0)
94 if nav > 0:
95 out[date] = sum(day.get(name, 0.0) for name in components) / nav
96 return out
99def bucket_to_offline_dates(lean_returns: dict[str, float], offline_dates: list[str]) -> dict[str, float]:
100 """Offline return on date D covers (D, next offline date]; Lean's calendar-day P&L is summed into those buckets."""
101 out = dict.fromkeys(offline_dates, 0.0)
102 for date, value in lean_returns.items():
103 position = bisect.bisect_left(offline_dates, date) - 1
104 if 0 <= position < len(offline_dates):
105 out[offline_dates[position]] += value
106 return out
109def live_decisions(book_history: list[dict], start: str, end: str) -> dict[str, str]:
110 """{date: engaged | vetoed | locked} for live's rebalance attempts in the window (warm-up records excluded)."""
111 out = {}
112 for record in book_history:
113 date = record.get("date", "")
114 if not (start <= date <= end) or record.get("gate_veto_reason") == "thin_universe_or_zero_top_n":
115 continue
116 decisions = record.get("book_member_decisions") or {}
117 # a vetoed record also lists the HELD members, reduced by the kill switch: locked needs a formed book
118 locked = bool(record.get("allocations")) and bool(decisions) and all(
119 decision.get("action") == "reduce_risk" and any("kill_switch" in reason for reason in decision.get("reasons", []))
120 for decision in decisions.values()
121 )
122 out[date] = "locked" if locked else ("engaged" if record.get("allocations") else "vetoed")
123 return out
126def offline_decisions(rebalance_log: list[dict]) -> dict[str, str]:
127 return {
128 entry["date"]: "locked" if entry.get("locked") and entry.get("engaged") else ("engaged" if entry["engaged"] else "vetoed")
129 for entry in rebalance_log
130 }
133def disagreement_table(live: dict[str, str], rebalance_log: list[dict]) -> dict:
134 """Where live and offline disagree, and why offline decided as it did: {"live_state->offline_state (reason)": n}, plus
135 `missing_offline` (live rebalanced, the simulator did not reach a rebalance that day) as its own count."""
136 offline = {entry["date"]: entry for entry in rebalance_log}
137 states = offline_decisions(rebalance_log)
138 table: dict[str, int] = {}
139 missing: list[str] = []
140 for date, state in sorted(live.items()):
141 if date not in offline:
142 missing.append(date)
143 continue
144 offline_state = states[date]
145 if offline_state == state:
146 continue
147 key = f"{state}->{offline_state} ({offline[date].get('reason') or 'none'})"
148 table[key] = table.get(key, 0) + 1
149 return {"disagreements": dict(sorted(table.items(), key=lambda item: -item[1])), "missing_offline": len(missing),
150 "missing_offline_dates": missing[:20]}
153def decision_agreement(live: dict[str, str], offline: dict[str, str], *, binary: bool = True) -> float | None:
154 """Share of live rebalance dates with the same offline decision. R-CAL's clause is binary - the book traded
155 (engaged) or did not (vetoed / locked); `binary=False` compares the three states. A date the offline book did not
156 rebalance on counts as a disagreement (`disagreement_table` reports how many those are)."""
157 if not live:
158 return None
159 if binary:
160 traded = lambda state: state == "engaged" # noqa: E731
161 return sum(1 for date, state in live.items() if date in offline and traded(offline[date]) == traded(state)) / len(live)
162 return sum(1 for date, state in live.items() if offline.get(date) == state) / len(live)
165def rebalance_phase(first_live_date: str | None, offline_dates: list[str], rebalance_every_bars: int) -> int:
166 """Counter start that puts the offline cadence on live's first in-window rebalance date."""
167 if not first_live_date or first_live_date not in offline_dates:
168 return 0
169 steps = offline_dates.index(first_live_date)
170 return (-steps) % max(1, rebalance_every_bars)
173def compare(lean: dict[str, float], offline_dates: list[str], offline_returns: list[float]) -> dict:
174 offline = dict(zip(offline_dates, offline_returns, strict=False))
175 common = [date for date in offline_dates if date in lean]
176 a = np.array([offline[date] for date in common])
177 b = np.array([lean[date] for date in common])
178 correlation = float(np.corrcoef(a, b)[0, 1]) if len(common) > 2 and a.std() > 0 and b.std() > 0 else None
179 years = len(common) / 252.0 if common else 0.0
180 return {
181 "days": len(common),
182 "daily_correlation": correlation,
183 "offline_annual_return": float(a.sum() / years) if years else None,
184 "lean_annual_return": float(b.sum() / years) if years else None,
185 "annual_return_gap": float((a.sum() - b.sum()) / years) if years else None,
186 "offline_sharpe": float(a.mean() / a.std() * np.sqrt(252)) if len(a) > 2 and a.std() > 0 else None,
187 "lean_sharpe": float(b.mean() / b.std() * np.sqrt(252)) if len(b) > 2 and b.std() > 0 else None,
188 }
191def live_book_weights(run: dict, history: list[dict], config: dict) -> dict[str, dict[str, float]]:
192 """{date: {ticker: end-of-day weight}} of live's book members (main pool incl. crypto), position x close / NAV."""
193 from evaluation.backtest_audit import daily_equity_from_chart
194 from evaluation.lean_attribution import (
195 closes_for_universe,
196 daily_ticker_pnl,
197 fills_from_order_events,
198 formed_book_by_date,
199 )
201 class_by_ticker = {
202 str(asset["ticker"]).upper(): str(asset.get("asset_class") or asset.get("security_type"))
203 for asset in config["phase1"]["universe"]["assets"]
204 }
205 fills = fills_from_order_events(run["order_events"])
206 daily_equity = daily_equity_from_chart(run["result"])
207 closes = closes_for_universe(config, ROOT_DIR, {fill.ticker for fill in fills})
208 pnl = daily_ticker_pnl(fills, closes, [date for date, _ in daily_equity])
209 members = formed_book_by_date(history, sorted(pnl))
210 nav_by_date = dict(daily_equity)
211 out = {}
212 last_nav = daily_equity[0][1] if daily_equity else 1.0
213 for date in sorted(pnl):
214 last_nav = nav_by_date.get(date, last_nav)
215 weights = {}
216 for ticker, entry in pnl[date].items():
217 if entry["position"] and ticker in members.get(date, frozenset()) and class_by_ticker.get(ticker) in ("equity", "crypto"):
218 close = closes.get(ticker, {}).get(date)
219 if close:
220 weights[ticker] = entry["position"] * close / last_nav
221 out[date] = weights
222 return out
225def compare_weights(live: dict[str, dict[str, float]], offline_dates: list[str], offline_weights: list[dict]) -> dict:
226 """Offline weights decided on D are held from the next session: compared with live's end-of-day weights there."""
227 l1, overlap, live_gross, offline_gross = [], [], [], []
228 for index, _date in enumerate(offline_dates[:-1]):
229 held_on = offline_dates[index + 1]
230 if held_on not in live:
231 continue
232 a, b = offline_weights[index], live[held_on]
233 names = set(a) | set(b)
234 l1.append(sum(abs(a.get(name, 0.0) - b.get(name, 0.0)) for name in names))
235 if names:
236 overlap.append(len(set(a) & set(b)) / len(names))
237 live_gross.append(sum(abs(value) for value in b.values()))
238 offline_gross.append(sum(abs(value) for value in a.values()))
239 mean = lambda values: float(np.mean(values)) if values else None # noqa: E731
240 return {"weight_l1": mean(l1), "name_overlap": mean(overlap), "live_gross": mean(live_gross), "offline_gross": mean(offline_gross)}
243def window_passes(row: dict) -> bool:
244 return (
245 row.get("daily_correlation") is not None and row["daily_correlation"] >= MIN_CORRELATION
246 and row.get("annual_return_gap") is not None and abs(row["annual_return_gap"]) <= MAX_ANNUAL_GAP
247 and row.get("decision_agreement") is not None and row["decision_agreement"] >= MIN_DECISION_AGREEMENT
248 )
251def topology_inputs_fn_for(harness, config: dict, peer_distance: float = 0.5):
252 """Live's learned-topology sizing inputs per (date, ticker) for the harness frame, at the mid peer bracket."""
253 from topology_sizing_research import topology_inputs_by_row
255 from evaluation.model_predictions import predict_heads
257 learning = config["phase_v2"].get("topology_learning", {})
258 ml = ROOT_DIR / "ml"
259 topo_model = json.loads((ml / "topology_model.json").read_text(encoding="utf-8"))
260 topo_schema = json.loads((ml / "topology_feature_schema.json").read_text(encoding="utf-8"))
261 mt_schema = json.loads((ml / "multitask_feature_schema.json").read_text(encoding="utf-8"))
262 mt_model = json.loads((ml / "multitask_model.json").read_text(encoding="utf-8"))
263 probabilities = predict_heads(
264 harness.frame, mt_model, list(mt_schema["model_input_names"]), ["direction"], model_kind="multitask", batched=True
265 )["direction"]
266 table = topology_inputs_by_row(
267 harness.frame, topo_model, topo_schema, probabilities, peer_distance,
268 temperature=float(learning.get("temperature", 0.35)), min_confidence=float(learning.get("min_confidence_for_learned", 0.2)),
269 )
270 return lambda symbol, date: table.get((str(date)[:10], str(symbol)))
273def calibrated_overrides(harness, *, phase: int = 0) -> dict:
274 """The `AsLiveHarness.as_live` keyword arguments of the calibrated simulator (R-CAL's `live_gates` rung): live's cadence
275 phase, next-open fills and the broker's per-order floor. The resize / cooldown / trailing-stop gates come from the
276 config through `build_as_live_kwargs`; the learned-topology sizing is plugged in with `use_topology`."""
277 return {
278 "rebalance_counter_start": phase,
279 "intraday_next_return_column": "next_intraday_return",
280 "min_commission_usd_by_ticker": harness.min_commission_usd_by_ticker,
281 "assumed_portfolio_value_usd": harness.initial_cash,
282 }
285def use_topology(harness, topology_fn) -> None:
286 """Switch the learned-topology sizing multiplier on (a function) or off (None) for the next runs."""
287 if harness.topology_inputs_fn is not topology_fn:
288 harness.topology_inputs_fn = topology_fn
289 harness._mechanisms.clear()
292def window_config(window: dict, default: dict) -> dict:
293 """The config a window is simulated with: the Lean run's own config (`evaluation.lean_attribution.run_config_path`: each
294 run's book, gates and sleeves), or `default` for a prediction window with no run or no kept config."""
295 if window.get("run_dir"):
296 from evaluation.lean_attribution import run_config_path
298 snapshot = run_config_path(ROOT_DIR / window["run_dir"], ROOT_DIR)
299 if snapshot is not None:
300 return json.loads(snapshot.read_text(encoding="utf-8"))
301 return default
304def run_window(window: dict, dataset: Path, config: dict, components: tuple[str, ...] = BOOK_COMPONENTS,
305 extra_ladder: dict | None = None, *, rcal2: bool = False, legacy_probability: str | None = None,
306 gate_warmup_days: int = 0) -> dict:
307 from as_live_levers import AsLiveHarness
309 from evaluation.backtest_audit import load_backtest_run
310 from evaluation.lean_attribution import attribute_run, find_book_history_for_run
312 config = window_config(window, config)
313 harness = AsLiveHarness(window["splits"], dataset_path=dataset, config=config, legacy_probability_path=legacy_probability,
314 gate_warmup_days=gate_warmup_days)
315 frame_dates = sorted(harness.session_dates)
316 rebalance_every = int(config["phase_v2"]["portfolio_book"].get("rebalance_every_bars", 10))
317 report: dict = {"window": window, "variants": {}}
319 live, lean = {}, {}
320 if window["run_dir"]:
321 run_dir = ROOT_DIR / window["run_dir"]
322 history_path = find_book_history_for_run(run_dir, ROOT_DIR / "visualization" / "book_history")
323 history = [json.loads(line) for line in history_path.read_text(encoding="utf-8").splitlines() if line.strip()]
324 attribution = attribute_run(load_backtest_run(run_dir), history, config, ROOT_DIR, period=(window["start"], window["end"]))
325 lean = lean_book_returns(attribution["daily_components"], attribution["daily_equity"], components)
326 report["lean_component_returns"] = {
327 name: lean_book_returns(attribution["daily_components"], attribution["daily_equity"], group)
328 for name, group in COMPONENT_GROUPS.items()
329 }
330 unmodelled = lean_book_returns(attribution["daily_components"], attribution["daily_equity"], UNMODELLED_COMPONENTS)
331 live = live_decisions(history, window["start"], window["end"])
332 live_weights = live_book_weights(load_backtest_run(run_dir), history, config)
333 report["lean_components"] = {name: round(entry["net"], 2) for name, entry in attribution["components"].items()}
334 report["live_decision_counts"] = {state: sum(1 for value in live.values() if value == state) for state in ("engaged", "vetoed", "locked")}
336 in_window = [date for date in frame_dates if window["start"] <= date <= window["end"]]
337 first_live = min(live) if live else None
338 # the simulator starts at the frame's first date; the window may start later (BT2's holdout stretch)
339 phase = rebalance_phase(first_live, frame_dates, rebalance_every) if first_live else 0
340 floors = dict(min_commission_usd_by_ticker=harness.min_commission_usd_by_ticker, assumed_portfolio_value_usd=harness.initial_cash)
341 no_gates = {"resize_threshold_weight": 0.0, "trade_cooldown_dates": 0, "trailing_stop_pct": None}
342 ladder = {
343 "v580": {"rebalance_session_dates": None, **no_gates},
344 "phase": {"rebalance_counter_start": phase, **no_gates},
345 "next_open": {"rebalance_counter_start": phase, "intraday_next_return_column": "next_intraday_return", **no_gates},
346 "min_fee": {"rebalance_counter_start": phase, "intraday_next_return_column": "next_intraday_return", **floors, **no_gates},
347 }
348 ladder["live_gates"] = {key: value for key, value in ladder["min_fee"].items() if key not in no_gates}
349 ladder["calibrated"] = dict(ladder["live_gates"], topology="mid")
350 if live:
351 ladder["replay"] = dict(ladder["calibrated"], decision_overrides=live)
352 ladder["calibrated_ungated"] = dict(ladder["calibrated"], gate="off", min_rank_confidence_spread=0.0)
353 if rcal2:
354 extra = bucket_to_offline_dates(unmodelled, sorted(harness.session_dates)) if window["run_dir"] else None
355 base = dict(ladder["calibrated"])
356 ladder["v610_member_pass"] = dict(base, mid_cycle_member_updates=True)
357 mechanisms = harness.v610_mechanisms(config, legacy=False)
358 ladder["v610_mechanisms"] = dict(base, **mechanisms, include=ANALYZER_INCLUDE)
359 ladder[RCAL2_VARIANT] = dict(base, **harness.v610_mechanisms(config, extra_returns=extra), include=ANALYZER_INCLUDE)
360 if live:
361 ladder["v610_replay"] = dict(ladder[RCAL2_VARIANT], decision_overrides=live)
362 ladder["v610_ungated"] = dict(ladder[RCAL2_VARIANT], gate="off", min_rank_confidence_spread=0.0)
363 for name, overrides in (extra_ladder or {}).items():
364 overrides = dict(overrides)
365 ladder[name] = dict(ladder[overrides.pop("base", "calibrated")], **overrides)
366 topology_fn = topology_inputs_fn_for(harness, config)
368 for name, overrides in ladder.items():
369 overrides = dict(overrides)
370 gate = overrides.pop("gate", "on")
371 use_topology = overrides.pop("topology", None) is not None
372 if (harness.topology_inputs_fn is not None) != use_topology:
373 harness.topology_inputs_fn = topology_fn if use_topology else None
374 harness._mechanisms.clear()
375 result = harness.as_live(gate=gate, log_weights=True, **overrides)
376 dates = list(result.per_date)
377 returns = list(result.per_date_net_return)
378 weights = list(result.weights_log)
379 keep = [index for index, date in enumerate(dates) if window["start"] <= date <= window["end"]]
380 dates = [dates[index] for index in keep]
381 returns = [returns[index] for index in keep]
382 weights = [weights[index] for index in keep]
383 row = {"offline_net_return_window": float(np.prod([1 + value for value in returns]) - 1) if returns else None}
384 if lean:
385 row.update(compare(bucket_to_offline_dates(lean, in_window), dates, returns))
386 offline_states = offline_decisions(result.rebalance_log)
387 row["decision_agreement"] = decision_agreement(live, offline_states)
388 row["decision_agreement_three_state"] = decision_agreement(live, offline_states, binary=False)
389 row["disagreement"] = disagreement_table(live, result.rebalance_log)
390 component_returns = getattr(result, "per_date_component_returns", None) or {}
391 if component_returns:
392 row["component_compare"] = {
393 name: compare(bucket_to_offline_dates(report["lean_component_returns"][name], in_window), dates,
394 [component_returns.get(name, {}).get(date, 0.0) for date in dates])
395 for name in COMPONENT_GROUPS if name in component_returns
396 }
397 row.update(compare_weights(live_weights, dates, weights))
398 else:
399 row.update({"offline_daily_returns": dict(zip(dates, returns, strict=False)),
400 "offline_sharpe": float(np.mean(returns) / np.std(returns) * np.sqrt(252)) if np.std(returns) > 0 else None})
401 component_returns = getattr(result, "per_date_component_returns", None) or {}
402 if component_returns:
403 row["offline_component_daily_returns"] = {
404 name: {date: series.get(date, 0.0) for date in dates} for name, series in component_returns.items()
405 }
406 report["variants"][name] = row
407 print(
408 f" {window['name']:14s} {name:16s} r={row.get('daily_correlation')} gap={row.get('annual_return_gap')} "
409 f"agree={row.get('decision_agreement')} offline_ret={row['offline_net_return_window']} "
410 f"l1={row.get('weight_l1')} overlap={row.get('name_overlap')} gross live/off={row.get('live_gross')}/{row.get('offline_gross')}",
411 flush=True,
412 )
413 return report
416ANALYZER_INCLUDE = ("kill_switch", "member_sizing", "hrp", "impact", "analyzer")
419def main() -> int:
420 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
421 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
422 parser.add_argument("--window", action="append", default=[])
423 parser.add_argument("--rcal2", action="store_true", help="V6.1.0: the three R-CAL2 windows and components")
424 parser.add_argument("--rcal3", action="store_true", help="V6.3.0: R-CAL2's clauses and components on V6.2.0 BT2's windows")
425 parser.add_argument("--components", default=None, help="comma list of attribution components to compare")
426 parser.add_argument("--predict", action="store_true", help="no Lean comparison: write the prediction only")
427 parser.add_argument("--legacy-probability", default=None, help="scripts/build_legacy_probability.py output (R-CAL2)")
428 parser.add_argument("--gate-warmup-days", type=int, default=0, help="rows before the window that warm the rolling-IC gate")
429 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v600" / "calibration.json"))
430 args = parser.parse_args()
431 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
432 texts = list(args.window) + (list(RCAL2_WINDOWS) if args.rcal2 else []) + (list(RCAL3_WINDOWS) if args.rcal3 else [])
433 args.rcal2 = args.rcal2 or args.rcal3
434 if not texts:
435 parser.error("pass --window or --rcal2")
436 components = tuple(args.components.split(",")) if args.components else (RCAL2_COMPONENTS if args.rcal2 else BOOK_COMPONENTS)
437 windows = [parse_window(text) for text in texts]
438 reports = {
439 window["name"]: run_window(window, Path(args.dataset), config, components, rcal2=args.rcal2 or args.predict,
440 legacy_probability=args.legacy_probability, gate_warmup_days=args.gate_warmup_days)
441 for window in windows
442 }
443 verdict = None
444 if not args.predict:
445 judged = RCAL2_VARIANT if args.rcal2 else CALIBRATED_VARIANT
446 passes = {name: window_passes(report["variants"][judged]) for name, report in reports.items()}
447 verdict = {"variant": judged, "per_window": passes, "calibrated": all(passes.values()),
448 "branch": "A" if all(passes.values()) else "B",
449 "thresholds": {"min_correlation": MIN_CORRELATION, "max_annual_gap": MAX_ANNUAL_GAP,
450 "min_decision_agreement": MIN_DECISION_AGREEMENT}}
451 print("R-CAL:", json.dumps(verdict))
452 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
453 Path(args.out).write_text(json.dumps({"windows": reports, "verdict": verdict, "components": list(components)}, indent=1,
454 default=str), encoding="utf-8")
455 print(f"written {args.out}")
456 return 0
459if __name__ == "__main__":
460 raise SystemExit(main())