Coverage for evaluation/feature_quality_audit.py: 100%

65 statements  

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

1"""Model-input feature quality audit (V5.8.0). 

2 

3Two V5.7/V5.8 findings were feature defects no metric surfaced: `bond_empirical_duration_beta` was one OLS slope over 

4the whole 2014-2021 history broadcast to every row (a leak that also acts as a ticker ID), and the volume/spread family 

5is constant for forex (Yahoo forex volume is 0), so the model had nothing forex-specific to rank on. This audit flags 

6both classes mechanically, per feature: 

7 

8 * `ticker_constant_share` - share of tickers whose value never changes across their rows (ticker-ID / leak suspect), 

9 * `class_constant` - per asset class, whether the feature has (near) zero cross-sectional variance on most dates, 

10 * `daily_ic` - mean univariate daily rank IC against the target, per split (sign stability across splits matters more 

11 than size for a single feature), 

12 * `permutation_drop` (optional) - validation IC drop of the model when the feature is shuffled within dates. 

13 

14Pure pandas/numpy; the model is passed in as a callable so this stays torch-free. 

15""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable 

20 

21import numpy as np 

22import pandas as pd 

23 

24 

25def _daily_ic(frame: pd.DataFrame, column: str, target: str, date_column: str, min_names: int) -> float | None: 

26 values = [] 

27 for _date, day in frame[[date_column, column, target]].dropna().groupby(date_column): 

28 if len(day) < min_names: 

29 continue 

30 x = day[column].rank().to_numpy() 

31 y = day[target].rank().to_numpy() 

32 if np.ptp(x) == 0.0 or np.ptp(y) == 0.0: 

33 continue 

34 value = float(np.corrcoef(x, y)[0, 1]) 

35 if np.isfinite(value): 

36 values.append(value) 

37 return float(np.mean(values)) if values else None 

38 

39 

40def feature_quality( 

41 frame: pd.DataFrame, 

42 features: list[str], 

43 *, 

44 target: str = "target_rank_20d", 

45 split_column: str = "split", 

46 class_column: str = "asset_class", 

47 ticker_column: str = "ticker", 

48 date_column: str = "date", 

49 min_names: int = 10, 

50 constant_tolerance: float = 1e-12, 

51 constant_date_share: float = 0.9, 

52) -> dict: 

53 """Per-feature diagnostics over `frame` (rows of every split). Returns {feature: {...}} plus a `flags` summary.""" 

54 report: dict[str, dict] = {} 

55 splits = [split for split in ("train", "validation", "backtest") if split in set(frame[split_column].unique())] 

56 for feature in features: 

57 if feature not in frame.columns: 

58 continue 

59 column = pd.to_numeric(frame[feature], errors="coerce") 

60 data = frame[[ticker_column, date_column, class_column, split_column, target]].assign(value=column) 

61 per_ticker_unique = data.groupby(ticker_column)["value"].nunique(dropna=True) 

62 ticker_constant_share = float((per_ticker_unique <= 1).mean()) if len(per_ticker_unique) else 0.0 

63 class_constant = {} 

64 for kind, group in data.groupby(class_column): 

65 per_date_std = group.groupby(date_column)["value"].std(ddof=0).dropna() 

66 if len(per_date_std): 

67 class_constant[str(kind)] = bool((per_date_std <= constant_tolerance).mean() >= constant_date_share) 

68 daily_ic = { 

69 split: _daily_ic(data[data[split_column] == split], "value", target, date_column, min_names) for split in splits 

70 } 

71 signs = {np.sign(value) for value in daily_ic.values() if value is not None and abs(value) > 1e-4} 

72 report[feature] = { 

73 "missing_share": float(column.isna().mean()), 

74 "ticker_constant_share": round(ticker_constant_share, 4), 

75 "class_constant": class_constant, 

76 "daily_ic": daily_ic, 

77 "ic_sign_stable": len(signs) <= 1, 

78 } 

79 flags = { 

80 "ticker_id_suspects": sorted(f for f, r in report.items() if r["ticker_constant_share"] >= 0.5), 

81 "constant_for_class": { 

82 kind: sorted(f for f, r in report.items() if r["class_constant"].get(kind)) 

83 for kind in sorted({k for r in report.values() for k in r["class_constant"]}) 

84 }, 

85 "ic_sign_unstable": sorted(f for f, r in report.items() if not r["ic_sign_stable"]), 

86 } 

87 return {"features": report, "flags": flags} 

88 

89 

90def permutation_ic_drop( 

91 frame: pd.DataFrame, 

92 features: list[str], 

93 predict: Callable[[pd.DataFrame], np.ndarray], 

94 *, 

95 target: str = "target_rank_20d", 

96 date_column: str = "date", 

97 min_names: int = 10, 

98 seed: int = 7, 

99) -> dict[str, float | None]: 

100 """Mean daily IC of `predict(frame)` minus the IC after shuffling one feature WITHIN each date (keeps the per-date 

101 distribution, breaks the link to the row). Positive = the model uses the feature.""" 

102 rng = np.random.default_rng(seed) 

103 base_scores = frame.assign(_score=predict(frame)) 

104 base = _daily_ic(base_scores, "_score", target, date_column, min_names) 

105 drops: dict[str, float | None] = {} 

106 for feature in features: 

107 if feature not in frame.columns or base is None: 

108 drops[feature] = None 

109 continue 

110 shuffled = frame.copy() 

111 shuffled[feature] = shuffled.groupby(date_column)[feature].transform( 

112 lambda values: values.to_numpy()[rng.permutation(len(values))] 

113 ) 

114 scored = shuffled.assign(_score=predict(shuffled)) 

115 value = _daily_ic(scored, "_score", target, date_column, min_names) 

116 drops[feature] = None if value is None else float(base - value) 

117 return drops 

118 

119 

120def select_feature_subset( 

121 features: list[str], 

122 *, 

123 permutation_drop: dict[str, float | None], 

124 early_ic: dict[str, float | None], 

125 late_ic: dict[str, float | None], 

126 ticker_id_suspects: list[str], 

127 min_abs_ic: float = 0.002, 

128) -> dict: 

129 """V6.2.0 smaller input set, chosen on the TRAIN split only (validation stays the judge). A feature is kept when the 

130 installed model uses it (permutation drop > 0 on the late train window), its own daily IC has the same sign and at 

131 least `min_abs_ic` size in both train halves (an in-sample drop alone keeps almost everything an overfit model 

132 touches), and it is not a ticker-ID suspect. Order follows `features` (the live vector's).""" 

133 kept, reasons = [], {} 

134 suspects = set(ticker_id_suspects) 

135 for feature in features: 

136 drop, early, late = permutation_drop.get(feature), early_ic.get(feature), late_ic.get(feature) 

137 if feature in suspects: 

138 reasons[feature] = "ticker_id_suspect" 

139 elif drop is None or drop <= 0.0: 

140 reasons[feature] = "unused_by_model" 

141 elif early is None or late is None or abs(early) < min_abs_ic or abs(late) < min_abs_ic or np.sign(early) != np.sign(late): 

142 reasons[feature] = "unstable_train_ic" 

143 else: 

144 kept.append(feature) 

145 return {"kept": kept, "dropped": reasons}