Coverage for evaluation/model_book_research.py: 100%

122 statements  

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

1"""The multi-asset model book's research, as pure functions (V6.6.9). 

2 

3The research engine (`evaluation/premia_research.py`) scores a sleeve whose signal is a table by session and ticker. This module 

4builds those tables from the models' walk-forward scores (aligned to the session they could be used at), the composites the rules 

5name, and decides what the pre-registered rules decide: which trials are eligible, which one is the candidate, whether it installs. 

6Nothing here reads a file the rules have not fixed, and nothing here knows the dates of a holdout. 

7""" 

8 

9from __future__ import annotations 

10 

11from collections.abc import Callable, Iterable, Mapping, Sequence 

12from pathlib import Path 

13from typing import Any 

14 

15import numpy as np 

16import pandas as pd 

17 

18from portfolio.model_book import ( # noqa: F401 (re-exported: the research and the live book build their rows from one definition) 

19 blend_rows, 

20 composite_signal, 

21 forward_fill_rows, 

22 low_volatility_score, 

23 momentum_12_1, 

24 signal_tables, 

25 trend_vote, 

26 within_class_z, 

27) 

28from portfolio.premia_signals import XS, SleeveSpec, WeightSettings, align_score_table 

29from portfolio.target_weights import NEXT_BAR_CLASSES 

30 

31CLASSES = ("equity", "bond", "forex", "crypto") 

32SELECTION = ("2019-01-01", "2021-04-01", "2023-06-30") 

33VERIFICATION = ("2023-07-01", "2026-11-02") 

34STALE_SCORE_ROWS = 5 # a crypto or forex score older than this many calendar rows is not carried forward 

35NON_SURVIVOR_SHARE = 0.30 

36HEADS = ("rank_20d", "rank_5d", "sector_neutral_rank_20d") 

37 

38# the forex name cap is 6%: a pair under $5,000 of a $100,000 book is below `forex_min_trade_usd` and could never open (audit item 4) 

39MODEL_SETTINGS = { 

40 "target_vol": 0.07, "gross_cap": 1.4, "name_cap": 0.05, 

41 "class_caps": {"equity": 0.80, "bond": 0.60, "crypto": 0.15, "forex": 0.12}, 

42 "name_cap_by_class": {"crypto": 0.05, "forex": 0.06}, 

43} 

44GUARD = {"guard_classes": ["forex"], "guard_lookback": 60, "guard_max_loss": 0.01} 

45ELIGIBLE = {"max_drawdown": 0.15, "volatility": 0.10, "mean_gross": 2.0, "class_breadth": 0.80} 

46LEAN_VS_ENGINE = {"correlation": 0.90, "annual_return_gap": 0.01} 

47 

48 

49def model_settings() -> WeightSettings: 

50 """The sizing every model-book trial shares (R-BOOK1 fixes it before any score).""" 

51 return WeightSettings(**MODEL_SETTINGS) 

52 

53 

54def universe_tickers(config: Mapping[str, Any]) -> list[str]: 

55 """The tickers the config's universe holds now. The installed models were trained with EOSUSD still present (#385); a score 

56 for a ticker the universe no longer lists is never ranked.""" 

57 return [str(asset["ticker"]) for asset in config["phase1"]["universe"]["assets"]] 

58 

59 

60def load_score_table( 

61 path: Path | str, sessions: Sequence[str], asset_class: Mapping[str, str], *, universe: Iterable[str] | None = None, end: str | None = None, 

62) -> pd.DataFrame: 

63 """A score file (`date,ticker,score`, keyed by dataset date) as a table by session, usable at that session (#390). 

64 

65 A crypto or forex score dated D reads bar D, which closes after D's equity decision, so it moves to the next row: the 

66 columns are carried over the calendar rows first (a Friday forex score serves Monday's decision) and then shifted one row 

67 through `align_score_table`. An equity or bond score dated D is the close of D and stays. Every score table the model book's 

68 research reads comes through here.""" 

69 table = pd.read_csv(path, dtype={"date": str, "ticker": str}) 

70 if end is not None: 

71 table = table[table["date"] <= end] 

72 if universe is not None: 

73 table = table[table["ticker"].isin(set(universe))] 

74 wide = table.pivot_table(index="date", columns="ticker", values="score", aggfunc="last").sort_index() 

75 wide = wide.reindex(sorted(set(wide.index) | set(map(str, sessions)))) 

76 late = [ticker for ticker in wide.columns if asset_class.get(ticker) in NEXT_BAR_CLASSES] 

77 wide[late] = wide[late].ffill(limit=STALE_SCORE_ROWS) 

78 return align_score_table(wide, asset_class).reindex(list(sessions)) 

79 

80 

81def _spec(trial: str, track: str, optimizer: str | None, every: int, table: str = "ml_a1", **extra: Any) -> SleeveSpec: 

82 params: dict[str, Any] = {"table": table, **GUARD, **extra} 

83 if optimizer is not None: 

84 params["optimizer"] = optimizer 

85 return SleeveSpec(trial, track, XS, "external_score", CLASSES, every, params) 

86 

87 

88def book_trials() -> list[SleeveSpec]: 

89 """R-BOOK1: twelve optimizer trials on one signal (`ml_a1`). The signal is fixed so that only the optimizer varies.""" 

90 return [ 

91 _spec("b02", "B1", "pooled", 20), 

92 _spec("b03", "B1", "inverse_vol", 20), 

93 _spec("b04", "B1", "class_risk_parity", 20), 

94 _spec("b05", "B1", "hrp", 20), 

95 _spec("b06", "B1", "mean_variance", 20), 

96 _spec("b07", "B1", "tilted_core", 20, kappa=1.0), 

97 _spec("b08", "B1", "tilted_core", 20, "mix_trend", kappa=1.0), 

98 _spec("b09", "B1", "inverse_vol", 5), 

99 _spec("b10", "B1", "class_risk_parity", 5), 

100 _spec("b11", "B1", "tilted_core", 5, kappa=1.0), 

101 _spec("b12", "B1", "class_risk_parity", 20, partial=0.5), 

102 _spec("b13", "B1", "tilted_core", 20, kappa=1.0, band=0.25), 

103 ] 

104 

105 

106def mix_trials() -> list[SleeveSpec]: 

107 """R-MIX1: six signal trials on one optimizer (pooled ranks, every 20 sessions).""" 

108 return [ 

109 _spec("m01", "M1", "pooled", 20, "mix_mom"), 

110 _spec("m02", "M1", "pooled", 20, "mix_lowvol"), 

111 _spec("m03", "M1", "pooled", 20, "mix_trend"), 

112 _spec("m04", "M1", "pooled", 20, vix_halve=0.95), 

113 _spec("m05", "M1", "pooled", 20, "mix_all4"), 

114 _spec("m06", "M1", "pooled", 20, "mix_a23"), 

115 ] 

116 

117 

118def control_trials() -> list[SleeveSpec]: 

119 """Scored, never selectable, counted in no N: V6.5.0's top-6 book through the aligned loader, and the model-free risk-parity core.""" 

120 return [ 

121 SleeveSpec("b01", "BC", XS, "external_score", CLASSES, 20, {"table": "ml_a1", "top_k": 6}), 

122 _spec("core", "BC", "core", 20, "const"), 

123 ] 

124 

125 

126CONTROL_IDS = ("b01", "core") 

127 

128 

129def candidate_pool() -> list[SleeveSpec]: 

130 """Every selectable model-driven trial: the 18 the install rule chooses among.""" 

131 return [*book_trials(), *mix_trials()] 

132 

133 

134def is_eligible(score: Mapping[str, Any]) -> tuple[bool, list[str]]: 

135 """R-INSTALL2's eligibility on the selection window: drawdown, volatility and gross within the ceiling, and a book that 

136 holds at least three of the four classes on at least 80% of its rebalance rows. Returns (eligible, the clauses that failed).""" 

137 failed = [] 

138 for key, ceiling in (("max_drawdown", ELIGIBLE["max_drawdown"]), ("volatility", ELIGIBLE["volatility"]), ("mean_gross", ELIGIBLE["mean_gross"])): 

139 value = score.get(key) 

140 if value is None or not np.isfinite(value) or value > ceiling: 

141 failed.append(key) 

142 breadth = score.get("class_breadth") 

143 if breadth is None or breadth < ELIGIBLE["class_breadth"]: 

144 failed.append("class_breadth") 

145 return not failed, failed 

146 

147 

148def pick_candidate(scores: Sequence[Mapping[str, Any]]) -> dict[str, Any]: 

149 """The eligible trial with the highest pooled Sharpe (the lower turnover on a tie). With none eligible the model-free core 

150 stands in, and the result says so. Controls never compete.""" 

151 pool = [score for score in scores if score["id"] not in CONTROL_IDS] 

152 verdicts = {score["id"]: is_eligible(score) for score in pool} 

153 eligible = [score for score in pool if verdicts[score["id"]][0] and score.get("sharpe") is not None] 

154 if not eligible: 

155 return {"candidate": "core", "reason": "no trial is eligible; the model-free core stands in", "eligible": [], 

156 "ineligible": {name: failed for name, (_, failed) in verdicts.items() if failed}} 

157 best = min(eligible, key=lambda score: (-round(float(score["sharpe"]), 12), float(score.get("turnover") or 0.0), score["id"])) 

158 return {"candidate": best["id"], "reason": "highest pooled Sharpe among the eligible", "eligible": sorted(score["id"] for score in eligible), 

159 "ineligible": {name: failed for name, (ok, failed) in verdicts.items() if not ok}} 

160 

161 

162def install_verdict( 

163 verification: Mapping[str, Any], lean: Mapping[str, Any] | None, *, survivor: bool = False, 

164) -> dict[str, Any]: 

165 """R-INSTALL2's install clauses on the verification window, each with its number. `verification` holds the engine's volatility, 

166 max_drawdown and mean_gross for the frozen candidate; `lean` the Lean run's `completed`, `engine_log_clean`, `correlation` 

167 and `annual_return_gap` (None before a run exists, which fails the Lean clauses). Sharpe is reported, not required.""" 

168 clauses: dict[str, dict[str, Any]] = {} 

169 

170 def add(name: str, value: Any, passed: bool) -> None: 

171 clauses[name] = {"value": value, "pass": bool(passed)} 

172 

173 for key, ceiling in (("volatility", ELIGIBLE["volatility"]), ("max_drawdown", ELIGIBLE["max_drawdown"]), ("mean_gross", ELIGIBLE["mean_gross"])): 

174 value = verification.get(key) 

175 add(key, value, value is not None and np.isfinite(value) and value <= ceiling) 

176 lean = lean or {} 

177 add("lean_completed", lean.get("completed"), bool(lean.get("completed")) and bool(lean.get("engine_log_clean"))) 

178 correlation, gap = lean.get("correlation"), lean.get("annual_return_gap") 

179 add("lean_correlation", correlation, correlation is not None and correlation >= LEAN_VS_ENGINE["correlation"]) 

180 add("lean_return_gap", gap, gap is not None and abs(gap) <= LEAN_VS_ENGINE["annual_return_gap"]) 

181 install = all(item["pass"] for item in clauses.values()) 

182 return {"install": install, "share": None if not install else (None if survivor else NON_SURVIVOR_SHARE), "survivor": survivor, 

183 "sharpe_reported": verification.get("sharpe"), "clauses": clauses, "failed": sorted(name for name, item in clauses.items() if not item["pass"])} 

184 

185 

186def rank_ic_diagnostics( 

187 table: pd.DataFrame, known: pd.DataFrame, asset_class: Mapping[str, str], *, horizons: Sequence[int] = (5, 20), classes: Sequence[str] = CLASSES, 

188 start: str, end: str, 

189) -> dict[str, dict[str, Any]]: 

190 """D1: the rank correlation between a score table and the return that followed it (the known close at the decision to the known 

191 close `horizon` sessions later), by class and horizon. Each date's correlation is kept every `horizon`-th date (non-overlapping) 

192 and the t-statistic is Newey-West on the daily series. Looks at the score only; it selects nothing.""" 

193 from evaluation.rank_ic_core import newey_west_t_stat 

194 

195 out: dict[str, dict[str, Any]] = {} 

196 window = table.loc[(table.index >= start) & (table.index <= end)] 

197 for horizon in horizons: 

198 forward = known.shift(-int(horizon)) / known - 1.0 

199 for name in classes: 

200 members = [ticker for ticker in window.columns if asset_class.get(ticker) == name and ticker in forward.columns] 

201 daily = [] 

202 for date, row in window[members].iterrows(): 

203 realised = forward.loc[date, members] 

204 both = pd.concat([row, realised], axis=1).dropna() 

205 if len(both) >= 4 and both.iloc[:, 0].nunique() > 1 and both.iloc[:, 1].nunique() > 1: 

206 daily.append((date, float(both.rank().corr().iloc[0, 1]))) 

207 series = pd.Series(dict(daily), dtype=float) 

208 sampled = series.iloc[:: int(horizon)] 

209 out[f"{name}_{horizon}d"] = { 

210 "class": name, "horizon": int(horizon), "n_dates": int(len(series)), "n_independent": int(len(sampled)), 

211 "mean_ic": float(sampled.mean()) if len(sampled) else None, 

212 "t_hac": newey_west_t_stat(series.to_numpy(), int(horizon) - 1) if len(series) else None, 

213 } 

214 return out 

215 

216 

217def daily_rank(frame: pd.DataFrame, values: np.ndarray) -> pd.Series: 

218 """The percentile rank of `values` among the names of the same date.""" 

219 return pd.Series(values, index=frame.index).groupby(frame["date"]).rank(pct=True) 

220 

221 

222def installed_score_tables( 

223 dataset: pd.DataFrame, exports: Mapping[str, tuple[Mapping[str, Any], Mapping[str, Any]]], *, start: str, end: str, 

224 sequence_window: int = 30, universe: Iterable[str] | None = None, predictor: Callable[..., Mapping[str, np.ndarray]] | None = None, 

225) -> dict[str, pd.DataFrame]: 

226 """The installed models' score tables on [start, end], defined exactly as the walk-forward tables are (V6.5.0): `inst_a1` the 

227 mean of the date's percentile ranks of the sequence model's rank_20d and rank_5d, `inst_a2` the multitask model's 

228 sector_neutral_rank_20d, `inst_a3` the sequence model's. `dataset` must hold earlier rows too: a sequence window reads the 

229 previous bars of its ticker. `exports` maps "multitask"/"sequence" to (export, feature schema).""" 

230 if predictor is None: 

231 from evaluation.model_predictions import predict_heads as predictor 

232 frame = dataset.copy() 

233 frame["date"] = frame["date"].astype(str).str[:10] 

234 if universe is not None: 

235 frame = frame[frame["ticker"].isin(set(universe))] 

236 frame = frame.sort_values(["ticker", "date"]).reset_index(drop=True) 

237 mask = ((frame["date"] >= start) & (frame["date"] <= end)).to_numpy() 

238 if not mask.any(): 

239 return {} 

240 heads = { 

241 kind: predictor( 

242 frame, export, schema["model_input_names"], list(HEADS), model_kind=kind, 

243 sequence_feature_schema=schema if kind == "sequence" else None, configured_window_size=sequence_window, row_mask=mask, batched=True, 

244 ) 

245 for kind, (export, schema) in exports.items() 

246 } 

247 out: dict[str, pd.DataFrame] = {} 

248 

249 def add(name: str, values: pd.Series) -> None: 

250 out[name] = pd.DataFrame({"date": frame.loc[mask, "date"], "ticker": frame.loc[mask, "ticker"], "score": values[mask]}).reset_index(drop=True) 

251 

252 if "sequence" in heads: 

253 sequence = heads["sequence"] 

254 add("inst_a1", (daily_rank(frame, sequence["rank_20d"]) + daily_rank(frame, sequence["rank_5d"])) / 2.0) 

255 add("inst_a3", pd.Series(sequence["sector_neutral_rank_20d"], index=frame.index)) 

256 if "multitask" in heads: 

257 add("inst_a2", pd.Series(heads["multitask"]["sector_neutral_rank_20d"], index=frame.index)) 

258 return out