Coverage for evaluation/lean_verdict.py: 100%
64 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"""R-LEAN13 (V6.4.0, Problems #221 / #225): is a confirming Lean run of an adopted change kept? Pure given two statistics dicts.
3The adopted book (10-session rebalance, 20-session hold, crypto core only) was decided on the offline simulator, which tracks Lean at a
4daily correlation of ~0.7. One Lean run (BT6) confirms or reverts it, judged against the run that differs only by the change (BT5):
6 (a) the strategy's Sharpe without a risk-free rate (T-bill sweep taken out) is not worse than the baseline's by more than 0.10,
7 (b) the portfolio's maximum drawdown is not worse than the baseline's by more than 1 percentage point,
8 (c) the engine log shows a complete run: statistics written, the interpreter teardown reached, and no model-inference failure.
9 (The teardown TIMEOUT is the PC's, Problems #104/#204, and is reported, not judged.)
11R-LEAN14 (V6.4.2, `--rule superiority`) adopts a change on Lean evidence instead of confirming one: clause (a) becomes "better
12than the baseline by at least the margin" (0.10), (b) and (c) are unchanged.
14Each run's statistics use the config it ran with (`ml/evaluation/run_configs/<run folder>.json`), the root config.json only
15when no frozen copy exists.
16"""
18from __future__ import annotations
20import json
21import re
22from pathlib import Path
23from typing import Any
25MAX_SHARPE_LOSS = 0.10
26MAX_DRAWDOWN_WORSENING = 0.01 # fraction of NAV: 1 percentage point
29def _row(stats: dict[str, Any], section: str, metric: str, column: str):
30 for row in (stats.get("sections") or {}).get(section) or []:
31 if row.get("metric") == metric:
32 return row.get(column)
33 return None
36def strategy_sharpe(stats: dict[str, Any]) -> Any:
37 """The strategy's annualised Sharpe (no risk-free rate) as the Lean report's statistics table prints it."""
38 return _row(stats, "efficiency", "Annualized Sharpe ratio (no risk-free rate)", "strategy")
41def max_drawdown(stats: dict[str, Any]) -> Any:
42 """The portfolio's maximum drawdown as the Lean report's statistics table prints it."""
43 return _row(stats, "runs", "Maximum drawdown", "portfolio")
46def engine_log_status(engine_log_text: str) -> dict[str, Any]:
47 """What a Lean engine log says about a run: whether teardown was reached, inference failures and a timed-out teardown."""
48 return {
49 "teardown_reached": bool(re.search(r"PythonInitializer\.Shutdown\(\): start", engine_log_text)),
50 "inference_failures": len(re.findall(r"inference failed", engine_log_text)),
51 "teardown_timed_out": "Operation timed out" in engine_log_text or "Failed to shutdown python" in engine_log_text,
52 }
55def r_lean13(baseline: dict[str, Any], candidate: dict[str, Any], candidate_engine_log: str) -> dict[str, Any]:
56 """{"checks": {...}, "keep": bool, "values": {...}}; a value that cannot be read fails its clause."""
57 base_sharpe, new_sharpe = strategy_sharpe(baseline), strategy_sharpe(candidate)
58 base_drawdown, new_drawdown = max_drawdown(baseline), max_drawdown(candidate)
59 log = engine_log_status(candidate_engine_log)
60 checks = {
61 "strategy_sharpe_within_0.10": None not in (base_sharpe, new_sharpe) and new_sharpe >= base_sharpe - MAX_SHARPE_LOSS,
62 "max_drawdown_within_1pp": None not in (base_drawdown, new_drawdown) and new_drawdown <= base_drawdown + MAX_DRAWDOWN_WORSENING,
63 "complete_run_no_inference_failure": candidate.get("status") == "OK" and log["teardown_reached"] and log["inference_failures"] == 0,
64 }
65 return {
66 "checks": checks, "keep": all(checks.values()),
67 "values": {"baseline_strategy_sharpe": base_sharpe, "candidate_strategy_sharpe": new_sharpe,
68 "baseline_max_drawdown": base_drawdown, "candidate_max_drawdown": new_drawdown, "engine_log": log},
69 }
72def r_lean14(baseline: dict[str, Any], candidate: dict[str, Any], candidate_engine_log: str, margin: float = MAX_SHARPE_LOSS) -> dict[str, Any]:
73 """R-LEAN13 with clause (a) turned into superiority: the strategy Sharpe must beat the baseline's by `margin`."""
74 result = r_lean13(baseline, candidate, candidate_engine_log)
75 base_sharpe, new_sharpe = result["values"]["baseline_strategy_sharpe"], result["values"]["candidate_strategy_sharpe"]
76 checks = dict(result["checks"])
77 checks.pop("strategy_sharpe_within_0.10")
78 checks = {f"strategy_sharpe_above_by_{margin:.2f}": None not in (base_sharpe, new_sharpe) and new_sharpe >= base_sharpe + margin,
79 **checks}
80 return dict(result, checks=checks, keep=all(checks.values()))
83RULES = {"non_inferiority": ("R-LEAN13", r_lean13), "superiority": ("R-LEAN14", r_lean14)}
86def run_config(run_dir: Path, root: Path, fallback: dict[str, Any]) -> dict[str, Any]:
87 """The config a run was frozen with (`ml/evaluation/run_configs/<folder>.json`), else `fallback`."""
88 frozen = Path(root) / "ml" / "evaluation" / "run_configs" / f"{Path(run_dir).name}.json"
89 return json.loads(frozen.read_text(encoding="utf-8")) if frozen.exists() else fallback
92def verdict_for_run_dirs(baseline_dir: Path, candidate_dir: Path, config: dict[str, Any], root: Path, rule: str = "non_inferiority",
93 margin: float = MAX_SHARPE_LOSS) -> dict[str, Any]:
94 """Statistics of both run folders (`backtest_statistics.compute_for_run_dir`, each with its own frozen config) and the
95 candidate's engine log."""
96 from evaluation.backtest_statistics import compute_for_run_dir
98 baseline = compute_for_run_dir(Path(baseline_dir), run_config(baseline_dir, root, config), Path(root))
99 candidate = compute_for_run_dir(Path(candidate_dir), run_config(candidate_dir, root, config), Path(root))
100 log_path = Path(candidate_dir) / "log.txt"
101 log = log_path.read_text(encoding="utf-8", errors="replace") if log_path.exists() else ""
102 name, judge = RULES[rule]
103 result = judge(baseline, candidate, log, margin) if rule == "superiority" else judge(baseline, candidate, log)
104 result.update(rule=name, baseline=Path(baseline_dir).name, candidate=Path(candidate_dir).name)
105 return result
108def main(argv: list[str] | None = None) -> int:
109 import argparse
111 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
112 parser.add_argument("--baseline", required=True, help="the run that differs only by the change (BT5)")
113 parser.add_argument("--candidate", required=True, help="the confirming run (BT6)")
114 parser.add_argument("--out", default="ml/evaluation/v640/r_lean13.json")
115 parser.add_argument("--rule", choices=sorted(RULES), default="non_inferiority",
116 help="non_inferiority (R-LEAN13, confirm an adopted change) or superiority (R-LEAN14, adopt one)")
117 parser.add_argument("--margin", type=float, default=MAX_SHARPE_LOSS, help="the superiority rule's Sharpe margin")
118 args = parser.parse_args(argv)
119 root = Path(__file__).resolve().parents[1]
120 config = json.loads((root / "config.json").read_text(encoding="utf-8"))
121 result = verdict_for_run_dirs(root / args.baseline, root / args.candidate, config, root, args.rule, args.margin)
122 out = root / args.out
123 out.parent.mkdir(parents=True, exist_ok=True)
124 out.write_text(json.dumps(result, indent=2, default=str), encoding="utf-8")
125 print(json.dumps(result, indent=2, default=str))
126 return 0 if result["keep"] else 1
129if __name__ == "__main__":
130 raise SystemExit(main())