Coverage for evaluation/rank_signal_calibration.py: 100%
192 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"""Calibrates `phase_v2.portfolio_book.min_rank_confidence_spread` from
2real data (V5.1, development/Problems.md) - the same "derive the number,
3don't guess it" discipline `aq evaluate --calibrate-edge` already
4established for `phase_v2.costs.edge_bps_per_rank_unit`.
6Deliberately reuses, never re-derives: `portfolio.rank_signal.select_raw_rank_score()`
7(the exact blend formula main.py's live Pass 1c applies),
8`portfolio.rank_signal.cross_sectional_rank_scores()` (the exact
9normalization main.py applies before book selection), and
10`portfolio.book_construction.build_rank_based_book()` +
11`compute_confidence_spread()` (the exact selection and gate-comparison
12main.py's live book uses). A calibrated threshold computed here can never
13silently disagree with what the live gate would have done on the same
14historical day, because it is the same code, not a parallel
15approximation.
16"""
18from __future__ import annotations
20import numpy as np
21import pandas as pd
23from portfolio.book_construction import build_rank_based_book, compute_confidence_spread
24from portfolio.rank_signal import cross_sectional_rank_scores, select_raw_rank_score
26_SPREAD_DISTRIBUTION_PERCENTILES = {"p10": 0.10, "p25": 0.25, "median": 0.50, "p75": 0.75}
29def compute_blended_raw_scores(
30 dataset: pd.DataFrame,
31 predictions_by_model_head: dict[str, dict[str, np.ndarray]],
32 policy: dict,
33) -> pd.Series:
34 """Row-by-row call into select_raw_rank_score() - one call per row,
35 exactly mirroring main.py's Pass 1c (one blend per symbol per bar).
37 `predictions_by_model_head` is `{"sequence": {"rank_20d": arr,
38 "rank_5d": arr}, "multitask": {...}}` - each array is row-index-aligned
39 with `dataset` (predict_head()'s own return shape), one entry per head
40 the caller actually loaded predictions for. A model absent from this
41 dict is treated as unavailable that row (select_raw_rank_score()'s own
42 "model still warming up" contract), never a KeyError.
44 Returns a float Series aligned to dataset.index; NaN wherever
45 select_raw_rank_score() returns (None, "no_rank_available") for that
46 row (every configured head missing a value)."""
47 num_rows = len(dataset)
48 scores = np.full(num_rows, np.nan, dtype=np.float64)
50 for row_index in range(num_rows):
51 payload_by_model: dict[str, dict[str, float] | None] = {}
52 for model_name, head_arrays in predictions_by_model_head.items():
53 payload: dict[str, float] = {}
54 for head_name, values in head_arrays.items():
55 value = values[row_index]
56 if value is not None and not (isinstance(value, float) and np.isnan(value)):
57 payload[head_name] = float(value)
58 payload_by_model[model_name] = payload or None
60 score, _source = select_raw_rank_score(
61 payload_by_model.get("sequence"), payload_by_model.get("multitask"), policy
62 )
63 if score is not None:
64 scores[row_index] = score
66 return pd.Series(scores, index=dataset.index)
69def calibrate_book_confidence_spread(
70 dataset: pd.DataFrame,
71 *,
72 raw_score_column: str,
73 ticker_column: str = "ticker",
74 date_column: str = "date",
75 top_n: int,
76 bottom_n: int,
77 percentile: float = 0.10,
78 candidate_metadata_by_ticker: dict[str, dict] | None = None,
79 session_asset_class: str | None = None,
80) -> dict:
81 """V5.7.0: `candidate_metadata_by_ticker` ({ticker: {"asset_class", "trading_eligible"}}, the same metadata the
82 as-live simulator and main.py's `book_candidate_trading_eligible` use) keeps ineligible names (a disabled forex
83 class, observation-only crypto) out of the selection while they still take part in the percentile normalization,
84 exactly like live; without it every row was a candidate and the floor was calibrated on a pool live never trades.
85 `session_asset_class` ("equity") keeps only dates on which that class has a row: live rebalances on equity-session
86 bars only, while the dataset also holds weekend dates with a handful of crypto rows.
88 Per date (sorted): normalizes that date's raw scores exactly as
89 main.py's Pass 1 does (cross_sectional_rank_scores()), selects the
90 natural top_n/bottom_n split with NO gate and NO hysteresis
91 (build_rank_based_book(..., min_rank_confidence_spread=0.0,
92 previous_allocations=None) - hysteresis is deliberately not replayed
93 here: this measures each day's independent natural dispersion, not one
94 particular incumbency-dependent walk through history), then computes
95 that selection's confidence spread via the SAME compute_confidence_spread()
96 the live gate calls.
98 Dates where selection comes back empty (fewer than 2 eligible names,
99 or one side has nothing to select at all) are EXCLUDED from the
100 distribution, not counted as a 0.0-spread day - a thin-universe date is
101 missing data, not evidence of low conviction.
103 Returns:
104 {"calibrated_min_rank_confidence_spread": float,
105 "percentile": float,
106 "num_dates_used": int,
107 "num_dates_skipped_thin_universe": int,
108 "spread_distribution": {"min", "p10", "p25", "median", "p75", "max"}}
110 An empty/all-thin dataset returns calibrated_min_rank_confidence_spread=0.0
111 (the gate's own "always engage" no-op value) and an all-None
112 distribution, never raises."""
113 spreads: list[float] = []
114 num_dates_skipped_thin_universe = 0
115 metadata = candidate_metadata_by_ticker or {}
116 session_tickers = (
117 {ticker for ticker, entry in metadata.items() if entry.get("asset_class") == session_asset_class}
118 if session_asset_class
119 else None
120 )
122 for _date, group in dataset.groupby(date_column, sort=True):
123 if session_tickers is not None and not set(map(str, group[ticker_column])) & session_tickers:
124 continue
125 raw_scores = {
126 str(ticker): float(score)
127 for ticker, score in zip(group[ticker_column], group[raw_score_column], strict=False)
128 if score is not None and not (isinstance(score, float) and np.isnan(score))
129 }
130 normalized = cross_sectional_rank_scores(raw_scores)
131 if not normalized:
132 num_dates_skipped_thin_universe += 1
133 continue
135 candidates = {
136 symbol: {
137 "predicted_rank_20d": rank,
138 "trading_eligible": bool(metadata.get(symbol, {}).get("trading_eligible", True)),
139 "asset_class": metadata.get(symbol, {}).get("asset_class"),
140 }
141 for symbol, rank in normalized.items()
142 }
143 allocations = build_rank_based_book(
144 candidates,
145 top_n=top_n,
146 bottom_n=bottom_n,
147 min_rank_confidence_spread=0.0,
148 spread_check_ranks=raw_scores,
149 )
150 if not allocations:
151 num_dates_skipped_thin_universe += 1
152 continue
154 long_symbols = [symbol for symbol, allocation in allocations.items() if allocation.role == "long"]
155 short_symbols = [symbol for symbol, allocation in allocations.items() if allocation.role == "short"]
156 spread = compute_confidence_spread(long_symbols, short_symbols, raw_scores, normalized)
157 if spread is not None:
158 spreads.append(spread)
159 else:
160 num_dates_skipped_thin_universe += 1
162 if not spreads:
163 return {
164 "calibrated_min_rank_confidence_spread": 0.0,
165 "percentile": percentile,
166 "num_dates_used": 0,
167 "num_dates_skipped_thin_universe": num_dates_skipped_thin_universe,
168 "spread_distribution": {"min": None, "p10": None, "p25": None, "median": None, "p75": None, "max": None},
169 }
171 spread_array = np.array(spreads, dtype=np.float64)
172 distribution = {"min": float(np.min(spread_array)), "max": float(np.max(spread_array))}
173 for name, quantile in _SPREAD_DISTRIBUTION_PERCENTILES.items():
174 distribution[name] = float(np.quantile(spread_array, quantile))
176 return {
177 "calibrated_min_rank_confidence_spread": float(np.quantile(spread_array, percentile)),
178 "percentile": percentile,
179 "num_dates_used": len(spreads),
180 "num_dates_skipped_thin_universe": num_dates_skipped_thin_universe,
181 "spread_distribution": distribution,
182 }
185def _build_reconciliation_result(
186 logged_record: dict,
187 offline_allocations: dict,
188 raw_scores_by_symbol: dict[str, float],
189) -> dict:
190 """V5.2.3 (development/Problems.md #91) - the diff/shaping core shared
191 by `reconcile_book_history_date()` (independent per-date, no
192 hysteresis) and `replay_book_history_reconciliation()` (walk-forward,
193 hysteresis-replayed): given one logged record and an ALREADY-COMPUTED
194 offline `build_rank_based_book()` result for that same date, produces
195 the reconciliation dict both callers return. Extracted so the two
196 reconciliation modes can never silently disagree on what counts as a
197 match/mismatch - see reconcile_book_history_date()'s own docstring for
198 the full field-by-field contract this returns (unchanged by this
199 refactor)."""
200 logged_allocations = logged_record.get("allocations", {})
201 # V5.5.0 (Problems.md #128) - an EMPTY logged book means live VETOED the
202 # rebalance (spread/rolling-IC gate: `gate_veto_reason`), not "selected
203 # nothing". Offline selects a book regardless (no gates here), so the
204 # diff on such a date would read as 0% overlap and inflate every
205 # only-offline count - the "overlap erosion" #94 chased was partly this.
206 # Such dates are flagged and excluded from the match statistics.
207 live_vetoed = not logged_allocations
208 logged_long = {symbol for symbol, entry in logged_allocations.items() if entry.get("role") == "long"}
209 logged_short = {symbol for symbol, entry in logged_allocations.items() if entry.get("role") == "short"}
211 offline_long = {symbol for symbol, allocation in offline_allocations.items() if allocation.role == "long"}
212 offline_short = {symbol for symbol, allocation in offline_allocations.items() if allocation.role == "short"}
214 logged_all = logged_long | logged_short
215 offline_all = offline_long | offline_short
217 symbols_matched = sorted(logged_all & offline_all)
218 symbols_only_logged = sorted(logged_all - offline_all)
219 symbols_only_offline = sorted(offline_all - logged_all)
220 role_mismatches = sorted(
221 symbol for symbol in symbols_matched if (symbol in logged_long) != (symbol in offline_long)
222 )
224 union_size = len(logged_all | offline_all)
225 overlap_fraction = (len(symbols_matched) / union_size) if union_size > 0 else None
227 num_offline_long = len(offline_long)
228 num_offline_short = len(offline_short)
229 per_symbol_deltas: dict[str, dict] = {}
230 for symbol in symbols_matched:
231 logged_raw_score = logged_allocations[symbol].get("raw_rank_score")
232 offline_raw_score = raw_scores_by_symbol.get(symbol)
233 raw_score_delta = (
234 offline_raw_score - logged_raw_score
235 if logged_raw_score is not None and offline_raw_score is not None
236 else None
237 )
239 logged_target_weight = logged_allocations[symbol].get("target_weight")
240 if logged_target_weight is not None and symbol in offline_long and num_offline_long > 0:
241 naive_offline_weight = 1.0 / num_offline_long
242 elif logged_target_weight is not None and symbol in offline_short and num_offline_short > 0:
243 naive_offline_weight = -1.0 / num_offline_short
244 else:
245 naive_offline_weight = None
246 weight_delta = (
247 logged_target_weight - naive_offline_weight
248 if logged_target_weight is not None and naive_offline_weight is not None
249 else None
250 )
252 per_symbol_deltas[symbol] = {"raw_score_delta": raw_score_delta, "weight_delta": weight_delta}
254 return {
255 "date": logged_record.get("date"),
256 "logged_symbols": {"long": sorted(logged_long), "short": sorted(logged_short)},
257 "offline_symbols": {"long": sorted(offline_long), "short": sorted(offline_short)},
258 "symbols_matched": symbols_matched,
259 "symbols_only_logged": symbols_only_logged,
260 "symbols_only_offline": symbols_only_offline,
261 "role_mismatches": role_mismatches,
262 "overlap_fraction": None if live_vetoed else overlap_fraction,
263 "per_symbol_deltas": per_symbol_deltas,
264 "live_vetoed": live_vetoed,
265 "gate_veto_reason": logged_record.get("gate_veto_reason") if live_vetoed else None,
266 }
269def reconcile_book_history_date(
270 logged_record: dict,
271 raw_scores_by_symbol: dict[str, float],
272 *,
273 top_n: int,
274 bottom_n: int,
275) -> dict:
276 """V5.2.2 (development/Problems.md) - `aq evaluate --reconcile-book-history`'s
277 per-date core: compares one `build_book_history_record()` log entry
278 (portfolio/book_construction.py - what main.py's LIVE book actually
279 selected that date, during a real Lean backtest) against a fresh
280 offline re-derivation of what the SAME raw scores would naturally
281 select today, with no gate and no hysteresis
282 (build_rank_based_book(..., min_rank_confidence_spread=0.0,
283 previous_allocations=None) - the exact same "independent natural
284 selection" convention calibrate_book_confidence_spread() above
285 already established).
287 `previous_allocations=None` is deliberate, not an oversight: this
288 cannot replay the live book's actual incumbency history from a single
289 date's log entry, so a flagged mismatch here can mean either a real
290 divergence OR "hysteresis correctly kept an incumbent that day's
291 natural ranking alone wouldn't pick" - callers printing this result
292 must carry that caveat, never over-read a mismatch as necessarily a
293 bug. `replay_book_history_reconciliation()` below is the hysteresis-
294 aware alternative (V5.2.3) when a caller has the FULL date-sorted log,
295 not just one record.
297 Weight comparison is best-effort and deliberately naive: offline has
298 no access to the live per-symbol `confidence` value or the neutrality
299 pass's inputs (both needed to reproduce main.py's real sizing formula),
300 so `per_symbol_deltas[symbol]["weight_delta"]` is computed against a
301 naive equal-weight baseline (`book_role_multiplier / count-on-that-role`),
302 not the live formula - it measures how far the logged (post-neutrality,
303 post-confidence-sizing) weight moved from a symmetric equal-weight
304 book, not a reconstruction error. `None` whenever the logged record's
305 own `target_weight` is `None` (neutrality was off for that run).
307 Returns:
308 {"date", "logged_symbols": {"long", "short"}, "offline_symbols":
309 {"long", "short"}, "symbols_matched", "symbols_only_logged",
310 "symbols_only_offline", "role_mismatches", "overlap_fraction",
311 "per_symbol_deltas": {symbol: {"raw_score_delta", "weight_delta"}}}
313 `overlap_fraction` is `symbols_matched / (logged | offline)`, `None`
314 when both sides are empty (nothing to compare, not a 0% overlap).
316 V5.3.1 (development/Problems.md #91/#97): `trading_eligible` used to
317 be hardcoded `True` for every symbol here, regardless of whether the
318 real live run actually considered it eligible that date - now read
319 from `logged_record["universe"][symbol]["trading_eligible"]` when
320 that data is present (`phase_v2.diagnostics.book_history.
321 include_full_universe` was on for the run that produced this log),
322 the SAME real per-date eligibility main.py's own book construction
323 used (main.py:2768). Falls back to `True` (today's exact prior
324 behavior, byte-identical) for any symbol missing from `"universe"` or
325 for a log with no `"universe"` key at all - never a KeyError."""
326 universe = logged_record.get("universe") or {}
327 normalized = cross_sectional_rank_scores(raw_scores_by_symbol)
328 candidates = {
329 symbol: {
330 "predicted_rank_20d": rank,
331 "trading_eligible": universe.get(symbol, {}).get("trading_eligible", True),
332 }
333 for symbol, rank in normalized.items()
334 }
335 offline_allocations = build_rank_based_book(
336 candidates,
337 top_n=top_n,
338 bottom_n=bottom_n,
339 min_rank_confidence_spread=0.0,
340 spread_check_ranks=raw_scores_by_symbol,
341 )
342 return _build_reconciliation_result(logged_record, offline_allocations, raw_scores_by_symbol)
345def replay_book_history_reconciliation(
346 logged_records: list[dict],
347 raw_scores_by_date: dict[str, dict[str, float]],
348 *,
349 top_n: int,
350 bottom_n: int,
351 hysteresis_rank_margin: float = 0.0,
352 hysteresis_survives_veto: bool = False,
353) -> list[dict]:
354 """V5.2.3 (development/Problems.md #91) - the hysteresis-aware
355 alternative to calling `reconcile_book_history_date()` independently
356 per date. `reconcile_book_history_date()` always passes
357 `previous_allocations=None`, so it cannot tell "the live book
358 genuinely diverged" apart from "the live book correctly held an
359 incumbent a from-scratch reselection wouldn't naturally pick" - this
360 function replays offline's OWN walk-forward selection across
361 `logged_records` (must already be date-sorted - not re-sorted here,
362 same precondition `evaluation/model_predictions.py::build_sequence_windows()`
363 already places on its own caller), carrying a `held_allocations` dict
364 forward exactly the way `evaluation/rank_book_simulator.py::_simulate_rank_book_core()`
365 and `main.py`'s own `_last_book_allocations` both already do: computed
366 with the STILL-OLD `held_allocations` as `previous_allocations`, then
367 overwritten from THAT SAME call's own output (never from the logged
368 record - offline's own history, not live's) before the next date.
370 `hysteresis_rank_margin=0.0` reproduces `build_rank_based_book()`'s
371 own no-op default, so passing it unset degrades to (a slower way of
372 computing) `reconcile_book_history_date()`'s independent-per-date
373 result for every date except that `held_allocations` is still seeded
374 from offline's own prior date rather than nothing - only truly
375 identical when `hysteresis_rank_margin` is also 0.0 everywhere.
377 Cold-start caveat: `held_allocations` starts EMPTY at the first
378 record in `logged_records`, regardless of how long the live book's
379 true incumbency history was before that date - early results in the
380 returned list are more likely to show a "divergence" that is really
381 just this function's own cold start, not live's. A caller printing
382 this should say so, not just print the raw numbers.
384 PRECONDITION (V5.3.2, development/Problems.md #91/#97/#99): `logged_records`
385 must be a SINGLE run's own records - e.g. one element of
386 `segment_logged_records_by_run()`'s return - never the raw cumulative
387 `visualization/book_history.jsonl` content as-is. That file accumulates
388 every historical backtest forever; passing its unsegmented content here
389 silently carries `held_allocations` across a real run boundary as if it
390 were one continuous backtest, corrupting incumbency for any symbol near
391 a selection boundary on those dates (confirmed empirically: 160 of 174
392 unique dates in the real file recur across more than one run, one date
393 in as many as 8). This is exactly the bug aq_cli.py's
394 --reconcile-book-history dispatch now guards against at the call site by
395 segmenting first - this function itself does not enforce it, since it
396 has no way to distinguish "one real run" from "one caller-assembled
397 slice" and never should (its whole job is to replay whatever forward-
398 sorted sequence of dates it's handed).
400 Returns a list of `_build_reconciliation_result()`-shaped dicts, one
401 per record in `logged_records`, in the same order. A `logged_record`
402 with no matching entry in `raw_scores_by_date` (e.g. that date fell
403 outside a caller's re-inference window) is skipped entirely - not a
404 KeyError, and `held_allocations` simply carries through unchanged to
405 the next date it CAN compute, the same "missing day doesn't reset
406 state" behavior a live gap in trading data would also produce."""
407 held_allocations: dict = {}
408 results: list[dict] = []
409 for logged_record in logged_records:
410 date = logged_record.get("date")
411 raw_scores_by_symbol = raw_scores_by_date.get(date)
412 if raw_scores_by_symbol is None:
413 continue
415 # V5.3.1 (development/Problems.md #91/#97) - reads real per-date
416 # trading_eligible from the logged "universe" payload when
417 # available, same as reconcile_book_history_date() above (see its
418 # docstring); falls back to True (unchanged prior behavior) when
419 # absent.
420 universe = logged_record.get("universe") or {}
421 normalized = cross_sectional_rank_scores(raw_scores_by_symbol)
422 candidates = {
423 symbol: {
424 "predicted_rank_20d": rank,
425 "trading_eligible": universe.get(symbol, {}).get("trading_eligible", True),
426 }
427 for symbol, rank in normalized.items()
428 }
429 offline_allocations = build_rank_based_book(
430 candidates,
431 top_n=top_n,
432 bottom_n=bottom_n,
433 min_rank_confidence_spread=0.0,
434 spread_check_ranks=raw_scores_by_symbol,
435 previous_allocations=held_allocations or None,
436 hysteresis_rank_margin=hysteresis_rank_margin,
437 )
438 results.append(_build_reconciliation_result(logged_record, offline_allocations, raw_scores_by_symbol))
440 # V5.5.0 (Problems.md #128) - live's hysteresis memory across a veto. A date live
441 # VETOED formed no book there, so offline's own selection for that date must not
442 # become the next date's anchor (offline has no gates and selects regardless):
443 # - before V5.5.0 a veto WIPED main.py's _last_book_allocations -> reset (default);
444 # - from V5.5.0 the last formed book survives -> keep the previous anchor untouched
445 # (hysteresis_survives_veto=True).
446 if logged_record.get("allocations"):
447 held_allocations = offline_allocations
448 elif not hysteresis_survives_veto:
449 held_allocations = {}
451 return results
454def summarize_book_history_reconciliation(per_date_results: list[dict]) -> dict:
455 """Aggregates a list of reconcile_book_history_date() results (one per
456 logged date) into a single report. An empty list returns a defined
457 all-zero/None summary, never raises - the CLI orchestrator always calls
458 this even when the log file turned out to contain zero usable dates.
460 `mean_weight_delta_abs`/`num_dates_with_weight_logged` are computed
461 only over dates that had at least one symbol with a non-None logged
462 `target_weight` (neutrality was on for that run) - callers must report
463 "weight deltas computed for N/M dates" rather than silently averaging
464 the missing dates away as zero, per reconcile_book_history_date()'s own
465 weight-comparison caveat."""
466 num_dates = len(per_date_results)
467 if num_dates == 0:
468 return {
469 "num_dates": 0,
470 "num_dates_live_vetoed": 0,
471 "num_dates_compared": 0,
472 "live_veto_reasons": {},
473 "num_dates_exact_match": 0,
474 "mean_overlap_fraction": None,
475 "mean_raw_score_delta_abs": None,
476 "mean_weight_delta_abs": None,
477 "num_dates_with_weight_logged": 0,
478 "num_symbols_only_logged_total": 0,
479 "num_symbols_only_offline_total": 0,
480 }
482 # V5.5.0: a live-vetoed date has no live selection to compare against, so it
483 # is reported separately and kept out of every match statistic below.
484 vetoed_results = [result for result in per_date_results if result.get("live_vetoed")]
485 live_veto_reasons: dict[str, int] = {}
486 for result in vetoed_results:
487 reason = result.get("gate_veto_reason") or "unknown"
488 live_veto_reasons[reason] = live_veto_reasons.get(reason, 0) + 1
489 all_results = per_date_results
490 per_date_results = [result for result in per_date_results if not result.get("live_vetoed")]
492 num_dates_exact_match = sum(
493 1
494 for result in per_date_results
495 if not result["symbols_only_logged"] and not result["symbols_only_offline"] and not result["role_mismatches"]
496 )
497 overlap_fractions = [result["overlap_fraction"] for result in per_date_results if result["overlap_fraction"] is not None]
498 raw_score_deltas = [
499 abs(delta["raw_score_delta"])
500 for result in per_date_results
501 for delta in result["per_symbol_deltas"].values()
502 if delta["raw_score_delta"] is not None
503 ]
504 weight_deltas = [
505 abs(delta["weight_delta"])
506 for result in per_date_results
507 for delta in result["per_symbol_deltas"].values()
508 if delta["weight_delta"] is not None
509 ]
510 num_dates_with_weight_logged = sum(
511 1
512 for result in per_date_results
513 if any(delta["weight_delta"] is not None for delta in result["per_symbol_deltas"].values())
514 )
516 return {
517 "num_dates": len(all_results),
518 "num_dates_live_vetoed": len(vetoed_results),
519 "num_dates_compared": len(per_date_results),
520 "live_veto_reasons": dict(sorted(live_veto_reasons.items())),
521 "num_dates_exact_match": num_dates_exact_match,
522 "mean_overlap_fraction": float(np.mean(overlap_fractions)) if overlap_fractions else None,
523 "mean_raw_score_delta_abs": float(np.mean(raw_score_deltas)) if raw_score_deltas else None,
524 "mean_weight_delta_abs": float(np.mean(weight_deltas)) if weight_deltas else None,
525 "num_dates_with_weight_logged": num_dates_with_weight_logged,
526 "num_symbols_only_logged_total": sum(len(result["symbols_only_logged"]) for result in per_date_results),
527 "num_symbols_only_offline_total": sum(len(result["symbols_only_offline"]) for result in per_date_results),
528 }
531def summarize_universe_snapshot_by_security_type(logged_records: list[dict]) -> dict:
532 """V5.2.3 (development/Problems.md #91) - aggregates the OPTIONAL
533 `"universe"` key `build_book_history_record()` adds when
534 `phase_v2.diagnostics.book_history.include_full_universe` was on for
535 the run that produced `logged_records` (V5.2.2 logs, and any V5.2.3
536 log written with the toggle still off, simply have no `"universe"`
537 key on any record - this function reads straight off the log's own
538 data, no re-inference or model loading needed, so it is always cheap
539 to attempt).
541 Exists to answer, directly from data, the question code-reading alone
542 could not settle: does a `security_type` that's absent from every
543 live book (e.g. crypto/FX, Problems.md #91) sit there because it
544 never gets a usable feature/score (`feature_ready` false), or because
545 it gets a real score that's simply never extreme enough to be
546 selected (`feature_ready` true, `mean_raw_rank_score` unremarkable)?
548 Per `security_type`: `num_symbol_dates` (raw count of (symbol, date)
549 observations seen for it - NOT unique symbols), `mean_raw_rank_score`
550 (over only the observations where `raw_rank_score` is not None -
551 never averages a missing score in as 0), `feature_ready_rate`,
552 `trading_eligible_rate`.
554 Returns `{"num_dates_with_universe_data": int, "by_security_type":
555 {security_type: {...}}}`. `num_dates_with_universe_data` is 0 (and
556 `by_security_type` is `{}`) when no record in `logged_records` carries
557 a `"universe"` key at all - callers must check this before reading
558 `by_security_type`, since a 0 there means "toggle was off for this
559 log", not "every security type had zero observations". Never raises
560 on an empty or all-missing-universe input."""
561 dates_with_universe_data = 0
562 observations_by_security_type: dict[str, list[dict]] = {}
564 for logged_record in logged_records:
565 universe = logged_record.get("universe")
566 if not universe:
567 continue
568 dates_with_universe_data += 1
569 for signal in universe.values():
570 security_type = signal.get("security_type") or "unknown"
571 observations_by_security_type.setdefault(security_type, []).append(signal)
573 by_security_type: dict[str, dict] = {}
574 for security_type, observations in observations_by_security_type.items():
575 raw_scores = [obs["raw_rank_score"] for obs in observations if obs.get("raw_rank_score") is not None]
576 num_observations = len(observations)
577 by_security_type[security_type] = {
578 "num_symbol_dates": num_observations,
579 "mean_raw_rank_score": float(np.mean(raw_scores)) if raw_scores else None,
580 "feature_ready_rate": (
581 sum(1 for obs in observations if obs.get("feature_ready")) / num_observations
582 if num_observations > 0
583 else None
584 ),
585 "trading_eligible_rate": (
586 sum(1 for obs in observations if obs.get("trading_eligible")) / num_observations
587 if num_observations > 0
588 else None
589 ),
590 }
592 return {
593 "num_dates_with_universe_data": dates_with_universe_data,
594 "by_security_type": by_security_type,
595 }
598def segment_logged_records_by_run(logged_records: list[dict]) -> list[list[dict]]:
599 """V5.3.2 (development/Problems.md #91/#97/#99) - `visualization/
600 book_history.jsonl` (and any log built the same way) is a cumulative,
601 NEVER-rotated file: every real backtest run's records get appended to
602 the same file, one after another, forever - a single real backtest
603 always logs forward in time, so a run boundary is wherever the date
604 sequence goes backwards (`record["date"] < previous_record["date"]`).
605 Extracted from summarize_universe_presence_by_symbol() (V5.3.1) so
606 aq_cli.py's --reconcile-book-history dispatch can reuse the identical
607 boundary-detection logic instead of re-deriving it a second time (see
608 that command's own V5.3.2 fix for why reconciling against an
609 unsegmented cumulative log silently merges unrelated runs together -
610 confirmed against the real file: 160 of 174 unique dates recur across
611 more than one run, one date in as many as 8).
613 A record with a missing `"date"` never triggers a boundary and is
614 folded into whichever run is currently open.
616 Returns the run segments (each a list of `logged_records` entries, in
617 original order) in the same chronological order as `logged_records`
618 itself - `result[-1]` is always the most recent run. Empty input
619 returns `[]`, never raises."""
620 runs: list[list[dict]] = []
621 current_run: list[dict] = []
622 previous_date: str | None = None
623 current_run_id: str | None = None
624 for record in logged_records:
625 date = record.get("date")
626 run_id = record.get("run_id")
627 # V5.7.0: records carry the run's start stamp; a changed id is a boundary even when the dates happen to continue.
628 new_run_id = run_id is not None and current_run_id is not None and run_id != current_run_id
629 if new_run_id or (previous_date is not None and date is not None and date < previous_date):
630 if current_run:
631 runs.append(current_run)
632 current_run = []
633 current_run.append(record)
634 previous_date = date if date is not None else previous_date
635 current_run_id = run_id if run_id is not None else current_run_id
637 if current_run:
638 runs.append(current_run)
640 return runs
643def summarize_universe_presence_by_symbol(logged_records: list[dict]) -> dict:
644 """V5.3.1 (development/Problems.md #91/#97) - `visualization/
645 book_history.jsonl` is a cumulative, NEVER-rotated log: every real
646 backtest run's records get appended to the same file, one after
647 another, forever. Averaging a per-symbol statistic across the whole
648 file (as an earlier round of this investigation did, finding "FX/crypto
649 absent from the universe on 32% of dates") silently mixes many
650 different runs together - a genuine, now-fixed gap in one old run can
651 look like a smaller, still-live problem once diluted into the average
652 of several newer, clean runs. This function segments `logged_records`
653 into contiguous runs FIRST (via segment_logged_records_by_run(), V5.3.2),
654 then computes each symbol's universe-absence rate PER RUN, so a stale
655 run's numbers can never dilute a fresh run's, and a genuine regression
656 in the MOST RECENT run (`result["runs"][-1]`) is always visible on its
657 own, not averaged away.
659 Absence here means "not a key in that date's `universe` payload at
660 all" (main.py's `signals` dict, main.py:2761-2772 - the SAME data that
661 also feeds real book candidacy, main.py:1735-1736's `continue` gate -
662 see development/Problems.md #97 for why this is a real book-
663 construction signal, not merely a diagnostic one). Only symbols that
664 appear in the universe payload on AT LEAST one date within a run are
665 scored for that run (an unrelated ticker that's never in ANY
666 universe snapshot isn't "100% absent", it's simply out of scope).
668 Same "log carries no data, degrade to zeros" contract as
669 summarize_universe_snapshot_by_security_type() - a `logged_records`
670 with no `"universe"` key anywhere returns `{"num_runs_detected": 0,
671 "runs": []}`, never raises.
673 Returns `{"num_runs_detected": int, "runs": [{"start_date", "end_date",
674 "num_records", "absence_rate_by_symbol": {symbol: float}}, ...]}`,
675 runs in the same chronological order as `logged_records` itself."""
676 runs = segment_logged_records_by_run(logged_records)
678 run_summaries: list[dict] = []
679 for run_records in runs:
680 universe_records = [record for record in run_records if record.get("universe")]
681 num_records = len(universe_records)
682 if num_records == 0:
683 continue
685 all_symbols: set[str] = set()
686 for record in universe_records:
687 all_symbols.update(record["universe"].keys())
689 absence_rate_by_symbol = {
690 symbol: 1.0 - (sum(1 for record in universe_records if symbol in record["universe"]) / num_records)
691 for symbol in all_symbols
692 }
694 run_summaries.append(
695 {
696 "start_date": universe_records[0].get("date"),
697 "end_date": universe_records[-1].get("date"),
698 "num_records": num_records,
699 "absence_rate_by_symbol": absence_rate_by_symbol,
700 }
701 )
703 return {"num_runs_detected": len(run_summaries), "runs": run_summaries}
706def summarize_book_member_diversion(logged_records: list[dict]) -> dict:
707 """V5.2.6 (development/Problems.md) - aggregates the OPTIONAL
708 `"book_member_decisions"` key `build_book_history_record()` adds when
709 `phase_v2.diagnostics.book_history.include_decisions` was on for the
710 run that produced `logged_records` - mirrors
711 `summarize_universe_snapshot_by_security_type()`'s own shape and
712 "log carries no data, degrade to zeros" contract exactly.
714 Exists to replace hypothesis with measurement: `book_allocations`
715 alone can never show whether a book-selected symbol actually became
716 a real trade, or was silently diverted to `simulate`/`reduce_risk`/
717 `retrain_candidate` by a risk/execution gate downstream of selection
718 (development/Problems.md - the crypto/FX zero-order-execution
719 finding, and the live-risk-gate-vs-offline-evaluator gap). Per-run,
720 NOT per-date - a single aggregate is more useful here than a per-date
721 breakdown, since the question is "how much, in total, across this
722 whole run" rather than "on which specific date".
724 Returns `{"num_records_with_decisions": int, "total_book_member_dates":
725 int, "action_counts": {action: count}, "reason_counts": {reason: count}}`.
726 `num_records_with_decisions` is 0 (and both count dicts are `{}`) when
727 no record in `logged_records` carries a `"book_member_decisions"` key
728 at all - callers must check this before reading the counts, same as
729 `num_dates_with_universe_data`'s own convention above. Never raises on
730 an empty or all-missing-decisions input."""
731 num_records_with_decisions = 0
732 total_book_member_dates = 0
733 action_counts: dict[str, int] = {}
734 reason_counts: dict[str, int] = {}
736 for logged_record in logged_records:
737 decisions = logged_record.get("book_member_decisions")
738 if not decisions:
739 continue
740 num_records_with_decisions += 1
741 for decision in decisions.values():
742 total_book_member_dates += 1
743 action = decision.get("action") or "unknown"
744 action_counts[action] = action_counts.get(action, 0) + 1
745 for reason in decision.get("reasons", []) or []:
746 reason_counts[reason] = reason_counts.get(reason, 0) + 1
748 return {
749 "num_records_with_decisions": num_records_with_decisions,
750 "total_book_member_dates": total_book_member_dates,
751 "action_counts": action_counts,
752 "reason_counts": reason_counts,
753 }