Coverage for evaluation/readme_research.py: 100%
383 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"""README builders for the as-live book and the V5.8.0 research / audit results.
3`generate_evaluation_report.update_readme_evaluation_sections()` calls these; each takes the directory the JSON reports
4live in and returns markdown, degrading to a "not run yet" line when its inputs are missing, so the README never shows a
5half-built table. Pure: reads JSON, no model, no network.
7Sources (all written by `aq evaluate ...` or the research scripts):
8 rank_book_simulation_as_live_<split>.json aq evaluate --rank-book --as-live --split <split>
9 class_sleeve_research_{forex,bond}.json scripts/class_sleeve_research.py
10 crypto_graduation_research.json scripts/crypto_graduation_research.py
11 rl_sizing_research.json scripts/rl_sizing_research.py
12 class_ic_audit_<split>.json aq evaluate --ic-by-class
13 gate_audit_<split>.json aq evaluate --audit-gates
14 head_audit.json aq evaluate --audit-heads
15 holdout_report.json scripts/holdout_report.py
16 lean_decision_overrides.json a Lean run that overruled an offline branch (label -> branch, shipped, reason)
17 v600/forex_research.json, v600/crypto_research.json the V6.0.0 rule decisions (R-FX6, R-CRYPTO); the shipped setting
18 is read from config.json, never typed here
19 v610/calibration.json, v610/research.json V6.1.0: R-CAL2 and the rule chain (model, head, book, legacy, gate)
20 v630/calibration.json, v630/research.json V6.3.0: R-CAL3 (replaces R-CAL2's table) and R-KILL / R-STAGGER2 / R-GATE3
21 v640/research.json V6.4.0: R-DEDUPE2 and leads L1-L10
22"""
24from __future__ import annotations
26import json
27from pathlib import Path
29SPLITS = ("validation", "backtest")
30AS_LIVE_MARKER_START = "<!-- AQ:ASLIVE_START -->"
31AS_LIVE_MARKER_END = "<!-- AQ:ASLIVE_END -->"
32RESEARCH_MARKER_START = "<!-- AQ:RESEARCH_START -->"
33RESEARCH_MARKER_END = "<!-- AQ:RESEARCH_END -->"
34LEAN_COMPARE_MARKER_START = "<!-- AQ:LEANCMP_START -->"
35LEAN_COMPARE_MARKER_END = "<!-- AQ:LEANCMP_END -->"
38def load_json(path: Path) -> dict | list | None:
39 try:
40 return json.loads(path.read_text(encoding="utf-8"))
41 except (OSError, ValueError):
42 return None
45def _num(value: object, spec: str = "+.3f") -> str:
46 if isinstance(value, bool) or not isinstance(value, (int, float)) or value != value:
47 return "n/a"
48 return format(value, spec)
51def _pct(value: object, spec: str = "+.2f") -> str:
52 return "n/a" if _num(value) == "n/a" else f"{format(float(value) * 100.0, spec)}%" # type: ignore[arg-type]
55def _per_split(evaluation_dir: Path, stem: str) -> dict[str, dict | None]:
56 """`<stem>_<split>.json` per split; the legacy un-suffixed file stands in for the split it names (its `split` key)."""
57 reports: dict[str, dict | None] = {split: load_json(evaluation_dir / f"{stem}_{split}.json") for split in SPLITS}
58 legacy = load_json(evaluation_dir / f"{stem}.json")
59 if isinstance(legacy, dict):
60 named = legacy.get("split")
61 if named in reports and reports[named] is None:
62 reports[named] = legacy
63 return {split: report if isinstance(report, dict) else None for split, report in reports.items()}
66def build_as_live_markdown(evaluation_dir: Path) -> str:
67 reports = _per_split(evaluation_dir, "rank_book_simulation_as_live")
68 legacy = load_json(evaluation_dir / "rank_book_simulation_as_live.json")
69 if not any(reports.values()) and isinstance(legacy, dict):
70 reports = {"older run, split not recorded": legacy}
71 if not any(reports.values()):
72 return "_Not run yet: `aq evaluate --rank-book --as-live --split validation` and `--split backtest`._"
73 rows = [
74 "| Split | Idealized Sharpe | **As-live Sharpe** | As-live net return | Max drawdown | Rebalances (vetoed) | With impact model |",
75 "|---|---|---|---|---|---|---|",
76 ]
77 for split, report in reports.items():
78 if not report:
79 rows.append(f"| {split} | not run | | | | | |")
80 continue
81 live = report.get("as_live") or {}
82 impact = report.get("as_live_with_impact_model") or {}
83 rows.append(
84 f"| {split} | {_num(report.get('idealized_net_sharpe'))} | **{_num(live.get('net_sharpe'))}** | "
85 f"{_pct(live.get('net_total_return'))} | {_pct(live.get('net_max_drawdown'), '.2f')} | "
86 f"{live.get('num_rebalances', 'n/a')} ({live.get('num_vetoed_rebalances', 'n/a')}) | {_num(impact.get('net_sharpe'))} |"
87 )
88 return (
89 "The offline book run through the same decision functions as `main.py` (blended head, rank groups, spread / rolling-IC "
90 "gates, kill switch, hysteresis, class sleeves and caps, one-bar lag). Sharpe subtracts no risk-free rate, and a "
91 "split with few engaged rebalances is a thin estimate.\n\n" + "\n".join(rows)
92 )
95def _sleeve_row(label: str, research: dict | None, minimum_setting: str, override: dict | None = None) -> str | None:
96 if not research:
97 return None
98 decision = research.get("decision") or {}
99 variant = decision.get("variant")
100 entry = (research.get("grid") or {}).get(variant) if variant else None
101 branch = decision.get("branch", "n/a")
102 shipped = variant if branch == "edge_pass" else f"{minimum_setting} (minimum cap; best effort: {variant})"
103 if isinstance(override, dict) and override.get("branch") and override.get("shipped"):
104 branch = f"{override['branch']} (offline: {branch})"
105 shipped = str(override["shipped"])
106 return (
107 f"| {label} | {branch} | {shipped} | {_num(((entry or {}).get('validation') or {}).get('net_sharpe'))} | "
108 f"{_num(((entry or {}).get('backtest') or {}).get('net_sharpe'))} | {_num((entry or {}).get('combined_backtest_drop'))} |"
109 )
112def _config_for(evaluation_dir: Path) -> dict:
113 config = load_json(evaluation_dir.parent.parent / "config.json")
114 return config if isinstance(config, dict) else {}
117def _forex_row_v6(evaluation_dir: Path, config: dict) -> str | None:
118 """R-FX6 (V6.0.0): the forex sleeve is dropped when none of the grid is positive on the backtest split."""
119 research = load_json(evaluation_dir / "v600" / "forex_research.json")
120 if not isinstance(research, dict) or not config:
121 return None
122 decision = research.get("decision") or {}
123 best = (research.get("grid") or {}).get(decision.get("best_validation_variant")) or {}
124 enabled = bool((config.get("phase_v2", {}).get("forex_risk") or {}).get("enabled", False))
125 shipped = "sleeve on (see config.json `forex_sleeve`)" if enabled else "off (`forex_risk.enabled` false; forex stays a feature class)"
126 return (
127 f"| Forex sleeve | R-FX6: {decision.get('branch', 'n/a')} | {shipped} | {_num((best.get('validation') or {}).get('net_sharpe'))} | "
128 f"{_num((best.get('backtest') or {}).get('net_sharpe'))} | n/a |"
129 )
132def _crypto_row_v6(evaluation_dir: Path, config: dict) -> str | None:
133 """R-CRYPTO (V6.0.0): limit exits, a route-aware fee and smaller graduates; the caps shown are the shipped ones."""
134 research = load_json(evaluation_dir / "v600" / "crypto_research.json")
135 if not isinstance(research, dict) or not config:
136 return None
137 decision = research.get("decision") or {}
138 winner = (research.get("results") or {}).get(decision.get("winner")) or {}
139 caps = ((config.get("phase_v2", {}).get("class_weight_caps") or {}).get("crypto")) or {}
140 limits = config.get("phase_v2", {}).get("limit_orders", {})
141 exits = ", ".join(limits.get("exit_asset_classes") or []) or "none"
142 shipped = f"per-name {caps.get('per_name_cap', 'n/a')}, class gross {caps.get('class_gross_cap', 'n/a')}; limit exits for {exits}"
143 return (
144 f"| Crypto graduates and fees | R-CRYPTO: {decision.get('winner', 'n/a')} | {shipped} | "
145 f"{_num((winner.get('validation') or {}).get('total_sharpe'))} | {_num((winner.get('backtest') or {}).get('total_sharpe'))} | n/a |"
146 )
149def _calibration_line(evaluation_dir: Path) -> str:
150 # V6.3.0: R-CAL3 (R-CAL2's clauses on V6.2.0's BT2) supersedes R-CAL2 once it exists.
151 rule, report = "R-CAL3", load_json(evaluation_dir / "v630" / "calibration.json")
152 if not isinstance(report, dict) or not isinstance(report.get("verdict"), dict):
153 rule, report = "R-CAL2", load_json(evaluation_dir / "v610" / "calibration.json")
154 verdict = (report or {}).get("verdict") if isinstance(report, dict) else None
155 if not isinstance(verdict, dict):
156 return "_Not run yet: `python scripts/lean_calibration.py --rcal2` (rule R-CAL2)._"
157 variant = verdict.get("variant", "v610")
158 cells = []
159 for name, window in ((report or {}).get("windows") or {}).items():
160 row = (window.get("variants") or {}).get(variant) or {}
161 cells.append(
162 f"| {name} | {_num(row.get('daily_correlation'), '.2f')} | {_pct(row.get('annual_return_gap'), '+.1f')} | "
163 f"{_pct(row.get('decision_agreement'), '.0f')} | {'pass' if (verdict.get('per_window') or {}).get(name) else 'fail'} |"
164 )
165 thresholds = verdict.get("thresholds") or {}
166 return (
167 f"Rule {rule} (daily correlation >= {_num(thresholds.get('min_correlation'), '.2f')}, annual return gap <= "
168 f"{_pct(thresholds.get('max_annual_gap'), '.0f')}, rebalance-decision agreement >= "
169 f"{_pct(thresholds.get('min_decision_agreement'), '.0f')} on every window): **branch {verdict.get('branch', '?')}** "
170 f"({'calibrated' if verdict.get('calibrated') else 'not calibrated'}).\n\n"
171 "| Window | Daily correlation | Return gap (annual) | Decision agreement | Verdict |\n|---|---|---|---|---|\n"
172 + "\n".join(cells)
173 )
176def _rule_chain_lines(evaluation_dir: Path) -> list[str]:
177 report = load_json(evaluation_dir / "v610" / "research.json")
178 if not isinstance(report, dict):
179 return ["_Not run yet: `python scripts/v610_research.py` (rules R-MODEL9, R-HEAD2, R-BOOK2, R-LEGACY, R-GATE)._"]
180 rows = []
181 for stage in ("model", "head", "book", "costs", "legacy", "gate"):
182 entry = report.get(stage)
183 if not isinstance(entry, dict):
184 continue
185 if "skipped" in entry:
186 rows.append(f"| {stage} | skipped | {entry['skipped']} |")
187 continue
188 variants = entry.get("variants") or {}
189 adopted = entry.get("adopted")
190 detail = []
191 for name, value in variants.items():
192 if "skipped" in value:
193 detail.append(f"{name} skipped ({value['skipped']})")
194 continue
195 verdict = (value.get("verdict") or {}).get("ungated") or {}
196 detail.append(f"{name} {_num(verdict.get('backtest_gain'), '+.3f')}")
197 rows.append(f"| {stage} | {adopted or 'none (incumbent stays)'} | {', '.join(detail) or 'n/a'} |")
198 if not rows:
199 return ["_Rule chain has no stage results yet._"]
200 return ["| Stage | Adopted | Backtest-Sharpe gain per variant (median over rebalance phases) |", "|---|---|---|", *rows]
203def _rule_chain_v620_lines(evaluation_dir: Path) -> list[str]:
204 """V6.2.0's chain (v620/research.json): R-DEDUPE on the gated book, R-STAGGER and R-MODEL10 on the ungated one."""
205 report = load_json(evaluation_dir / "v620" / "research.json")
206 if not isinstance(report, dict):
207 return ["_Not run yet: `python scripts/v620_research.py` (rules R-DEDUPE, R-STAGGER, R-MODEL10)._"]
208 rows = []
209 dedupe = report.get("dedupe")
210 if isinstance(dedupe, dict):
211 verdict = dedupe.get("verdict") or {}
212 rows.append(f"| R-DEDUPE (crypto counted once in the gate) | {'adopted' if dedupe.get('adopted') else 'none (double count stays)'} "
213 f"| once: backtest {_num(verdict.get('backtest_gain'))}, validation {_num(verdict.get('validation_change'))} (gated) |")
214 stagger = report.get("stagger")
215 if isinstance(stagger, dict):
216 detail = []
217 for name, value in (stagger.get("variants") or {}).items():
218 verdict = value.get("verdict") or {}
219 failed = [key for key, ok in {**verdict.get("checks", {}), **verdict.get("extra_checks", {})}.items() if not ok]
220 detail.append(f"{name}: backtest {_num(verdict.get('backtest_gain'))}, validation {_num(verdict.get('validation_change'))}"
221 + (f" (fails {', '.join(failed)})" if failed else ""))
222 rows.append(f"| R-STAGGER (tranche book) | {stagger.get('adopted') or 'none (one book stays)'} | {'; '.join(detail) or 'n/a'} |")
223 model = report.get("model")
224 if isinstance(model, dict):
225 skipped = [name for name, value in (model.get("variants") or {}).items() if "skipped" in value]
226 rows.append(f"| R-MODEL10 (regularised ensembles) | {model.get('adopted') or 'none (installed models stay)'} "
227 f"| {len(skipped)} candidates fail the IC clauses (yardstick: resampled control ensembles) |")
228 if not rows:
229 return ["_V6.2.0 rule chain has no stage results yet._"]
230 return ["| Rule | Adopted | Median-Sharpe change per variant (every rebalance phase) |", "|---|---|---|", *rows]
233def _failed(verdict: dict, extra: dict | None = None) -> list[str]:
234 return [key for key, ok in {**(verdict.get("checks") or {}), **(extra or {})}.items() if not ok]
237def _rule_chain_v630_lines(evaluation_dir: Path) -> list[str]:
238 """V6.3.0's chain (v630/research.json): R-KILL and R-STAGGER2 ungated, R-GATE3 as-live only on R-CAL3 branch A."""
239 report = load_json(evaluation_dir / "v630" / "research.json")
240 if not isinstance(report, dict):
241 return ["_Not run yet: `python scripts/v630_research.py` (rules R-KILL, R-STAGGER2, R-GATE3)._"]
242 rows = []
243 kill = report.get("kill")
244 if isinstance(kill, dict):
245 detail = []
246 for name, value in (kill.get("variants") or {}).items():
247 verdict = value.get("verdict") or {}
248 failed = _failed(verdict, value.get("extra_checks"))
249 detail.append(f"{name}: backtest {_num(verdict.get('backtest_gain'))}, validation {_num(verdict.get('validation_change'))}, "
250 f"lock stability {_num(value.get('stability'), '.2f')}" + (f" (fails {', '.join(failed)})" if failed else ""))
251 base = ((kill.get("base") or {}).get("backtest") or {}).get("stability_jaccard_median")
252 rows.append(f"| R-KILL (kill-switch window / release band; KS0 lock stability {_num(base, '.2f')}) | branch {kill.get('branch', '?')}: "
253 f"{kill.get('adopted') or 'none (KS0 stays)'} | {'; '.join(detail) or 'n/a'} |")
254 stagger = report.get("stagger")
255 if isinstance(stagger, dict):
256 verdict = stagger.get("verdict") or {}
257 failed = _failed(verdict, stagger.get("extra_checks"))
258 rows.append(f"| R-STAGGER2 (S2, second look) | {'S2' if stagger.get('adopted') else 'none (one book stays)'} | backtest "
259 f"{_num(verdict.get('backtest_gain'))}, validation {_num(verdict.get('validation_change'))}"
260 + (f" (fails {', '.join(failed)})" if failed else "") + " |")
261 gates = report.get("gates")
262 if isinstance(gates, dict):
263 if "skipped" in gates:
264 rows.append(f"| R-GATE3 (rolling-IC floor / window) | skipped | {gates['skipped']} |")
265 else:
266 detail = [f"{name} {_num((value.get('verdict') or {}).get('backtest_gain'))}" for name, value in (gates.get("variants") or {}).items()]
267 rows.append(f"| R-GATE3 (rolling-IC floor / window) | {gates.get('adopted') or 'none (gate stays)'} | {', '.join(detail)} |")
268 if not rows:
269 return ["_V6.3.0 rule chain has no stage results yet._"]
270 return ["| Rule | Adopted | Median-Sharpe change per variant (every rebalance phase) |", "|---|---|---|", *rows]
273def _r_lean14_rows(evaluation_dir: Path) -> list[str]:
274 """V6.4.2: one row per R-LEAN14 verdict (`v642/r_lean14_bt*.json`), each half of BT6 against BT5 on Lean."""
275 rule = load_json(evaluation_dir / "v642" / "r_lean14_rule.json")
276 variants = rule.get("variants", {}) if isinstance(rule, dict) else {}
277 rows = []
278 for path in sorted((evaluation_dir / "v642").glob("r_lean14_bt*.json")):
279 verdict = load_json(path)
280 if not isinstance(verdict, dict) or not isinstance(verdict.get("values"), dict):
281 continue
282 key = path.stem.rsplit("_", 1)[-1].upper()
283 values = verdict["values"]
284 failed = [name for name, ok in (verdict.get("checks") or {}).items() if not ok]
285 rows.append(
286 f"| R-LEAN14 {key} ({(variants.get(key) or {}).get('change', 'one half of BT6')} alone, run {verdict.get('candidate')} "
287 f"against {verdict.get('baseline')}) | {'adopted' if verdict.get('keep') else 'none (config unchanged)'} | strategy Sharpe "
288 f"{_num(values.get('candidate_strategy_sharpe'), '.2f')} against {_num(values.get('baseline_strategy_sharpe'), '.2f')}, max "
289 f"drawdown {_pct(values.get('candidate_max_drawdown'), '.2f')} against {_pct(values.get('baseline_max_drawdown'), '.2f')}"
290 + (f" (fails {', '.join(failed)})" if failed else "") + " |"
291 )
292 return rows
295def _rule_chain_v640_lines(evaluation_dir: Path) -> list[str]:
296 """V6.4.0's chain (v640/research.json): one row per lead (R-DEDUPE2, L2-L10); L1 has its own table below."""
297 report = load_json(evaluation_dir / "v640" / "research.json")
298 if not isinstance(report, dict):
299 return ["_Not run yet: `python scripts/v640_research.py` (leads L1-L10, R-DEDUPE2)._"]
300 rows = []
302 def verdict_text(entry: dict) -> str:
303 verdict = entry.get("verdict") or {}
304 failed = _failed(verdict, entry.get("extra_checks") or entry.get("checks"))
305 gain = f"backtest {_num(verdict.get('backtest_gain'))}, validation {_num(verdict.get('validation_change'))}" if verdict else "n/a"
306 return gain + (f" (fails {', '.join(failed)})" if failed else "")
308 def add(label: str, stage, variants_key: str = "variants", adopted_key: str = "adopted", none_text: str = "none (unchanged)"):
309 if not isinstance(stage, dict) or variants_key not in stage:
310 return
311 detail = [f"{name}: {verdict_text(value)}" for name, value in (stage.get(variants_key) or {}).items()]
312 rows.append(f"| {label} | {stage.get(adopted_key) or none_text} | {'; '.join(detail) or 'n/a'} |")
314 dedupe = report.get("dedupe")
315 if isinstance(dedupe, dict):
316 rows.append(f"| R-DEDUPE2 (crypto counted once in the gate; validation + backtest + holdout span) | "
317 f"{'once' if dedupe.get('adopted') else 'none (twice stays)'} | {verdict_text({'verdict': dedupe.get('verdict')})} |")
318 add("L2 direction overlay (calibrated on validation)", report.get("l2"), none_text="none (direction = diagnostic only)")
319 l3 = report.get("l3")
320 if isinstance(l3, dict):
321 add("L3a legacy budget", l3, "budgets", "budget_adopted", "none (0.05 / 0.02 stays)")
322 model = l3.get("model") or {}
323 if isinstance(model, dict) and ("checks" in model or "reason" in model or "skipped" in model):
324 failed = [key for key, ok in (model.get("checks") or {}).items() if not ok]
325 rows.append(f"| L3b legacy as a model input (yardstick 0.034) | {'v640_leg' if model.get('adopted') else 'none (models unchanged)'} | "
326 f"{model.get('reason') or model.get('skipped') or ('fails ' + ', '.join(failed) if failed else 'all clauses pass')} |")
327 add("L4 within-class ranks", report.get("l4"), none_text="none (pooled equity + crypto ranks stay)")
328 add("L5 rebalance / hold grid", report.get("l5"), none_text="none (20 / 40 stays)")
329 add("L6 staggered book (phase spread)", report.get("l6"), none_text="none (one book stays)")
330 add("L7 kill-switch confirmation", report.get("l7"), none_text="none (KS0 stays)")
331 l8 = report.get("l8")
332 if isinstance(l8, dict):
333 decision = l8.get("decision") or {}
334 rows.append(f"| L8 expert ablation (legacy signal) | {', '.join(decision.get('disable') or []) or 'none disabled'} | "
335 f"no contribution on both splits: {', '.join(decision.get('candidates_with_no_contribution') or []) or 'none'}; "
336 f"non-inferior: {decision.get('non_inferior')} |")
337 l9 = report.get("l9")
338 if isinstance(l9, dict) and "decision" in l9:
339 rows.append(f"| L9 crypto graduates against core only | {'graduates kept' if l9['decision'].get('keep_graduates') else 'core only'} | "
340 f"graduates beat core-only: {l9['decision'].get('graduates_beat_core_only_on')} |")
341 add("L10 residual head blend", report.get("l10"), none_text="none (rank_20d / rank_5d stay)")
342 lean = load_json(evaluation_dir / "v640" / "r_lean13.json")
343 if isinstance(lean, dict) and isinstance(lean.get("values"), dict):
344 values = lean["values"]
345 failed = [name for name, ok in (lean.get("checks") or {}).items() if not ok]
346 rows.append(
347 f"| R-LEAN13 (Lean confirm of the adopted L5 + L9 changes, run {lean.get('candidate')} against {lean.get('baseline')}) | "
348 f"{'kept' if lean.get('keep') else 'reverted'} | strategy Sharpe {_num(values.get('candidate_strategy_sharpe'), '.2f')} against "
349 f"{_num(values.get('baseline_strategy_sharpe'), '.2f')}, max drawdown {_pct(values.get('candidate_max_drawdown'), '.2f')} "
350 f"against {_pct(values.get('baseline_max_drawdown'), '.2f')}"
351 + (f" (fails {', '.join(failed)})" if failed else "") + " |"
352 )
353 rows += _r_lean14_rows(evaluation_dir)
354 if not rows:
355 return ["_V6.4.0 rule chain has no stage results yet._"]
356 return ["| Lead | Adopted | Median-Sharpe change per variant (every rebalance phase) |", "|---|---|---|", *rows]
359def _l1_lines(evaluation_dir: Path) -> list[str]:
360 report = load_json(evaluation_dir / "v640" / "research.json")
361 stage = report.get("l1") if isinstance(report, dict) else None
362 if not isinstance(stage, dict):
363 return ["_Not run yet: stage `l1` of `scripts/v640_research.py`._"]
364 rows = ["| Split | Dates engaged / vetoed | IC all | IC engaged | IC margin | Sharpe margin (median over phases) |", "|---|---|---|---|---|---|"]
365 for split, skill in (stage.get("skill") or {}).items():
366 margins = (stage.get("margins") or {}).get(split) or {}
367 rows.append(f"| {split}{' (report only)' if split == 'holdout' else ''} | {skill.get('engaged_dates')} / {skill.get('vetoed_dates')} | "
368 f"{_num((skill.get('all') or {}).get('daily_mean_ic'))} | {_num((skill.get('engaged') or {}).get('daily_mean_ic'))} | "
369 f"{_num(margins.get('ic_margin'))} | {_num(margins.get('sharpe_margin'))} |")
370 verdict = stage.get("verdict") or {}
371 rows.append("")
372 rows.append(f"Bar (+0.02 IC and +0.15 Sharpe on both splits): **{verdict.get('reading', 'n/a')}**.")
373 return rows
376def _l2_lines(evaluation_dir: Path) -> list[str]:
377 report = load_json(evaluation_dir / "v640" / "research.json")
378 stage = report.get("l2") if isinstance(report, dict) else None
379 if not isinstance(stage, dict) or not stage.get("heads"):
380 return ["_Not run yet: stage `l2` of `scripts/v640_research.py`._"]
381 rows = ["| Head (direction_20d) | Validation ECE | Log-loss raw -> cross-fitted best | Backtest log-loss raw -> calibrated | Backtest balanced accuracy |",
382 "|---|---|---|---|---|"]
383 for kind, entry in stage["heads"].items():
384 validation = entry.get("validation") or {}
385 cross = {k: v for k, v in (validation.get("cross_fitted_log_loss") or {}).items() if v is not None}
386 best = min(cross, key=cross.get) if cross else None
387 rows.append(f"| {kind}{' (used)' if kind == stage.get('chosen_head') else ''} | {_num(validation.get('ece'), '.4f')} | "
388 f"{_num(validation.get('log_loss'), '.4f')} -> {_num(cross.get(best), '.4f') if best else 'n/a'} ({best or 'n/a'}) | "
389 f"{_num(entry.get('backtest_raw_log_loss'), '.4f')} -> {_num(entry.get('backtest_calibrated_log_loss'), '.4f')} | "
390 f"{_num(entry.get('backtest_balanced_accuracy'), '.3f')} |")
391 return rows
394def _crypto_row(research: dict | None) -> str | None:
395 if not research:
396 return None
397 decision = research.get("decision") or {}
398 config = decision.get("config") or decision.get("best_capped_config")
399 results = research.get("results") or {}
400 name = f"capped {decision.get('per_name_cap')}/{decision.get('class_gross_cap')}"
401 entry = results.get(name) or results.get(config) or {}
402 core = results.get("core_only") or {}
403 drop = None
404 if isinstance(entry.get("backtest"), dict) and isinstance(core.get("backtest"), dict):
405 drop = core["backtest"].get("net_sharpe", 0.0) - entry["backtest"].get("net_sharpe", 0.0)
406 shipped = f"per-name {decision.get('per_name_cap')}, class gross {decision.get('class_gross_cap')}"
407 if decision.get("branch") != "edge_pass":
408 shipped += " (minimum cap + loss guard)"
409 return (
410 f"| Crypto graduates | {decision.get('branch', 'n/a')} | {shipped} | "
411 f"{_num((entry.get('validation') or {}).get('net_sharpe'))} | {_num((entry.get('backtest') or {}).get('net_sharpe'))} | {_num(drop)} |"
412 )
415def _rl_row(research: dict | None) -> str | None:
416 if not research:
417 return None
418 decision = research.get("decision") or {}
419 low, high = (decision.get("range") or [None, None])[:2]
420 guarded = decision.get("shadow_guard", False)
421 sharpe = {}
422 for split in SPLITS:
423 part = (research.get("splits") or {}).get(split) or {}
424 entry = part.get("minimum_range_with_shadow_guard") if guarded else (part.get("ranges") or {}).get(f"{low}-{high}")
425 sharpe[split] = (entry or {}).get("sharpe_gain")
426 shipped = f"range [{low}, {high}]" + (" + shadow guard" if guarded else "")
427 return (
428 f"| RL sizing | {decision.get('branch', 'n/a')} | {shipped} | {_num(sharpe['validation'])} (gain) | "
429 f"{_num(sharpe['backtest'])} (gain) | n/a |"
430 )
433def _topology_row(research: dict | None) -> str | None:
434 if not research:
435 return None
436 decision = research.get("decision") or {}
437 results = research.get("results") or {}
438 mid, off = results.get("on_mid") or {}, results.get("off") or {}
439 shipped = "learned topology ON (shrink-only 0.5..1.0)" if decision.get("topology_learning_enabled", True) else "learned topology OFF"
440 deltas = [
441 (mid.get(split) or {}).get("net_sharpe", float("nan")) - (off.get(split) or {}).get("net_sharpe", float("nan"))
442 for split in SPLITS
443 ]
444 return (
445 f"| Learned topology | {decision.get('branch', 'n/a')} | {shipped} | {_num(deltas[0])} (ON mid vs OFF) | "
446 f"{_num(deltas[1])} (ON mid vs OFF) | n/a |"
447 )
450def _class_ic_lines(evaluation_dir: Path) -> list[str]:
451 reports = _per_split(evaluation_dir, "class_ic_audit")
452 lines: list[str] = []
453 for split, report in reports.items():
454 head = ((report or {}).get("heads") or {}).get("target_return_20d")
455 if not head:
456 continue
457 pooled = head.get("pooled") or {}
458 between = head.get("between_class") or head.get("between") or {}
459 within = head.get("within") or {}
460 parts = ", ".join(
461 f"{name} {_num(stats.get('mean_ic'))} (t {_num(stats.get('hac_t'), '.2f')})" for name, stats in sorted(within.items())
462 )
463 between_ic = between.get("mean_ic") if isinstance(between, dict) else between
464 lines.append(
465 f"| {split} | {_num(pooled.get('mean_ic'))} (t {_num(pooled.get('hac_t'), '.2f')}) | {_num(between_ic)} | {parts or 'n/a'} |"
466 )
467 if not lines:
468 return ["_Not run yet: `aq evaluate --ic-by-class --split validation|backtest`._"]
469 return ["| Split | Pooled rank_20d IC | Between-class IC | Within-class IC (HAC t) |", "|---|---|---|---|", *lines]
472def _gate_lines(evaluation_dir: Path) -> list[str]:
473 reports = _per_split(evaluation_dir, "gate_audit")
474 lines = [
475 f"| {split} | {report.get('num_decisions', 'n/a')} | {_pct(report.get('veto_share'), '.0f')} | "
476 f"{_pct(report.get('false_veto_share_of_vetoes'), '.0f')} | {_num(report.get('mean_forward_ic_vetoed'))} | {_num(report.get('mean_forward_ic_all'))} |"
477 for split, report in reports.items()
478 if report
479 ]
480 if not lines:
481 return ["_Not run yet: `aq evaluate --audit-gates --split validation|backtest`._"]
482 return [
483 "| Split | Rebalance dates | Vetoed | False vetoes (of vetoes) | Forward IC on vetoed dates | Forward IC overall |",
484 "|---|---|---|---|---|---|",
485 *lines,
486 ]
489def _head_line(evaluation_dir: Path) -> str:
490 audit = load_json(evaluation_dir / "head_audit.json")
491 if not isinstance(audit, dict):
492 return "_Not run yet: `aq evaluate --audit-heads`._"
493 failing = audit.get("failing_in_decision_path") or []
494 return (
495 f"**{audit.get('num_passed', 'n/a')}/{audit.get('num_components', 'n/a')}** components pass their own gate; "
496 f"failing and read by the live path: {', '.join(f'`{name}`' for name in failing) if failing else 'none'}."
497 )
500def _holdout_line(evaluation_dir: Path) -> str:
501 report = load_json(evaluation_dir / "holdout_report.json")
502 if not isinstance(report, dict):
503 return "_Not run yet: `python scripts/holdout_report.py` (one look, after the config freeze)._"
504 live = report.get("as_live_book") or {}
505 ideal = report.get("idealized_book") or {}
506 return (
507 f"Window {report.get('first_date', '?')} .. {report.get('last_date', '?')}, {report.get('tickers', '?')} tickers: "
508 f"as-live Sharpe **{_num(live.get('net_sharpe'))}** ({_pct(live.get('net_total_return'))}, drawdown "
509 f"{_pct(live.get('net_max_drawdown'), '.2f')}, {live.get('num_vetoed_rebalances', 'n/a')}/{live.get('num_rebalances', 'n/a')} "
510 f"rebalances vetoed), idealized {_num(ideal.get('net_sharpe'))}."
511 )
514def build_research_markdown(evaluation_dir: Path) -> str:
515 overrides = load_json(evaluation_dir / "lean_decision_overrides.json")
516 overrides = overrides if isinstance(overrides, dict) else {}
517 config = _config_for(evaluation_dir)
518 sleeve_rows = [
519 row
520 for row in (
521 _forex_row_v6(evaluation_dir, config) or _sleeve_row(
522 "Forex sleeve", load_json(evaluation_dir / "class_sleeve_research_forex.json"), "gross 0.10",
523 overrides.get("Forex sleeve"),
524 ),
525 _sleeve_row(
526 "Bond sleeve", load_json(evaluation_dir / "class_sleeve_research_bond.json"), "gross 0.10",
527 overrides.get("Bond sleeve"),
528 ),
529 _crypto_row_v6(evaluation_dir, config) or _crypto_row(load_json(evaluation_dir / "crypto_graduation_research.json")),
530 _rl_row(load_json(evaluation_dir / "rl_sizing_research.json")),
531 _topology_row(load_json(evaluation_dir / "topology_sizing_research.json")),
532 )
533 if row
534 ]
535 sleeves = (
536 [
537 "| Area | Rule branch | Shipped setting | Validation Sharpe | Backtest Sharpe | Book Sharpe cost |",
538 "|---|---|---|---|---|---|",
539 *sleeve_rows,
540 ]
541 if sleeve_rows
542 else ["_Not run yet: `scripts/class_sleeve_research.py`, `crypto_graduation_research.py`, `rl_sizing_research.py`._"]
543 )
544 blocks = [
545 "**Sleeves and overlays** (rule R-SLEEVE: ship at the researched budget when the variant is net-positive on both "
546 "splits and costs the combined book <= 0.05 Sharpe; otherwise ship at the minimum cap with a loss guard). The Sharpe "
547 "columns belong to the named variant (for a minimum-cap area the best-effort one, not the shipped cap); RL rows show "
548 "the Sharpe gain over the same book without RL. A Lean run can overrule the offline branch "
549 "(`lean_decision_overrides.json`); the row then names both.",
550 "\n".join(sleeves),
551 "**Offline simulator against Lean** — " + _calibration_line(evaluation_dir),
552 "**V6.1.0 rule chain** (each variant is one change, scored on every rebalance phase of both splits; the holdout is "
553 "never used to select)",
554 "\n".join(_rule_chain_lines(evaluation_dir)),
555 "**V6.2.0 rule chain** (pre-registered, the T-bill sweep off in every score so alpha is judged ex-carry)",
556 "\n".join(_rule_chain_v620_lines(evaluation_dir)),
557 "**V6.3.0 rule chain** (pre-registered; the kill switch scored on the ungated book with its lock path perturbed by "
558 "0.5 bp noise; T-bill sweep off)",
559 "\n".join(_rule_chain_v630_lines(evaluation_dir)),
560 "**V6.4.0 rule chain** (pre-registered in `scripts/v640_research.py` before any score; as-live unless a lead says ungated; "
561 "the holdout is read only where a lead's bar names it)",
562 "\n".join(_rule_chain_v640_lines(evaluation_dir)),
563 "**L1: does the rank skill sit on the days the gate lets the book trade?**",
564 "\n".join(_l1_lines(evaluation_dir)),
565 "**L2: calibration of the direction heads** (fitted on validation only)",
566 "\n".join(_l2_lines(evaluation_dir)),
567 "**Where the rank edge sits** (pooled vs between-class vs within-class IC against the 20-day return)",
568 "\n".join(_class_ic_lines(evaluation_dir)),
569 "**Rolling-IC gate audit** (a false veto is a vetoed date whose realised book return was positive)",
570 "\n".join(_gate_lines(evaluation_dir)),
571 "**Head promotability** — " + _head_line(evaluation_dir),
572 "**Holdout (looked at once)** — " + _holdout_line(evaluation_dir),
573 ]
574 return "\n\n".join(blocks)
577def _lean_row(label: str, period: dict) -> str:
578 return (
579 f"| {label} | {_num(period.get('sharpe_no_risk_free'))} | {_pct(period.get('net_return'))} | "
580 f"{_pct(period.get('max_drawdown'), '.2f')} |"
581 )
584def build_lean_vs_offline_markdown(evaluation_dir: Path) -> str:
585 """The audited Lean run next to the offline books and the public benchmarks over the SAME dates, one block per
586 window (backtest split, then the holdout). Lean rows come from `backtest_audit.json` `periods`
587 (`aq evaluate --audit-backtest --period START..END`); offline rows from the as-live / holdout / benchmark reports."""
588 audit = load_json(evaluation_dir / "backtest_audit.json")
589 periods = (audit or {}).get("periods") if isinstance(audit, dict) else None
590 if not periods:
591 return (
592 "_Not run yet: `aq evaluate --audit-backtest --backtest-dir <run> --period <backtest split> --period <holdout>`._"
593 )
594 run_id = (audit or {}).get("run_id", "?")
595 as_live = load_json(evaluation_dir / "rank_book_simulation_as_live_backtest.json")
596 as_live = (as_live or {}).get("as_live") if isinstance(as_live, dict) else None
597 ideal_report = load_json(evaluation_dir / "rank_book_simulation_as_live_backtest.json")
598 benchmarks = load_json(evaluation_dir / "benchmark_comparison.json")
599 baselines = {
600 row.get("strategy"): row for row in ((benchmarks or {}).get("baselines") or []) if isinstance(row, dict)
601 } if isinstance(benchmarks, dict) else {}
602 holdout = load_json(evaluation_dir / "holdout_report.json")
603 holdout = holdout if isinstance(holdout, dict) else {}
604 holdout_start = str(holdout.get("first_date") or "2025-07-01")
606 header = ["| Book | Net Sharpe (no risk-free) | Net return | Max drawdown |", "|---|---|---|---|"]
607 blocks: list[str] = []
608 for period in periods:
609 start, end = str(period.get("start", "?")), str(period.get("end", "?"))
610 is_holdout = start >= holdout_start
611 rows = [_lean_row(f"**Lean run `{run_id}`** (engine: fills, fees, slippage)", period)]
612 if is_holdout:
613 live = holdout.get("as_live_book") or {}
614 ideal = holdout.get("idealized_book") or {}
615 rows.append(
616 f"| Offline as-live book | {_num(live.get('net_sharpe'))} | {_pct(live.get('net_total_return'))} | "
617 f"{_pct(live.get('net_max_drawdown'), '.2f')} |"
618 )
619 rows.append(
620 f"| Offline idealized book | {_num(ideal.get('net_sharpe'))} | {_pct(ideal.get('net_total_return'))} | "
621 f"{_pct(ideal.get('net_max_drawdown'), '.2f')} |"
622 )
623 else:
624 if as_live:
625 rows.append(
626 f"| Offline as-live book | {_num(as_live.get('net_sharpe'))} | {_pct(as_live.get('net_total_return'))} | "
627 f"{_pct(as_live.get('net_max_drawdown'), '.2f')} |"
628 )
629 if isinstance(ideal_report, dict) and ideal_report.get("idealized_net_sharpe") is not None:
630 rows.append(
631 f"| Offline idealized book | {_num(ideal_report.get('idealized_net_sharpe'))} | "
632 f"{_pct(ideal_report.get('idealized_net_total_return'))} | n/a |"
633 )
634 for key, label in (("sp500", "S&P 500 buy and hold"), ("60_40", "60/40 buy and hold")):
635 row = baselines.get(key)
636 if row:
637 rows.append(
638 f"| {label} | {_num(row.get('net_sharpe'))} | "
639 f"{_num(row.get('total_return_pct'), '+.2f')}% | n/a |"
640 )
641 blocks.append(f"**{'Holdout' if is_holdout else 'Backtest split'} ({start} to {end})**\n\n" + "\n".join(header + rows))
642 return (
643 "\n\n".join(blocks)
644 + "\n\n_Same dates and the same Sharpe formula in every row; the Lean row is the engine's equity curve, the offline "
645 "rows are simulations. A Lean row far below the as-live row means the offline number did not transfer._"
646 )
649def refresh_readme_best_effort() -> bool:
650 """Re-render every auto-generated README block from what is on disk. Never raises: a report bug must not fail the
651 audit or research script that called it."""
652 try:
653 from generate_evaluation_report import update_readme_evaluation_sections
655 return bool(update_readme_evaluation_sections())
656 except Exception as exc:
657 print(f"warning: README refresh failed: {exc}")
658 return False