Coverage for portfolio/generation_blend.py: 100%

165 statements  

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

1"""Several model generations sharing one book (V6.6.1): how capital moves between them, and the blended weights the target-weights path trades. 

2 

3A generation is a frozen signal producer with its own target weights. They blend upstream of `ml/target_weights.csv`, so one file reaches Lean, the offline engine and 

4the live path, and a generation can't have a code path of its own. A blend is convex, so a cap every generation respects holds for the book (`formal/AetherFormal/GenerationBlend.lean`). 

5 

6Two ways to move capital: 

7 

8- `ladder`: the ramping generation gains capital at a fixed rate, the older ones give it up in proportion to what they hold, 70/30, 64/36, ... 0/100. One gains at a time. 

9- `dynamic`: each generation's target comes from its own record. Its score is its Sharpe so far shrunk toward what it claimed at admission, and targets are proportional to the 

10 scores above a floor, which is the best split of uncorrelated books of equal risk. Any number can hold capital at once: an old generation still earning keeps a share, one that stops 

11 fades out, and shares move a fixed fraction of the way to their targets each session, so nothing jumps, a new generation included. 

12 

13Evidence alone is slow: at one false alarm in five years a decay detector needs over a year to see a Sharpe fall from 1 to 0. So shrinkage keeps a short record from moving much capital, and 

14a generation's capital leaves at once only on a guard trip or a dead state. Taking risk off is not rate-capped. 

15 

16Stdlib only at import. Non-finite input holds the shares; output is always in [0, 1] and sums to at most 1, with the rest in T-bills. 

17""" 

18 

19from __future__ import annotations 

20 

21import math 

22from collections.abc import Mapping 

23from dataclasses import dataclass 

24 

25GAINING_STAGES = frozenset({"ramping"}) 

26HOLDING_STAGES = frozenset({"active", "fading", "winding_down", "ramping"}) 

27DEAD_STATES = frozenset({"dead"}) 

28SHARE_TOLERANCE = 1e-9 

29MODES = ("ladder", "dynamic") 

30EW_HALF_LIFE_SESSIONS = 126.0 

31EW_MIN_SESSIONS = 20 

32 

33 

34@dataclass(frozen=True) 

35class GlidePolicy: 

36 """How capital moves between generations: the glide length, a newcomer's entry share, the retirement floor and the paper caps.""" 

37 glide_sessions: int = 252 

38 entry_share: float = 0.30 

39 retire_share: float = 0.05 # 10% of a 0.0127 weight is below the 0.002 deadband: a residue that could never trade 

40 blend_every: int = 21 

41 tier2_paper_cap: float = 0.30 

42 hold_on_watch: bool = False 

43 accelerate_on_decaying: float = 1.0 

44 mode: str = "ladder" 

45 half_life_sessions: int = 126 # dynamic: sessions to move half way to a target 

46 prior_sessions: float = 252.0 # dynamic: how many sessions of record weigh as much as the claim at admission 

47 score_floor: float = 0.0 # dynamic: a score at or below this earns no share 

48 max_generations: int = 4 

49 min_evidence_sessions: int = 60 # dynamic: with no generation past this and no positive score, nothing is known yet, so hold 

50 

51 

52def _finite(value, default: float) -> float: 

53 try: 

54 number = float(value) 

55 except (TypeError, ValueError): 

56 return default 

57 return number if math.isfinite(number) else default 

58 

59 

60def resolve_glide_policy(raw: Mapping | None) -> GlidePolicy: 

61 """A `GlidePolicy` from config, every share clipped to [0, 1] and every missing or non-finite value at its default.""" 

62 raw = raw or {} 

63 defaults = GlidePolicy() 

64 

65 def share(name: str) -> float: 

66 return max(0.0, min(1.0, _finite(raw.get(name), getattr(defaults, name)))) 

67 

68 return GlidePolicy( 

69 glide_sessions=max(1, int(_finite(raw.get("glide_sessions"), defaults.glide_sessions))), entry_share=share("entry_share"), retire_share=share("retire_share"), 

70 blend_every=max(1, int(_finite(raw.get("blend_every"), defaults.blend_every))), tier2_paper_cap=share("tier2_paper_cap"), hold_on_watch=bool(raw.get("hold_on_watch", defaults.hold_on_watch)), 

71 accelerate_on_decaying=max(1.0, _finite(raw.get("accelerate_on_decaying"), defaults.accelerate_on_decaying)), 

72 mode=str(raw.get("mode")) if raw.get("mode") in MODES else defaults.mode, 

73 half_life_sessions=max(1, int(_finite(raw.get("half_life_sessions"), defaults.half_life_sessions))), 

74 prior_sessions=max(0.0, _finite(raw.get("prior_sessions"), defaults.prior_sessions)), 

75 score_floor=_finite(raw.get("score_floor"), defaults.score_floor), 

76 max_generations=max(1, int(_finite(raw.get("max_generations"), defaults.max_generations))), 

77 min_evidence_sessions=max(0, int(_finite(raw.get("min_evidence_sessions"), defaults.min_evidence_sessions))), 

78 ) 

79 

80 

81def blend_generation_rows(rows_by_generation: Mapping[str, Mapping[str, float]], shares: Mapping[str, float]) -> dict[str, float]: 

82 """The book: each generation's weights times its share, summed per name. A generation with no row counts as flat; a name that nets to zero leaves the row.""" 

83 book: dict[str, float] = {} 

84 for generation, row in rows_by_generation.items(): 

85 share = _finite(shares.get(generation, 0.0), 0.0) 

86 if share <= 0.0: 

87 continue 

88 for ticker, weight in row.items(): 

89 book[ticker] = book.get(ticker, 0.0) + share * _finite(weight, 0.0) 

90 return {ticker: weight for ticker, weight in book.items() if weight != 0.0} 

91 

92 

93def _evidence_multiplier(states: Mapping[str, str], ramping: str, older: list[str], policy: GlidePolicy) -> float: 

94 if policy.hold_on_watch and states.get(ramping) in ("watch", "decaying"): 

95 return 0.0 

96 if policy.accelerate_on_decaying > 1.0 and any(states.get(name) == "decaying" for name in older): 

97 return policy.accelerate_on_decaying 

98 return 1.0 

99 

100 

101def update_generation_shares( 

102 shares: Mapping[str, float], stages: Mapping[str, str], states: Mapping[str, str], caps: Mapping[str, float], policy: GlidePolicy, *, sessions: int = 1, 

103) -> dict[str, float]: 

104 """The shares after `sessions` sessions. A generation out of a holding stage, or dead, or with a guard trip (state `tripped`), drops to zero at once; a new ramping 

105 generation enters at `entry_share`; below `retire_share` a generation is gone, and what it held passes to the ramping one up to its cap. What no one may hold stays in T-bills.""" 

106 numbers = {name: _finite(value, math.nan) for name, value in shares.items()} 

107 if any(math.isnan(value) or value < 0.0 for value in numbers.values()) or sum(numbers.values()) > 1.0 + SHARE_TOLERANCE: 

108 return {name: _finite(value, 0.0) for name, value in shares.items()} # damaged shares: hold, don't guess 

109 sessions = max(0, int(sessions)) 

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

111 for name, stage in stages.items(): 

112 value = numbers.get(name, 0.0) 

113 if stage not in HOLDING_STAGES or states.get(name) in DEAD_STATES or states.get(name) == "tripped": 

114 out[name] = 0.0 

115 else: 

116 out[name] = value 

117 ramping = [name for name in stages if stages[name] in GAINING_STAGES and states.get(name) not in DEAD_STATES and states.get(name) != "tripped"] 

118 # One generation gains at a time, the oldest ramping: its successor waits, so two handovers can't overlap. 

119 gainer = sorted(ramping)[0] if ramping else None 

120 if gainer is None: 

121 return _retire_small(out, None, 1.0, policy) 

122 cap = max(0.0, min(1.0, _finite(caps.get(gainer, 1.0), 1.0))) 

123 older = [name for name in out if name != gainer and out[name] > 0.0] 

124 if out[gainer] <= 0.0: 

125 wanted = min(cap, policy.entry_share) 

126 else: 

127 step = (1.0 - policy.entry_share) / float(policy.glide_sessions) * _evidence_multiplier(states, gainer, older, policy) * sessions 

128 wanted = min(cap, out[gainer] + step) 

129 increase = max(0.0, wanted - out[gainer]) 

130 from_tbills = min(increase, max(0.0, 1.0 - sum(out.values()))) 

131 give = sum(out[name] for name in older) 

132 taken = min(increase - from_tbills, give) 

133 if give > 0.0: 

134 for name in older: 

135 out[name] -= taken * (out[name] / give) 

136 out[gainer] += from_tbills + taken 

137 return _retire_small(out, gainer, cap, policy) 

138 

139 

140def _retire_small(shares: dict[str, float], gainer: str | None, cap: float, policy: GlidePolicy) -> dict[str, float]: 

141 """Below `retire_share` a generation is gone, and what it held passes to the gainer up to its cap; the rest stays in T-bills.""" 

142 out = dict(shares) 

143 for name, value in shares.items(): 

144 # The tolerance keeps a share of exactly `retire_share` in float arithmetic from reading as just under it, as the exact-arithmetic model says. 

145 if name != gainer and 0.0 < value < policy.retire_share - SHARE_TOLERANCE: 

146 out[name] = 0.0 

147 if gainer is not None: 

148 out[gainer] = min(cap, out[gainer] + value) 

149 return {name: max(0.0, min(1.0, value)) for name, value in out.items()} 

150 

151 

152def ew_update(state: tuple[float, float, float, int], value: float, half_life: float = EW_HALF_LIFE_SESSIONS) -> tuple[float, float, float, int]: 

153 """One more session of an exponentially weighted record: (weight, weighted sum, weighted squares, sessions). A non-finite return leaves it as it is.""" 

154 number = _finite(value, math.nan) 

155 if math.isnan(number): 

156 return state 

157 decay = 0.5 ** (1.0 / float(half_life)) 

158 weight, total, squares, sessions = state 

159 return weight * decay + 1.0, total * decay + number, squares * decay + number * number, sessions + 1 

160 

161 

162def ew_sharpe(state: tuple[float, float, float, int], *, sessions_per_year: float = 252.0) -> float | None: 

163 """The annualised Sharpe of that record. None until it holds `EW_MIN_SESSIONS` or if it has no variance.""" 

164 weight, total, squares, sessions = state 

165 if sessions < EW_MIN_SESSIONS or weight <= 0.0: 

166 return None 

167 mean = total / weight 

168 variance = squares / weight - mean * mean 

169 return mean / math.sqrt(variance) * math.sqrt(sessions_per_year) if variance > 0.0 else None 

170 

171 

172def shrunk_sharpe(observed: float | None, sessions: int, prior: float, prior_sessions: float) -> float: 

173 """What a generation's Sharpe is believed to be: its record and its claim, weighted by sessions of record against `prior_sessions`. No usable record leaves the claim.""" 

174 claim = _finite(prior, 0.0) 

175 number = _finite(observed, math.nan) 

176 count = max(0.0, _finite(sessions, 0.0)) 

177 if math.isnan(number) or count + prior_sessions <= 0.0: 

178 return claim 

179 return (count * number + prior_sessions * claim) / (count + prior_sessions) 

180 

181 

182def dynamic_targets(scores: Mapping[str, float], caps: Mapping[str, float], policy: GlidePolicy) -> dict[str, float]: 

183 """Each generation's target: proportional to its score above the floor, for the best `max_generations`. What a capped generation can't hold goes to the others, and what none may hold stays in T-bills.""" 

184 usable = {name: _finite(score, math.nan) - policy.score_floor for name, score in scores.items()} 

185 positive = sorted(((value, name) for name, value in usable.items() if value > 0.0), key=lambda item: (-item[0], item[1]))[: policy.max_generations] 

186 targets = dict.fromkeys(scores, 0.0) 

187 open_names = {name: value for value, name in positive} 

188 remaining = 1.0 

189 while open_names and remaining > SHARE_TOLERANCE: 

190 total = sum(open_names.values()) 

191 over = { 

192 name: max(0.0, min(1.0, _finite(caps.get(name, 1.0), 1.0))) for name, value in open_names.items() 

193 if remaining * value / total > max(0.0, min(1.0, _finite(caps.get(name, 1.0), 1.0))) + SHARE_TOLERANCE 

194 } 

195 if not over: 

196 for name, value in open_names.items(): 

197 targets[name] = remaining * value / total 

198 break 

199 for name, cap in over.items(): 

200 targets[name] = cap 

201 remaining -= cap 

202 del open_names[name] 

203 return targets 

204 

205 

206def step_toward(shares: Mapping[str, float], targets: Mapping[str, float], fraction: float, retire_share: float) -> dict[str, float]: 

207 """A fixed fraction of the way to the targets, so nothing jumps. A blend of two allocations that each sum to at most one sums to at most one (proved in Lean). A generation headed to nothing 

208 is gone below `retire_share`, as it couldn't trade its residue.""" 

209 step = max(0.0, min(1.0, _finite(fraction, 0.0))) 

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

211 for name in sorted(set(shares) | set(targets)): 

212 before, target = _finite(shares.get(name, 0.0), 0.0), _finite(targets.get(name, 0.0), 0.0) 

213 value = before + step * (target - before) 

214 out[name] = 0.0 if target <= 0.0 and value < retire_share - SHARE_TOLERANCE else value 

215 return out 

216 

217 

218def repair_shares(shares: Mapping[str, float]) -> dict[str, float]: 

219 """An allocation that is a valid one: a NaN or negative share is zero, and a total above one is scaled down to one 

220 (formal/AetherFormal/DynamicTargets.lean, `repair_valid`). V6.6.7 (#375): an invalid allocation used to be returned 

221 as it was, so a tripped or dead generation kept its share, and an over-allocated book stayed over-allocated.""" 

222 numbers = {name: max(0.0, _finite(value, 0.0)) for name, value in shares.items()} 

223 total = sum(numbers.values()) 

224 if total > 1.0 + SHARE_TOLERANCE: 

225 numbers = {name: value / total for name, value in numbers.items()} 

226 return numbers 

227 

228 

229def dynamic_generation_shares( 

230 shares: Mapping[str, float], stages: Mapping[str, str], states: Mapping[str, str], evidence: Mapping[str, Mapping], caps: Mapping[str, float], policy: GlidePolicy, *, sessions: int = 1, 

231) -> dict[str, float]: 

232 """The `dynamic` mode. `evidence` holds, per generation, `ew_sharpe`, `sessions` and `prior`. A generation out of a holding stage, dead or tripped drops to zero at once, whatever its score; 

233 `winding_down` aims for zero. With no positive score and no generation past `min_evidence_sessions`, nothing is known yet, so shares hold.""" 

234 numbers = repair_shares(shares) 

235 now = { 

236 name: 0.0 if stage not in HOLDING_STAGES or states.get(name) in DEAD_STATES or states.get(name) == "tripped" else numbers.get(name, 0.0) 

237 for name, stage in stages.items() 

238 } 

239 scores: dict[str, float] = {} 

240 seasoned = False 

241 for name, stage in stages.items(): 

242 if stage not in HOLDING_STAGES or stage == "winding_down" or states.get(name) in DEAD_STATES or states.get(name) == "tripped": 

243 scores[name] = -math.inf 

244 continue 

245 record = evidence.get(name) or {} 

246 count = int(_finite(record.get("sessions"), 0.0)) 

247 seasoned = seasoned or count >= policy.min_evidence_sessions 

248 scores[name] = shrunk_sharpe(record.get("ew_sharpe"), count, _finite(record.get("prior"), 0.0), policy.prior_sessions) 

249 finite_scores = {name: (score if math.isfinite(score) else policy.score_floor - 1.0) for name, score in scores.items()} 

250 targets = dynamic_targets(finite_scores, caps, policy) 

251 if not any(value > 0.0 for value in targets.values()) and not seasoned: 

252 return {name: max(0.0, min(1.0, value)) for name, value in now.items()} 

253 fraction = 1.0 - 0.5 ** (max(0, int(sessions)) / float(policy.half_life_sessions)) 

254 return {name: max(0.0, min(1.0, value)) for name, value in step_toward(now, targets, fraction, policy.retire_share).items()} 

255 

256 

257def blend_due(*, decided_today: bool, sessions_since_blend: int, guard_tripped: bool, policy: GlidePolicy) -> bool: 

258 """Whether to write a blended row. A row retargets every name and resets drift, so not daily: on a generation's decision day, every `blend_every` sessions, or on a guard trip.""" 

259 return bool(decided_today or guard_tripped or int(sessions_since_blend) >= policy.blend_every)