Coverage for evaluation/feature_reconciliation.py: 100%
76 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 Workstream B (development/Problems.md #91/#100) - the XOM
2feature-level investigation's pure diff core.
4`reconcile_feature_snapshot()` compares a single symbol's logged LIVE
5feature values (the `feature_snapshot.base_features` dict main.py's
6book-history diagnostic captured for that bar) against the same symbol/
7date row from `ml/datasets/full_dataset.csv` - the precomputed feature
8columns `train.py::engineer_features()` wrote from the same underlying
9`features/technical_indicators.py` functions the live path also calls.
10A divergence between the two for the same (ticker, date) is the concrete
11root cause this tool exists to surface or rule out: XOM is the one tracked
12ticker whose live-vs-offline book-selection mismatch never resolved across
13#91/#97/#99/#100 (140 appearances across 9 real runs, 77% mismatch, the
14worst of the five tracked tickers), and the existing
15`book_history.jsonl` records `raw_rank_score`/`feature_ready`/
16`trading_eligible` per symbol but no raw feature values - so nothing to
17diff against the offline dataset until this field exists.
19Pure: no I/O, no `self`, never raises on well-formed inputs - same
20shaping-only convention `reconcile_book_history_date()`'s own
21`_build_reconciliation_result()` already established. The CLI
22(`aq evaluate --reconcile-features`) owns the dataset load, the run-
23segmenting, the (ticker, date) join, and the per-date loop calling this
24function; this module only computes the diff, so it is unit-testable
25without a Lean backtest or a real dataset.
27What this function compares and what it deliberately does NOT:
28- Compares ONLY features present in the logged `base_features` snapshot
29 (main.py::_build_model_input()'s output - the price/volume-derived
30 technicals, regime/topology/liquidity signals, and peer-return features
31 the model actually saw live). The offline dataset has MORE columns
32 (expanded one-hot `regime_trend_*`/`topology_risk_*`/`bond_*`/`alt_*`/
33 `sens_*`/`macro_*`/`futures_*`/`options_*` - each derived in
34 `_build_regime_payload`/`_build_topology_payload` and flattened into
35 separate dataset columns by `train.py::engineer_features()`); those
36 appear in `features_only_in_offline` (informational, not a divergence)
37 since the live path carries them as structured sub-payloads, not as
38 the flat keys this function compares.
39- A feature present in the snapshot but NOT in the offline row is a
40 `features_only_in_logged` entry (informational - the live path computed
41 something the offline pipeline didn't, e.g. a feature added after the
42 dataset was built), NOT a divergence either.
43- Only the INTERSECTION is diffed, with `abs_delta` and `relative_delta`
44 per feature, sorted by `abs_delta` desc so the worst offender is first.
45- `offline_value` is read via `.get()` - a NaN/None column in the offline
46 row for that date degrades to `None`, same convention the existing
47 reconciliation uses for missing raw scores.
48"""
50from __future__ import annotations
52from collections.abc import Mapping
53from typing import Any
55DEFAULT_ABS_TOLERANCE = 1e-9
56DEFAULT_REL_TOLERANCE = 1e-6
57_RELATIVE_EPS = 1e-12
60def _coerce_float(value: Any) -> float | None:
61 """Coerce a dataset value to float, returning None for NaN/None/
62 non-numeric - the offline dataset stores features as CSV strings that
63 pandas reads as float64 but may carry NaN for warmup-period rows.
64 Mirrors the degrade-on-missing convention every other reconciliation
65 field uses, never raises."""
66 if value is None:
67 return None
68 try:
69 as_float = float(value)
70 except (TypeError, ValueError):
71 return None
72 if as_float != as_float: # NaN - the only float != itself
73 return None
74 return as_float
77def reconcile_feature_snapshot(
78 logged_feature_snapshot: Mapping[str, Any],
79 offline_dataset_row: Mapping[str, Any],
80 *,
81 abs_tolerance: float = DEFAULT_ABS_TOLERANCE,
82 rel_tolerance: float = DEFAULT_REL_TOLERANCE,
83) -> dict:
84 """Compare one logged feature snapshot (one symbol, one date's
85 `base_features` dict) against the matching offline dataset row for
86 the same (ticker, date).
88 Args:
89 logged_feature_snapshot: the `base_features` dict main.py's
90 `_build_model_input()` built for that bar, as captured in the
91 `feature_snapshot` field of one `book_history.jsonl` record's
92 per-symbol entry. Only the feature names present here are
93 diffed - the live path is the source of truth for what the
94 model actually saw.
95 offline_dataset_row: the matching `full_dataset.csv` row (a
96 pandas Series or dict) for the same ticker/date, keyed by
97 column name. Missing/NaN columns degrade to None, not a crash.
98 abs_tolerance: features whose `abs_delta` is at or below this are
99 considered matched (float reconstruction noise). Default
100 1e-9 - the live and offline paths both call the same pure
101 `features/technical_indicators.py` functions, so a genuine
102 match should be bit-identical up to float order noise; this
103 default is deliberately tight so even small systematic drift
104 surfaces.
105 rel_tolerance: features whose `relative_delta` is at or below
106 this are also considered matched (covers the case where
107 abs_delta is tiny in absolute terms but the offline value is
108 also tiny - a rel floor avoids noise on near-zero features).
110 Returns:
111 {"features_compared": int,
112 "features_matched": int,
113 "features_diverged": int,
114 "max_abs_delta": float | None,
115 "feature_deltas": list[dict], sorted by abs_delta desc, each
116 {"feature", "logged_value", "offline_value", "abs_delta",
117 "relative_delta", "diverged": bool},
118 "features_only_in_logged": sorted list[str],
119 "features_only_in_offline": sorted list[str]}
121 `max_abs_delta` is None only when zero features were compared (the
122 snapshot and the row share no feature names); 0.0 when all compared
123 features match exactly. `features_diverged` counts features whose
124 abs_delta exceeds BOTH tolerances (abs AND rel, not either - a near-
125 zero offline value with a tiny abs_delta but large relative_delta is
126 noise, not a real divergence).
127 """
128 logged_keys = set(logged_feature_snapshot.keys())
129 offline_keys = set(offline_dataset_row.keys())
130 common = sorted(logged_keys & offline_keys)
132 feature_deltas: list[dict] = []
133 max_abs_delta: float | None = None
134 matched = 0
135 diverged = 0
137 for feature in common:
138 logged_value = _coerce_float(logged_feature_snapshot.get(feature))
139 offline_value = _coerce_float(offline_dataset_row.get(feature))
140 # Either side missing/NaN: no comparison possible for this feature
141 # - degrade to None rather than a spurious "diverged" or "matched".
142 if logged_value is None or offline_value is None:
143 feature_deltas.append({
144 "feature": feature,
145 "logged_value": logged_value,
146 "offline_value": offline_value,
147 "abs_delta": None,
148 "relative_delta": None,
149 "diverged": False,
150 })
151 continue
153 abs_delta = abs(offline_value - logged_value)
154 relative_delta = abs_delta / max(abs(offline_value), _RELATIVE_EPS)
155 is_diverged = abs_delta > abs_tolerance and relative_delta > rel_tolerance
157 feature_deltas.append({
158 "feature": feature,
159 "logged_value": logged_value,
160 "offline_value": offline_value,
161 "abs_delta": abs_delta,
162 "relative_delta": relative_delta,
163 "diverged": is_diverged,
164 })
165 if is_diverged:
166 diverged += 1
167 else:
168 matched += 1
169 if max_abs_delta is None or abs_delta > max_abs_delta:
170 max_abs_delta = abs_delta
172 feature_deltas.sort(key=lambda entry: (entry["abs_delta"] is None, -(entry["abs_delta"] or 0.0)))
174 return {
175 "features_compared": len(common),
176 "features_matched": matched,
177 "features_diverged": diverged,
178 "max_abs_delta": max_abs_delta,
179 "feature_deltas": feature_deltas,
180 "features_only_in_logged": sorted(logged_keys - offline_keys),
181 "features_only_in_offline": sorted(offline_keys - logged_keys),
182 }
185def summarize_feature_reconciliation(per_date_results: list[dict]) -> dict:
186 """Aggregate a list of per-date `reconcile_feature_snapshot()` results
187 (one per logged record for the target symbol) into a single report,
188 mirroring `summarize_book_history_reconciliation()`'s shape: an empty
189 list returns a defined all-zero summary, never raises.
191 Surfaces WHICH specific features diverge most often and by how much -
192 the XOM investigation's entire point (a per-feature root cause, not a
193 single "mismatch" number). A feature that diverges on 77% of XOM's
194 appearances but 0% of every other tracked ticker's is the concrete
195 signal this tool exists to produce.
197 Returns:
198 {"num_dates": int,
199 "num_dates_with_comparison": int,
200 "num_features_compared_per_date": {"min": int|None, "max": int|None,
201 "mean": float|None},
202 "total_divergences": int,
203 "dates_with_any_divergence": int,
204 "features_diverged_most_often": list[{"feature", "diverged_count",
205 "diverged_fraction", "max_abs_delta", "mean_abs_delta"}]
206 sorted by diverged_count desc, capped at 20,
207 "features_never_compared": sorted list[str] - features present in
208 every logged snapshot but missing from the offline row every
209 time (e.g. a feature added live after the dataset was built).}
210 """
211 num_dates = len(per_date_results)
212 if num_dates == 0:
213 return {
214 "num_dates": 0,
215 "num_dates_with_comparison": 0,
216 "num_features_compared_per_date": {"min": None, "max": None, "mean": None},
217 "total_divergences": 0,
218 "dates_with_any_divergence": 0,
219 "features_diverged_most_often": [],
220 "features_never_compared": [],
221 }
223 compared_counts: list[int] = []
224 dates_with_any_divergence = 0
225 total_divergences = 0
226 feature_divergence_counts: dict[str, list[float]] = {}
227 feature_presence_in_logged: dict[str, int] = {}
228 feature_compared_count: dict[str, int] = {}
229 only_in_logged_accumulator: dict[str, int] = {}
231 for result in per_date_results:
232 compared = result.get("features_compared", 0)
233 compared_counts.append(compared)
234 diverged = result.get("features_diverged", 0)
235 total_divergences += diverged
236 if diverged > 0:
237 dates_with_any_divergence += 1
238 for entry in result.get("feature_deltas", []):
239 feature = entry["feature"]
240 feature_compared_count[feature] = feature_compared_count.get(feature, 0) + 1
241 if entry.get("diverged"):
242 feature_divergence_counts.setdefault(feature, []).append(entry["abs_delta"])
243 for feature in result.get("features_only_in_logged", []):
244 only_in_logged_accumulator[feature] = only_in_logged_accumulator.get(feature, 0) + 1
245 # Only count a feature as "present in logged snapshot" if it was in
246 # that snapshot at all (common or only_in_logged), so
247 # features_never_compared doesn't penalize a feature that simply
248 # wasn't logged for a given date (e.g. a warmup-bar snapshot with
249 # fewer keys).
250 for entry in result.get("feature_deltas", []):
251 feature = entry["feature"]
252 feature_presence_in_logged[feature] = feature_presence_in_logged.get(feature, 0) + 1
253 for feature in result.get("features_only_in_logged", []):
254 feature_presence_in_logged[feature] = feature_presence_in_logged.get(feature, 0) + 1
256 features_diverged_most_often = [
257 {
258 "feature": feature,
259 "diverged_count": len(deltas),
260 "diverged_fraction": len(deltas) / num_dates,
261 "max_abs_delta": max(deltas),
262 "mean_abs_delta": sum(deltas) / len(deltas),
263 }
264 for feature, deltas in feature_divergence_counts.items()
265 ]
266 features_diverged_most_often.sort(key=lambda item: item["diverged_count"], reverse=True)
267 features_diverged_most_often = features_diverged_most_often[:20]
269 features_never_compared = sorted(
270 feature for feature, present in feature_presence_in_logged.items()
271 if present == num_dates and feature_compared_count.get(feature, 0) == 0
272 )
274 return {
275 "num_dates": num_dates,
276 "num_dates_with_comparison": sum(1 for count in compared_counts if count > 0),
277 "num_features_compared_per_date": {
278 "min": min(compared_counts) if compared_counts else None,
279 "max": max(compared_counts) if compared_counts else None,
280 "mean": (sum(compared_counts) / len(compared_counts)) if compared_counts else None,
281 },
282 "total_divergences": total_divergences,
283 "dates_with_any_divergence": dates_with_any_divergence,
284 "features_diverged_most_often": features_diverged_most_often,
285 "features_never_compared": features_never_compared,
286 }