Coverage for risk/rl_sizing.py: 100%

105 statements  

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

1"""Offline-trained contextual-bandit sizing overlay (development/Problems.md 

2#71, Phase 4.12, Component E) - a SHRINK-ONLY multiplier layered on top of 

3risk/position_sizing.py::build_dynamic_position_sizing()'s output, never 

4replacing it. Pure Python, no numpy/torch at runtime, matching 

5topology/learned_topology.py's exact "pure inference, model trained offline, 

6degrades to a strict no-op when the model is missing/malformed/disabled" 

7split. 

8 

9Honest framing, not oversold (see train_rl_sizing.py's own module docstring 

10for the full data-source story): this is a full-information contextual 

11bandit fit offline over ml/datasets/*.csv (the SAME rows train.py already 

12builds), NOT online/off-policy reinforcement learning against live 

13exploration data - main.py has never logged a stochastic sizing action, and 

14risk/position_sizing.py's own established rule (topology_sizing_multiplier()'s 

15docstring) forbids ever randomizing a live sizing decision. The offline 

16reward for every candidate action is computable in closed form from the 

17already-known forward return, so no exploration is needed to fit this - see 

18train_rl_sizing.py. 

19 

20What this CAN plausibly do: learn to shrink size in STATE-CONDITIONAL 

21low-edge regimes (e.g. high implied volatility + backwardation + tightening 

22financial conditions - exactly the alt-data features Problems.md #71's 

23Component D added), reducing turnover/fees in the states this project's own 

24Backtest 1 measured were the most costly. What it CANNOT do: manufacture 

25alpha where none exists - if the underlying signal doesn't clear costs 

26anywhere, the reward-maximizing policy over a shrink-only action set 

27degenerates to "always pick the smallest multiplier," which is a `max_*_multiplier` 

28config change, not a model, and is the intended "give up gracefully" behavior, 

29not a bug. 

30 

31Default OFF (phase_v2.dynamic_risk.rl_sizing_enabled) - see 

32risk/position_sizing.py's rl_multiplier param and main.py's wiring.""" 

33 

34from __future__ import annotations 

35 

36import json 

37import math 

38from pathlib import Path 

39from typing import Any 

40 

41# Fixed, order-significant state key list - the trained artifact carries 

42# its OWN copy of this same list (model["state_keys"]) and 

43# rl_sizing_multiplier() below refuses to score anything (falls back to 

44# 1.0) if the two disagree, rather than silently reordering/misaligning 

45# a state vector against weights trained for a different order. Every key 

46# here is already computed once per bar as part of the existing base 

47# feature/topology payload - no new computation, no new data source. 

48RL_SIZING_STATE_KEYS = [ 

49 "confidence", 

50 "rolling_volatility_20d", 

51 "regime_signal_risk_score", 

52 "topology_correlation_strength", 

53 "liquidity_spread_proxy", 

54 "bond_credit_spread_level", 

55 "alt_implied_volatility_level", 

56 "alt_implied_vol_term_structure", 

57 "alt_financial_conditions_change", 

58 # V5.4.1 - regime trend one-hots: lets the linear policy learn 

59 # regime-conditional sizing (e.g. be more conservative in bearish) 

60 # rather than a single global multiplier that averages across regimes. 

61 "regime_trend_bullish", 

62 "regime_trend_bearish", 

63 "regime_trend_sideways", 

64] 

65 

66# V5.7.0 - the forex sleeve's own policy: trained on book-level (20-day, per-order-fee) rewards over the forex pool, with 

67# the two inputs that decide whether a small FX order is worth its dollar minimum. `log_order_notional` is 

68# log(base book weight x NAV), computed by the caller (not a base feature). 

69FOREX_RL_SIZING_STATE_KEYS = [ 

70 "confidence", 

71 "rolling_volatility_20d", 

72 "liquidity_spread_proxy", 

73 "fx_carry_3m", 

74 "log_order_notional", 

75 "regime_signal_risk_score", 

76 "alt_implied_volatility_level", 

77] 

78 

79DEFAULT_MIN_RL_MULTIPLIER = 0.6 

80DEFAULT_MAX_RL_MULTIPLIER = 1.0 

81 

82 

83def build_rl_sizing_state( 

84 base_features: dict[str, Any], 

85 confidence: float, 

86 state_keys: list[str] | None = None, 

87 extra_state: dict[str, Any] | None = None, 

88) -> dict[str, Any] | None: 

89 """Pulls RL_SIZING_STATE_KEYS out of the SAME base_features dict 

90 main.py's _build_model_input_impl() already assembled this bar (plus 

91 the model's own separately-computed confidence score, not itself a 

92 base_feature) - no new computation, no new data source. Returns None 

93 if any key is absent (e.g. Component D's alt-data features not yet in 

94 input_set/retrained), which rl_sizing_multiplier() treats identically 

95 to "no model" - a strict 1.0 no-op, never a crash or a partially-built 

96 state vector.""" 

97 state = {} 

98 extra_state = extra_state or {} 

99 for key in state_keys or RL_SIZING_STATE_KEYS: 

100 if key == "confidence": 

101 continue 

102 if key in extra_state: 

103 state[key] = float(extra_state[key]) 

104 continue 

105 if key not in base_features: 

106 return None 

107 state[key] = float(base_features[key]) 

108 state["confidence"] = float(confidence) 

109 return state 

110 

111 

112def _softmax_argmax_index(scores: list[float]) -> int: 

113 """Deterministic argmax - NOT a sampled draw from the softmax 

114 distribution. topology_sizing_multiplier()'s docstring establishes the 

115 project-wide rule this module also follows: "probabilistic scoring may 

116 only ever produce a bounded, continuous adjustment, never a randomized 

117 or amplified decision." A stochastic policy is legitimate during 

118 OFFLINE training (see train_rl_sizing.py - exploration there costs 

119 nothing, it's arithmetic over historical rows) and forbidden at live 

120 inference. Ties broken toward the LAST action with the max score - by 

121 convention the action list is built low-to-high multiplier 

122 (see rl_sizing_multiplier()), so a tie prefers the larger (less 

123 aggressive shrink) multiplier, matching a zero-initialized/untrained 

124 model's intended "prefer no-op" default.""" 

125 best_index = 0 

126 best_score = scores[0] 

127 for index, score in enumerate(scores): 

128 if score >= best_score: 

129 best_score = score 

130 best_index = index 

131 return best_index 

132 

133 

134def rl_sizing_multiplier( 

135 model: dict[str, Any] | None, 

136 state: dict[str, Any] | None, 

137 rl_sizing_enabled: bool, 

138 min_rl_multiplier: float = DEFAULT_MIN_RL_MULTIPLIER, 

139 max_rl_multiplier: float = DEFAULT_MAX_RL_MULTIPLIER, 

140 expected_state_keys: list[str] | None = None, 

141) -> tuple[float, str]: 

142 """`expected_state_keys` (V5.7.0, default RL_SIZING_STATE_KEYS) is the key list the CALLER's state was built with; a 

143 model trained for another list (the forex policy) is refused, never silently misaligned. 

144 

145 Bounded, deterministic (argmax, never sampled), shrink-only size 

146 adjustment - exact contract clone of 

147 risk/position_sizing.py::rank_sizing_multiplier()/topology_sizing_multiplier(): 

148 returns (1.0, "<reason>") whenever the flag is off, the model is 

149 missing/malformed, the state is incomplete, or the model's own 

150 state_keys disagree with RL_SIZING_STATE_KEYS - every failure mode is a 

151 strict no-op, never a crash and never an amplified size. 

152 

153 THREE safety properties, all enforced HERE rather than trusted from the 

154 artifact (an untrusted/stale/hand-edited model file must never be able 

155 to violate them): 

156 1. Argmax, never sampled - see _softmax_argmax_index()'s docstring. 

157 2. Clamped to [min_rl_multiplier, max_rl_multiplier] AFTER the argmax, 

158 so a corrupted/adversarial action table can never emit a 

159 multiplier outside the configured band, regardless of what the 

160 model file claims its own actions are. 

161 3. max_rl_multiplier defaults to 1.0 - SHRINK-ONLY, matching 

162 topology_sizing_multiplier()'s "never amplifies size beyond what 

163 deterministic-only sizing already computed" rule. Amplification 

164 (max_rl_multiplier > 1.0) is technically possible via config but 

165 is NOT the shipped/recommended posture for v1 - see 

166 development/Problems.md #71's abandon criteria.""" 

167 if not rl_sizing_enabled or model is None or state is None: 

168 return 1.0, "rl_sizing_disabled_or_absent" 

169 

170 try: 

171 state_keys = model.get("state_keys") 

172 actions = model.get("actions") 

173 weights = model.get("weights") 

174 bias = model.get("bias") 

175 mean = model.get("mean") 

176 scale = model.get("scale") 

177 if state_keys != (expected_state_keys or RL_SIZING_STATE_KEYS): 

178 return 1.0, "rl_sizing_state_key_mismatch" 

179 if not actions or not weights or not bias or not mean or not scale: 

180 return 1.0, "rl_sizing_malformed_model" 

181 if len(weights) != len(actions) or len(bias) != len(actions): 

182 return 1.0, "rl_sizing_malformed_model" 

183 

184 standardized = [] 

185 for key, mean_value, scale_value in zip(state_keys, mean, scale, strict=False): 

186 raw = float(state[key]) 

187 denominator = float(scale_value) if float(scale_value) != 0.0 else 1.0 

188 standardized.append((raw - float(mean_value)) / denominator) 

189 

190 scores = [] 

191 for action_weights, action_bias in zip(weights, bias, strict=False): 

192 if len(action_weights) != len(standardized): 

193 return 1.0, "rl_sizing_malformed_model" 

194 score = float(action_bias) + sum(w * x for w, x in zip(action_weights, standardized, strict=False)) 

195 scores.append(score) 

196 

197 # V5.5.0 (Problems.md #117): a NaN/inf score used to fall through to 

198 # the argmax below. NaN compares False with everything, so a NaN at 

199 # scores[0] pinned best_index to 0 - the MOST aggressive shrink 

200 # (0.6x) - instead of the strict no-op every other failure returns. 

201 if not all(math.isfinite(score) for score in scores): 

202 return 1.0, "rl_sizing_non_finite_score" 

203 

204 best_index = _softmax_argmax_index(scores) 

205 raw_multiplier = float(actions[best_index]) 

206 except (KeyError, TypeError, ValueError, ZeroDivisionError): 

207 return 1.0, "rl_sizing_malformed_model" 

208 

209 # V6.6.7 (#368, formal/AetherFormal/RlSizing.lean): a band that is not finite or has min > max is a strict no-op; 

210 # max(min, min(raw, max)) with min 1.2 and max 1.0 returned 1.2, an amplified size from a shrink-only control 

211 try: 

212 low, high = float(min_rl_multiplier), float(max_rl_multiplier) 

213 except (TypeError, ValueError): 

214 return 1.0, "rl_sizing_invalid_bounds" 

215 if not (math.isfinite(low) and math.isfinite(high)) or low > high: 

216 return 1.0, "rl_sizing_invalid_bounds" 

217 clamped = max(low, min(raw_multiplier, high)) 

218 return clamped, "rl_sizing_policy_scaled_sizing" 

219 

220 

221def load_rl_sizing_model(path: Path) -> dict[str, Any] | None: 

222 """Missing file -> None (fresh checkout / never trained - the 

223 documented default state). Malformed JSON -> None (never raises). 

224 Mirrors main.py's own "missing/malformed model -> None, never a hard 

225 failure" convention already established for every other optional 

226 learned artifact (topology, gating, experts).""" 

227 if not path.exists(): 

228 return None 

229 try: 

230 return json.loads(path.read_text(encoding="utf-8")) 

231 except (OSError, ValueError): 

232 return None 

233 

234 

235def resolve_rl_shadow_guard(raw: dict[str, Any] | None) -> dict[str, Any]: 

236 """`phase_v2.dynamic_risk.rl_shadow_guard` -> {"enabled", "window_bars", "tolerance_nav_fraction"}; absent = 

237 disabled (RL, when enabled, is never switched off by its own track record - the pre-V5.8.0 behaviour).""" 

238 raw = raw or {} 

239 try: 

240 window = max(1, int(raw.get("window_bars", 60))) 

241 tolerance = max(0.0, float(raw.get("tolerance_nav_fraction", 0.002))) 

242 except (TypeError, ValueError): 

243 window, tolerance = 60, 0.002 

244 return {"enabled": bool(raw.get("enabled", False)), "window_bars": window, "tolerance_nav_fraction": tolerance} 

245 

246 

247def rl_excess_return(positions: dict[str, tuple[float, float]], returns: dict[str, float]) -> float: 

248 """V5.8.0: one bar's return (NAV fraction) of the RL-sized book minus the same book at constant 1.0 sizing. 

249 `positions` maps symbol -> (signed weight actually held, RL multiplier applied when it was sized); the constant book 

250 would have held weight / multiplier, so the excess is weight * (1 - 1/multiplier) * return. Non-finite or 

251 non-positive multipliers and missing returns contribute nothing.""" 

252 total = 0.0 

253 for symbol, (weight, multiplier) in positions.items(): 

254 value = returns.get(symbol) 

255 try: 

256 weight, multiplier, value = float(weight), float(multiplier), float(value) 

257 except (TypeError, ValueError): 

258 continue 

259 if not (math.isfinite(weight) and math.isfinite(multiplier) and math.isfinite(value)) or multiplier <= 0.0: 

260 continue 

261 total += weight * (1.0 - 1.0 / multiplier) * value 

262 return total 

263 

264 

265def rl_shadow_guard_allows(excess_history: list[float], guard: dict[str, Any]) -> bool: 

266 """True while RL may size: always when the guard is off; otherwise the summed excess return over the trailing 

267 `window_bars` must not be below -`tolerance_nav_fraction` (RL that has cost more than the tolerance against 

268 constant sizing falls back to 1.0 until the loss leaves the window).""" 

269 if not guard.get("enabled", False): 

270 return True 

271 # at least one bar, as resolve_rl_shadow_guard clamps it: xs[-0:] is the whole history (V6.6.7, #368) 

272 window = max(1, int(guard.get("window_bars", 60))) 

273 recent = excess_history[-window:] 

274 return sum(value for value in recent if math.isfinite(value)) >= -float(guard.get("tolerance_nav_fraction", 0.002))