Coverage for scripts/overlap_vs_sharpe_analysis.py: 100%
58 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"""Overlap-vs-Lean-Sharpe correlation (ordinal pairing).
3book_history.jsonl segments were appended in wall-clock order and backtest dirs are
4chronological; real runs share the SAME sim window, so window-matching is ambiguous by
5construction. Ordinal pairing of the last-N segments with the last-N completed runs is the
6documented approximation. Segments are never de-duplicated by window: every run is its own
7point (collapsing identical windows merged distinct runs into one, V5.6.0).
8"""
10from __future__ import annotations
12import glob
13import json
14import re
15from pathlib import Path
17import numpy as np
19SHARPE_PATTERN = re.compile(r"STATISTICS:: Sharpe Ratio\s*(-?[\d.]+)")
22def parse_engine_sharpe(log_text: str) -> float | None:
23 values = SHARPE_PATTERN.findall(log_text)
24 return float(values[-1]) if values else None
27def collect_backtest_sharpes(pattern: str = "backtests/2026-*") -> list[tuple[str, float]]:
28 """(directory name, Lean Sharpe) of every chronologically sorted run whose ENGINE log has statistics."""
29 sharpes = []
30 for directory in sorted(glob.glob(pattern)):
31 logs = glob.glob(directory + "/log.txt")
32 if not logs:
33 continue
34 sharpe = parse_engine_sharpe(Path(logs[0]).read_text(encoding="utf-8", errors="ignore"))
35 if sharpe is not None:
36 sharpes.append((Path(directory).name, sharpe))
37 return sharpes
40def segment_overlaps(runs: list[dict]) -> list[tuple[str, str, float, int]]:
41 """One (start, end, mean overlap, n dates) per reconciled run that has any overlap reading."""
42 segments = []
43 for run in runs:
44 meta = run.get("run_metadata", {})
45 if not meta.get("start_date"):
46 continue
47 overlaps = [e["overlap_fraction"] for e in run.get("per_date", []) if e.get("overlap_fraction") is not None]
48 if overlaps:
49 segments.append((meta["start_date"], meta.get("end_date"), float(np.mean(overlaps)), len(overlaps)))
50 return segments
53def pair_ordinally(segments: list, dir_sharpes: list[tuple[str, float]]) -> list[dict]:
54 n = min(len(segments), len(dir_sharpes))
55 rows = []
56 for (start, end, mean_overlap, n_dates), (dir_name, sharpe) in zip(segments[len(segments) - n :], dir_sharpes[len(dir_sharpes) - n :], strict=False):
57 rows.append(
58 {
59 "segment": f"{start}..{end}",
60 "mean_overlap": round(mean_overlap, 4),
61 "n_dates": n_dates,
62 "backtest_dir": dir_name,
63 "lean_sharpe": sharpe,
64 }
65 )
66 return rows
69def main() -> None:
70 import pandas as pd
71 from scipy.stats import spearmanr
73 reconciliation = json.loads(Path("ml/evaluation/book_history_reconciliation.json").read_text(encoding="utf-8"))
74 runs = reconciliation.get("all_runs") or [reconciliation]
75 dir_sharpes = collect_backtest_sharpes()
76 print(f"runs with parsable sharpe: {len(dir_sharpes)}")
77 segments = segment_overlaps(runs)
78 print(f"dated segments with overlap readings: {len(segments)}")
80 rows = pair_ordinally(segments, dir_sharpes)
81 df = pd.DataFrame(rows)
82 print(df.to_string(index=False))
84 result: dict = {"pairs": rows}
85 if len(df) >= 4:
86 rho, pval = spearmanr(df["mean_overlap"], df["lean_sharpe"])
87 result["spearman"] = {"n": int(len(df)), "rho": round(float(rho), 4), "p": round(float(pval), 4)}
88 print(f"\nSpearman(overlap, lean_sharpe): rho={rho:.3f} p={pval:.3f} (n={len(df)})")
89 else:
90 print(f"\nonly {len(df)} paired - inconclusive")
91 Path("ml/evaluation/overlap_vs_sharpe_analysis.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
92 print("written ml/evaluation/overlap_vs_sharpe_analysis.json")
95if __name__ == "__main__":
96 main()