Coverage for evaluation/leakage_audit.py: 100%
66 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"""Label / feature leakage audit (V6.4.3), four checks a dataset can fail without any test noticing:
3(a) tail NaN: a feature computed with a forward-looking window is NaN on each ticker's last rows only;
4(b) label shuffle: with each target shuffled within its date, no feature may keep an IC (a nonzero one means the
5 pipeline aligns targets by something other than date and ticker);
6(c) single-feature IC: one raw feature with |IC| > 0.15 against a forward rank is implausible and gets reviewed;
7(d) identity: how much IC a pure asset-identity prior (each ticker's mean train target) and the class one-hots carry -
8 a model that cannot beat them has learned who the asset is, not what it will do.
9Pure; operates on an in-memory frame.
10"""
12from __future__ import annotations
14from typing import TYPE_CHECKING, Any
16import numpy as np
17import pandas as pd
19from evaluation.gate_audit import daily_rank_ic
21if TYPE_CHECKING:
22 from collections.abc import Sequence
25def _mean_ic(frame: pd.DataFrame, score: str, target: str, date_column: str, min_names: int) -> float | None:
26 ic = daily_rank_ic(frame, score_column=score, target_column=target, date_column=date_column, min_names_per_date=min_names)
27 return float(np.mean(list(ic.values()))) if ic else None
30def tail_nan_check(frame: pd.DataFrame, feature_columns: Sequence[str], *, ticker_column: str = "ticker", date_column: str = "date",
31 horizon: int = 20, threshold: float = 0.05) -> dict[str, Any]:
32 """Whether each feature goes missing in the last `horizon` rows of every ticker more often than the threshold, a sign it was built from future data."""
33 ordered = frame.sort_values([ticker_column, date_column])
34 position_from_end = ordered.groupby(ticker_column).cumcount(ascending=False)
35 tail = position_from_end < horizon
36 result = {}
37 for column in feature_columns:
38 missing = ordered[column].isna()
39 tail_rate, body_rate = float(missing[tail].mean()), float(missing[~tail].mean()) if (~tail).any() else 0.0
40 result[column] = {"tail_nan_rate": tail_rate, "body_nan_rate": body_rate, "flag": tail_rate - body_rate > threshold}
41 return result
44def label_shuffle_check(frame: pd.DataFrame, feature_columns: Sequence[str], target_column: str, *, date_column: str = "date",
45 min_names: int = 20, seed: int = 7, max_abs_t: float = 3.0) -> dict[str, Any]:
46 """A shuffled target's IC is sampling noise around 0; |t| above `max_abs_t` is not."""
47 rng = np.random.default_rng(seed)
48 shuffled = frame[[date_column, target_column, *feature_columns]].copy()
49 shuffled[target_column] = shuffled.groupby(date_column)[target_column].transform(lambda s: rng.permutation(s.to_numpy()))
50 result = {}
51 for column in feature_columns:
52 ic = list(daily_rank_ic(shuffled, score_column=column, target_column=target_column, date_column=date_column,
53 min_names_per_date=min_names).values())
54 mean = float(np.mean(ic)) if ic else None
55 t = float(mean / (np.std(ic, ddof=1) / np.sqrt(len(ic)))) if len(ic) > 2 and np.std(ic, ddof=1) > 0 else 0.0
56 result[column] = {"shuffled_ic": mean, "t": t, "flag": abs(t) > max_abs_t}
57 return result
60def single_feature_ic(frame: pd.DataFrame, feature_columns: Sequence[str], target_column: str, *, date_column: str = "date",
61 min_names: int = 20, threshold: float = 0.15) -> dict[str, Any]:
62 """Each feature's mean IC against the target, flagged when its size suggests it reads the future."""
63 result = {}
64 for column in feature_columns:
65 value = _mean_ic(frame, column, target_column, date_column, min_names)
66 result[column] = {"ic": value, "flag": value is not None and abs(value) > threshold}
67 return result
70def centre_by_group(frame: pd.DataFrame, target_column: str, group_column: str, *, date_column: str = "date") -> pd.Series:
71 """`target_column` minus its mean over the same (date, group). A percentile rank in a group of n names averages
72 (n+1)/2n, so with separate rank groups or small sectors the raw label means differ by group size alone (V6.4.4)."""
73 return frame[target_column] - frame.groupby([date_column, group_column])[target_column].transform("mean")
76def identity_check(train: pd.DataFrame, evaluation: pd.DataFrame, target_column: str, *, ticker_column: str = "ticker",
77 date_column: str = "date", class_columns: Sequence[str]=(), model_score_column: str | None = None, min_names: int = 20,
78 group_column: str | None = None) -> dict[str, Any]:
79 """IC of an asset-identity prior (each ticker's mean train target) and an asset-class prior against the model's.
80 With `group_column` (V6.4.4) the same figures are also computed on the group-centred target ("group_centred"): the
81 raw priors mostly read the group-size artifact of percentile ranks, which a book ranking within groups cannot trade."""
82 out = _identity_figures(train, evaluation, target_column, ticker_column=ticker_column, date_column=date_column,
83 class_columns=class_columns, model_score_column=model_score_column, min_names=min_names)
84 if group_column and group_column in train.columns and group_column in evaluation.columns:
85 centred = "_target_group_centred"
86 out["group_centred"] = _identity_figures(
87 train.assign(**{centred: centre_by_group(train, target_column, group_column, date_column=date_column)}),
88 evaluation.assign(**{centred: centre_by_group(evaluation, target_column, group_column, date_column=date_column)}),
89 centred, ticker_column=ticker_column, date_column=date_column, class_columns=class_columns,
90 model_score_column=model_score_column, min_names=min_names)
91 out["group_column"] = group_column
92 return out
95def _identity_figures(train: pd.DataFrame, evaluation: pd.DataFrame, target_column: str, *, ticker_column: str, date_column: str,
96 class_columns, model_score_column: str | None, min_names: int) -> dict[str, Any]:
97 prior = train.groupby(ticker_column)[target_column].mean()
98 scored = evaluation.assign(_identity_prior=evaluation[ticker_column].map(prior))
99 out = {"identity_prior_ic": _mean_ic(scored, "_identity_prior", target_column, date_column, min_names)}
100 present = [c for c in class_columns if c in evaluation.columns]
101 if present:
102 train_class = train[present].to_numpy(dtype=float).argmax(axis=1)
103 class_mean = pd.Series(train[target_column].to_numpy(dtype=float), index=train_class).groupby(level=0).mean()
104 eval_class = pd.Series(evaluation[present].to_numpy(dtype=float).argmax(axis=1), index=evaluation.index)
105 scored = scored.assign(_class_prior=eval_class.map(class_mean))
106 out["class_prior_ic"] = _mean_ic(scored, "_class_prior", target_column, date_column, min_names)
107 if model_score_column and model_score_column in evaluation.columns:
108 out["model_ic"] = _mean_ic(evaluation, model_score_column, target_column, date_column, min_names)
109 if out["identity_prior_ic"] is not None and out["model_ic"] is not None:
110 out["model_minus_identity"] = out["model_ic"] - out["identity_prior_ic"]
111 return out
114def audit_leakage(frame: pd.DataFrame, *, feature_columns: Sequence[str], target_column: str = "target_rank_20d", ticker_column: str = "ticker",
115 date_column: str = "date", split_column: str = "split", horizon: int = 20, class_columns: Sequence[str]=(),
116 model_score_column: str | None = None, min_names: int = 20, seed: int = 7, group_column: str | None = None) -> dict[str, Any]:
117 """All four checks; (b) and (c) on the validation split, (d) fit on train and read on validation."""
118 validation = frame[frame[split_column] == "validation"] if split_column in frame else frame
119 train = frame[frame[split_column] == "train"] if split_column in frame else frame
120 report = {
121 "tail_nan": tail_nan_check(frame, feature_columns, ticker_column=ticker_column, date_column=date_column, horizon=horizon),
122 "label_shuffle": label_shuffle_check(validation, feature_columns, target_column, date_column=date_column,
123 min_names=min_names, seed=seed),
124 "single_feature_ic": single_feature_ic(validation, feature_columns, target_column, date_column=date_column, min_names=min_names),
125 "identity": identity_check(train, validation, target_column, ticker_column=ticker_column, date_column=date_column,
126 class_columns=class_columns, model_score_column=model_score_column, min_names=min_names,
127 group_column=group_column),
128 }
129 report["flagged"] = sorted(
130 {column for check in ("tail_nan", "label_shuffle", "single_feature_ic") for column, row in report[check].items() if row["flag"]}
131 )
132 return report