Coverage for evaluation/feature_parity.py: 100%
159 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 Workstream A - the train-vs-live feature-parity audit's pure core.
3Background (development/Problems.md #91/#98/#100 lineage): XOM is the one
4tracked ticker whose live-vs-offline book-selection mismatch never resolved,
5and two prior root causes WERE feature-computation drifts between the
6offline training pipeline and the live Lean path (the bond duration-beta's
7rolling-vs-full-history drift, V5.2.5; missing split/dividend factor files,
8#100). This module is the systematic version of those one-off checks: for
9every model-input feature family that can be recomputed from data already
10on disk, it re-derives the RAW value and pushes it through the shipped
11scaler artifact (`ml/scaler_stats.json`) in the forward direction -
12`clip((raw - mean) / scale, +-clip_sigma)` - comparing against the scaled
13column actually stored in `ml/datasets/full_dataset.csv`.
15Three layers are covered here:
161. **Scaler-artifact consistency** - does `scaler_stats.json` still describe
17 the dataset it is supposed to scale? (A stale artifact after a dataset
18 rebuild would mis-scale live inference systemically - an XOM-class bug.)
192. **Formula parity** - the per-ticker OHLCV-recomputable families (10 base
20 technicals + 6 shared indicators + 2 liquidity) re-derived row-faithfully
21 from `train.py::engineer_features()` / `add_liquidity_features()`.
223. **Cross-sectional + macro families** - cs_momentum_rank_20 and the three
23 macro proxies, rebuilt from a close-price pivot using the same shared
24 functions both sides import.
26Families deliberately NOT recomputable offline (regime payload chain, alt-
27data FRED inputs, cross-asset sensitivity regressions' driver series, bond
28treasury inputs, topology/peer correlation graphs) get structured verdicts
29from the driver instead: "SHARED_FUNCTION_CALLSITE" where both sides call
30one `features/*.py` function (verified by inspection), so the residual risk
31is call-site parameters only.
33Pure: no I/O, no torch, no Lean imports - mirrors the repo's established
34"pure core + thin CLI driver" convention (see feature_reconciliation.py).
35"""
37from __future__ import annotations
39from typing import Any
41import numpy as np
42import pandas as pd
44from features.macro_features import (
45 credit_spread_proxy,
46 crypto_risk_appetite_proxy,
47 yield_curve_slope_proxy,
48)
49from features.technical_indicators import (
50 average_true_range_pct,
51 bollinger_pctb,
52 cross_sectional_momentum_rank,
53 distance_from_52w_high,
54 macd_histogram_normalized,
55 relative_strength_index,
56 volume_zscore,
57)
58from liquidity.market_liquidity import estimate_high_low_spread
60DEFAULT_LONG_LOOKBACK_WINDOW_BARS = 260
61DEFAULT_CROSS_SECTIONAL_WINDOW_BARS = 25
63BASE_TECHNICAL_FEATURES = [
64 "close_to_close_return_1d",
65 "close_to_close_return_5d",
66 "close_to_close_return_20d",
67 "rolling_volatility_5d",
68 "rolling_volatility_20d",
69 "momentum_5d",
70 "momentum_20d",
71 "high_low_range_pct",
72 "open_close_range_pct",
73 "volume_change_1d",
74]
75INDICATOR_FEATURES = [
76 "rsi_14",
77 "atr_pct_14",
78 "bollinger_pctb_20",
79 "volume_zscore_20",
80 "macd_histogram_norm",
81 "dist_52w_high",
82]
83LIQUIDITY_FEATURES = ["liquidity_log_dollar_volume", "liquidity_spread_proxy"]
84MACRO_PROXIES_BY_KEY = {
85 "long_duration": ("macro_yield_curve_slope_proxy", yield_curve_slope_proxy),
86 "high_yield": ("macro_credit_spread_proxy", credit_spread_proxy),
87 "crypto": ("macro_crypto_risk_appetite_proxy", crypto_risk_appetite_proxy),
88}
89DEFAULT_MACRO_REFERENCE_TICKERS = {
90 "long_duration": "TLT",
91 "short_duration": "SHY",
92 "high_yield": "HYG",
93 "investment_grade": "LQD",
94 "crypto": "BTCUSD",
95}
98def load_scaler_mapping(scaler_stats: dict[str, Any]) -> tuple[dict[str, tuple[float, float, float]], list[str]]:
99 """Maps `ml/scaler_stats.json` into {feature_name: (mean, scale, clip)}
100 and reports which schema names it does NOT cover (by design: the binary
101 regime/topology/asset-class one-hots skip StandardScaler entirely)."""
102 names = list(scaler_stats["feature_names"])
103 means = scaler_stats["mean"]
104 scales = scaler_stats["scale"]
105 clip = float(scaler_stats.get("clip_sigma", 10.0))
106 mapping = {name: (float(means[i]), float(scales[i]), clip) for i, name in enumerate(names)}
107 return mapping, []
110def forward_scale(raw_values: np.ndarray, mean: float, scale: float, clip: float) -> np.ndarray:
111 """The exact live/offline transform: clip((raw - mean) / scale, +-clip)."""
112 return np.clip((np.asarray(raw_values, dtype=float) - mean) / scale, -clip, clip)
115def compute_base_technicals_replica(frame: pd.DataFrame, *, long_window_bars: int = DEFAULT_LONG_LOOKBACK_WINDOW_BARS) -> dict[str, np.ndarray]:
116 """Row-faithful replica of train.py::engineer_features()'s inline base
117 technicals + Phase-6 indicator block (train.py:656-748), which itself is
118 line-mirrored by main.py::_build_model_input() (both files carry explicit
119 cross-reference comments asserting parity). First row is NaN exactly like
120 train's `[np.nan]` seed convention; volatility degrades to 0.0 under two
121 observations exactly like train's guard."""
122 closes = frame["close"].tolist()
123 opens = frame["open"].tolist()
124 highs = frame["high"].tolist()
125 lows = frame["low"].tolist()
126 volumes = frame["volume"].tolist()
127 n = len(frame)
129 columns: dict[str, list[float]] = {
130 **{name: [np.nan] for name in BASE_TECHNICAL_FEATURES},
131 **{name: [np.nan] for name in INDICATOR_FEATURES},
132 }
134 for index in range(1, n):
135 previous_close = closes[index - 1]
136 previous_volume = volumes[index - 1]
137 current_close = closes[index]
138 current_open = opens[index]
140 close_5 = closes[max(0, index - 5)]
141 close_20 = closes[max(0, index - 20)]
143 all_recent_returns = [
144 closes[position] / closes[position - 1] - 1.0
145 for position in range(1, index + 1)
146 if closes[position - 1] != 0
147 ]
148 recent_returns_5 = all_recent_returns[-5:]
149 recent_returns_20 = all_recent_returns[-20:]
151 def _sample_std(values: list[float]) -> float:
152 if len(values) < 2:
153 return 0.0
154 mean_value = sum(values) / len(values)
155 variance = sum((value - mean_value) ** 2 for value in values) / (len(values) - 1)
156 return float(np.sqrt(max(variance, 0.0)))
158 columns["close_to_close_return_1d"].append(current_close / previous_close - 1.0 if previous_close else 0.0)
159 columns["close_to_close_return_5d"].append(current_close / close_5 - 1.0 if close_5 else 0.0)
160 columns["close_to_close_return_20d"].append(current_close / close_20 - 1.0 if close_20 else 0.0)
161 columns["rolling_volatility_5d"].append(_sample_std(recent_returns_5))
162 columns["rolling_volatility_20d"].append(_sample_std(recent_returns_20))
163 columns["momentum_5d"].append(current_close / close_5 - 1.0 if close_5 else 0.0)
164 columns["momentum_20d"].append(current_close / close_20 - 1.0 if close_20 else 0.0)
165 columns["high_low_range_pct"].append((highs[index] - lows[index]) / current_close if current_close else 0.0)
166 columns["open_close_range_pct"].append((current_close - current_open) / current_open if current_open else 0.0)
167 raw_volume_change = 0.0 if previous_volume == 0 else volumes[index] / previous_volume - 1.0
168 columns["volume_change_1d"].append(max(-1.0, min(20.0, raw_volume_change)))
170 trailing_closes = closes[: index + 1]
171 columns["rsi_14"].append(relative_strength_index(trailing_closes, period=14))
172 columns["atr_pct_14"].append(
173 average_true_range_pct(highs[: index + 1], lows[: index + 1], trailing_closes, period=14)
174 )
175 columns["bollinger_pctb_20"].append(bollinger_pctb(trailing_closes, period=20))
176 columns["volume_zscore_20"].append(volume_zscore(volumes[: index + 1], period=20))
178 long_window_start = max(0, index + 1 - long_window_bars)
179 long_trailing_closes = closes[long_window_start : index + 1]
180 columns["macd_histogram_norm"].append(macd_histogram_normalized(long_trailing_closes))
181 columns["dist_52w_high"].append(distance_from_52w_high(long_trailing_closes, window=long_window_bars))
183 return {name: np.asarray(values, dtype=float) for name, values in columns.items()}
186def compute_liquidity_replica(
187 frame: pd.DataFrame,
188 *,
189 security_type: str = "equity",
190 cross_sectional_window_bars: int = DEFAULT_CROSS_SECTIONAL_WINDOW_BARS,
191 typical_spread_by_type: dict[str, float] | None = None,
192) -> dict[str, np.ndarray]:
193 """Row-faithful replica of train.py::add_liquidity_features()
194 (train.py:946-988): log1p dollar volume plus the Corwin-Schultz spread
195 proxy over a trailing window, static-spread fallback below two bars."""
196 from liquidity.market_liquidity import TYPICAL_SPREAD_BY_TYPE
198 spreads = typical_spread_by_type or TYPICAL_SPREAD_BY_TYPE
199 fallback = float(spreads.get(str(security_type), 0.001))
200 closes = frame["close"].tolist()
201 volumes = frame["volume"].tolist()
202 highs = frame["high"].tolist()
203 lows = frame["low"].tolist()
205 log_dollar_volume: list[float] = []
206 spread_proxy: list[float] = []
207 for index in range(len(frame)):
208 log_dollar_volume.append(float(np.log1p(max(closes[index] * volumes[index], 0.0))))
209 window_start = max(0, index + 1 - cross_sectional_window_bars)
210 window_highs = highs[window_start : index + 1]
211 window_lows = lows[window_start : index + 1]
212 estimated = estimate_high_low_spread(window_highs, window_lows) if len(window_highs) >= 2 else None
213 spread_proxy.append(float(estimated) if estimated is not None else fallback)
215 return {
216 "liquidity_log_dollar_volume": np.asarray(log_dollar_volume, dtype=float),
217 "liquidity_spread_proxy": np.asarray(spread_proxy, dtype=float),
218 }
221_MIDNIGHT_SECURITY_TYPES = ("crypto", "forex")
224def forex_calendar_momentum_rows(frame: pd.DataFrame, ticker: str, holidays: frozenset[int] = frozenset()) -> pd.DataFrame:
225 """(date, ticker, momentum_20d) for one forex pair on Lean's fill-forward calendar (flat bars on open days without
226 a row, features/cross_asset_timing.py), INCLUDING the filler rows: live's forex pool holds Sunday's flat-bar
227 momentum at Monday's equity tick, which no dataset row carries. `frame` needs `date` and `close`."""
228 from features.cross_asset_timing import day_ordinal, fill_forward_open_forex_days
230 ordered = frame.sort_values("date")
231 ordinals, closes = fill_forward_open_forex_days(
232 [day_ordinal(stamp) for stamp in ordered["date"]], ordered["close"].tolist(), holidays
233 )
234 momentum = [float("nan")] + [
235 closes[i] / closes[max(0, i - 20)] - 1.0 if closes[max(0, i - 20)] else float("nan") for i in range(1, len(closes))
236 ]
237 return pd.DataFrame({"date": [pd.Timestamp.fromordinal(o) for o in ordinals], "ticker": ticker, "momentum_20d": momentum})
240def build_momentum_pool(
241 dataset: pd.DataFrame, security_types: dict[str, str] | None, forex_holidays: frozenset[int] = frozenset()
242) -> pd.DataFrame:
243 """(date, ticker, momentum_20d) for the cross-asset replicas: each ticker's stored momentum_20d, except forex pairs,
244 whose momentum is re-derived on Lean's fill-forward calendar WITH the filler rows (forex_calendar_momentum_rows)."""
245 security_types = security_types or {}
246 stored = dataset[["date", "ticker", "momentum_20d"]]
247 forex_tickers = {ticker for ticker, kind in security_types.items() if kind == "forex"}
248 parts = [stored[~stored["ticker"].isin(forex_tickers)]]
249 for ticker in forex_tickers:
250 rows = dataset[dataset["ticker"] == ticker]
251 if not rows.empty:
252 parts.append(forex_calendar_momentum_rows(rows.assign(date=pd.to_datetime(rows["date"])), ticker, forex_holidays))
253 result = pd.concat(parts, ignore_index=True)
254 result["date"] = pd.to_datetime(result["date"])
255 return result
258def _momentum_arrays(momentum_long: pd.DataFrame, security_types: dict[str, str] | None) -> dict[str, tuple[np.ndarray, np.ndarray]]:
259 """ticker -> (availability keys, stored momentum_20d) on each ticker's OWN rows. A daily bar is visible once its
260 period closed: equity at that day's close (ordinal + 0.5), crypto/forex at the next midnight (ordinal + 1.0).
261 The stored column (computed on the raw, pre-dropna history) is used rather than re-deriving momentum from the
262 dataset's closes, which have holes where the label guard dropped rows."""
263 security_types = security_types or {}
264 arrays: dict[str, tuple[np.ndarray, np.ndarray]] = {}
265 for ticker, group in momentum_long.groupby("ticker", sort=False):
266 group = group.sort_values("date")
267 ordinals = np.array([pd.Timestamp(stamp).toordinal() for stamp in group["date"]], dtype=float)
268 offset = 1.0 if security_types.get(ticker, "equity") in _MIDNIGHT_SECURITY_TYPES else 0.5
269 arrays[ticker] = (ordinals + offset, group["momentum_20d"].to_numpy(dtype=float))
270 return arrays
273def _momentum_before(arrays: dict[str, tuple[np.ndarray, np.ndarray]], key: float) -> dict[str, float]:
274 """Each ticker's latest stored momentum among the bars visible STRICTLY before `key` - what main.py's
275 latest_momentum_by_symbol holds when it builds the payload at the start of a tick (pool includes stale tickers)."""
276 momentum: dict[str, float] = {}
277 for ticker, (keys, values) in arrays.items():
278 end = int(np.searchsorted(keys, key, side="left"))
279 if end == 0:
280 continue
281 value = float(values[end - 1])
282 if np.isfinite(value):
283 momentum[ticker] = value
284 return momentum
287def _row_keys(momentum_long: pd.DataFrame, security_types: dict[str, str] | None) -> pd.Series:
288 security_types = security_types or {}
289 ordinals = np.array([pd.Timestamp(stamp).toordinal() for stamp in momentum_long["date"]], dtype=float)
290 offsets = np.array([1.0 if security_types.get(ticker, "equity") in _MIDNIGHT_SECURITY_TYPES else 0.5 for ticker in momentum_long["ticker"]])
291 return pd.Series(ordinals + offsets, index=momentum_long.index)
294def compute_macro_proxies_replica(
295 momentum_long: pd.DataFrame,
296 security_types: dict[str, str] | None = None,
297 *,
298 reference_tickers: dict[str, str] | None = None,
299) -> pd.DataFrame:
300 """Replica of train.py::build_macro_features_by_date() (Problems.md #135): the three macro proxies a row
301 sees are those of the reference tickers' momentum over the bars visible STRICTLY before the row's own tick,
302 fed through the shared proxy functions. `momentum_long`: (ticker, date, momentum_20d); one output row per input row."""
303 references = {**DEFAULT_MACRO_REFERENCE_TICKERS, **(reference_tickers or {})}
304 arrays = _momentum_arrays(momentum_long, security_types)
305 keys = _row_keys(momentum_long, security_types)
306 by_key: dict[float, tuple[float, float, float]] = {}
307 for key in sorted(set(keys)):
308 momentum = _momentum_before(arrays, key)
309 by_key[key] = (
310 yield_curve_slope_proxy(momentum.get(references["long_duration"]), momentum.get(references["short_duration"])),
311 credit_spread_proxy(momentum.get(references["high_yield"]), momentum.get(references["investment_grade"])),
312 crypto_risk_appetite_proxy(momentum.get(references["crypto"])),
313 )
314 result = momentum_long[["date", "ticker"]].copy()
315 rows = [by_key[key] for key in keys]
316 result["macro_yield_curve_slope_proxy"] = [row[0] for row in rows]
317 result["macro_credit_spread_proxy"] = [row[1] for row in rows]
318 result["macro_crypto_risk_appetite_proxy"] = [row[2] for row in rows]
319 return result
322def compute_cs_momentum_rank_replica(momentum_long: pd.DataFrame, security_types: dict[str, str] | None = None) -> pd.DataFrame:
323 """Replica of train.py::build_cross_sectional_momentum_rank_features() (Problems.md #135): the shared
324 cross_sectional_momentum_rank() over every ticker's momentum from the bars visible strictly before the
325 row's own tick - the pool includes tickers whose latest bar is old, as main.py's windows do."""
326 arrays = _momentum_arrays(momentum_long, security_types)
327 keys = _row_keys(momentum_long, security_types)
328 pools = {key: _momentum_before(arrays, key) for key in sorted(set(keys))}
329 ranks = [cross_sectional_momentum_rank(pools[key], ticker) for key, ticker in zip(keys, momentum_long["ticker"], strict=False)]
330 result = momentum_long[["date", "ticker"]].copy()
331 result["cs_momentum_rank_recomputed"] = ranks
332 return result
335def summarize_comparison(
336 stored_scaled: np.ndarray,
337 recomputed_raw: np.ndarray,
338 mean: float,
339 scale: float,
340 clip: float,
341 warmup_excluded: int = 0,
342) -> dict[str, Any]:
343 """Forward-direction comparison for ONE feature over ONE ticker slice:
344 recomputed raw -> scaler artifact -> stored column. Warmup rows (where a
345 replica legitimately cannot see pre-dataset history) are excluded from
346 the head of each ticker's series by the caller before this runs."""
347 valid = ~(np.isnan(stored_scaled) | np.isnan(recomputed_raw))
348 stored_valid = stored_scaled[valid]
349 expected = forward_scale(recomputed_raw[valid], mean, scale, clip)
350 delta = np.abs(expected - stored_valid)
351 saturated = int(np.sum(np.abs(stored_valid) >= clip - 1e-9))
352 mismatches = int(np.sum(delta > 1e-9))
353 return {
354 "n_compared": int(valid.sum()),
355 "warmup_excluded_per_ticker": warmup_excluded,
356 "max_abs_delta": float(delta.max()) if delta.size else None,
357 "mean_abs_delta": float(delta.mean()) if delta.size else None,
358 "n_mismatch_gt_1e-9": mismatches,
359 "n_saturated_at_clip": saturated,
360 "verdict": "PASS" if mismatches == 0 else "FAIL",
361 }