Coverage for evaluation/engaged_day_skill.py: 100%

68 statements  

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

1"""Rank skill on the days the rolling-IC gate lets the book trade (V6.4.0, lead L1). Pure given a scored frame. 

2 

3The gate vetoes most rebalances, so the pooled IC (~0.05) mixes days the book trades with days it sits out. The question 

4is whether the engaged days carry clearly more skill than all days (then the gate protects capital) or the same (then it 

5hides weakness). This module splits a scored frame by the gate's per-date verdict and reports, for each subset, the daily 

6rank IC (mean, non-overlapping mean, HAC t), the top-N / bottom-N spread of the forward return, and, from a simulated 

7as-live run, the Sharpe of the days whose most recent rebalance was engaged against all days. 

8""" 

9 

10from __future__ import annotations 

11 

12import math 

13import statistics 

14 

15import numpy as np 

16import pandas as pd 

17 

18from evaluation.gate_audit import daily_rank_ic 

19from evaluation.rank_ic_core import newey_west_t_stat 

20 

21# the owner's pre-set margins: the gate protects capital only if engaged days beat all days by this much on both splits 

22MIN_IC_MARGIN = 0.02 

23MIN_SHARPE_MARGIN = 0.15 

24 

25 

26def gate_labels(gate_fn, dates) -> dict[str, bool]: 

27 """{date: the rolling-IC gate engaged}; `gate_fn(date)` is `AsLiveHarness.gate_for(...)`'s callable.""" 

28 return {str(date): bool((gate_fn(str(date)) or {}).get("engaged", False)) for date in dates} 

29 

30 

31def _non_overlapping(values: dict[str, float], calendar: list[str], horizon: int) -> list[float]: 

32 """Greedy sample of `values` at least `horizon` sessions apart on `calendar` (labels of nearer dates share a window).""" 

33 position = {day: index for index, day in enumerate(calendar)} 

34 chosen, last = [], None 

35 for day in sorted(values, key=lambda d: position.get(d, math.inf)): 

36 index = position.get(day) 

37 if index is None or (last is not None and index - last < horizon): 

38 continue 

39 chosen.append(values[day]) 

40 last = index 

41 return chosen 

42 

43 

44def _spread(day: pd.DataFrame, score_column: str, forward_column: str, top_n: int, bottom_n: int) -> float | None: 

45 day = day[[score_column, forward_column]].dropna() 

46 if len(day) < top_n + bottom_n: 

47 return None 

48 ordered = day.sort_values(score_column) 

49 return float(ordered[forward_column].tail(top_n).mean() - ordered[forward_column].head(bottom_n).mean()) 

50 

51 

52def subset_skill(frame: pd.DataFrame, dates: set[str] | None, calendar: list[str], *, score_column: str, target_column: str, 

53 forward_column: str, top_n: int, bottom_n: int, horizon: int, min_names: int) -> dict: 

54 """Skill over `dates` (None = every date of the frame).""" 

55 data = frame 

56 if dates is not None: 

57 data = frame[frame["date"].astype(str).str[:10].isin(dates)] 

58 ics = daily_rank_ic(data, score_column=score_column, target_column=target_column, min_names_per_date=min_names) 

59 spreads = [ 

60 value for _day, part in data.groupby(data["date"].astype(str).str[:10], sort=True) 

61 if (value := _spread(part, score_column, forward_column, top_n, bottom_n)) is not None 

62 ] 

63 sampled = _non_overlapping(ics, calendar, horizon) 

64 return { 

65 "n_dates": len(ics), 

66 "daily_mean_ic": float(np.mean(list(ics.values()))) if ics else None, 

67 "non_overlapping_mean_ic": float(np.mean(sampled)) if sampled else None, 

68 "non_overlapping_n": len(sampled), 

69 "hac_t": float(newey_west_t_stat(list(ics.values()), horizon - 1)) if len(ics) > 1 else None, 

70 "long_short_spread": float(np.mean(spreads)) if spreads else None, 

71 } 

72 

73 

74def engaged_vs_all(frame: pd.DataFrame, labels: dict[str, bool], *, score_column: str = "live_rank_score", 

75 target_column: str = "target_rank_20d", forward_column: str = "target_return_20d", top_n: int = 6, 

76 bottom_n: int = 6, horizon: int = 20, min_names: int = 10) -> dict: 

77 """{"all", "engaged", "vetoed"} skill dicts plus the IC difference; `labels` from `gate_labels`. Dates the gate has no 

78 verdict on count as vetoed.""" 

79 calendar = sorted(set(frame["date"].astype(str).str[:10])) 

80 engaged = {day for day in calendar if labels.get(day, False)} 

81 vetoed = set(calendar) - engaged 

82 kwargs = dict(score_column=score_column, target_column=target_column, forward_column=forward_column, top_n=top_n, 

83 bottom_n=bottom_n, horizon=horizon, min_names=min_names) 

84 result = {"all": subset_skill(frame, None, calendar, **kwargs), 

85 "engaged": subset_skill(frame, engaged, calendar, **kwargs) if engaged else None, 

86 "vetoed": subset_skill(frame, vetoed, calendar, **kwargs) if vetoed else None, 

87 "engaged_dates": len(engaged), "vetoed_dates": len(vetoed)} 

88 one, other = (result["engaged"] or {}).get("daily_mean_ic"), result["all"]["daily_mean_ic"] 

89 result["ic_margin"] = None if one is None or other is None else one - other 

90 return result 

91 

92 

93def sharpe(series, periods: int = 252) -> float | None: 

94 values = [float(value) for value in series if value is not None and math.isfinite(value)] 

95 if len(values) < 3: 

96 return None 

97 std = statistics.stdev(values) 

98 return None if std <= 0.0 else statistics.fmean(values) / std * math.sqrt(periods) 

99 

100 

101def engaged_window_returns(per_date_net_return: dict[str, float], rebalance_log: list[dict]) -> tuple[list[float], list[float]]: 

102 """(returns on days whose most recent rebalance was engaged, every day's return): each day belongs to the latest 

103 rebalance on or before it. `rebalance_log` = the simulator's [{"date", "engaged", ...}].""" 

104 entries = sorted(((str(entry["date"])[:10], bool(entry.get("engaged"))) for entry in rebalance_log), key=lambda e: e[0]) 

105 engaged_returns, all_returns = [], [] 

106 pointer, current = 0, None 

107 for day in sorted(per_date_net_return): 

108 while pointer < len(entries) and entries[pointer][0] <= day: 

109 current = entries[pointer][1] 

110 pointer += 1 

111 all_returns.append(per_date_net_return[day]) 

112 if current: 

113 engaged_returns.append(per_date_net_return[day]) 

114 return engaged_returns, all_returns 

115 

116 

117def l1_verdict(per_split: dict[str, dict]) -> dict: 

118 """The owner's bar: on BOTH splits the engaged days beat all days by >= +0.02 IC and >= +0.15 Sharpe (median across 

119 rebalance phases). `per_split` = {split: {"ic_margin": float | None, "sharpe_margin": float | None}}.""" 

120 checks = {} 

121 for split, values in per_split.items(): 

122 checks[split] = { 

123 "ic_margin_ge_0.02": values.get("ic_margin") is not None and values["ic_margin"] >= MIN_IC_MARGIN, 

124 "sharpe_margin_ge_0.15": values.get("sharpe_margin") is not None and values["sharpe_margin"] >= MIN_SHARPE_MARGIN, 

125 } 

126 passed = bool(checks) and all(all(split.values()) for split in checks.values()) 

127 return {"checks": checks, "gate_protects_capital": passed, 

128 "reading": "the gate protects capital" if passed else "the gate hides weakness, not protects capital"}