Coverage for scripts/promotion_gate_null_gate_scheme.py: 100%
80 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.7 - null calibration of the promotion gate's era flip-FRACTION under
2the gate's OWN 90-day non-overlapping era scheme
3(train.split_into_non_overlapping_eras semantics, replicated torch-free).
5Question answered: with zero skill, what opposite-sign flip FRACTION does
6the existing max_era_sign_flip_fraction knob need to tolerate so it stops
7blocking statistically-typical noise?
9Method mirrors promotion_gate_null_calibration.py: permute target ranks
10within each date (destroys alignment, preserves marginals), per-date
11Spearman IC series, bucket dates into consecutive era_length_days windows,
12per-era mean IC, count eras opposite to the overall mean sign relative to
13eligible eras (num_dates >= era_min_observations). Real model's own
14fraction reported alongside.
15"""
17from __future__ import annotations
19import json
20import sys
21from pathlib import Path
23import numpy as np
24import pandas as pd
26ROOT_DIR = Path(__file__).resolve().parents[1]
27sys.path.insert(0, str(ROOT_DIR))
29N_PERMS = 400
30ERA_LENGTH_DAYS = 90
31ERA_MIN_OBSERVATIONS = 3
34def main() -> int:
35 ds = pd.read_csv(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv")
36 ds = ds[ds["date"] >= "2019-01-01"]
37 scored = pd.read_csv(ROOT_DIR / "ml" / "evaluation" / "gate_sweep_scored.csv")
38 ds = ds.merge(scored, on=["date", "ticker"], how="inner")
39 ds["target_rank"] = ds.groupby("date")["target_rank_20d"].rank(pct=True)
40 ds["pred_rank"] = ds.groupby("date")["raw_blended_score"].rank(pct=True)
41 ds = ds.dropna(subset=["target_rank", "pred_rank"])
43 dates = sorted(ds["date"].unique())
44 date_idx = {d: i for i, d in enumerate(dates)}
45 tickers = sorted(ds["ticker"].unique())
46 t_idx = {t: i for i, t in enumerate(tickers)}
47 n_dates, n_tickers = len(dates), len(tickers)
49 R = np.full((n_dates, n_tickers), np.nan)
50 T = R.copy()
51 for row in ds.itertuples(index=False):
52 R[date_idx[row.date], t_idx[row.ticker]] = row.pred_rank
53 T[date_idx[row.date], t_idx[row.ticker]] = row.target_rank
54 counts = (~np.isnan(R) & ~np.isnan(T)).sum(axis=1)
55 valid = counts >= 10
57 def ic_series(target: np.ndarray) -> np.ndarray:
58 out = np.full(n_dates, np.nan)
59 for i in range(n_dates):
60 if not valid[i]:
61 continue
62 r = R[i][~np.isnan(R[i])]
63 t = target[i][~np.isnan(T[i])]
64 rc, tc = r - r.mean(), t - t.mean()
65 denom = np.sqrt((rc * rc).sum() * (tc * tc).sum())
66 out[i] = float((rc * tc).sum() / denom) if denom else np.nan
67 return out
69 # Era buckets under the gate's own scheme: consecutive 90-day windows
70 # from the FIRST valid date (split_into_non_overlapping_eras semantics,
71 # train.py:4203).
72 start_ts = pd.Timestamp(dates[0])
73 era_id_for_date = np.array(
74 [(pd.Timestamp(d) - start_ts).days // ERA_LENGTH_DAYS for d in dates]
75 )
76 era_ids = sorted(set(era_id_for_date[valid].tolist()))
78 def flip_fraction(ic: np.ndarray) -> tuple[float, int]:
79 overall_mean = np.nanmean(ic[valid])
80 eligible = opposite = 0
81 for eid in era_ids:
82 mask = (era_id_for_date == eid) & valid & ~np.isnan(ic)
83 vals = ic[mask]
84 if len(vals) < ERA_MIN_OBSERVATIONS:
85 continue
86 eligible += 1
87 era_mean = float(np.mean(vals))
88 if abs(era_mean) >= 0.05 and (
89 (overall_mean > 0 and era_mean < 0) or (overall_mean < 0 and era_mean > 0)
90 ):
91 opposite += 1
92 frac = opposite / eligible if eligible else 0.0
93 return frac, eligible
95 real_ic = ic_series(T)
96 real_frac, n_eras = flip_fraction(real_ic)
98 rng = np.random.default_rng(42)
99 fracs = []
100 T_work = T.copy()
101 for _ in range(N_PERMS):
102 for i in range(n_dates):
103 if valid[i]:
104 row = T_work[i]
105 finite = ~np.isnan(row)
106 row[finite] = rng.permutation(row[finite])
107 frac, _e = flip_fraction(ic_series(T_work))
108 fracs.append(frac)
109 arr = np.array(fracs)
111 summary = {
112 "era_length_days": ERA_LENGTH_DAYS,
113 "n_eras_eligible_real": n_eras,
114 "real_flip_fraction": round(real_frac, 4),
115 "null_flip_fraction": {
116 "p50": round(float(np.percentile(arr, 50)), 4),
117 "p75": round(float(np.percentile(arr, 75)), 4),
118 "p95": round(float(np.percentile(arr, 95)), 4),
119 "max": round(float(arr.max()), 4),
120 },
121 "configured_max_era_sign_flip_fraction": 0.34,
122 "P(null fraction > 0.34)": round(float((arr > 0.34).mean()), 4),
123 "recommended_max": float(min(0.49, round(float(np.percentile(arr, 95)) + 0.01, 2))),
124 "n_perms": N_PERMS,
125 }
126 out = ROOT_DIR / "ml" / "evaluation" / "promotion_gate_null_gate_scheme.json"
127 out.write_text(json.dumps(summary, indent=2), encoding="utf-8")
128 print(json.dumps(summary, indent=2))
129 return 0
132if __name__ == "__main__":
133 sys.exit(main())