Coverage for evaluation/class_ic_audit.py: 100%

53 statements  

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

1"""Within- vs between-asset-class rank-IC decomposition (V5.8.0). 

2 

3The pooled rank IC of the book's head mixes two different bets: ranking names WITHIN an asset class (what a sector- or 

4class-neutral book monetises) and ranking the CLASSES against each other (bonds below equities in a sell-off, which is a 

5market-direction bet in a dollar-neutral book). On the 2021-25 holdout the pooled rank_20d IC was +0.069 while the 

6within-bond IC was -0.001, so a pooled number alone cannot say whether a sleeve has an edge. 

7 

8Per date this reports the pooled IC, the within-class IC of every class with enough names, and the between-class IC 

9(class-mean prediction vs class-mean realized rank, needs >= 3 classes). Each series gets its mean, HAC t and date count. 

10Pure pandas/numpy, no I/O. 

11""" 

12 

13from __future__ import annotations 

14 

15from collections import defaultdict 

16 

17import numpy as np 

18import pandas as pd 

19 

20from evaluation.rank_ic_core import newey_west_t_stat 

21 

22 

23def _spearman(predictions: np.ndarray, targets: np.ndarray) -> float | None: 

24 if len(predictions) < 2: 

25 return None 

26 prediction_rank = pd.Series(predictions).rank().to_numpy() 

27 target_rank = pd.Series(targets).rank().to_numpy() 

28 if np.ptp(prediction_rank) == 0.0 or np.ptp(target_rank) == 0.0: 

29 return None 

30 value = float(np.corrcoef(prediction_rank, target_rank)[0, 1]) 

31 return value if np.isfinite(value) else None 

32 

33 

34def _summary(values: list[float], horizon: int) -> dict: 

35 finite = [value for value in values if value is not None and np.isfinite(value)] 

36 return { 

37 "mean_ic": float(np.mean(finite)) if finite else None, 

38 "hac_t": newey_west_t_stat(finite, max(horizon - 1, 0)) if len(finite) >= 2 else 0.0, 

39 "num_dates": len(finite), 

40 "positive_share": float(np.mean([value > 0 for value in finite])) if finite else None, 

41 } 

42 

43 

44def class_ic_decomposition( 

45 frame: pd.DataFrame, 

46 *, 

47 prediction: str, 

48 target: str, 

49 class_column: str = "asset_class", 

50 date_column: str = "date", 

51 horizon: int = 20, 

52 min_names_per_class: int = 5, 

53 min_names_pooled: int = 10, 

54) -> dict: 

55 """`frame` has one row per ticker-date with a prediction, a realized target (a return or a per-date rank of it) and 

56 an asset class. Rows with a non-finite prediction or target are dropped. Returns 

57 {"pooled", "within": {class: summary}, "between", "within_weighted", "class_share_of_pooled"}.""" 

58 columns = [date_column, class_column, prediction, target] 

59 data = frame[columns].copy() 

60 data = data[np.isfinite(data[prediction].astype(float)) & np.isfinite(data[target].astype(float))] 

61 pooled: list[float] = [] 

62 between: list[float] = [] 

63 within: dict[str, list[float]] = defaultdict(list) 

64 within_weighted: list[float] = [] 

65 for _date, day in data.groupby(date_column, sort=True): 

66 if len(day) >= min_names_pooled: 

67 value = _spearman(day[prediction].to_numpy(float), day[target].to_numpy(float)) 

68 if value is not None: 

69 pooled.append(value) 

70 weighted_sum, weight_total = 0.0, 0 

71 class_means = [] 

72 for kind, group in day.groupby(class_column): 

73 if len(group) >= min_names_per_class: 

74 value = _spearman(group[prediction].to_numpy(float), group[target].to_numpy(float)) 

75 if value is not None: 

76 within[str(kind)].append(value) 

77 weighted_sum += value * len(group) 

78 weight_total += len(group) 

79 class_means.append((float(group[prediction].mean()), float(group[target].mean()))) 

80 if weight_total: 

81 within_weighted.append(weighted_sum / weight_total) 

82 if len(class_means) >= 3: 

83 means = np.asarray(class_means) 

84 value = _spearman(means[:, 0], means[:, 1]) 

85 if value is not None: 

86 between.append(value) 

87 pooled_summary = _summary(pooled, horizon) 

88 within_weighted_summary = _summary(within_weighted, horizon) 

89 share = None 

90 if pooled_summary["mean_ic"] and within_weighted_summary["mean_ic"] is not None: 

91 share = 1.0 - within_weighted_summary["mean_ic"] / pooled_summary["mean_ic"] 

92 return { 

93 "prediction": prediction, 

94 "target": target, 

95 "pooled": pooled_summary, 

96 "within": {kind: _summary(values, horizon) for kind, values in sorted(within.items())}, 

97 "within_weighted": within_weighted_summary, 

98 "between": _summary(between, horizon), 

99 # 1 - within/pooled: how much of the pooled IC is NOT explained by ranking inside classes (None if pooled ~ 0) 

100 "class_share_of_pooled": share, 

101 }