Coverage for features/training_splits.py: 100%

98 statements  

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

1"""How a dataset is split for training, with nothing of the training stack (V6.6.1): walls between train, validation and backtest, label purges, purged folds, yearly walk-forward windows and 

2ranked inputs. Moved unchanged from `train.py` and `train_cross_sectional.py`, which import them from here, so `aether_quant` can offer them without torch or sklearn.""" 

3 

4from __future__ import annotations 

5 

6from typing import TYPE_CHECKING, Any 

7 

8import numpy as np 

9import pandas as pd 

10 

11if TYPE_CHECKING: 

12 from numpy.typing import ArrayLike 

13 

14_SPLIT_ORDER = {"train": 0, "validation": 1, "backtest": 2} 

15TARGET = "target_sector_neutral_rank_20d" 

16PURGE_DAYS = 20 

17FIRST_TEST_YEAR = 2019 

18 

19 

20def purge_label_overlap(splits: list[Any], horizon_rows: int) -> list[Any]: 

21 """V5.7.0: relabel "purged" every row whose forward label window reaches into a LATER split. A row labelled 

22 `horizon_rows` bars ahead (the 20-day return / rank targets) carries information from the next split's prices, so the 

23 last `horizon_rows` rows of train (and of validation) leak the validation (and backtest) period into the data the model 

24 is fitted, early-stopped and selected on. `splits` is one asset's per-row split labels in date order (None / NaN rows 

25 are outside every window and stay as they are); purged rows are kept in the frame as feature context but match no 

26 split filter. `horizon_rows <= 0` returns the labels unchanged.""" 

27 result = list(splits) 

28 if horizon_rows <= 0: 

29 return result 

30 first_index: dict[str, int] = {} 

31 for index in range(len(splits) - 1, -1, -1): 

32 label = splits[index] 

33 if not isinstance(label, str) or label not in _SPLIT_ORDER: 

34 continue 

35 rank = _SPLIT_ORDER[label] 

36 later_starts = [start for name, start in first_index.items() if _SPLIT_ORDER[name] > rank] 

37 if later_starts and min(later_starts) - index <= horizon_rows: 

38 result[index] = "purged" 

39 first_index[label] = index 

40 return result 

41 

42 

43def purge_label_overlap_calendar(splits: list[Any], dates: list[Any], calendar_days: int) -> list[Any]: 

44 """`purge_label_overlap` in calendar days. A pooled rank mixes classes: 20 crypto bars are 20 days but 20 equity sessions are 

45 about 28, so a crypto row kept by a 20-row purge can have a rank built from equity returns past the boundary. 

46 `calendar_days <= 0` returns the labels unchanged.""" 

47 result = list(splits) 

48 if calendar_days <= 0: 

49 return result 

50 stamps = [pd.Timestamp(date) for date in dates] 

51 first_date: dict[str, pd.Timestamp] = {} 

52 for index in range(len(splits) - 1, -1, -1): 

53 label = splits[index] 

54 if not isinstance(label, str) or label not in _SPLIT_ORDER: 

55 continue 

56 rank = _SPLIT_ORDER[label] 

57 later_starts = [start for name, start in first_date.items() if _SPLIT_ORDER[name] > rank] 

58 if later_starts and (min(later_starts) - stamps[index]).days <= calendar_days: 

59 result[index] = "purged" 

60 first_date[label] = stamps[index] 

61 return result 

62 

63 

64def assign_split(date_value: pd.Timestamp, windows: dict[str, Any]) -> str | None: 

65 """Which window a date falls in (training, validation or backtest), or None outside them.""" 

66 date_stamp = pd.Timestamp(date_value) 

67 training = windows["training"] 

68 validation = windows["validation"] 

69 backtest = windows["backtest"] 

70 

71 if pd.Timestamp(training["start"]) <= date_stamp <= pd.Timestamp(training["end"]): 

72 return "train" 

73 if pd.Timestamp(validation["start"]) <= date_stamp <= pd.Timestamp(validation["end"]): 

74 return "validation" 

75 if pd.Timestamp(backtest["start"]) <= date_stamp <= pd.Timestamp(backtest["end"]): 

76 return "backtest" 

77 return None 

78 

79 

80def assign_split_series(dates: pd.Series, windows: dict[str, Any]) -> pd.Series: 

81 """assign_split() for a whole column at once (V5.8.0: the per-row apply ran once per dataset row); same inclusive 

82 bounds and precedence, None outside every window.""" 

83 stamps = pd.to_datetime(dates) 

84 labels = pd.Series([None] * len(stamps), index=dates.index, dtype=object) 

85 for split_name, key in (("backtest", "backtest"), ("validation", "validation"), ("train", "training")): 

86 window = windows[key] 

87 inside = (stamps >= pd.Timestamp(window["start"])) & (stamps <= pd.Timestamp(window["end"])) 

88 labels[inside.to_numpy()] = split_name # earlier splits written last win on overlap, as in assign_split() 

89 return labels 

90 

91 

92def purged_embargoed_folds( 

93 dates: ArrayLike, 

94 n_folds: int, 

95 horizon_days: int, 

96 embargo_days: int = 0, 

97) -> list[tuple[np.ndarray, np.ndarray]]: 

98 """Phase 2 of the 5/10 -> 9/10 roadmap: a standard purged/embargoed 

99 K-fold split (Lopez de Prado-style) over `dates` (any array-like of 

100 orderable date values, one entry per dataset row - duplicates expected, 

101 since every asset shares each date). Layered *inside* the existing 

102 fixed phase1.windows train split as an additional diagnostic for 

103 hyperparameter/early-stopping robustness and a more honest in-sample IC 

104 distribution - it does NOT replace the top-level train/validation/backtest 

105 wall (that stays the single no-lookahead-across-the-wall boundary; see 

106 assign_split()), nor does it change which rows actually get promoted. 

107 

108 For each of `n_folds` contiguous, equal-width date-range folds (assigned 

109 by unique date, not by row, so every asset's same-date rows always fall 

110 in the same fold together): the *validation* fold is exactly that 

111 date-range; the *training* rows are every row from the OTHER folds, 

112 minus (a) any row whose own forward-return window (horizon_days ahead) 

113 would overlap the validation fold's date range at all ("purge" - a 

114 training row labeled using information that reaches into the validation 

115 window leaks), and (b) any row falling within `embargo_days` immediately 

116 AFTER the validation fold's end date ("embargo" - guards against 

117 lookback-feature leakage, e.g. rolling_volatility_20d/momentum_20d 

118 computed just after the validation window still partially "sees" it). 

119 

120 Returns a list of (train_row_indices, validation_row_indices) index 

121 arrays into `dates` itself (positional, 0-based) - same shape 

122 convention as sklearn's KFold.split(), so this composes with any 

123 existing sklearn-based tooling without adapting a different interface. 

124 Returns [] (never raises) when there are fewer unique dates than 

125 `n_folds`, matching this codebase's "guard against thin data" convention 

126 throughout train.py (e.g. build_cross_sectional_rank_targets()'s 

127 min_universe_size gate).""" 

128 # pd.to_datetime(), not np.asarray(): `dates` in real callers (e.g. 

129 # assess_ranking_quality_from_predictions(), fed train_multitask.py/ 

130 # train_sequence.py's `frame["date"]`) is a plain string array - 

131 # build_feature_dataset() stringifies the date column 

132 # (dataset["date"].dt.strftime(...)) before any trainer ever reads it. 

133 # A raw np.asarray() on strings stays strings, and `era_start + Timedelta` 

134 # below would then raise "can only concatenate str to str" - explicit 

135 # datetime coercion here makes this function robust to string, 

136 # Timestamp, or datetime64 input alike, matching every other 

137 # date-accepting function in this file (e.g. assign_split()'s own 

138 # pd.Timestamp(date_value) coercion). 

139 # 

140 # np.unique(), not sorted(set(dates_array.tolist())): for a raw 

141 # datetime64[ns] numpy array (as opposed to a pandas Series, whose 

142 # .tolist() preserves Timestamp objects), .tolist() silently degrades 

143 # to plain nanosecond ints - Python's stdlib datetime can't represent 

144 # nanosecond precision - which would then compare incompatibly against 

145 # the still-datetime64 dates_array below. np.unique() preserves dtype 

146 # natively and needs no such workaround. 

147 dates_array = pd.to_datetime(np.asarray(dates)) 

148 unique_dates = np.unique(dates_array) 

149 if len(unique_dates) < n_folds: 

150 return [] 

151 

152 fold_boundaries = np.array_split(unique_dates, n_folds) 

153 folds: list[tuple[np.ndarray, np.ndarray]] = [] 

154 horizon = pd.Timedelta(horizon_days, unit="D") 

155 embargo = pd.Timedelta(embargo_days, unit="D") 

156 

157 for fold_dates in fold_boundaries: # n_folds <= the unique dates, so no fold is empty 

158 validation_start = fold_dates[0] 

159 validation_end = fold_dates[-1] 

160 validation_mask = (dates_array >= validation_start) & (dates_array <= validation_end) 

161 

162 # Purge: a training row's own forward-return window (up to 

163 # horizon_days ahead of its own date) must not reach into the 

164 # validation date range - equivalently, exclude any row whose date 

165 # falls within horizon_days BEFORE the validation window starts. 

166 purge_start = validation_start - horizon 

167 purged_mask = (dates_array >= purge_start) & (dates_array < validation_start) 

168 

169 # Embargo: exclude rows in the embargo_days immediately after the 

170 # validation window ends. 

171 embargo_end = validation_end + embargo 

172 embargoed_mask = (dates_array > validation_end) & (dates_array <= embargo_end) 

173 

174 excluded_mask = validation_mask | purged_mask | embargoed_mask 

175 train_indices = np.where(~excluded_mask)[0] 

176 validation_indices = np.where(validation_mask)[0] 

177 if len(train_indices) == 0 or len(validation_indices) == 0: 

178 continue 

179 folds.append((train_indices, validation_indices)) 

180 

181 return folds 

182 

183 

184def annual_windows(dates: list[str], *, first_test_year: int = FIRST_TEST_YEAR, purge_days: int = PURGE_DAYS) -> list[dict]: 

185 """Expanding windows: each test year is scored by a model trained on everything up to `purge_days` before it, since a 

186 20-day label of a row closer than that is still open on the test year's first day.""" 

187 last_year = int(max(dates)[:4]) 

188 windows = [] 

189 for year in range(first_test_year, last_year + 1): 

190 test_start = f"{year}-01-01" 

191 train_end = (pd.Timestamp(test_start) - pd.Timedelta(days=purge_days + 1)).strftime("%Y-%m-%d") 

192 if any(date <= train_end for date in dates): 

193 windows.append({"train_end": train_end, "test_start": test_start, "test_end": f"{year}-12-31"}) 

194 return windows 

195 

196 

197def rank_inputs(frame: pd.DataFrame, features: list[str]) -> pd.DataFrame: 

198 """Within-(date, class) percentile rank minus one half; a missing value reads as the middle of its group.""" 

199 grouped = frame.groupby(["date", "_class"], sort=False) 

200 ranked = grouped[features].rank(pct=True) - 0.5 

201 return ranked.fillna(0.0).astype("float32") 

202 

203 

204def centred_label(frame: pd.DataFrame, target: str = TARGET) -> pd.Series: 

205 """The target minus its mean over the same date and class, so class size does not shift the label.""" 

206 return (frame[target] - frame.groupby(["date", "_class"], sort=False)[target].transform("mean")).astype("float32") 

207