Coverage for portfolio/trend_sleeve.py: 100%

108 statements  

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

1"""Trend sleeve (V6.4.4): a small directional time-series-momentum book next to the market-neutral one. 

2 

3Time-series momentum (Moskowitz, Ooi & Pedersen 2012) is the one classic alpha source the project lacked: each 

4instrument is held long when its own trailing return is positive and short when negative, sized by inverse volatility 

5so every name contributes a similar risk, the whole sleeve aimed at `target_vol` of NAV a year. The instruments 

6(`symbols`: broad equity indices, Treasuries, oil) leave the main book's and the bond sleeve's pools while it is on, so 

7each symbol has one owner. 

8 

9Pure, no I/O, no Lean imports. `main.py` and `evaluation/trend_sleeve_backtest.py` call the same functions. 

10""" 

11 

12from __future__ import annotations 

13 

14import math 

15from collections.abc import Mapping, Sequence 

16from dataclasses import dataclass 

17 

18TREND_SIGNALS = ("sign_252", "sign_126", "sign_63", "sign_blend") 

19BLEND_LOOKBACKS = (63, 126, 252) 

20 

21 

22@dataclass(frozen=True) 

23class TrendSleeveConfig: 

24 """Settings of the trend sleeve: on or off, its symbols, the signal and the volatility target.""" 

25 enabled: bool = False 

26 symbols: tuple[str, ...] = () 

27 signal: str = "sign_252" 

28 target_vol: float = 0.03 

29 vol_window: int = 60 

30 max_weight_per_name: float = 0.08 

31 gross_cap: float = 0.25 

32 rebalance_every_bars: int = 20 

33 min_weight_change: float = 0.005 

34 

35 @property 

36 def history_needed(self) -> int: 

37 """Closes a symbol needs before it can carry a signal and a volatility.""" 

38 return max(*signal_lookbacks(self.signal), self.vol_window) + 1 

39 

40 

41def signal_lookbacks(signal: str) -> tuple[int, ...]: 

42 """The lookbacks a trend signal name stands for (`sign_252` is 252; `sign_blend` the blend's).""" 

43 if signal == "sign_blend": 

44 return BLEND_LOOKBACKS 

45 return (int(signal.split("_", 1)[1]),) 

46 

47 

48def resolve_trend_sleeve_config(raw: Mapping | None) -> TrendSleeveConfig: 

49 """`phase_v2.trend_sleeve` -> TrendSleeveConfig. Absent block = disabled; a malformed number keeps its default.""" 

50 raw = raw or {} 

51 defaults = TrendSleeveConfig() 

52 

53 def _number(key: str, default: float, minimum: float) -> float: 

54 try: 

55 value = float(raw.get(key, default)) 

56 except (TypeError, ValueError): 

57 return default 

58 return value if math.isfinite(value) and value >= minimum else default 

59 

60 signal = str(raw.get("signal", defaults.signal)) 

61 symbols = raw.get("symbols") or () 

62 return TrendSleeveConfig( 

63 enabled=bool(raw.get("enabled", False)), 

64 symbols=tuple(str(symbol) for symbol in symbols) if isinstance(symbols, (list, tuple)) else (), 

65 signal=signal if signal in TREND_SIGNALS else defaults.signal, 

66 target_vol=_number("target_vol", defaults.target_vol, 0.0), 

67 vol_window=int(_number("vol_window", defaults.vol_window, 2)), 

68 max_weight_per_name=_number("max_weight_per_name", defaults.max_weight_per_name, 0.0), 

69 gross_cap=_number("gross_cap", defaults.gross_cap, 0.0), 

70 rebalance_every_bars=int(_number("rebalance_every_bars", defaults.rebalance_every_bars, 1)), 

71 min_weight_change=_number("min_weight_change", defaults.min_weight_change, 0.0), 

72 ) 

73 

74 

75def _clean(closes: Sequence[float]) -> list[float] | None: 

76 values = [] 

77 for value in closes: 

78 try: 

79 number = float(value) 

80 except (TypeError, ValueError): 

81 return None 

82 if not math.isfinite(number) or number <= 0.0: 

83 return None 

84 values.append(number) 

85 return values 

86 

87 

88def trend_signal(closes: Sequence[float], signal: str) -> float | None: 

89 """sign_N: the sign of the trailing N-session log return (-1, 0, +1); sign_blend: the mean of sign_63/126/252. 

90 None when the history is shorter than the longest lookback + 1 or holds a non-finite / non-positive close.""" 

91 if signal not in TREND_SIGNALS: 

92 return None 

93 lookbacks = signal_lookbacks(signal) 

94 values = _clean(closes[-(max(lookbacks) + 1):]) if len(closes) >= max(lookbacks) + 1 else None 

95 if values is None: 

96 return None 

97 signs = [] 

98 for lookback in lookbacks: 

99 change = math.log(values[-1] / values[-1 - lookback]) 

100 signs.append(0.0 if change == 0.0 else math.copysign(1.0, change)) 

101 return sum(signs) / len(signs) 

102 

103 

104def annualised_vol(closes: Sequence[float], window: int, annualization: float = 252.0) -> float | None: 

105 """Sample std of the last `window` daily log returns x sqrt(annualization); None if too short, flat or invalid.""" 

106 if len(closes) < window + 1: 

107 return None 

108 values = _clean(closes[-(window + 1):]) 

109 if values is None: 

110 return None 

111 returns = [math.log(values[i] / values[i - 1]) for i in range(1, len(values))] 

112 mean = sum(returns) / len(returns) 

113 variance = sum((value - mean) ** 2 for value in returns) / (len(returns) - 1) 

114 vol = math.sqrt(variance) * math.sqrt(annualization) 

115 return vol if math.isfinite(vol) and vol > 0.0 else None 

116 

117 

118def trend_sleeve_weights( 

119 closes_by_symbol: Mapping[str, Sequence[float]], config: TrendSleeveConfig, *, annualization: float = 252.0 

120) -> dict[str, float]: 

121 """Signed target weight (fraction of NAV) per symbol of `config.symbols` with a non-zero signal and a volatility: 

122 w = s * (target_vol / sqrt(N_active)) / sigma, each |w| capped at max_weight_per_name, then all scaled down so that 

123 sum |w| <= gross_cap. {} when disabled or nothing qualifies.""" 

124 if not config.enabled or config.target_vol <= 0.0: 

125 return {} 

126 active: dict[str, tuple[float, float]] = {} 

127 for symbol in config.symbols: 

128 closes = closes_by_symbol.get(symbol) 

129 if not closes: 

130 continue 

131 signal = trend_signal(closes, config.signal) 

132 vol = annualised_vol(closes, config.vol_window, annualization) 

133 if signal is None or vol is None or signal == 0.0: 

134 continue 

135 active[symbol] = (signal, vol) 

136 if not active: 

137 return {} 

138 per_name_vol = config.target_vol / math.sqrt(len(active)) 

139 weights = {} 

140 for symbol, (signal, vol) in active.items(): 

141 weight = signal * per_name_vol / vol 

142 cap = config.max_weight_per_name 

143 weights[symbol] = max(-cap, min(cap, weight)) 

144 gross = sum(abs(weight) for weight in weights.values()) 

145 if config.gross_cap <= 0.0: 

146 return {} 

147 if gross > config.gross_cap: 

148 scale = config.gross_cap / gross 

149 weights = {symbol: weight * scale for symbol, weight in weights.items()} 

150 return {symbol: weight for symbol, weight in weights.items() if weight != 0.0} 

151 

152 

153def apply_min_change(previous: Mapping[str, float], target: Mapping[str, float], min_change: float) -> dict[str, float]: 

154 """Keeps a held weight when the new target moves it by less than `min_change` (fewer small, fee-heavy trades). A 

155 symbol whose target is missing or zero always closes; a new symbol always opens.""" 

156 out: dict[str, float] = {} 

157 for symbol, weight in target.items(): 

158 if not math.isfinite(float(weight)) or weight == 0.0: 

159 continue 

160 held = previous.get(symbol) 

161 if held is not None and held != 0.0 and abs(float(weight) - float(held)) < float(min_change) \ 

162 and math.copysign(1.0, held) == math.copysign(1.0, weight): 

163 out[symbol] = float(held) 

164 else: 

165 out[symbol] = float(weight) 

166 return out