Coverage for evaluation/rank_ic_core.py: 100%
81 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.5 (development/Problems.md #102) - the genuinely light, torch-free
2core of this codebase's rank-IC pipeline (correlation math + realized-
3outcome resolution + aggregation), extracted so `main.py`'s live/backtest
4decision path can import it directly with zero risk of pulling in the
5training stack.
7Before this module existed, the only home for this logic was split
8across `train.py::_rank_ic_from_arrays()` (imports `torch`/`sklearn` at
9module scope) and `performance/rank_ic_monitor.py` (imports
10`train._rank_ic_from_arrays`, and is itself imported transitively by
11`performance/__init__.py` via `.trigger_worker` - so even `from
12performance import anything` drags in the full training stack). `main.py`
13already hit and documented this exact class of failure once
14(development/Problems.md #16 - Lean's hard, non-configurable 90-second
15`Initialize()` isolator timeout) and has a standing deferred-import
16workaround for the `performance` package specifically because of it. A
17new live rolling-IC gate (`portfolio/rolling_ic_gate.py`) needs this same
18math available as a genuinely safe top-level import.
20`train.py::_rank_ic_from_arrays()` and `performance/rank_ic_monitor.py`'s
21two functions are now thin re-export aliases over this module - moved,
22not duplicated. Every existing caller (train.py's own IC call sites,
23performance/trigger_worker.py, and every test importing either) keeps
24working unchanged.
25"""
27from __future__ import annotations
29import bisect
30from collections import defaultdict
31from typing import TYPE_CHECKING, Any
33import numpy as np
34import pandas as pd
36if TYPE_CHECKING:
37 from numpy.typing import ArrayLike
40def rank_ic_from_arrays(
41 predictions: np.ndarray,
42 targets: np.ndarray,
43 dates: np.ndarray,
44 non_overlapping_stride: int = 1,
45 min_names_per_date: int = 2,
46) -> dict[str, Any]:
47 """Per-date Spearman rank correlation ("rank-IC") between a model's raw
48 rank_5d/20d prediction score and the realized cross-sectional rank
49 target (target_rank_5d/20d - already a per-date percentile rank of
50 forward return, see train.py::build_cross_sectional_rank_targets()).
51 This is the standard evaluation metric for a cross-sectional/long-short
52 signal: a mean rank-IC of 0.02-0.05 with a real t-stat is a genuine,
53 monetizable edge in this literature.
55 Spearman(A, B) = Pearson(rank(A), rank(B)); target_rank is already
56 rank(realized return) rescaled to [0, 1] (a positive affine transform,
57 which Pearson is invariant to), so only the model's own raw prediction
58 needs an explicit per-date rank transform before a plain Pearson
59 correlation against target_rank directly reproduces the true Spearman
60 correlation between prediction and realized return.
62 `non_overlapping_stride` (e.g. 5 for the 5d horizon, 20 for the 20d
63 horizon) subsamples to every Nth unique date before computing -
64 consecutive daily rows share most of their forward-return window, so
65 the naive daily IC series is autocorrelated and its plain t-stat
66 overstates significance; the non-overlapping subsample gives a more
67 honest (if noisier, fewer-observation) significance check. Pass 1
68 (default) for the full, autocorrelated series.
70 `min_names_per_date` (V5.3.5, development/Problems.md #102) - default 2
71 reproduces this function's original behavior exactly (train.py's/
72 performance/rank_ic_monitor.py's existing callers are unaffected). A
73 date with exactly 2 names is mathematically FORCED to a Pearson
74 correlation of either +1 or -1 (two points always fit a line, tie
75 aside) - a legitimate computation, but statistically uninformative,
76 and it gets averaged into mean_ic with the exact same weight as a
77 date with 100 names. portfolio/rolling_ic_gate.py's offline
78 calibration/replay tools raise this well above 2 specifically because
79 a walk-forward rolling-IC distribution's early, thin-universe dates
80 were found (V5.3.5, real data) to produce spurious +-1 readings that
81 dominate the low end of the distribution.
83 Dates with fewer than `min_names_per_date` eligible (non-NaN target)
84 assets, or zero variance on either side (e.g. every asset tied),
85 contribute no IC value for that date (skipped, not a spurious 0.0 -
86 which would misrepresent "undefined" as "no correlation")."""
87 frame = pd.DataFrame({"date": np.asarray(dates), "prediction": predictions, "target_rank": targets})
88 frame = frame.dropna(subset=["target_rank"])
90 if non_overlapping_stride > 1:
91 unique_dates = sorted(frame["date"].unique())
92 keep_dates = set(unique_dates[::non_overlapping_stride])
93 frame = frame[frame["date"].isin(keep_dates)]
95 ic_values = []
96 for _, group in frame.groupby("date"):
97 if len(group) < min_names_per_date:
98 continue
99 prediction_rank = group["prediction"].rank(pct=True)
100 if prediction_rank.nunique() < 2 or group["target_rank"].nunique() < 2:
101 continue
102 correlation = float(np.corrcoef(prediction_rank, group["target_rank"])[0, 1])
103 if not np.isnan(correlation):
104 ic_values.append(correlation)
106 if not ic_values:
107 return {"mean_ic": 0.0, "std_ic": 0.0, "t_stat": 0.0, "num_dates": 0, "ic_values": []}
109 ic_array = np.asarray(ic_values)
110 mean_ic = float(ic_array.mean())
111 std_ic = float(ic_array.std(ddof=1)) if len(ic_array) >= 2 else 0.0
112 t_stat = float(mean_ic / (std_ic / np.sqrt(len(ic_array)))) if std_ic > 0 else 0.0
113 return {
114 "mean_ic": mean_ic,
115 "std_ic": std_ic,
116 "t_stat": t_stat,
117 "num_dates": int(len(ic_array)),
118 "ic_values": [float(value) for value in ic_values],
119 }
122def newey_west_t_stat(values: ArrayLike, lags: int) -> float:
123 """HAC (Newey-West, Bartlett weights) t-statistic of the mean of a daily IC series. Consecutive daily ICs of an
124 h-day-horizon signal share most of their forward window, so the plain t-stat overstates significance; the
125 non-overlapping subsample is honest but throws away (h-1)/h of the dates (14 of 261 on the validation split).
126 `lags` ~ horizon - 1. Returns 0.0 when fewer than 2 finite values or no variance."""
127 series = np.asarray([float(value) for value in values if value is not None and np.isfinite(value)], dtype=float)
128 n = len(series)
129 if n < 2:
130 return 0.0
131 mean = float(series.mean())
132 centered = series - mean
133 long_run_variance = float(centered @ centered) / n
134 for lag in range(1, min(int(lags), n - 1) + 1):
135 weight = 1.0 - lag / (int(lags) + 1.0)
136 long_run_variance += 2.0 * weight * float(centered[lag:] @ centered[:-lag]) / n
137 # a constant series has float-noise variance (~1e-33), which would read as an enormous t
138 if long_run_variance <= 1e-18:
139 return 0.0
140 return mean / float(np.sqrt(long_run_variance / n))
143def resolve_realized_rank_ic_observations(events: list[dict], horizon_days: int = 20) -> list[dict]:
144 """Resolves each event's `resolved_predicted_rank_20d` against its own
145 ticker's close price `horizon_days` TRADING days later (i.e.
146 `horizon_days` positions ahead in that ticker's own date-sorted event
147 sequence). Events missing either `resolved_predicted_rank_20d` or
148 `close_price` (model unavailable/still warming up that bar), or whose
149 horizon hasn't elapsed yet (not enough future events for that ticker),
150 are silently skipped - never raises. `created_at` is truncated to its
151 date component (`"YYYY-MM-DDTHH:MM:SSZ"[:10]`), matching
152 experience/redis_queue.py::build_experience_event()'s ISO-8601 format.
154 Returns one dict per resolved observation:
155 `{"ticker", "origin_date", "mode", "resolved_predicted_rank_20d",
156 "realized_return_20d", "realized_rank_20d"}` - the last field is the
157 per-origin-date cross-sectional percentile rank of `realized_return_20d`
158 (pandas `.rank(pct=True)`, same convention as
159 train.py::build_cross_sectional_rank_targets()'s target-side ranking),
160 computed once every usable event has been resolved."""
161 usable = [
162 event
163 for event in events
164 if event.get("resolved_predicted_rank_20d") is not None and event.get("close_price") is not None
165 ]
166 if not usable:
167 return []
169 dated_closes_by_ticker: dict[str, list[tuple]] = defaultdict(list)
170 for event in usable:
171 origin_date = str(event["created_at"])[:10]
172 dated_closes_by_ticker[event["ticker"]].append((origin_date, float(event["close_price"])))
173 for dated_closes in dated_closes_by_ticker.values():
174 dated_closes.sort(key=lambda entry: entry[0])
176 resolved: list[dict] = []
177 for event in usable:
178 ticker = event["ticker"]
179 origin_date = str(event["created_at"])[:10]
180 dated_closes = dated_closes_by_ticker[ticker]
181 dates_only = [entry[0] for entry in dated_closes]
182 position = bisect.bisect_left(dates_only, origin_date) # the event's own date is in `dates_only`, so this is its first row
184 future_position = position + horizon_days
185 if future_position >= len(dated_closes):
186 continue
188 origin_close = dated_closes[position][1]
189 _future_date, future_close = dated_closes[future_position]
190 if origin_close <= 0:
191 continue
193 resolved.append(
194 {
195 "ticker": ticker,
196 "origin_date": origin_date,
197 "mode": event.get("mode"),
198 "resolved_predicted_rank_20d": float(event["resolved_predicted_rank_20d"]),
199 "realized_return_20d": future_close / origin_close - 1.0,
200 }
201 )
203 if not resolved:
204 return []
206 frame = pd.DataFrame(resolved)
207 frame["realized_rank_20d"] = frame.groupby("origin_date")["realized_return_20d"].rank(pct=True)
208 return frame.to_dict(orient="records")
211def aggregate_rank_ic_observations(
212 observations: list[dict], non_overlapping_stride: int = 1, min_names_per_date: int = 2
213) -> dict[str, Any]:
214 """Runs rank_ic_from_arrays() over resolve_realized_rank_ic_observations()'s
215 output - shares the exact same tested correlation core every other IC
216 metric in this codebase goes through. `min_names_per_date` - see
217 rank_ic_from_arrays()'s own docstring; default 2 preserves this
218 function's original behavior exactly."""
219 if not observations:
220 return {"mean_ic": 0.0, "std_ic": 0.0, "t_stat": 0.0, "num_dates": 0, "ic_values": []}
222 predictions = np.array([observation["resolved_predicted_rank_20d"] for observation in observations])
223 targets = np.array([observation["realized_rank_20d"] for observation in observations])
224 dates = np.array([observation["origin_date"] for observation in observations])
225 return rank_ic_from_arrays(
226 predictions, targets, dates, non_overlapping_stride=non_overlapping_stride, min_names_per_date=min_names_per_date
227 )