Coverage for evaluation/sim_lean_calibration.py: 100%
43 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"""Where does the offline simulator part ways with Lean? (V6.4.3, rule R-CAL4)
3`scripts/lean_calibration.py` runs the as-live simulator as a ladder of increasingly live-like variants against a
4finished Lean run. This module reads such a report and decomposes what is left of the gap:
6- `rung_attribution`: the daily-correlation and return-gap change each rung of the ladder buys, so the mechanism that
7 closes most of the gap (cadence phase, next-open fills, fee floor, live gates, topology sizing, ...) is named;
8- `daily_gap_breakdown`: on two aligned daily return series, the tracking error, the share of the squared gap carried
9 by the worst days, the gap's autocorrelation (a persistent gap is a modelling difference, a noisy one is fills) and
10 the gap on rebalance days against the days in between;
11- `gap_report`: both for every window of a calibration report.
12Pure; no I/O.
13"""
15from __future__ import annotations
17from typing import TYPE_CHECKING, Any
19import numpy as np
21if TYPE_CHECKING:
22 from collections.abc import Iterable, Sequence
24LADDER_ORDER = ("v580", "phase", "next_open", "min_fee", "live_gates", "calibrated", "v610_member_pass", "v610_mechanisms", "v610")
27def rung_attribution(variants: dict[str, dict], order: Sequence[str]=LADDER_ORDER) -> list[dict]:
28 """[{"rung", "daily_correlation", "delta_correlation", "annual_return_gap", "delta_gap"}] along the ladder."""
29 rows, previous = [], None
30 for name in order:
31 row = variants.get(name)
32 if not row:
33 continue
34 correlation, gap = row.get("daily_correlation"), row.get("annual_return_gap")
35 entry = {"rung": name, "daily_correlation": correlation, "annual_return_gap": gap,
36 "decision_agreement": row.get("decision_agreement"), "weight_l1": row.get("weight_l1"),
37 "name_overlap": row.get("name_overlap")}
38 if previous is not None:
39 entry["delta_correlation"] = (correlation - previous["daily_correlation"]
40 if correlation is not None and previous["daily_correlation"] is not None else None)
41 entry["delta_gap"] = (abs(gap) - abs(previous["annual_return_gap"])
42 if gap is not None and previous["annual_return_gap"] is not None else None)
43 rows.append(entry)
44 previous = entry
45 return rows
48def daily_gap_breakdown(lean: dict[str, float], offline: dict[str, float], *, rebalance_dates: Iterable[str]=(), worst_share: float = 0.05) -> dict[str, Any]:
49 """Statistics of the daily gap offline - lean over their common dates."""
50 common = sorted(set(lean) & set(offline))
51 if len(common) < 3:
52 return {"days": len(common)}
53 a = np.array([offline[d] for d in common], dtype=float)
54 b = np.array([lean[d] for d in common], dtype=float)
55 gap = a - b
56 squared = gap**2
57 k = max(1, int(round(len(gap) * worst_share)))
58 worst = np.argsort(squared)[::-1][:k]
59 rebalance = np.array([d in set(rebalance_dates) for d in common])
60 autocorrelation = float(np.corrcoef(gap[:-1], gap[1:])[0, 1]) if gap[:-1].std() > 0 and gap[1:].std() > 0 else None
61 out = {
62 "days": len(common),
63 "daily_correlation": float(np.corrcoef(a, b)[0, 1]) if a.std() > 0 and b.std() > 0 else None,
64 "tracking_error_annual": float(gap.std(ddof=1) * np.sqrt(252)),
65 "mean_gap_annual": float(gap.mean() * 252),
66 "worst_days_share_of_squared_gap": float(squared[worst].sum() / squared.sum()) if squared.sum() > 0 else 0.0,
67 "worst_days": [{"date": common[i], "offline": float(a[i]), "lean": float(b[i])} for i in worst[:10]],
68 "gap_autocorrelation": autocorrelation,
69 }
70 if rebalance.any() and (~rebalance).any():
71 out["mean_abs_gap_rebalance_days"] = float(np.abs(gap[rebalance]).mean())
72 out["mean_abs_gap_other_days"] = float(np.abs(gap[~rebalance]).mean())
73 return out
76def gap_report(calibration: dict[str, Any], *, variant: str = "calibrated") -> dict[str, Any]:
77 """{window: {"ladder": rung_attribution, "best_rung", "judged": the `variant` row}} for a lean_calibration.py report."""
78 out = {}
79 for name, window in (calibration.get("windows") or {}).items():
80 variants = window.get("variants") or {}
81 ladder = rung_attribution(variants)
82 scored = [row for row in ladder if row.get("daily_correlation") is not None]
83 out[name] = {
84 "ladder": ladder,
85 "best_rung": max(scored, key=lambda row: row["daily_correlation"])["rung"] if scored else None,
86 "judged": variants.get(variant),
87 }
88 return out