Coverage for portfolio/rank_signal.py: 100%

112 statements  

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

1"""Rank signal resolution and cross-sectional normalization (V5.1 Phase 1, 

2development/Problems.md #73 - the sigmoid-at-inference/raw-at-training 

3mismatch). Two responsibilities, both pure: 

4 

51. WHICH head(s) drive live trading - previously hardcoded in main.py 

6 (always prefer the sequence model's rank_20d, fall back to multitask's), 

7 now a config-driven, promotion-gate-aware blend resolved once per run. 

82. HOW that raw score becomes a [0,1] rank - previously a raw model output 

9 passed straight through (which, combined with a since-fixed sigmoid/raw 

10 training mismatch, meant live values compressed into roughly 

11 [0.5, 0.7] instead of spanning [0,1] - IC is invariant to any monotone 

12 transform, which is exactly why no rank-IC-based gate ever caught it). 

13 Cross-sectional percentile normalization, computed fresh each bar over 

14 whichever symbols have a raw score, is the fix that survives regardless 

15 of what scale the underlying model head happens to output at - the 

16 same reasoning train.py::_rank_ic_from_arrays() already documents for 

17 why it ranks predictions before comparing them. 

18""" 

19 

20from __future__ import annotations 

21 

22from typing import Any 

23 

24 

25def resolve_rank_signal_policy(training_metrics_by_model: dict[str, dict | None], config: dict[str, Any]) -> dict[str, Any]: 

26 """Resolved ONCE in main.py::Initialize() (never per-bar - the 

27 promotion-gate verdicts this reads only change when a new model is 

28 installed). Reads phase_v2.rank_signal: 

29 

30 heads: {"rank_20d": 1.0, "rank_5d": 0.0} - the blend weights. 

31 model_priority: ["sequence", "multitask"] - which model's value for 

32 a given head wins when both are available. 

33 demote_not_promotable_heads: when true, a head whose backtest 

34 promotion-gate verdict (backtest.{head}_ranking_quality.quality_status, 

35 checked against the FIRST model in model_priority that has a 

36 verdict for it - the same precedence select_raw_rank_score() uses 

37 at runtime) is not in min_promotion_status has its weight zeroed 

38 and redistributed proportionally across the surviving heads. 

39 A head configured at weight 0.0 is still checked and can still 

40 become a survivor - "listed with zero weight" means "tracked, 

41 currently inactive," not "not configured" (development/Problems.md); 

42 it only actually receives weight if every positively-weighted head 

43 gets demoted, in which case survivors split the freed weight 

44 equally rather than dividing by the now-zero surviving total. 

45 

46 Returns {"heads": {...}, "model_priority": [...], "normalization": ..., 

47 "demoted": [...], "reason": "...", "demotion_fallback": bool, "failed_heads": [...]}. 

48 

49 FAIL-OPEN, always: never raises. Missing/unreadable metrics for a head 

50 leave that head's configured weight untouched (a promotion verdict 

51 that cannot be checked is not evidence of a problem). If demotion 

52 would zero out EVERY head's weight, the entire operation is skipped 

53 and the originally configured policy is returned unchanged, with 

54 reason recording why - demoting every head would silently stop the 

55 book from ever engaging, a far bigger behavior change than "prefer a 

56 different head" implies. 

57 """ 

58 rank_signal_config = config.get("phase_v2", {}).get("rank_signal", {}) 

59 heads = dict(rank_signal_config.get("heads", {"rank_20d": 1.0})) 

60 model_priority = list(rank_signal_config.get("model_priority", ["sequence", "multitask"])) 

61 normalization = str(rank_signal_config.get("normalization", "cross_sectional")) 

62 demote_enabled = bool(rank_signal_config.get("demote_not_promotable_heads", True)) 

63 min_promotion_status = set(rank_signal_config.get("min_promotion_status", ["promotable", "watchlist"])) 

64 

65 if not demote_enabled or not heads: 

66 return { 

67 "heads": heads, "model_priority": model_priority, "normalization": normalization, 

68 "demoted": [], "reason": "demotion_disabled_or_no_heads_configured", 

69 "demotion_fallback": False, "failed_heads": [], 

70 } 

71 

72 demoted: list[str] = [] 

73 surviving_heads: dict[str, float] = {} 

74 for head_name, weight in heads.items(): 

75 status = _resolve_head_quality_status(head_name, model_priority, training_metrics_by_model) 

76 if status is None or status in min_promotion_status: 

77 surviving_heads[head_name] = weight 

78 elif weight > 0.0: 

79 # A head already at 0.0 weight can't be meaningfully "demoted" 

80 # (there's nothing to redistribute away from it) - only a 

81 # positively-weighted head's demotion is worth recording. 

82 demoted.append(head_name) 

83 

84 if not surviving_heads: 

85 # Demoting every head would silently stop the book from ever 

86 # engaging - a far bigger behavior change than "prefer a 

87 # different head" implies. Leave the configured policy untouched. 

88 # demotion_fallback / failed_heads make the fail-open visible: the book then trades heads that failed their gate. 

89 return { 

90 "heads": heads, "model_priority": model_priority, "normalization": normalization, 

91 "demoted": [], "reason": "all_heads_would_be_demoted_policy_unchanged", 

92 "demotion_fallback": True, "failed_heads": demoted, 

93 } 

94 

95 total_weight = sum(surviving_heads.values()) 

96 if total_weight > 0.0: 

97 redistributed = {name: weight / total_weight for name, weight in surviving_heads.items()} 

98 else: 

99 # Every positively-weighted head got demoted, leaving only 

100 # zero-weight survivors (heads tracked but not currently primary) - 

101 # split the freed weight equally among them rather than dividing 

102 # by a zero total. 

103 redistributed = {name: 1.0 / len(surviving_heads) for name in surviving_heads} 

104 # Zero-weighted entries for demoted heads are kept (not dropped) so 

105 # select_raw_rank_score()'s blend loop can still see - and skip - them 

106 # without a KeyError, and so state.json's rank_head_weights stays a 

107 # complete, auditable record of every configured head. 

108 for head_name in heads: 

109 redistributed.setdefault(head_name, 0.0) 

110 

111 reason = "no_demotion_needed" if not demoted else f"demoted:{','.join(demoted)}" 

112 return { 

113 "heads": redistributed, "model_priority": model_priority, "normalization": normalization, 

114 "demoted": demoted, "reason": reason, "demotion_fallback": False, "failed_heads": demoted, 

115 } 

116 

117 

118def _resolve_head_quality_status( 

119 head_name: str, model_priority: list[str], training_metrics_by_model: dict[str, dict | None] 

120) -> str | None: 

121 """First model in model_priority that has a backtest ranking_quality 

122 verdict for `head_name` wins - the same precedence 

123 select_raw_rank_score() uses to pick which model's VALUE feeds the 

124 blend, so the demotion decision and the runtime value come from the 

125 same model whenever possible. Returns None (never raises) when no 

126 configured model has a verdict for this head - e.g. an older metrics 

127 file predating this head, or the metrics file missing entirely.""" 

128 for model_name in model_priority: 

129 metrics = training_metrics_by_model.get(model_name) 

130 if not metrics: 

131 continue 

132 quality = (metrics.get("backtest", {}) or {}).get(f"{head_name}_ranking_quality") 

133 if quality: 

134 return quality.get("quality_status") 

135 return None 

136 

137 

138def select_raw_rank_score( 

139 sequence_prediction: dict[str, Any] | None, multitask_payload: dict[str, Any] | None, policy: dict[str, Any] 

140) -> tuple[float | None, str]: 

141 """Replaces main.py's previous hardcode (always prefer the sequence 

142 model's rank_20d, fall back to multitask's). Now a weighted blend 

143 across policy["heads"], each head's own value resolved via 

144 policy["model_priority"] (sequence before multitask, by default). 

145 

146 Returns (score, source) where source records exactly which heads/ 

147 models contributed, e.g. "sequence:0.6*rank_5d+0.4*rank_20d" or 

148 "sequence:1.0*rank_20d,multitask:1.0*rank_5d" when different heads 

149 come from different models. Returns (None, "no_rank_available") when 

150 no configured head has a value from any model this bar (e.g. every 

151 model still warming up).""" 

152 payload_by_model = {"sequence": sequence_prediction, "multitask": multitask_payload} 

153 model_priority = policy.get("model_priority", ["sequence", "multitask"]) 

154 heads = policy.get("heads", {}) 

155 

156 weighted_sum = 0.0 

157 total_weight_used = 0.0 

158 contributions: list[str] = [] 

159 

160 for head_name, weight in heads.items(): 

161 if weight <= 0.0: 

162 continue 

163 value, model_used = _resolve_head_value(head_name, model_priority, payload_by_model) 

164 if value is None: 

165 continue 

166 weighted_sum += weight * float(value) 

167 total_weight_used += weight 

168 contributions.append(f"{model_used}:{weight:g}*{head_name}") 

169 

170 if total_weight_used <= 0.0: 

171 return None, "no_rank_available" 

172 

173 score = weighted_sum / total_weight_used 

174 source = ",".join(contributions) 

175 return score, source 

176 

177 

178def _resolve_head_value( 

179 head_name: str, model_priority: list[str], payload_by_model: dict[str, dict | None] 

180) -> tuple[float | None, str | None]: 

181 for model_name in model_priority: 

182 payload = payload_by_model.get(model_name) 

183 if payload and payload.get(head_name) is not None: 

184 return float(payload[head_name]), model_name 

185 return None, None 

186 

187 

188def cross_sectional_rank_scores(scores_by_symbol: dict[str, float]) -> dict[str, float]: 

189 """Per-bar percentile rank across whatever symbols have a raw score 

190 this bar, ties averaged (matching pandas' `.rank(pct=True)` semantics - 

191 the same transform train.py::_rank_ic_from_arrays() applies to 

192 predictions before computing rank-IC, so a raw score's absolute scale 

193 can never matter, only its ordering within this bar's cross-section). 

194 Pure Python - no pandas import on the runtime hot path. 

195 

196 <=1 eligible symbol returns {} (no meaningful cross-section to rank 

197 within, so the book has no view this bar) - NEVER a spurious 0.5 for 

198 a lone symbol, which would silently look like "predicted median" 

199 rather than "no ranking possible.".""" 

200 if len(scores_by_symbol) <= 1: 

201 return {} 

202 

203 ordered = sorted(scores_by_symbol.items(), key=lambda item: item[1]) 

204 n = len(ordered) 

205 

206 # Average-rank tie handling: every symbol sharing a raw score value 

207 # gets the mean of the positions that tied group would have spanned. 

208 ranks: dict[str, float] = {} 

209 index = 0 

210 while index < n: 

211 group_end = index 

212 while group_end + 1 < n and ordered[group_end + 1][1] == ordered[index][1]: 

213 group_end += 1 

214 # Positions are 1-indexed for the standard rank formula; percentile 

215 # rank then divides by n so ties land on the correct SHARED 

216 # percentile rather than each tied member getting a distinct one. 

217 average_position = (index + 1 + group_end + 1) / 2.0 

218 percentile = average_position / n 

219 for tied_index in range(index, group_end + 1): 

220 symbol = ordered[tied_index][0] 

221 ranks[symbol] = percentile 

222 index = group_end + 1 

223 

224 return ranks 

225 

226 

227MAIN_RANK_GROUP = "main" 

228 

229 

230def rank_group_by_symbol(asset_class_by_symbol: dict[str, str | None], separate_rank_groups: dict[str, Any] | None) -> dict[str, str]: 

231 """{symbol: rank group} from `phase1.target.ranking.separate_rank_groups` ({group: [asset classes]}): a symbol whose 

232 class is listed under a group belongs to it, everything else to "main". The same mapping train.py uses to build the 

233 grouped rank targets (V5.7.0), so live ranks each group the way the model was trained.""" 

234 class_to_group: dict[str, str] = {} 

235 for group, classes in (separate_rank_groups or {}).items(): 

236 for kind in classes or (): 

237 class_to_group[str(kind)] = str(group) 

238 return { 

239 str(symbol): class_to_group.get(str(kind), MAIN_RANK_GROUP) if kind is not None else MAIN_RANK_GROUP 

240 for symbol, kind in asset_class_by_symbol.items() 

241 } 

242 

243 

244def sector_relative_scores( 

245 scores_by_symbol: dict[str, float], sector_by_symbol: dict[str, str] | None, min_sector_size: int = 3 

246) -> dict[str, float]: 

247 """Each score minus the mean of its sector's scores in this cross-section (V6.4.0, lead L4): a rank within the sector's 

248 own peers rather than across sectors. A sector with fewer than `min_sector_size` scored names (or none mapped) is 

249 de-meaned by the whole cross-section's mean instead, so its names keep their relative order.""" 

250 if not scores_by_symbol: 

251 return {} 

252 overall = sum(scores_by_symbol.values()) / len(scores_by_symbol) 

253 members: dict[str, list[float]] = {} 

254 for symbol, score in scores_by_symbol.items(): 

255 members.setdefault((sector_by_symbol or {}).get(str(symbol), ""), []).append(score) 

256 means = { 

257 sector: (sum(values) / len(values) if sector and len(values) >= min_sector_size else overall) 

258 for sector, values in members.items() 

259 } 

260 return {symbol: score - means[(sector_by_symbol or {}).get(str(symbol), "")] for symbol, score in scores_by_symbol.items()} 

261 

262 

263def grouped_cross_sectional_rank_scores( 

264 scores_by_symbol: dict[str, float], group_by_symbol: dict[str, str] | None, 

265 sector_by_symbol: dict[str, str] | None = None, min_sector_size: int = 3, 

266) -> dict[str, float]: 

267 """cross_sectional_rank_scores() applied WITHIN each rank group (V5.8.0): a model trained on grouped rank targets 

268 (bonds ranked among bonds, forex among forex) emits scores that are only comparable inside their group, so the 

269 percentile is taken per group. With no mapping (or every symbol in "main") this equals cross_sectional_rank_scores(). 

270 

271 `sector_by_symbol` (V6.4.0, `rank_signal.normalization: "sector_relative"`, default None = off) de-means each group's 

272 scores by their sector's mean first (`sector_relative_scores`), so the percentile ranks a name against its sector peers.""" 

273 if not group_by_symbol: 

274 scores = sector_relative_scores(scores_by_symbol, sector_by_symbol, min_sector_size) if sector_by_symbol else scores_by_symbol 

275 return cross_sectional_rank_scores(scores) 

276 by_group: dict[str, dict[str, float]] = {} 

277 for symbol, score in scores_by_symbol.items(): 

278 by_group.setdefault(group_by_symbol.get(str(symbol), MAIN_RANK_GROUP), {})[symbol] = score 

279 ranks: dict[str, float] = {} 

280 for group_scores in by_group.values(): 

281 if sector_by_symbol: 

282 group_scores = sector_relative_scores(group_scores, sector_by_symbol, min_sector_size) 

283 ranks.update(cross_sectional_rank_scores(group_scores)) 

284 return ranks