Coverage for scripts/promotion_gate_null_calibration.py: 100%
91 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"""V5.3.6 WS-E - promotion-gate null calibration.
3Question: when the model has ZERO skill, how often does the promotion gate
4apparatus (non-overlapping stride-20 t-stat >= 2.0; era sign-flip count)
5still produce alarming readings? Establishes false-positive rates so
6`not_promotable` verdicts can be read against a calibrated null.
8Method: destroy cross-sectional alignment by permuting prediction ranks
9WITHIN each date (preserves marginals, kills signal), then compute per-date
10Spearman IC between prediction-ranks and REAL target ranks over the
11backtest window; derive non-overlapping stride-20 t-stats and per-era mean
12signs; repeat N times.
13"""
15from __future__ import annotations
17import json
18import sys
19from pathlib import Path
21import numpy as np
22import pandas as pd
24ROOT_DIR = Path(__file__).resolve().parents[1]
25sys.path.insert(0, str(ROOT_DIR))
27N_PERMS = 400
28STRIDE = 20
31def main() -> int:
32 ds = pd.read_csv(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv")
33 ds = ds[ds["date"] >= "2019-01-01"]
35 scored = pd.read_csv(ROOT_DIR / "ml" / "evaluation" / "gate_sweep_scored.csv")
36 ds = ds.merge(scored, on=["date", "ticker"], how="inner")
37 ds["target_rank"] = ds.groupby("date")["target_rank_20d"].rank(pct=True)
38 ds["pred_rank"] = ds.groupby("date")["raw_blended_score"].rank(pct=True)
39 ds = ds.dropna(subset=["target_rank", "pred_rank"])
41 dates = sorted(ds["date"].unique())
42 date_idx = {d: i for i, d in enumerate(dates)}
43 n_dates = len(dates)
44 tickers = sorted(ds["ticker"].unique())
45 ticker_idx = {t: i for i, t in enumerate(tickers)}
47 R = np.full((n_dates, len(tickers)), np.nan)
48 T = R.copy()
49 for row in ds.itertuples(index=False):
50 R[date_idx[row.date], ticker_idx[row.ticker]] = row.pred_rank
51 T[date_idx[row.date], ticker_idx[row.ticker]] = row.target_rank
53 counts = (~np.isnan(R) & ~np.isnan(T)).sum(axis=1)
54 valid_dates = counts >= 10
55 print(f"dates with >=10 names: {valid_dates.sum()}/{n_dates}")
57 def ic_series(target_matrix: np.ndarray) -> np.ndarray:
58 out = np.full(n_dates, np.nan)
59 for i in range(n_dates):
60 if not valid_dates[i]:
61 continue
62 r = R[i][~np.isnan(R[i])]
63 t = target_matrix[i][~np.isnan(T[i])] # same names as r: R and T are filled from the same rows
64 rc = r - r.mean()
65 tc = t - t.mean()
66 denom = np.sqrt((rc * rc).sum() * (tc * tc).sum())
67 out[i] = float((rc * tc).sum() / denom) if denom else np.nan
68 return out
70 def t_stat(ic: np.ndarray) -> float:
71 vals = ic[~np.isnan(ic)]
72 vals = vals[::STRIDE]
73 if len(vals) < 3 or vals.std(ddof=1) == 0:
74 return 0.0
75 return float(vals.mean() / vals.std(ddof=1) * np.sqrt(len(vals)))
77 ERA_RANGES = {
78 "era_0_good": ("2019-01-01", "2019-04-01"),
79 "era_1_bad": ("2019-04-01", "2019-09-01"),
80 "era_2_bad": ("2019-12-01", "2020-03-01"),
81 "era_3_bad": ("2020-06-01", "2020-09-01"),
82 "rest": ("1900-01-01", "2099-12-31"),
83 }
84 era_masks = []
85 for name, (a, b) in ERA_RANGES.items():
86 mask = np.zeros(n_dates, dtype=bool)
87 for i, d in enumerate(dates):
88 if a <= d <= b and (name != "rest" or not any(ea <= d <= eb for (ea, eb) in list(ERA_RANGES.values())[:-1])):
89 mask[i] = valid_dates[i]
90 era_masks.append(mask)
92 def era_negative_count(ic: np.ndarray) -> int:
93 signs = []
94 for mask in era_masks[:-1]:
95 vals = ic[mask]
96 vals = vals[~np.isnan(vals)]
97 if len(vals):
98 signs.append(vals.mean() < 0)
99 return int(sum(signs))
101 # Real (unpermuted) baseline
102 real_ic = ic_series(T)
103 real_t = t_stat(real_ic)
104 real_neg = era_negative_count(real_ic)
105 print(f"REAL: t={real_t:.3f} negative_eras={real_neg}")
107 rng = np.random.default_rng(42)
108 t_null, neg_null = [], []
109 T_work = T.copy()
110 for _perm in range(N_PERMS):
111 for i in range(n_dates):
112 if valid_dates[i]:
113 row = T_work[i]
114 finite = ~np.isnan(row)
115 row[finite] = rng.permutation(row[finite])
116 ic = ic_series(T_work)
117 t_null.append(t_stat(ic))
118 neg_null.append(era_negative_count(ic))
119 t_arr = np.array(t_null)
120 neg_arr = np.array(neg_null)
122 summary = {
123 "n_perms": N_PERMS,
124 "stride": STRIDE,
125 "real": {"t_stat": round(real_t, 4), "negative_eras": real_neg},
126 "null_t_stat": {
127 "p50": round(float(np.percentile(t_arr, 50)), 4),
128 "p95": round(float(np.percentile(t_arr, 95)), 4),
129 "p99": round(float(np.percentile(t_arr, 99)), 4),
130 "max": round(float(t_arr.max()), 4),
131 "P(null t>=2.0)": round(float((t_arr >= 2.0).mean()), 4),
132 },
133 "null_negative_eras": {
134 "mode": int(np.bincount(neg_arr).argmax()),
135 "P(null neg>=2)": round(float((neg_arr >= 2).mean()), 4),
136 "P(null neg>=3)": round(float((neg_arr >= 3).mean()), 4),
137 "observed_real_is_unusual": bool(real_neg > np.percentile(neg_arr, 95)),
138 },
139 }
140 out = ROOT_DIR / "ml" / "evaluation" / "promotion_gate_null_calibration.json"
141 out.parent.mkdir(parents=True, exist_ok=True)
142 out.write_text(json.dumps(summary, indent=2), encoding="utf-8")
143 print(json.dumps(summary, indent=2))
144 return 0
147if __name__ == "__main__":
148 sys.exit(main())