Coverage for lab/lab_dataset.py: 100%

108 statements  

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

1"""The lab's datasets: features, forward rank targets and split labels in the production dataset's column layout, and the 

2sealed-holdout rule every lab read goes through. 

3 

4A row of `aq dataset build` is (date, ticker): its features use closes up to that date (`features/feature_registry.py`), 

5its targets the closes after it (`evaluation/signal_tools.forward_rank_targets`), and its split comes from date windows 

6with the label horizon purged at each boundary: a train row whose 20-day label reaches into validation is labelled 

7`purged`, kept for the sequence windows and never fitted or scored. 

8""" 

9 

10from __future__ import annotations 

11 

12import json 

13from collections.abc import Mapping, Sequence 

14from pathlib import Path 

15from typing import Any 

16 

17import numpy as np 

18import pandas as pd 

19 

20from evaluation.signal_tools import forward_rank_targets 

21from features import feature_registry 

22 

23SPLITS = ("train", "validation", "backtest", "holdout") 

24PURGED = "purged" 

25ID_COLUMNS = ("date", "ticker", "close", "split") 

26 

27 

28class HoldoutSealed(PermissionError): 

29 """A lab read reached a sealed holdout row.""" 

30 

31 

32def parse_splits(text: str) -> dict[str, tuple[str, str]]: 

33 """'train:2021-06-01..2023-12-31,validation:2024-01-01..2024-12-31' -> {split: (start, end)} (ISO dates, inclusive).""" 

34 out: dict[str, tuple[str, str]] = {} 

35 for part in [item.strip() for item in text.split(",") if item.strip()]: 

36 name, _, span = part.partition(":") 

37 start, _, end = span.partition("..") 

38 if name not in SPLITS or not start or not end: 

39 raise ValueError(f"bad split {part!r}: write NAME:START..END with NAME in {', '.join(SPLITS)}") 

40 pd.Timestamp(start), pd.Timestamp(end) 

41 out[name] = (start, end) 

42 return out 

43 

44 

45def default_splits(dates: Sequence[str]) -> dict[str, tuple[str, str]]: 

46 """60% train, 20% validation, 20% backtest of the dates in order (no holdout).""" 

47 ordered = sorted(set(dates)) 

48 if len(ordered) < 10: 

49 raise ValueError("need at least 10 dates to split") 

50 first, second = int(len(ordered) * 0.6), int(len(ordered) * 0.8) 

51 return {"train": (ordered[0], ordered[first - 1]), "validation": (ordered[first], ordered[second - 1]), "backtest": (ordered[second], ordered[-1])} 

52 

53 

54def label_splits(dates: pd.Series, windows: Mapping[str, tuple[str, str]], *, horizon: int, calendar: Sequence[str]) -> pd.Series: 

55 """Each date's split; `purged` when its `horizon`-session label reaches past its own window's end (kept, so a sequence 

56 model's window still sees that date as live does, but never fitted or scored); None outside every window.""" 

57 order = {date: index for index, date in enumerate(sorted(set(calendar)))} 

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

59 positions = dates.map(order) 

60 for name, (start, end) in windows.items(): 

61 inside = (dates >= start) & (dates <= end) 

62 ends = [index for date, index in order.items() if date <= end] 

63 last = max(ends) if ends else -1 

64 labels[inside] = "purged" 

65 labels[inside & (positions + horizon <= last)] = name 

66 return labels 

67 

68 

69def build_dataset(closes: pd.DataFrame, *, features: str | Sequence[str] = "core", targets: Sequence[int] = (5, 20), 

70 splits: Mapping[str, tuple[str, str]] | None = None, min_names: int = 3) -> pd.DataFrame: 

71 """The long dataset: `date, ticker, close, <features>, target_return_*, target_rank_*d, target_direction_20d, split`.""" 

72 names = feature_registry.resolve(features) 

73 closes = closes.sort_index() 

74 closes.index = closes.index.astype(str) 

75 feats = feature_registry.build_long(closes, names) 

76 horizons = sorted({int(horizon) for horizon in targets}) 

77 target = forward_rank_targets(closes, horizons).drop(columns=["split"]) 

78 frame = feats.merge(target, on=["date", "ticker"], how="inner") 

79 price = closes.stack(future_stack=True).rename("close").reset_index() 

80 price.columns = ["date", "ticker", "close"] 

81 frame = frame.merge(price.astype({"date": str, "ticker": str}), on=["date", "ticker"], how="left") 

82 longest = max(horizons) 

83 frame[f"target_direction_{longest}d"] = (frame[f"target_return_{longest}d"] > 0).astype(float).where(frame[f"target_return_{longest}d"].notna()) 

84 windows = dict(splits or default_splits(list(closes.index))) 

85 frame["split"] = label_splits(frame["date"], windows, horizon=longest, calendar=list(closes.index)) 

86 frame = frame[frame["split"].notna()] 

87 counts = frame.groupby("date")["ticker"].transform("count") 

88 frame = frame[counts >= min_names] 

89 ordered = ["date", "ticker", "close", *names, *[column for column in frame.columns if column.startswith("target_")], "split"] 

90 return frame[ordered].sort_values(["date", "ticker"]).reset_index(drop=True) 

91 

92 

93def feature_columns(frame: pd.DataFrame) -> list[str]: 

94 """The dataset's feature columns: everything that is not an id, the close, a target or the split.""" 

95 return [column for column in frame.columns if column not in ID_COLUMNS and not column.startswith("target_") and not column.startswith("_")] 

96 

97 

98def target_columns(frame: pd.DataFrame) -> list[str]: 

99 """The dataset's target columns (`target_*`).""" 

100 return [column for column in frame.columns if column.startswith("target_")] 

101 

102 

103def holdout_window(config: Mapping[str, Any]) -> tuple[str, str] | None: 

104 """The project config's holdout window, found by key wherever the split windows live.""" 

105 stack: list[Any] = [config] 

106 while stack: 

107 node = stack.pop() 

108 if isinstance(node, Mapping): 

109 holdout = node.get("holdout") 

110 if isinstance(holdout, Mapping) and "start" in holdout and "end" in holdout and ("validation" in node or "backtest" in node): 

111 return str(holdout["start"]), str(holdout["end"]) 

112 stack.extend(node.values()) 

113 return None 

114 

115 

116def seal(frame: pd.DataFrame, *, window: tuple[str, str] | None = None, allow: bool = False) -> pd.DataFrame: 

117 """`frame` without sealed rows: split == 'holdout', and (for the project's data) any date inside `window`. 

118 With `allow` the rows stay: only `aq lab eval --holdout --i-understand-this-spends-it`, after recording the spend.""" 

119 if allow: 

120 return frame 

121 keep = pd.Series(True, index=frame.index) 

122 if "split" in frame.columns: 

123 keep &= frame["split"].astype(str) != "holdout" 

124 if window is not None and "date" in frame.columns: 

125 dates = frame["date"].astype(str) 

126 keep &= ~((dates >= window[0]) & (dates <= window[1])) 

127 return frame[keep] 

128 

129 

130def load_dataset(path: Path, *, project_config: Path | None = None, allow_holdout: bool = False) -> pd.DataFrame: 

131 """Read a dataset CSV with its sealed rows removed. A project dataset (under `ml/datasets/`) also drops the config's 

132 holdout window, since its rows carry no `holdout` label.""" 

133 frame = pd.read_csv(path, dtype={"date": str, "ticker": str}, low_memory=False) 

134 window = None 

135 if project_config is not None and project_config.exists(): 

136 window = holdout_window(json.loads(project_config.read_text(encoding="utf-8"))) 

137 return seal(frame, window=window, allow=allow_holdout) 

138 

139 

140def dataset_info(frame: pd.DataFrame) -> dict[str, Any]: 

141 """Rows, dates, tickers, splits with windows, features with their NaN share, targets, label balance, holdout present.""" 

142 splits = {} 

143 for name, part in frame.groupby("split") if "split" in frame.columns else []: 

144 splits[str(name)] = {"rows": len(part), "start": str(part["date"].min()), "end": str(part["date"].max())} 

145 features = feature_columns(frame) 

146 direction = [column for column in frame.columns if column.startswith("target_direction")] 

147 return { 

148 "rows": len(frame), "dates": int(frame["date"].nunique()) if "date" in frame else 0, "tickers": int(frame["ticker"].nunique()) if "ticker" in frame else 0, 

149 "splits": splits, "features": {name: round(float(frame[name].isna().mean()), 4) for name in features}, 

150 "targets": target_columns(frame), 

151 "label_balance": {name: round(float(frame[name].mean()), 4) for name in direction}, 

152 "holdout_rows": int((frame["split"] == "holdout").sum()) if "split" in frame.columns else 0, 

153 } 

154 

155 

156def leakage_report(frame: pd.DataFrame, *, target: str = "target_rank_20d", horizon: int = 20) -> dict[str, Any]: 

157 """`evaluation/leakage_audit.audit_leakage` on a lab dataset (tail NaN, label shuffle, single-feature IC, asset prior).""" 

158 from evaluation.leakage_audit import audit_leakage 

159 

160 data = frame.copy() 

161 if "_class" not in data.columns: 

162 data["_class"] = "all" 

163 return audit_leakage(data, feature_columns=feature_columns(frame), target_column=target, horizon=horizon, min_names=max(3, min(20, int(data.groupby("date")["ticker"].count().median())))) 

164 

165 

166def rank_features(frame: pd.DataFrame, names: Sequence[str]) -> np.ndarray: 

167 """Within-date percentile ranks minus one half (missing = 0), float32: the inputs every lab model reads.""" 

168 data = frame.copy() 

169 data["_class"] = data.get("_class", "all") 

170 from features.training_splits import rank_inputs 

171 

172 return rank_inputs(data, list(names)).to_numpy(dtype=np.float32)