Coverage for features/technical_indicators.py: 100%

83 statements  

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

1"""Shared, pure technical-indicator implementations (Phase 6) - imported by 

2BOTH train.py::engineer_features() (offline, full history via a Python 

3loop) and main.py::_build_model_input() (runtime, one bar at a time from a 

4rolling deque) so both sides compute every indicator identically by 

5construction, not by hand-matched duplicated formulas (the train/runtime 

6parity convention this codebase already uses for every other feature, see 

7development/Changelog.md). 

8 

9Each function takes a plain list of trailing values (already sliced to the 

10right window by the caller) and returns a single scalar float, matching 

11how train.py::engineer_features()'s existing loop already computes 

12close_to_close_return_5d/rolling_volatility_20d/etc one row at a time from 

13Python lists, not vectorized pandas. Every function returns a documented 

14neutral default when there isn't enough history yet, so nothing ever 

15raises and no extra dropna is needed - the same "adaptive lookback" 

16contract every existing base feature already has. 

17 

18Chosen to fit main.py's existing self.symbol_windows (deque(maxlen=25), up 

19to 24 trailing bars - see train.py::CROSS_SECTIONAL_WINDOW_BARS) except 

20macd_histogram_normalized()/distance_from_52w_high(), which need a longer 

21history and are read from a separate, longer buffer (main.py's 

22self.symbol_long_windows, deque(maxlen=260)) - main.py:264-268 explicitly 

23forbids resizing symbol_windows itself, so a second buffer is the only 

24option for indicators needing more than ~24 bars. 

25""" 

26 

27from __future__ import annotations 

28 

29RSI_NEUTRAL = 50.0 

30BOLLINGER_PCTB_NEUTRAL = 0.5 

31VOLUME_ZSCORE_NEUTRAL = 0.0 

32MACD_HISTOGRAM_NEUTRAL = 0.0 

33DIST_52W_HIGH_NEUTRAL = 0.0 

34CROSS_SECTIONAL_MOMENTUM_RANK_NEUTRAL = 0.5 

35 

36 

37def relative_strength_index(closes: list[float], period: int = 14) -> float: 

38 """Wilder's RSI over the trailing `period` closes (needs period+1 

39 closes for period price changes) - a bounded [0, 100] mean-reversion 

40 state, a genuinely different signal shape from any existing 

41 return/volatility feature (bounded and non-linear, vs. an unbounded 

42 return). Returns RSI_NEUTRAL (50.0, "neither overbought nor oversold") 

43 when fewer than period+1 closes are available.""" 

44 if len(closes) < period + 1: 

45 return RSI_NEUTRAL 

46 window = closes[-(period + 1):] 

47 gains = [] 

48 losses = [] 

49 for index in range(1, len(window)): 

50 change = window[index] - window[index - 1] 

51 gains.append(max(change, 0.0)) 

52 losses.append(max(-change, 0.0)) 

53 average_gain = sum(gains) / period 

54 average_loss = sum(losses) / period 

55 if average_loss == 0: 

56 return 100.0 if average_gain > 0 else RSI_NEUTRAL 

57 relative_strength = average_gain / average_loss 

58 return 100.0 - (100.0 / (1.0 + relative_strength)) 

59 

60 

61def average_true_range_pct(highs: list[float], lows: list[float], closes: list[float], period: int = 14) -> float: 

62 """ATR (Wilder's simple-average variant) as a % of the latest close - 

63 a gap-aware volatility measure distinct from rolling_volatility_20d's 

64 close-to-close-only stddev (a true range captures overnight 

65 gaps/intraday extremes a close-only measure misses entirely). Needs 

66 period+1 bars (period true-range values, each needing a previous 

67 close). Returns 0.0 when insufficient history or the latest close is 

68 zero.""" 

69 if len(closes) < period + 1: 

70 return 0.0 

71 true_ranges = [] 

72 for index in range(len(closes) - period, len(closes)): 

73 high = highs[index] 

74 low = lows[index] 

75 previous_close = closes[index - 1] 

76 true_ranges.append(max(high - low, abs(high - previous_close), abs(low - previous_close))) 

77 atr = sum(true_ranges) / period 

78 latest_close = closes[-1] 

79 return atr / latest_close if latest_close else 0.0 

80 

81 

82def bollinger_pctb(closes: list[float], period: int = 20, num_std: float = 2.0) -> float: 

83 """%B: where the latest close sits within its trailing `period`-bar 

84 Bollinger Band, normalized so 0.0 = lower band, 1.0 = upper band, 0.5 = 

85 the middle (SMA) - a bounded, self-normalizing measure of price 

86 extension, distinct from the raw high_low_range_pct/rolling_volatility 

87 features already in this codebase. Returns BOLLINGER_PCTB_NEUTRAL 

88 (0.5) when fewer than `period` closes exist yet, or the band has zero 

89 width (constant price - degenerate either way, not a real signal).""" 

90 if len(closes) < period: 

91 return BOLLINGER_PCTB_NEUTRAL 

92 window = closes[-period:] 

93 mean = sum(window) / period 

94 variance = sum((value - mean) ** 2 for value in window) / period 

95 std = variance ** 0.5 

96 if std == 0: 

97 return BOLLINGER_PCTB_NEUTRAL 

98 upper = mean + num_std * std 

99 lower = mean - num_std * std 

100 return (closes[-1] - lower) / (upper - lower) 

101 

102 

103def volume_zscore(volumes: list[float], period: int = 20) -> float: 

104 """Latest volume's z-score against its own trailing `period`-bar 

105 mean/std - a self-normalizing participation measure. Robust to the 

106 exact class of raw-volume-unit discontinuity that broke 

107 volume_change_1d before its clamp fix (see development/Problems.md): 

108 a z-score compresses a single extreme outlier's effect on the bar it 

109 occurs on relative to a raw ratio, though a persisting outlier would 

110 still distort the trailing window's own mean/std for subsequent bars, 

111 same as any rolling statistic. Returns VOLUME_ZSCORE_NEUTRAL (0.0) when 

112 fewer than `period` volumes exist yet, or the trailing window has zero 

113 variance (a flat volume series).""" 

114 if len(volumes) < period: 

115 return VOLUME_ZSCORE_NEUTRAL 

116 window = volumes[-period:] 

117 mean = sum(window) / period 

118 variance = sum((value - mean) ** 2 for value in window) / period 

119 std = variance ** 0.5 

120 return (volumes[-1] - mean) / std if std else VOLUME_ZSCORE_NEUTRAL 

121 

122 

123def cross_sectional_momentum_rank(momentum_by_symbol: dict[str, float], symbol: str) -> float: 

124 """Per-date percentile rank ([0, 1], ties averaged - matches pandas' 

125 .rank(pct=True) convention, same as 

126 build_cross_sectional_rank_targets()'s target-side ranking) of 

127 `symbol`'s own momentum_20d among every symbol present in 

128 `momentum_by_symbol` - the best-documented daily cross-sectional 

129 anomaly (12-1 month momentum), reusing the exact percentile-rank 

130 convention already established for the ranking targets. Returns 

131 CROSS_SECTIONAL_MOMENTUM_RANK_NEUTRAL (0.5, the exact middle) when 

132 `symbol` has fewer than 2 total entries to rank against (undefined 

133 otherwise, e.g. a single-asset universe or a thin trading day).""" 

134 if len(momentum_by_symbol) < 2 or symbol not in momentum_by_symbol: 

135 return CROSS_SECTIONAL_MOMENTUM_RANK_NEUTRAL 

136 own_value = momentum_by_symbol[symbol] 

137 values = list(momentum_by_symbol.values()) 

138 count_less = sum(1 for value in values if value < own_value) 

139 count_equal = sum(1 for value in values if value == own_value) 

140 return (count_less + (count_equal + 1) / 2.0) / len(values) 

141 

142 

143def macd_histogram_normalized(closes: list[float], fast: int = 12, slow: int = 26, signal: int = 9) -> float: 

144 """MACD histogram (MACD line - its own signal line), normalized by the 

145 latest close so its scale is comparable across assets at very 

146 different price levels (a raw MACD histogram is in the asset's own 

147 raw price units). Both EMAs are recomputed fresh from the trailing 

148 window passed in each call (an approximation of a true "since 

149 inception" EMA, which never fully forgets old data) - a deliberate 

150 simplification so this is exactly reproducible from a bounded window 

151 on both the offline (full history slice) and runtime 

152 (self.symbol_long_windows, maxlen=260) sides, with no persistent EMA 

153 state to keep in sync between them. Needs at least `slow + signal` 

154 closes; returns MACD_HISTOGRAM_NEUTRAL (0.0) otherwise, or when the 

155 latest close is zero.""" 

156 if len(closes) < slow + signal or closes[-1] == 0: 

157 return MACD_HISTOGRAM_NEUTRAL 

158 

159 def _ema_series(values: list[float], period: int) -> list[float]: 

160 multiplier = 2.0 / (period + 1) 

161 ema_values = [values[0]] 

162 for value in values[1:]: 

163 ema_values.append((value - ema_values[-1]) * multiplier + ema_values[-1]) 

164 return ema_values 

165 

166 fast_ema = _ema_series(closes, fast) 

167 slow_ema = _ema_series(closes, slow) 

168 macd_line = [fast_value - slow_value for fast_value, slow_value in zip(fast_ema, slow_ema, strict=False)] 

169 signal_line = _ema_series(macd_line, signal) 

170 histogram = macd_line[-1] - signal_line[-1] 

171 return histogram / closes[-1] 

172 

173 

174def distance_from_52w_high(closes: list[float], window: int = 252) -> float: 

175 """close / trailing-`window`-bar max close - 1: how far the latest 

176 close sits below its own trailing high (0.0 = at the high, negative 

177 otherwise) - a genuine anchoring-effect measure distinct from 

178 everything else in this codebase (every existing return/momentum 

179 feature is relative to a bar N periods ago, not to a rolling extreme). 

180 Returns DIST_52W_HIGH_NEUTRAL (0.0) when fewer than 2 closes exist yet, 

181 or the trailing high is zero.""" 

182 if len(closes) < 2: 

183 return DIST_52W_HIGH_NEUTRAL 

184 trailing_high = max(closes[-window:]) 

185 return closes[-1] / trailing_high - 1.0 if trailing_high else DIST_52W_HIGH_NEUTRAL