Coverage for features/feature_registry.py: 100%

75 statements  

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

1"""The features the lab can build from a dates x tickers close table, by name (`aq features list`). 

2 

3Each builder reads closes up to its own date only (a trailing window), so a table built on a prefix of the dates equals 

4the same rows of a table built on all of them. Technical indicators reuse `features/technical_indicators.py` over a 

5rolling window. The production dataset's frame-level features (macro, bonds, options, alt data) need inputs a close 

6table does not have; they are listed as production-only groups and are not buildable here. 

7""" 

8 

9from __future__ import annotations 

10 

11from collections.abc import Callable, Mapping, Sequence 

12from dataclasses import dataclass, field 

13 

14import numpy as np 

15import pandas as pd 

16 

17from features import technical_indicators as ti 

18 

19 

20@dataclass(frozen=True) 

21class FeatureSpec: 

22 """One registered feature: its builder, the inputs it reads, its lookback, its group and what it measures.""" 

23 name: str 

24 group: str 

25 lookback: int 

26 description: str 

27 builder: Callable[[pd.DataFrame], pd.DataFrame] = field(repr=False, compare=False) 

28 

29 

30def _returns(closes: pd.DataFrame) -> pd.DataFrame: 

31 return closes.astype(float).where(lambda frame: frame > 0).pct_change(fill_method=None) 

32 

33 

34def _ret(window: int) -> Callable[[pd.DataFrame], pd.DataFrame]: 

35 def build(closes: pd.DataFrame) -> pd.DataFrame: 

36 clean = closes.astype(float).where(lambda frame: frame > 0) 

37 return clean / clean.shift(window) - 1.0 

38 

39 return build 

40 

41 

42def _vol(window: int) -> Callable[[pd.DataFrame], pd.DataFrame]: 

43 return lambda closes: _returns(closes).rolling(window, min_periods=window).std() 

44 

45 

46def _mom_12_1(closes: pd.DataFrame) -> pd.DataFrame: 

47 clean = closes.astype(float).where(lambda frame: frame > 0) 

48 return clean.shift(21) / clean.shift(252) - 1.0 

49 

50 

51def _dist_high(window: int) -> Callable[[pd.DataFrame], pd.DataFrame]: 

52 def build(closes: pd.DataFrame) -> pd.DataFrame: 

53 clean = closes.astype(float).where(lambda frame: frame > 0) 

54 return clean / clean.rolling(window, min_periods=window).max() - 1.0 

55 

56 return build 

57 

58 

59def _rolling_indicator(window: int, indicator: Callable[[list[float]], float]) -> Callable[[pd.DataFrame], pd.DataFrame]: 

60 def build(closes: pd.DataFrame) -> pd.DataFrame: 

61 return closes.astype(float).rolling(window, min_periods=window).apply(lambda values: indicator(list(values)), raw=True) 

62 

63 return build 

64 

65 

66def _reversal_5(closes: pd.DataFrame) -> pd.DataFrame: 

67 return -_ret(5)(closes) 

68 

69 

70def _skew_60(closes: pd.DataFrame) -> pd.DataFrame: 

71 return _returns(closes).rolling(60, min_periods=60).skew() 

72 

73 

74def _vol_ratio(closes: pd.DataFrame) -> pd.DataFrame: 

75 returns = _returns(closes) 

76 long = returns.rolling(60, min_periods=60).std() 

77 return returns.rolling(20, min_periods=20).std() / long.where(long > 0) 

78 

79 

80FEATURES: dict[str, FeatureSpec] = {spec.name: spec for spec in ( 

81 FeatureSpec("ret_1", "momentum", 1, "1-session return", _ret(1)), 

82 FeatureSpec("ret_5", "momentum", 5, "5-session return", _ret(5)), 

83 FeatureSpec("ret_20", "momentum", 20, "20-session return", _ret(20)), 

84 FeatureSpec("ret_60", "momentum", 60, "60-session return", _ret(60)), 

85 FeatureSpec("ret_120", "momentum", 120, "120-session return", _ret(120)), 

86 FeatureSpec("mom_12_1", "momentum", 252, "12-month return skipping the last month", _mom_12_1), 

87 FeatureSpec("rev_5", "reversal", 5, "minus the 5-session return (short-term reversal)", _reversal_5), 

88 FeatureSpec("vol_20", "volatility", 20, "20-session standard deviation of daily returns", _vol(20)), 

89 FeatureSpec("vol_60", "volatility", 60, "60-session standard deviation of daily returns", _vol(60)), 

90 FeatureSpec("vol_ratio_20_60", "volatility", 60, "20- over 60-session volatility", _vol_ratio), 

91 FeatureSpec("skew_60", "volatility", 60, "60-session skew of daily returns", _skew_60), 

92 FeatureSpec("dist_high_252", "trend", 252, "distance below the 252-session high", _dist_high(252)), 

93 FeatureSpec("dist_high_60", "trend", 60, "distance below the 60-session high", _dist_high(60)), 

94 FeatureSpec("rsi_14", "technical", 15, "14-session relative strength index (technical_indicators.relative_strength_index)", 

95 _rolling_indicator(15, ti.relative_strength_index)), 

96 FeatureSpec("bollinger_20", "technical", 20, "Bollinger %B over 20 sessions (technical_indicators.bollinger_pctb)", _rolling_indicator(20, ti.bollinger_pctb)), 

97 FeatureSpec("macd_hist", "technical", 60, "normalised MACD histogram 12/26/9 (technical_indicators.macd_histogram_normalized)", 

98 _rolling_indicator(60, ti.macd_histogram_normalized)), 

99)} 

100 

101SETS: dict[str, tuple[str, ...]] = { 

102 "example": ("ret_1", "ret_5", "ret_20", "ret_60", "vol_20", "vol_60"), 

103 "momentum": ("ret_5", "ret_20", "ret_60", "ret_120", "mom_12_1", "rev_5"), 

104 "core": ("ret_1", "ret_5", "ret_20", "ret_60", "ret_120", "rev_5", "vol_20", "vol_60", "vol_ratio_20_60", "dist_high_60"), 

105 "all": tuple(FEATURES), 

106} 

107 

108PRODUCTION_ONLY_GROUPS = ("macro", "bonds", "alt_data", "cross_asset_sensitivity", "derivatives_macro", "options", "fx_carry") 

109 

110 

111def resolve(names: str | Sequence[str]) -> list[str]: 

112 """Feature names from a set name, a comma list, or a list; unknown names raise KeyError with the closest matches.""" 

113 import difflib 

114 

115 items = [part.strip() for part in names.split(",")] if isinstance(names, str) else list(names) 

116 out: list[str] = [] 

117 for item in items: 

118 if not item: 

119 continue 

120 if item in SETS: 

121 out += [name for name in SETS[item] if name not in out] 

122 elif item in FEATURES: 

123 if item not in out: 

124 out.append(item) 

125 else: 

126 close = difflib.get_close_matches(item, [*FEATURES, *SETS], n=3) 

127 raise KeyError(f"unknown feature {item!r}" + (f"; did you mean {', '.join(close)}?" if close else "")) 

128 return out 

129 

130 

131def build_wide(closes: pd.DataFrame, names: str | Sequence[str]) -> dict[str, pd.DataFrame]: 

132 """{feature: dates x tickers table} for the chosen features; inf becomes NaN.""" 

133 return {name: FEATURES[name].builder(closes).replace([np.inf, -np.inf], np.nan) for name in resolve(names)} 

134 

135 

136def build_long(closes: pd.DataFrame, names: str | Sequence[str]) -> pd.DataFrame: 

137 """Long rows `date, ticker, <features>` (rows where every feature is missing are dropped).""" 

138 wide = build_wide(closes, names) 

139 long = pd.concat({name: table.stack(future_stack=True) for name, table in wide.items()}, axis=1) 

140 long.index.names = ["date", "ticker"] 

141 long = long.reset_index().astype({"date": str, "ticker": str}) 

142 return long.dropna(how="all", subset=list(wide)).reset_index(drop=True) 

143 

144 

145def catalog() -> list[dict]: 

146 """Every buildable feature: name, group, lookback, description.""" 

147 return [{"name": spec.name, "group": spec.group, "lookback": spec.lookback, "description": spec.description} for spec in FEATURES.values()] 

148 

149 

150def groups_of(names: Sequence[str]) -> Mapping[str, list[str]]: 

151 """{group: [features]} for `names`.""" 

152 out: dict[str, list[str]] = {} 

153 for name in names: 

154 out.setdefault(FEATURES[name].group if name in FEATURES else "other", []).append(name) 

155 return out