Coverage for scripts/v650_lean.py: 100%
261 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.5.0 from selection to verdict: weight files and run configs of a frozen candidate, and the R-EDGE1 / R-LEAN19 judgements.
3 python scripts/v650_lean.py g2 # the R-LEAN20 run over the selection window
4 python scripts/v650_lean.py freeze # hashes the candidate and records it, before any later row exists
5 python scripts/v650_lean.py verify # E1 (5 phases), E2, E4 (40 placebos per null), E5 (+ 20 placebos)
6 python scripts/v650_lean.py pool # R-LEAN19: every survivor alone and the combination, 5 phases + the long window
7 python scripts/v650_lean.py judge --status status.txt
9`freeze` must run before `verify` and `pool`: they generate rows after 2023-06-30, and refuse without a matching freeze.
10"""
12from __future__ import annotations
14import argparse
15import hashlib
16import json
17import math
18import sys
19from pathlib import Path
21import numpy as np
22import pandas as pd
24ROOT = Path(__file__).resolve().parents[1]
25sys.path.insert(0, str(ROOT))
26sys.path.insert(0, str(ROOT / "scripts"))
28from build_pre2013_root import universe_for_root # noqa: E402
29from v650_instrument import RUN_CONFIGS, WEIGHTS, target_path_config # noqa: E402
30from v650_research import GATE, OUT, check_rules, load_context, read_json, write_json # noqa: E402
31from v650_trials import ALL_SPECS # noqa: E402
33from evaluation.premia_research import build_context, nulls_for, phase_offsets, weights_for # noqa: E402
34from evaluation.trial_ledger import append_trial, deflation_inputs, read_ledger # noqa: E402
35from portfolio.premia_signals import ResearchPanel, combine_sleeves, null_signal, sleeve_signal # noqa: E402
36from portfolio.target_weights import write_weight_file # noqa: E402
38FREEZE = OUT / "freeze.json"
39LEDGER = OUT / "trial_ledger.jsonl"
40SPECS = {spec.id: spec for spec in ALL_SPECS}
41PHASES = 5
42E4_DRAWS = 40
43E5_DRAWS = 20
44ANNUALIZATION = 365.0
47def candidate_definition() -> dict:
48 """The survivors and the combination method chosen on the selection window (rule T6)."""
49 gate = read_json(GATE, {})
50 survivors = gate.get("survivors") or []
51 if not survivors:
52 raise SystemExit("no survivor: nothing to verify; R-LEAN19 runs on the ablations")
53 if len(survivors) == 1:
54 return {"survivors": survivors, "method": None}
55 combination = read_json(OUT / "selection_combination.json", {})
56 results = combination.get("results") or {}
57 if not results:
58 raise SystemExit("run `v650_research.py combine` first")
59 best = max(results, key=lambda name: results[name]["sharpe"] if results[name]["sharpe"] is not None else -math.inf)
60 return {"survivors": survivors, "method": {"t6_inverse_vol": "inverse_vol", "t6_hrp": "hrp"}[best], "chosen": best}
63def candidate_rows(definition: dict, context, *, start: str, end: str, phase_index: int, null_mode: str | None = None, seed: int = 0) -> dict:
64 """Target weights of the candidate on [start, end]. `null_mode` removes the skill from every sleeve's signal with the
65 same pipeline after it, which is what makes a placebo comparable."""
66 sleeves = {}
67 for name in definition["survivors"]:
68 spec = SPECS[name]
69 signal = sleeve_signal(spec, context.panel)
70 if null_mode:
71 mode = null_mode if null_mode in nulls_for(spec) else "sign_block"
72 signal = null_signal(signal, mode, seed=seed, asset_class=context.panel.asset_class)
73 offsets = phase_offsets(spec.rebalance_every, PHASES)
74 offset = offsets[phase_index % len(offsets)]
75 sleeves[name] = weights_for(spec, context, signal, start=start, end=end, phase_offset=offset)
76 if definition["method"] is None:
77 return sleeves[definition["survivors"][0]]
78 return combine_sleeves(sleeves, context.panel, method=definition["method"], settings=context.settings, start=start, end=end)
81def make_run(name: str, rows: dict, window: tuple[str, str], base: dict, *, data_root: str | None = None, sweep: bool = True) -> dict:
82 """Writes the run's weight file and frozen config (and which data root it reads)."""
83 WEIGHTS.mkdir(parents=True, exist_ok=True)
84 sha = write_weight_file(rows, WEIGHTS / f"{name}.csv")
85 config = target_path_config(base, weights_path=f"ml/evaluation/v650/weights/{name}.csv", weights_sha256=sha, window=window)
86 if not sweep:
87 config["phase_v2"]["cash_sweep"]["enabled"] = False
88 text = json.dumps(config, indent=4)
89 (RUN_CONFIGS / f"{name}.json").write_text(text, encoding="utf-8", newline="\n")
90 if data_root:
91 (RUN_CONFIGS / f"{name}.dataroot").write_text(data_root + "\n", encoding="utf-8", newline="\n")
92 return {"name": name, "weights_sha": sha, "config_sha": hashlib.sha256(text.encode("utf-8")).hexdigest(), "rows": len(rows)}
95def _base() -> dict:
96 return json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
99def freeze_digest(definition: dict) -> dict:
100 code = ["portfolio/premia_signals.py", "portfolio/target_weights.py", "portfolio/financing.py", "evaluation/target_weights_engine.py",
101 "evaluation/premia_research.py", "scripts/v650_trials.py", "scripts/v650_lean.py", "main.py"]
102 return {"candidate": definition, "code": {path: hashlib.sha256((ROOT / path).read_bytes()).hexdigest() for path in code}}
105def stage_g2(args) -> int:
106 rules = check_rules()
107 definition = candidate_definition()
108 context = load_context()
109 start, end = rules["windows"]["selection_lean"]
110 rows = candidate_rows(definition, context, start=start, end=end, phase_index=0)
111 print(json.dumps(make_run("v650_g2", rows, (start, end), _base()), indent=1))
112 return 0
115def stage_freeze(args) -> int:
116 check_rules()
117 definition = candidate_definition()
118 digest = freeze_digest(definition)
119 write_json(FREEZE, digest)
120 from vault_record import record
122 recorded = record("freeze", ["ml/evaluation/v650/freeze.json", "ml/evaluation/v650/selection_gate.json"], {"survivors": float(len(definition["survivors"]))})
123 print(json.dumps({**digest, "vault": recorded}, indent=1))
124 return 0 if recorded["ok"] else 1
127def check_freeze() -> dict:
128 frozen = read_json(FREEZE, None)
129 if frozen is None:
130 raise SystemExit("no freeze.json: run `v650_lean.py freeze` before any row after the selection window")
131 now = freeze_digest(frozen["candidate"])
132 if now["code"] != frozen["code"]:
133 changed = [path for path in now["code"] if now["code"][path] != frozen["code"][path]]
134 raise SystemExit(f"code changed since the freeze: {changed}")
135 return frozen["candidate"]
138def pre2013_context(base: dict):
139 manifest = json.loads((ROOT / "data_pre2013" / "pre2013_manifest.json").read_text(encoding="utf-8"))
140 config = universe_for_root(base, manifest)
141 return build_context(ROOT, config, data_dir="data_pre2013"), config
144def stage_verify(args) -> int:
145 rules = check_rules()
146 definition = check_freeze()
147 base = _base()
148 runs: dict[str, dict] = {}
149 context = load_context()
150 window = tuple(rules["windows"]["verification"])
151 for phase in range(PHASES):
152 runs[f"v650_e1_p{phase}"] = make_run(f"v650_e1_p{phase}", candidate_rows(definition, context, start=window[0], end=window[1], phase_index=phase), window, base)
153 long_window = tuple(rules["windows"]["long"])
154 runs["v650_e2"] = make_run("v650_e2", candidate_rows(definition, context, start=long_window[0], end=long_window[1], phase_index=0), long_window, base)
155 rng = np.random.default_rng(650)
156 for mode in ("null_a", "null_b"):
157 for draw in range(E4_DRAWS):
158 name = f"v650_e4_{mode}_{draw:02d}"
159 null_mode = "time_shift" if mode == "null_b" else "asset_block"
160 rows = candidate_rows(definition, context, start=window[0], end=window[1], phase_index=int(rng.integers(PHASES)), null_mode=null_mode, seed=1_000 + draw)
161 runs[name] = make_run(name, rows, window, base)
162 early, config = pre2013_context(base)
163 early_window = tuple(rules["windows"]["pre2013"])
164 available = [name for name in definition["survivors"] if SPECS[name].universe != ("crypto",)]
165 early_definition = {**definition, "survivors": available}
166 if available:
167 # a crypto sleeve has no bars before 2014 and an ML sleeve no scores: their weight goes to what can run (disclosed in rules.json)
168 if len(available) == 1:
169 early_definition["method"] = None
170 runs["v650_e5"] = make_run("v650_e5", candidate_rows(early_definition, early, start=early_window[0], end=early_window[1], phase_index=0),
171 early_window, config, data_root="data_pre2013", sweep=False)
172 for draw in range(E5_DRAWS):
173 name = f"v650_e5_null_{draw:02d}"
174 rows = candidate_rows(early_definition, early, start=early_window[0], end=early_window[1], phase_index=int(rng.integers(PHASES)),
175 null_mode="time_shift", seed=2_000 + draw)
176 runs[name] = make_run(name, rows, early_window, config, data_root="data_pre2013", sweep=False)
177 write_json(OUT / "verify_runs.json", runs)
178 print(f"{len(runs)} runs written; E5 sleeves: {available}")
179 (OUT / "verify_run_list.txt").write_text(" ".join(f"ml/evaluation/run_configs/{name}.json" for name in runs) + "\n", encoding="utf-8", newline="\n")
180 return 0
183def stage_pool(args) -> int:
184 rules = check_rules()
185 check_freeze()
186 survivors = (read_json(GATE, {}).get("survivors") or [])
187 base = _base()
188 context = load_context()
189 window = tuple(rules["windows"]["verification"])
190 long_window = tuple(rules["windows"]["long"])
191 runs = {}
192 members = {name: {"survivors": [name], "method": None} for name in survivors}
193 combination = candidate_definition()
194 if combination["method"] is not None:
195 members[combination["chosen"]] = combination
196 for name, definition in members.items():
197 for phase in range(PHASES):
198 run = f"v650_pool_{name}_p{phase}"
199 runs[run] = make_run(run, candidate_rows(definition, context, start=window[0], end=window[1], phase_index=phase), window, base)
200 run = f"v650_pool_{name}_long"
201 runs[run] = make_run(run, candidate_rows(definition, context, start=long_window[0], end=long_window[1], phase_index=0), long_window, base)
202 write_json(OUT / "pool_runs.json", runs)
203 (OUT / "pool_run_list.txt").write_text(" ".join(f"ml/evaluation/run_configs/{name}.json" for name in runs) + "\n", encoding="utf-8", newline="\n")
204 print(f"{len(runs)} pool runs written")
205 return 0
208def lean_statistics(run_dir: Path) -> dict:
209 from evaluation.backtest_audit import load_backtest_run
211 run = load_backtest_run(run_dir)
212 stats = run["result"].get("statistics") or run["result"].get("Statistics") or {}
213 def number(key: str) -> float | None:
214 text = str(stats.get(key, "")).replace("%", "").replace("$", "").replace(",", "")
215 try:
216 return float(text)
217 except ValueError:
218 return None
219 return {"lean_sharpe": number("Sharpe Ratio"), "annual_std": number("Annual Standard Deviation"), "drawdown_pct": number("Drawdown"),
220 "net_profit_pct": number("Net Profit"), "orders": number("Total Orders"), "fees": number("Total Fees")}
223def strategy_series(run_dir: Path, config: dict, *, data_dir: str = "data") -> pd.Series:
224 """The ex-T-bill daily return of a run; with no sweep (the pre-2013 run) it is the NAV's daily return."""
225 from evaluation.alpha_proof import strategy_daily_returns
226 from evaluation.backtest_audit import daily_equity_from_chart, load_backtest_run
228 run = load_backtest_run(run_dir)
229 if data_dir != "data" or not config["phase_v2"]["cash_sweep"]["enabled"]:
230 points = daily_equity_from_chart(run["result"])
231 return pd.Series(dict(points), dtype=float).sort_index().pct_change().dropna()
232 return strategy_daily_returns(run, config, ROOT)
235def stage_judge(args) -> int:
236 """R-LEAN19 over the pool. `--status` is the runner's status file; the gated ablations come from ablation_table.json."""
237 check_rules()
238 from evaluation.alpha_proof import alpha_regression, benchmark_daily_returns, sharpe, to_sessions
240 done = {}
241 for line in Path(args.status).read_text(encoding="utf-8-sig").splitlines():
242 parts = line.split()
243 if len(parts) == 3 and parts[0] == "LEAN_DONE":
244 done[parts[1]] = ROOT / parts[2]
245 members: dict[str, dict] = {}
246 for run, run_dir in done.items():
247 if not run.startswith("v650_pool_"):
248 continue
249 name, _, tail = run[len("v650_pool_"):].rpartition("_")
250 members.setdefault(name, {"phases": {}, "long": None})
251 if tail == "long":
252 members[name]["long"] = run_dir
253 else:
254 members[name]["phases"][tail] = run_dir
256 def describe(run_dir: Path) -> dict:
257 config = json.loads((RUN_CONFIGS / f"{run_dir.name}.json").read_text(encoding="utf-8"))
258 y = strategy_series(run_dir, config)
259 stats = lean_statistics(run_dir)
260 stats["strategy_sharpe"] = sharpe(y.to_numpy(dtype=float), ANNUALIZATION)
261 log = (run_dir / "log.txt").read_text(encoding="utf-8", errors="replace")
262 stats["complete"] = "PythonInitializer.Shutdown(): start" in log and "Runtime Error" not in log
263 benchmarks = benchmark_daily_returns(ROOT, config, start=str(y.index.min()), end=str(y.index.max()))
264 alpha = alpha_regression(to_sessions(y, benchmarks.index), benchmarks)
265 stats["alpha_annual"], stats["alpha_t"] = alpha.get("alpha_annual"), alpha.get("t_hac")
266 stats["betas"] = alpha.get("betas")
267 stats["locked"] = "total_drawdown_limit_breached" in log or "kill_switch" in log
268 stats["run"] = run_dir.name
269 return stats
271 pool: dict[str, dict] = {}
272 detail: dict[str, dict] = {}
273 for name, runs in sorted(members.items()):
274 phases = {phase: describe(run_dir) for phase, run_dir in sorted(runs["phases"].items())}
275 detail[name] = {"phases": phases}
276 def median(key: str, phases: dict = phases) -> float | None:
277 values = [entry[key] for entry in phases.values() if entry.get(key) is not None]
278 return float(np.median(values)) if values else None
279 entry = {key: median(key) for key in ("lean_sharpe", "strategy_sharpe", "annual_std", "drawdown_pct", "alpha_annual", "alpha_t")}
280 entry["complete"] = all(item["complete"] for item in phases.values()) and len(phases) == PHASES
281 entry["worst_phase_drawdown_pct"] = max(item["drawdown_pct"] or 0.0 for item in phases.values())
282 if runs["long"] is not None:
283 detail[name]["long"] = describe(runs["long"])
284 entry["long_strategy_sharpe"] = detail[name]["long"]["strategy_sharpe"]
285 pool[name] = entry
286 append_trial(LEDGER, trial_id=name, track="pool", window="verification", role="verification" if name in SPECS else "candidate",
287 annualised_sharpe=entry["strategy_sharpe"], n_obs=0, engine="lean", detail={"lean_sharpe": entry["lean_sharpe"]})
288 table = read_json(OUT / "ablation_table.json", {})
289 baseline_row = table["BT11 baseline"]
290 baseline = {"lean_sharpe": baseline_row["lean_sharpe"], "strategy_sharpe": baseline_row["strategy_sharpe"]}
291 for label, row in table.items():
292 if label.startswith("BT") and label not in ("BT11 baseline", "BT12 flag off"):
293 pool[label] = {"lean_sharpe": row["lean_sharpe"], "strategy_sharpe": row["strategy_sharpe"], "annual_std": row["annual_std"],
294 "drawdown_pct": row["drawdown_pct"], "complete": row["complete"], "long_strategy_sharpe": None}
295 verdict = judge_fallback(pool, baseline)
296 write_json(OUT / "r_lean19.json", {"baseline": baseline, "pool": pool, "verdict": verdict, "detail": detail})
297 for name, entry in sorted(pool.items(), key=lambda item: -(item[1]["strategy_sharpe"] or -9)):
298 print(f"{name:26s} lean {entry['lean_sharpe']:6.3f} strat {entry['strategy_sharpe']:6.3f} vol {entry['annual_std']:.3f} dd {entry['drawdown_pct']:5.1f} "
299 f"alpha {entry.get('alpha_annual')} t {entry.get('alpha_t')} long {entry.get('long_strategy_sharpe')}")
300 print(json.dumps(verdict, indent=1))
301 return 0
304def judge_edge(e1: list[float | None], e2_t: float | None, dsr: float | None, null_a: list[float], null_b: list[float], candidate_sharpe: float | None,
305 early_sharpe: float | None, early_alpha: float | None) -> dict:
306 """R-EDGE1 as a pure function of the figures."""
307 usable = [value for value in e1 if value is not None]
308 e1_median = float(np.median(usable)) if len(usable) == len(e1) and usable else None
309 beaten_a = sum(value >= candidate_sharpe for value in null_a) if candidate_sharpe is not None else None
310 beaten_b = sum(value >= candidate_sharpe for value in null_b) if candidate_sharpe is not None else None
311 clauses = {
312 "E1": e1_median is not None and e1_median >= 1.0,
313 "E2": e2_t is not None and e2_t >= 3.0,
314 "E3": dsr is not None and dsr >= 0.95,
315 "E4": beaten_a is not None and len(null_a) >= E4_DRAWS and len(null_b) >= E4_DRAWS and beaten_a <= 1 and beaten_b <= 1,
316 "E5": early_sharpe is not None and early_alpha is not None and early_sharpe > 0.0 and early_alpha > 0.0,
317 }
318 return {"verified": all(clauses.values()), "clauses": clauses, "e1_median": e1_median, "beaten_by_null_a": beaten_a, "beaten_by_null_b": beaten_b}
321def judge_fallback(pool: dict[str, dict], baseline: dict) -> dict:
322 """R-LEAN19: the best by median ex-T-bill Sharpe installs iff it clears every clause; otherwise nothing changes."""
323 def clauses(entry: dict) -> dict:
324 return {
325 "lean_sharpe": entry.get("lean_sharpe") is not None and entry["lean_sharpe"] >= baseline["lean_sharpe"] + 0.10,
326 "strategy_sharpe": entry.get("strategy_sharpe") is not None and entry["strategy_sharpe"] >= baseline["strategy_sharpe"] + 0.10,
327 "vol": entry.get("annual_std") is not None and entry["annual_std"] <= 0.10,
328 "drawdown": entry.get("drawdown_pct") is not None and entry["drawdown_pct"] <= 15.0,
329 "complete": bool(entry.get("complete")),
330 "long_window": entry.get("long_strategy_sharpe") is None or entry["long_strategy_sharpe"] > 0.0,
331 }
332 ranked = sorted(pool, key=lambda name: pool[name]["strategy_sharpe"] if pool[name].get("strategy_sharpe") is not None else -math.inf, reverse=True)
333 table = {name: clauses(pool[name]) for name in ranked}
334 best = ranked[0] if ranked else None
335 return {"best": best, "install": best if best is not None and all(table[best].values()) else None, "clauses": table}
338def main() -> int:
339 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
340 commands = parser.add_subparsers(dest="command", required=True)
341 for name in ("g2", "freeze", "verify", "pool"):
342 commands.add_parser(name)
343 judge = commands.add_parser("judge")
344 judge.add_argument("--status", required=True)
345 args = parser.parse_args()
346 return {"g2": stage_g2, "freeze": stage_freeze, "verify": stage_verify, "pool": stage_pool, "judge": stage_judge}[args.command](args)
349__all__ = ["ResearchPanel", "append_trial", "deflation_inputs", "judge_edge", "judge_fallback", "read_ledger"]
351if __name__ == "__main__":
352 raise SystemExit(main())