Coverage for evaluation/classification_parity.py: 100%

78 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Lean-vs-offline classification parity (V6.4.0, lead L11, rule R-L11). 

2 

3A Lean run's book history logs the head probability behind each book call (`member_probabilities`). The same head scored 

4offline (`evaluation.model_predictions.predict_head`) on the same (date, ticker) rows must agree: this module scores both 

5on the identical population of calls and compares them to a pre-registered tolerance. Pure: no I/O, numpy only. 

6""" 

7 

8from __future__ import annotations 

9 

10import math 

11 

12import numpy as np 

13 

14TOLERANCE = {"accuracy": 0.01, "neg_log_loss": 0.01, "median_abs_probability_gap": 0.005} 

15 

16 

17def _scores(truth: np.ndarray, probability: np.ndarray) -> dict: 

18 """Accuracy of the head's own call (p >= 0.5) and the negative log-loss against the 20-bar forward direction.""" 

19 clipped = np.clip(probability, 1e-15, 1.0 - 1e-15) 

20 return { 

21 "accuracy": float(((probability >= 0.5).astype(int) == truth).mean()), 

22 "neg_log_loss": float(np.mean(truth * np.log(clipped) + (1 - truth) * np.log(1.0 - clipped))), 

23 } 

24 

25 

26def lean_vs_offline_classification(calls: dict, offline_probability: dict[tuple[str, str], float]) -> dict: 

27 """`calls` = `evaluation.backtest_statistics.lean_book_calls(...)` (truth, probability, dates, tickers); 

28 `offline_probability` = {(date, TICKER): the head's probability of "up"} for the same rows (late-bar names lagged as 

29 live is). Rows lacking either probability are dropped and counted; the verdict needs at least one matched row.""" 

30 truth, lean_p, offline_p = [], [], [] 

31 missing_lean = missing_offline = 0 

32 for index, label in enumerate(calls.get("truth", [])): 

33 lean_value = calls["probability"][index] 

34 offline_value = offline_probability.get((calls["dates"][index], calls["tickers"][index])) 

35 if lean_value is None: 

36 missing_lean += 1 

37 continue 

38 if offline_value is None or not math.isfinite(offline_value): 

39 missing_offline += 1 

40 continue 

41 truth.append(label) 

42 lean_p.append(lean_value) 

43 offline_p.append(float(offline_value)) 

44 result = { 

45 "n_calls": len(calls.get("truth", [])), "n_matched": len(truth), 

46 "missing_lean_probability": missing_lean, "missing_offline_probability": missing_offline, 

47 "tolerance": dict(TOLERANCE), 

48 } 

49 if not truth: 

50 return {**result, "lean": None, "offline": None, "deltas": None, "within_tolerance": None, 

51 "reason": "no call has both a logged and an offline probability"} 

52 truth_array = np.asarray(truth, dtype=int) 

53 lean_array, offline_array = np.asarray(lean_p, dtype=float), np.asarray(offline_p, dtype=float) 

54 lean, offline = _scores(truth_array, lean_array), _scores(truth_array, offline_array) 

55 gap = np.abs(lean_array - offline_array) 

56 deltas = { 

57 "accuracy": lean["accuracy"] - offline["accuracy"], 

58 "neg_log_loss": lean["neg_log_loss"] - offline["neg_log_loss"], 

59 "median_abs_probability_gap": float(np.median(gap)), 

60 "max_abs_probability_gap": float(gap.max()), 

61 } 

62 checks = { 

63 "accuracy": abs(deltas["accuracy"]) <= TOLERANCE["accuracy"], 

64 "neg_log_loss": abs(deltas["neg_log_loss"]) <= TOLERANCE["neg_log_loss"], 

65 "median_abs_probability_gap": deltas["median_abs_probability_gap"] <= TOLERANCE["median_abs_probability_gap"], 

66 } 

67 return {**result, "lean": lean, "offline": offline, "deltas": deltas, "checks": checks, 

68 "within_tolerance": all(checks.values()), "reason": None} 

69 

70 

71def offline_probability_map(frame, probability_column: str, date_column: str = "date", ticker_column: str = "ticker") -> dict: 

72 """{(YYYY-MM-DD, TICKER): finite probability} from a scored frame (the harness's lagged frame for late-bar names).""" 

73 dates = frame[date_column].astype(str).str[:10].tolist() 

74 tickers = frame[ticker_column].astype(str).str.upper().tolist() 

75 values = frame[probability_column].tolist() 

76 return {(day, ticker): float(value) for day, ticker, value in zip(dates, tickers, values, strict=False) if isinstance(value, (int, float)) and math.isfinite(value)} 

77 

78 

79def classification_parity_for_run_dir(run_dir, config: dict, root, *, dataset_path=None, ml_dir=None, source: str | None = None) -> dict: 

80 """`aq evaluate --classification-parity`: a Lean run's logged book-call probabilities against the same head scored 

81 offline on the same rows. Needs a run whose book history carries `member_probabilities` (V6.4.0 diagnostics) and the 

82 dataset rows of those dates; late-bar names use the previous row's prediction, as live's stale-bar convention does.""" 

83 import json 

84 from pathlib import Path 

85 

86 import pandas as pd 

87 

88 from evaluation.backtest_statistics import LEAN_PROBABILITY_SOURCE, lean_book_calls 

89 from evaluation.lean_attribution import closes_for_universe, find_book_history_for_run 

90 from evaluation.live_parity import LATE_BAR_ASSET_CLASSES, lag_predictions_for_tickers 

91 from evaluation.model_predictions import predict_head 

92 

93 root = Path(root) 

94 source = source or LEAN_PROBABILITY_SOURCE 

95 model_kind = {"direction_prob_multitask": "multitask", "direction_prob_sequence": "sequence"}.get(source) 

96 if model_kind is None: 

97 return {"status": "unsupported_source", "source": source, "within_tolerance": None} 

98 history_path = find_book_history_for_run(Path(run_dir), root / "visualization" / "book_history") 

99 if history_path is None: 

100 return {"status": "no_book_history", "source": source, "within_tolerance": None} 

101 history = [json.loads(line) for line in Path(history_path).read_text(encoding="utf-8").splitlines() if line.strip()] 

102 tickers = {str(ticker).upper() for record in history for ticker in (record.get("allocations") or {})} 

103 closes = closes_for_universe(config, root, tickers) 

104 sorted_closes = {ticker: sorted(series) for ticker, series in closes.items()} 

105 calls = lean_book_calls(history, closes, sorted_closes, source=source) 

106 if not any(value is not None for value in calls["probability"]): 

107 return {"status": "no_logged_probabilities", "source": source, "n_calls": len(calls["truth"]), "within_tolerance": None, 

108 "reason": "the run's book history has no member_probabilities (diagnostics.book_history.include_probabilities)"} 

109 

110 ml_dir = Path(ml_dir) if ml_dir else root / "ml" 

111 model_filename, schema_filename = {"multitask": ("multitask_model.json", "multitask_feature_schema.json"), 

112 "sequence": ("sequence_model.json", "sequence_feature_schema.json")}[model_kind] 

113 model_export = json.loads((ml_dir / model_filename).read_text(encoding="utf-8")) 

114 schema = json.loads((ml_dir / schema_filename).read_text(encoding="utf-8")) 

115 dataset_path = Path(dataset_path) if dataset_path else ml_dir / "datasets" / "full_dataset.csv" 

116 first = (pd.Timestamp(min(calls["dates"])) - pd.Timedelta(days=15)).strftime("%Y-%m-%d") 

117 parts = [] 

118 for chunk in pd.read_csv(dataset_path, chunksize=40_000): 

119 chunk = chunk[chunk["ticker"].astype(str).str.upper().isin(tickers)] 

120 parts.append(chunk[chunk["date"].astype(str).str[:10] >= first]) 

121 frame = pd.concat(parts, ignore_index=True) 

122 window = int(config.get("phase_v2", {}).get("sequence_model", {}).get("window_size", 30)) 

123 frame["direction_probability"] = predict_head( 

124 frame, model_export, schema["model_input_names"], "direction_20d", model_kind=model_kind, 

125 sequence_feature_schema=schema if model_kind == "sequence" else None, configured_window_size=window, 

126 ) 

127 asset_class = {str(asset["ticker"]).upper(): str(asset.get("security_type", "")) for asset in config["phase1"]["universe"]["assets"]} 

128 late = {ticker for ticker, kind in asset_class.items() if kind in LATE_BAR_ASSET_CLASSES} 

129 frame = lag_predictions_for_tickers(frame.assign(ticker=frame["ticker"].astype(str).str.upper()), 

130 prediction_column="direction_probability", tickers=late) 

131 result = lean_vs_offline_classification(calls, offline_probability_map(frame, "direction_probability")) 

132 return {"status": "ok", "source": source, "head": "direction_20d", "model": model_kind, "book_history": str(history_path), **result}