Coverage for portfolio/premia_signals.py: 100%

317 statements  

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

1"""Rule-based sleeves and the weight pipeline of V6.5.0 (`portfolio/target_weights.py` runs what this produces). 

2 

3A signal is a table of session x ticker, each row known at that session's equity close: equity closes of the session 

4itself, crypto and forex closes of the bars dated before it (`known_closes`, the timing of `features/cross_asset_timing.py`), 

5FRED series lagged a day. NaN means "not tradable today". `tests/test_premia_signals.py::test_no_lookahead` holds every 

6sleeve to it: a signal computed on data cut at D equals row D computed on all the data. 

7 

8`signal_to_weights` turns a signal into target weights: within-class ranks (each class its own budget, so a pooled rank 

9cannot reward group size, Problems.md #259) or per-asset risk-scaled directions, then one ex-ante volatility target, 

10then the caps. Nothing here is fitted to returns. 

11""" 

12 

13from __future__ import annotations 

14 

15import math 

16from collections.abc import Callable, Mapping 

17from dataclasses import dataclass, field 

18 

19import numpy as np 

20import pandas as pd 

21 

22from portfolio.target_weights import NEXT_BAR_CLASSES 

23 

24TRADING_DAYS = 252.0 

25VOL_WINDOW = 60 

26MIN_HISTORY = 61 

27XS = "cross_sectional" 

28TS = "time_series" 

29DIRECT = "direct" 

30POOLED = "cross_sectional_pooled" 

31RISK_ASSETS_TREND = ("SPY", "QQQ", "IWM", "EEM", "TLT", "IEF", "USO") 

32 

33 

34@dataclass(frozen=True) 

35class WeightSettings: 

36 """How a sleeve's signal becomes weights: the volatility target, the gross cap and the per-name and per-class caps.""" 

37 target_vol: float = 0.07 

38 gross_cap: float = 1.4 

39 name_cap: float = 0.15 

40 class_caps: Mapping[str, float] = field(default_factory=lambda: {"crypto": 0.15}) 

41 name_cap_by_class: Mapping[str, float] = field(default_factory=lambda: {"crypto": 0.05}) 

42 

43 def __post_init__(self) -> None: 

44 # V6.6.7 (#372, formal/AetherFormal/PremiaCaps.lean): the caps hold only when they are finite and not negative. A 

45 # negative name cap made np.clip(x, -cap, cap) return the cap for every name (all equal shorts), and a negative 

46 # class or gross cap, or volatility target, flipped every sign 

47 values = {"target_vol": self.target_vol, "gross_cap": self.gross_cap, "name_cap": self.name_cap, 

48 **{f"class_caps[{k}]": v for k, v in self.class_caps.items()}, 

49 **{f"name_cap_by_class[{k}]": v for k, v in self.name_cap_by_class.items()}} 

50 for name, value in values.items(): 

51 if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0.0: 

52 raise ValueError(f"WeightSettings.{name} must be a finite number >= 0, got {value!r}") 

53 

54 

55@dataclass(frozen=True) 

56class SleeveSpec: 

57 """A sleeve to research or trade: its id, track, kind (time series or cross-sectional), family, universe, rebalance cadence and parameters.""" 

58 id: str 

59 track: str 

60 kind: str 

61 family: str 

62 universe: tuple[str, ...] 

63 rebalance_every: int 

64 params: Mapping[str, float] = field(default_factory=dict) 

65 

66 

67@dataclass 

68class ResearchPanel: 

69 """What sleeves may read: `known` closes by session, each ticker's class, and FRED series as {key: dated rows}.""" 

70 

71 known: pd.DataFrame 

72 asset_class: Mapping[str, str] 

73 fred: Mapping[str, pd.Series] = field(default_factory=dict) 

74 extras: Mapping[str, pd.DataFrame] = field(default_factory=dict) 

75 

76 def truncated(self, end: str) -> ResearchPanel: 

77 return ResearchPanel( 

78 self.known[self.known.index <= end], self.asset_class, 

79 {key: series[series.index <= end] for key, series in self.fred.items()}, 

80 {key: frame[frame.index <= end] for key, frame in self.extras.items()}, 

81 ) 

82 

83 

84def known_closes(dates: list[str], tickers: list[str], closes: np.ndarray, asset_class: Mapping[str, str], sessions: set[str]) -> pd.DataFrame: 

85 """Closes known at each session's equity close. A crypto or forex bar dated D closes at the midnight after that 

86 close, so on session D the latest usable bar of those classes is the one dated before D.""" 

87 frame = pd.DataFrame(closes, index=dates, columns=tickers, dtype=float).ffill() 

88 lagged = [ticker for ticker in tickers if asset_class.get(ticker) in NEXT_BAR_CLASSES] 

89 frame[lagged] = frame[lagged].shift(1) 

90 return frame.loc[[date for date in dates if date in sessions]] 

91 

92 

93def fred_series_table(fred_rows: Mapping[str, list[dict]], keys: tuple[str, ...]) -> dict[str, pd.Series]: 

94 """{key: value by date string} from `load_cached_fred_series()` rows.""" 

95 out: dict[str, pd.Series] = {} 

96 for key in keys: 

97 rows = fred_rows.get(key) or [] 

98 pairs = {str(row["date"])[:10]: row.get("value") for row in rows} 

99 series = pd.to_numeric(pd.Series(pairs, dtype=object), errors="coerce").dropna().sort_index() 

100 out[key] = series.astype(float) 

101 return out 

102 

103 

104def _asof(series: pd.Series, sessions: pd.Index, *, lag_sessions: int = 1) -> pd.Series: 

105 """The value published by each session's close, a session late: FRED's daily marks post after the equity tick.""" 

106 if series is None or series.empty: 

107 return pd.Series(np.nan, index=sessions) 

108 union = series.reindex(series.index.union(sessions)).ffill() 

109 return union.reindex(sessions).shift(lag_sessions) 

110 

111 

112def _columns(panel: ResearchPanel, universe: tuple[str, ...]) -> list[str]: 

113 return [ticker for ticker in panel.known.columns if panel.asset_class.get(ticker) in universe or ticker in universe] 

114 

115 

116def _returns_over(known: pd.DataFrame, window: int, skip: int = 0) -> pd.DataFrame: 

117 return known.shift(skip) / known.shift(window) - 1.0 

118 

119 

120def _residual_daily(known: pd.DataFrame, market: str = "SPY", window: int = VOL_WINDOW) -> pd.DataFrame: 

121 daily = known.pct_change(fill_method=None) 

122 bench = daily[market] 

123 covariance = daily.rolling(window, min_periods=window).cov(bench) 

124 variance = bench.rolling(window, min_periods=window).var() 

125 beta = covariance.div(variance, axis=0).shift(1) 

126 return daily.sub(beta.mul(bench, axis=0)) 

127 

128 

129def _zscore(series: pd.Series, window: int = 252) -> pd.Series: 

130 mean = series.rolling(window, min_periods=window).mean() 

131 std = series.rolling(window, min_periods=window).std() 

132 return ((series - mean) / std).replace([np.inf, -np.inf], np.nan).clip(-2.0, 2.0) / 2.0 

133 

134 

135def _direct(panel: ResearchPanel, exposures: Mapping[str, pd.Series]) -> pd.DataFrame: 

136 frame = pd.DataFrame(np.nan, index=panel.known.index, columns=panel.known.columns) 

137 for ticker, series in exposures.items(): 

138 if ticker in frame.columns: 

139 frame[ticker] = series.reindex(frame.index) 

140 return frame 

141 

142 

143def crypto_trend(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

144 """Long while the trailing return over the lookback is positive; flat otherwise (long-only: no reliable short venue).""" 

145 known = panel.known[_columns(panel, spec.universe)] 

146 lookbacks = [int(value) for key, value in spec.params.items() if key.startswith("lookback")] 

147 votes = [(_returns_over(known, lookback) > 0.0).astype(float).where(known.shift(lookback).notna()) for lookback in lookbacks] 

148 return sum(votes) / len(votes) 

149 

150 

151def cross_sectional_return(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

152 """Rank on the trailing return over `lookback`, skipping the last `skip` sessions.""" 

153 known = panel.known[_columns(panel, spec.universe)] 

154 return _returns_over(known, int(spec.params["lookback"]), int(spec.params.get("skip", 0))) 

155 

156 

157def fx_carry_signal(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

158 """Rank on the 3-month rate differential; `momentum_weight` adds a rank of the trailing 63-session return.""" 

159 known = panel.known[_columns(panel, spec.universe)] 

160 carry = panel.extras["fx_carry"].reindex(index=known.index, columns=known.columns).where(known.notna()) 

161 weight = float(spec.params.get("momentum_weight", 0.0)) 

162 if weight <= 0.0: 

163 return carry 

164 momentum = _returns_over(known, 63) 

165 return carry.rank(axis=1, pct=True) * (1.0 - weight) + momentum.rank(axis=1, pct=True) * weight 

166 

167 

168def residual_reversal(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

169 """Rank against the market-residual return of the last `window` sessions.""" 

170 known = panel.known 

171 residual = _residual_daily(known)[_columns(panel, spec.universe)] 

172 return -residual.rolling(int(spec.params["window"]), min_periods=int(spec.params["window"])).sum() 

173 

174 

175def residual_momentum(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

176 """Rank on the market-residual return from `lookback` to `skip` sessions ago.""" 

177 residual = _residual_daily(panel.known)[_columns(panel, spec.universe)] 

178 lookback, skip = int(spec.params["lookback"]), int(spec.params["skip"]) 

179 return residual.shift(skip).rolling(lookback - skip, min_periods=lookback - skip).sum() 

180 

181 

182def low_volatility(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

183 """Minus the trailing volatility of each name's returns: the low-volatility signal.""" 

184 known = panel.known[_columns(panel, spec.universe)] 

185 return -known.pct_change(fill_method=None).rolling(VOL_WINDOW, min_periods=VOL_WINDOW).std() 

186 

187 

188def time_series_momentum(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

189 """Direction of the trailing return, averaged over the lookbacks.""" 

190 columns = [ticker for ticker in _columns(panel, spec.universe) if not spec.params.get("trend_set") or ticker in RISK_ASSETS_TREND] 

191 known = panel.known[columns] 

192 lookbacks = [int(value) for key, value in spec.params.items() if key.startswith("lookback")] 

193 votes = [np.sign(_returns_over(known, lookback)) for lookback in lookbacks] 

194 return sum(votes) / len(votes) 

195 

196 

197def bond_slope_timing(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

198 """Long duration against the short end while the 10y-3m slope is above its one-year mean, and the reverse.""" 

199 sessions = panel.known.index 

200 slope = _asof(panel.fred.get("treasury_10yr"), sessions) - _asof(panel.fred.get("treasury_3mo"), sessions) 

201 tilt = _zscore(slope) 

202 return _direct(panel, {"IEF": tilt * 0.5, "TLT": tilt * 0.5, "SHY": -tilt}) 

203 

204 

205def bond_credit_timing(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

206 """Long credit against duration while the BAA spread is narrowing over the last quarter, and the reverse.""" 

207 sessions = panel.known.index 

208 spread = _asof(panel.fred.get("credit_spread_baa10y"), sessions) 

209 tilt = _zscore(-(spread - spread.shift(63))) 

210 return _direct(panel, {"HYG": tilt, "LQD": tilt, "IEF": -2.0 * tilt}) 

211 

212 

213def vix_ratio(panel: ResearchPanel) -> pd.Series: 

214 """VIX over VIX3M as known at each session (above 1 is backwardation, a stressed market).""" 

215 sessions = panel.known.index 

216 return _asof(panel.fred.get("implied_volatility_vix"), sessions) / _asof(panel.fred.get("implied_volatility_3m"), sessions) 

217 

218 

219def vix_term_structure(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

220 """Long SPY while VIX is below VIX3M. `threshold` gives an on/off rule; without it, exposure grows with the gap.""" 

221 ratio = vix_ratio(panel) 

222 threshold = spec.params.get("threshold") 

223 if threshold is not None: 

224 exposure = (ratio < float(threshold)).astype(float).where(ratio.notna()) 

225 else: 

226 exposure = ((1.0 - ratio) / 0.1).clip(0.0, 1.0) 

227 return _direct(panel, {"SPY": exposure}) 

228 

229 

230def turn_of_month(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

231 """Hold SPY over the month's last session and the next three. A decision is filled at the next open, so the holding 

232 days are decided one session earlier. Calendar arithmetic only (weekdays, no holiday table: never reads the future).""" 

233 sessions = pd.DatetimeIndex(panel.known.index) 

234 exposure = np.zeros(len(sessions)) 

235 for position, day in enumerate(sessions): 

236 month_end = (day + pd.offsets.BMonthEnd(0)).normalize() 

237 weekdays_left = int(np.busday_count(day.date(), month_end.date())) 

238 weekdays_in = int(np.busday_count(day.replace(day=1).date(), day.date())) 

239 # holding tomorrow means: tomorrow is the month's last weekday, or among the first three of the next month 

240 holds_tomorrow = weekdays_left <= 1 or weekdays_in <= 1 

241 exposure[position] = 1.0 if holds_tomorrow else 0.0 

242 return _direct(panel, {"SPY": pd.Series(exposure, index=panel.known.index)}) 

243 

244 

245def external_score(panel: ResearchPanel, spec: SleeveSpec) -> pd.DataFrame: 

246 """A score table computed elsewhere (a walk-forward model, COT positioning, earnings surprise), already as of each session.""" 

247 known = panel.known[_columns(panel, spec.universe)] 

248 return panel.extras[spec.params["table"]].reindex(index=known.index, columns=known.columns) 

249 

250 

251def align_score_table(table: pd.DataFrame, asset_class: Mapping[str, str]) -> pd.DataFrame: 

252 """A score table keyed by dataset date: a crypto or forex score dated D reads bar D, which closes after D's equity 

253 decision, so it may only be used a row later. `test_no_lookahead` can't see into a precomputed table.""" 

254 aligned = table.copy() 

255 late = [ticker for ticker in aligned.columns if asset_class.get(ticker) in NEXT_BAR_CLASSES] 

256 aligned[late] = aligned[late].shift(1) 

257 return aligned 

258 

259 

260FAMILIES: dict[str, Callable[[ResearchPanel, SleeveSpec], pd.DataFrame]] = { 

261 "crypto_trend": crypto_trend, 

262 "cross_sectional_return": cross_sectional_return, 

263 "fx_carry": fx_carry_signal, 

264 "residual_reversal": residual_reversal, 

265 "residual_momentum": residual_momentum, 

266 "low_volatility": low_volatility, 

267 "time_series_momentum": time_series_momentum, 

268 "bond_slope_timing": bond_slope_timing, 

269 "bond_credit_timing": bond_credit_timing, 

270 "vix_term_structure": vix_term_structure, 

271 "turn_of_month": turn_of_month, 

272 "external_score": external_score, 

273} 

274 

275 

276def sleeve_signal(spec: SleeveSpec, panel: ResearchPanel) -> pd.DataFrame: 

277 """The sleeve's raw signal, masked where a name lacks enough history for its risk estimate.""" 

278 signal = FAMILIES[spec.family](panel, spec) 

279 # a signal never trades a ticker without enough price history for its risk estimate 

280 history = panel.known[signal.columns].notna().rolling(MIN_HISTORY, min_periods=MIN_HISTORY).sum() >= MIN_HISTORY 

281 return signal.where(history) 

282 

283 

284def _raw_weights(row: pd.Series, kind: str, volatility: pd.Series, asset_class: Mapping[str, str], top_k: int | None = None) -> pd.Series: 

285 live = row.dropna() 

286 if live.empty: 

287 return pd.Series(dtype=float) 

288 if kind == XS: 

289 pieces = [] 

290 for _, members in live.groupby(asset_class.get): 

291 if len(members) < 4: 

292 continue # a class with under four live names has no cross-section to rank: it holds nothing, by design (V6.6.9, audit item 2) 

293 ranks = members.rank(pct=True) - (len(members) + 1) / (2.0 * len(members)) 

294 if top_k: 

295 # the book as it trades today: equal weight in the best and worst k (a third of a small class) 

296 count = min(top_k, len(members) // 3) or 1 

297 ordered = members.sort_values(kind="mergesort") 

298 ranks = pd.Series(0.0, index=members.index) 

299 ranks[ordered.index[:count]] = -1.0 

300 ranks[ordered.index[-count:]] = 1.0 

301 gross = ranks.abs().sum() 

302 if gross > 0.0: 

303 pieces.append(ranks / gross) 

304 return pd.concat(pieces) if pieces else pd.Series(dtype=float) 

305 if kind == POOLED: 

306 # Ranks stay centred within a class, so knowing a name's group still earns nothing (#259), but a class's gross follows its breadth: a 

307 # 15-name sector gets the conviction per name of a 60-name one, not the same budget spread over a quarter of the names. 

308 pieces = [] 

309 for _, members in live.groupby(asset_class.get): 

310 if len(members) >= 4: 

311 pieces.append(members.rank(pct=True) - (len(members) + 1) / (2.0 * len(members))) 

312 return pd.concat(pieces) if pieces else pd.Series(dtype=float) 

313 if kind == TS: 

314 vol = volatility.reindex(live.index) 

315 return (live / vol).replace([np.inf, -np.inf], np.nan).dropna() 

316 return live 

317 

318 

319def scale_and_cap(raw: pd.Series, covariance: pd.DataFrame, asset_class: Mapping[str, str], settings: WeightSettings) -> dict[str, float]: 

320 """One ex-ante volatility target, then the per-name, per-class and gross caps. Crypto is long-only.""" 

321 weights = raw.copy() 

322 crypto = [ticker for ticker in weights.index if asset_class.get(ticker) == "crypto"] 

323 weights[crypto] = weights[crypto].clip(lower=0.0) 

324 weights = weights[weights != 0.0] 

325 if weights.empty: 

326 return {} 

327 names = list(weights.index) 

328 matrix = covariance.reindex(index=names, columns=names).fillna(0.0).to_numpy() 

329 vector = weights.to_numpy(float) 

330 variance = float(vector @ matrix @ vector) * TRADING_DAYS 

331 if not np.isfinite(variance) or variance <= 0.0: 

332 return {} 

333 return _apply_weight_caps(weights * (settings.target_vol / np.sqrt(variance)), asset_class, settings) 

334 

335 

336def _apply_weight_caps(weights: pd.Series, asset_class: Mapping[str, str], settings: WeightSettings) -> dict[str, float]: 

337 """The per-name, per-class and gross caps, in that order (formal/AetherFormal/PremiaCaps.lean).""" 

338 weights = weights.copy() 

339 for ticker in weights.index: 

340 cap = settings.name_cap_by_class.get(asset_class.get(ticker), settings.name_cap) 

341 weights[ticker] = float(np.clip(weights[ticker], -cap, cap)) 

342 for name, cap in settings.class_caps.items(): 

343 members = [ticker for ticker in weights.index if asset_class.get(ticker) == name] 

344 gross = weights[members].abs().sum() if members else 0.0 

345 if gross > cap: 

346 weights[members] = weights[members] * (cap / gross) 

347 gross = weights.abs().sum() 

348 if gross > settings.gross_cap: 

349 weights = weights * (settings.gross_cap / gross) 

350 return {ticker: float(value) for ticker, value in weights.items() if value != 0.0} 

351 

352 

353def signal_to_weights( 

354 signal: pd.DataFrame, 

355 panel: ResearchPanel, 

356 *, 

357 kind: str, 

358 rebalance_every: int, 

359 phase_offset: int = 0, 

360 settings: WeightSettings | None = None, 

361 start: str | None = None, 

362 end: str | None = None, 

363 listed: Callable[[str, str], bool] | None = None, 

364 top_k: int | None = None, 

365 optimizer: Callable[[pd.Series, pd.DataFrame, Mapping[str, str]], pd.Series] | None = None, 

366 long_window: int = 126, 

367 adjust: Callable[[dict[str, float], dict[str, float]], dict[str, float]] | None = None, 

368 guard: Callable[[str, dict[str, float]], dict[str, float]] | None = None, 

369) -> dict[str, dict[str, float]]: 

370 """{date: {ticker: weight}} on every `rebalance_every`-th session from `start`, counted from `phase_offset`. 

371 

372 `optimizer` (V6.6.9, `portfolio.book_optimizer`) replaces the rank-to-weight step: it gets the session's scores, the 

373 last `long_window` sessions of daily returns of the signal's names and the classes, and returns raw weights that 

374 `scale_and_cap` then takes to the one volatility target. `adjust(previous_row, new_row)` runs after the caps (a 

375 no-trade band, a partial move) and `guard(date, row)` last (a class loss guard). All three default to None, which is 

376 the path as it was.""" 

377 settings = settings or WeightSettings() 

378 daily = panel.known.pct_change(fill_method=None) 

379 sessions = [date for date in signal.index if (start is None or date >= start) and (end is None or date <= end)] 

380 rows: dict[str, dict[str, float]] = {} 

381 previous: str | None = None 

382 position = {date: i for i, date in enumerate(panel.known.index)} 

383 for count, date in enumerate(sessions): 

384 if count < phase_offset or (count - phase_offset) % rebalance_every: 

385 continue 

386 row = signal.loc[date] 

387 if listed is not None: 

388 row = row[[listed(ticker, date) for ticker in row.index]] 

389 at = position[date] 

390 window = daily.iloc[max(0, at - VOL_WINDOW + 1):at + 1] 

391 live = row.dropna().index 

392 history = window[live] 

393 if optimizer is None: 

394 raw = _raw_weights(row, kind, history.std(), panel.asset_class, top_k) 

395 else: 

396 raw = optimizer(row, daily.iloc[max(0, at - int(long_window) + 1):at + 1][list(row.index)], panel.asset_class) 

397 weights = scale_and_cap(raw, history.cov(), panel.asset_class, settings) if not raw.empty else {} 

398 if adjust is not None: 

399 weights = adjust(rows[previous] if previous is not None else {}, weights) 

400 if guard is not None: 

401 weights = guard(date, weights) 

402 rows[date] = weights 

403 previous = date 

404 return rows 

405 

406 

407def null_signal(signal: pd.DataFrame, mode: str, *, seed: int, asset_class: Mapping[str, str], block: int = 60, min_shift: int = 252) -> pd.DataFrame: 

408 """A signal with the skill removed, for placebos. 

409 

410 `asset_block`: relabel assets within their class, held for `block` sessions; keeps turnover and persistence. 

411 `time_shift`: a circular shift of at least a year; keeps each asset's long-run tilt, so a survivor or class effect that 

412 an asset relabelling would credit as skill is matched here. 

413 `sign_block`: for time-series and timing sleeves, reverse the position per asset in `block`-session blocks (a long/flat 

414 signal in 0..1 swaps long and flat).""" 

415 rng = np.random.default_rng(seed) 

416 values = signal.to_numpy(dtype=float).copy() 

417 available = np.isfinite(values) 

418 rows, columns = values.shape 

419 if mode == "time_shift": 

420 if rows <= 2 * min_shift: 

421 raise ValueError("signal too short for a time shift of at least a year") 

422 shift = int(rng.integers(min_shift, rows - min_shift)) 

423 shifted = np.roll(values, shift, axis=0) 

424 shifted[~available] = np.nan 

425 return pd.DataFrame(shifted, index=signal.index, columns=signal.columns) 

426 if mode == "asset_block": 

427 groups: dict[str, list[int]] = {} 

428 for column, ticker in enumerate(signal.columns): 

429 groups.setdefault(str(asset_class.get(ticker)), []).append(column) 

430 out = np.full_like(values, np.nan) 

431 for start in range(0, rows, block): 

432 stop = min(start + block, rows) 

433 for members in groups.values(): 

434 permuted = rng.permutation(members) 

435 out[start:stop, members] = values[start:stop, permuted] 

436 out[~available] = np.nan 

437 return pd.DataFrame(out, index=signal.index, columns=signal.columns) 

438 if mode == "sign_block": 

439 finite = values[available] 

440 long_flat = finite.size > 0 and finite.min() >= 0.0 

441 out = values.copy() 

442 for start in range(0, rows, block): 

443 stop = min(start + block, rows) 

444 for column in range(columns): 

445 if rng.random() < 0.5: 

446 out[start:stop, column] = (1.0 - values[start:stop, column]) if long_flat else -values[start:stop, column] 

447 return pd.DataFrame(out, index=signal.index, columns=signal.columns) 

448 raise ValueError(f"unknown placebo mode {mode!r}") 

449 

450 

451def combine_sleeves( 

452 sleeve_weights: Mapping[str, Mapping[str, Mapping[str, float]]], 

453 panel: ResearchPanel, 

454 *, 

455 method: str = "inverse_vol", 

456 every: int = 21, 

457 settings: WeightSettings | None = None, 

458 start: str | None = None, 

459 end: str | None = None, 

460) -> dict[str, dict[str, float]]: 

461 """A fixed-rule mix of sleeves, never fitted to their returns: each month a sleeve's budget comes from the trailing year of its 

462 own gross returns (inverse volatility, or hierarchical risk parity), and the sum is scaled to one volatility target. 

463 

464 A sleeve whose trailing year has no variance (it has not started, or held nothing) gets no budget until the next month's recompute, and a 

465 sleeve that starts mid-month waits for it too (V6.6.9, audit item 3). With no sleeve usable the budgets are equal. The model book's blend does 

466 not use this: its shares are fixed (`portfolio/model_book.py`).""" 

467 from portfolio.hrp_allocation import compute_hrp_weights 

468 

469 settings = settings or WeightSettings() 

470 sessions = list(panel.known.index) 

471 daily = panel.known.pct_change(fill_method=None).fillna(0.0) 

472 held: dict[str, pd.DataFrame] = {} 

473 for name, rows in sleeve_weights.items(): 

474 frame = pd.DataFrame.from_dict({date: dict(row) for date, row in rows.items()}, orient="index").reindex(columns=panel.known.columns) 

475 frame = frame.reindex(sessions) 

476 marked = frame.notna().any(axis=1) | frame.index.isin(list(rows)) 

477 frame = frame.where(~marked, frame.fillna(0.0)).ffill().fillna(0.0) 

478 held[name] = frame 

479 # a weight decided at D earns from the session after D 

480 sleeve_returns = pd.DataFrame({name: (frame.shift(1) * daily).sum(axis=1) for name, frame in held.items()}) 

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

482 budget: dict[str, float] = {} 

483 active = [date for date in sessions if (start is None or date >= start) and (end is None or date <= end)] 

484 position = {date: i for i, date in enumerate(sessions)} 

485 changes = sorted({date for rows in sleeve_weights.values() for date in rows}) 

486 change_set = set(changes) 

487 for count, date in enumerate(active): 

488 at = position[date] 

489 if count % every == 0 or not budget: 

490 history = sleeve_returns.iloc[max(0, at - 251):at + 1] 

491 usable = [name for name in history.columns if history[name].std() > 0.0] 

492 if len(usable) == 0: 

493 budget = {name: 1.0 / len(held) for name in held} 

494 elif method == "hrp" and len(usable) >= 2: 

495 budget = {name: float(value) for name, value in compute_hrp_weights(history[usable]).items()} 

496 else: 

497 inverse = 1.0 / history[usable].std() 

498 budget = {name: float(value) for name, value in (inverse / inverse.sum()).items()} 

499 elif date not in change_set: 

500 continue 

501 mixture = sum(held[name].iloc[at] * budget.get(name, 0.0) for name in held) 

502 mixture = mixture[mixture != 0.0] 

503 window = panel.known.pct_change(fill_method=None).iloc[max(0, at - VOL_WINDOW + 1):at + 1] 

504 out[date] = scale_and_cap(mixture, window[list(mixture.index)].cov(), panel.asset_class, settings) if not mixture.empty else {} 

505 return out