Coverage for portfolio/book_neutrality.py: 100%

58 statements  

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

1"""Cross-symbol book neutralization (V5.1 Phase 0/1, item 6 of the V5.1 

2roadmap - development/Problems.md). 

3 

4Every existing weight computation in this codebase (risk/position_sizing.py, 

5main.py:1723-1726's inline book-role formula) is per-symbol: it never looks 

6at what any other symbol in the same bar's book is doing. This module is the 

7one deliberate cross-symbol pass, applied once per rebalance bar AFTER every 

8symbol's raw book weight is known - it never changes a symbol's role (long/ 

9short), only rescales magnitudes so the book as a whole is dollar-neutral, 

10sector-neutral, and gross-capped. 

11 

12Deliberately its own module, not folded into portfolio/book_construction.py: 

13build_rank_based_book() decides WHICH symbols and WHICH side (a per-bar, 

14whole-universe decision already); this module decides HOW MUCH, given that 

15selection is already final - same separation-of-concerns split 

16book_construction.py's own docstring draws between itself and 

17risk/position_sizing.py. 

18""" 

19 

20from __future__ import annotations 

21 

22 

23def _clip(value: float, low: float, high: float) -> float: 

24 return max(low, min(value, high)) 

25 

26 

27def _shrink_sectors_to_cap(weights: dict[str, float], sector_by_symbol: dict[str, str], cap: float) -> None: 

28 """Step 2, in place: every bucket whose |net| exceeds `cap` is scaled (sign preserved) so its net lands on it.""" 

29 symbols_by_sector: dict[str, list[str]] = {} 

30 for symbol in weights: 

31 symbols_by_sector.setdefault(sector_by_symbol.get(symbol, "Unknown"), []).append(symbol) 

32 for members in symbols_by_sector.values(): 

33 bucket_net = sum(weights[symbol] for symbol in members) 

34 if abs(bucket_net) > cap: 

35 shrink_factor = cap / abs(bucket_net) 

36 for symbol in members: 

37 weights[symbol] *= shrink_factor 

38 

39 

40def apply_book_neutrality( 

41 raw_weights_by_symbol: dict[str, float], 

42 *, 

43 sector_by_symbol: dict[str, str], 

44 dollar_neutral: bool, 

45 sector_neutral: bool, 

46 gross_exposure_cap: float, 

47 max_weight_per_name: float, 

48 sector_max_net_weight: float, 

49 reapply_sector_cap_after_dollar_neutral: bool = False, 

50) -> tuple[dict[str, float], dict]: 

51 """Deterministic 4-step pipeline over an already-selected book's raw 

52 per-symbol weights (main.py's today-formula: 

53 min(max_position_weight, 0.10 + 0.15*confidence) * book_role_multiplier, 

54 one entry per book-selected symbol only - not the whole universe). 

55 

56 Steps, always in this order: 

57 1. Per-name cap: clip every weight to [-max_weight_per_name, +max_weight_per_name]. 

58 2. Sector neutrality (if sector_neutral): within each sector bucket, 

59 if |bucket net| exceeds sector_max_net_weight, SHRINK the whole 

60 bucket (every member, proportionally, sign preserved, never 

61 amplified) so its net lands exactly at the cap. A bucket already 

62 within the cap is left untouched. 

63 

64 Deliberately NOT "demean to exact zero" (the pre-V5.1.3 behavior - 

65 see Problems.md #81). Demeaning only preserves information when a 

66 bucket has genuine within-bucket weight dispersion to fall back 

67 on. Both of this module's callers (main.py's book formula, 

68 evaluation/rank_book_simulator.py) equal-weight every name within 

69 a role, so a bucket that is monolithic to one role - e.g. every 

70 Forex ticker maps to a single "Forex" bucket, and Forex can never 

71 appear on the opposite leg - has NO within-bucket dispersion: 

72 demeaning drove every member to exactly zero, silently erasing the 

73 entire position instead of bounding a genuine sector tilt. 

74 Shrink-toward-cap degrades gracefully in every case: an already- 

75 balanced bucket is untouched, a lopsided or monolithic bucket is 

76 shrunk (never erased) toward the cap, and a single-member bucket 

77 (net == its own weight) needs no special case - same code path. 

78 3. Dollar neutrality (if dollar_neutral): scale the LARGER leg down 

79 so sum(long) == sum(|short|). Scale-down only, never up - this can 

80 never increase gross exposure. A one-sided book (no shorts, or no 

81 longs) has nothing to balance against; that step is skipped for 

82 that bar rather than zeroing the book out, and the skip is 

83 recorded in diagnostics. 

84 4. Gross cap: scale everything by min(1, gross_exposure_cap / gross). 

85 

86 Step 3 shrinks one leg only, so a sector holding both a long and a short can end above its cap (proved in 

87 formal/AetherFormal/BookNeutrality.lean, `sector_cap_counterexample`). `reapply_sector_cap_after_dollar_neutral` 

88 (default False, the shipped behaviour) runs step 2 again after step 3: every sector then ends within its cap, and 

89 the book may be left slightly off dollar-neutral (recorded as "sector_cap_reapplied"). 

90 

91 A non-positive max_weight_per_name skips step 1 like the other two caps (V6.4.3: a cap of 0 zeroed the book and a 

92 negative one turned every weight, shorts included, into a long of |cap|). 

93 

94 Returns (weights, diagnostics) where diagnostics is JSON-serializable 

95 (state.json's state["book_neutrality"]): 

96 {"pre_gross", "post_gross", "net_before", "net_after", 

97 "per_sector_net": {sector: net_weight, ...}, "steps_applied": [...]} 

98 

99 Never raises. An empty input returns ({}, diagnostics-with-zeros). Pure 

100 dict-in/dict-out - result does not depend on input dict iteration order 

101 (every step is a symmetric sum/mean over the group, not a positional 

102 operation).""" 

103 steps_applied: list[str] = [] 

104 

105 if not raw_weights_by_symbol: 

106 return {}, { 

107 "pre_gross": 0.0, 

108 "post_gross": 0.0, 

109 "net_before": 0.0, 

110 "net_after": 0.0, 

111 "per_sector_net": {}, 

112 "steps_applied": ["empty_book_no_op"], 

113 } 

114 

115 net_before = sum(raw_weights_by_symbol.values()) 

116 

117 # Step 1: per-name cap. 

118 if max_weight_per_name > 0.0: 

119 weights = { 

120 symbol: _clip(weight, -max_weight_per_name, max_weight_per_name) 

121 for symbol, weight in raw_weights_by_symbol.items() 

122 } 

123 steps_applied.append("per_name_cap") 

124 else: 

125 weights = dict(raw_weights_by_symbol) 

126 steps_applied.append("per_name_cap_skipped_nonpositive_cap") 

127 

128 # Step 2: sector neutrality - shrink each bucket's net toward the cap, 

129 # never demean to exact zero. See the docstring above (Problems.md #81). 

130 # 

131 # GUARDRAIL: sector_max_net_weight <= 0.0 is skipped entirely rather 

132 # than applied - a configured cap of exactly 0.0 would otherwise give 

133 # shrink_factor = 0.0 / |bucket_net| = 0.0 for every non-flat bucket, 

134 # scaling every member to nothing. That is precisely the "demean to 

135 # exact zero" behavior Problems.md #81 fixed (see the docstring above), 

136 # reintroduced through config instead of code. A non-positive value 

137 # cannot be honestly enforced by shrink-toward-cap at all (there is no 

138 # cap to shrink toward), so it is treated the same as sector_neutral 

139 # being off for this step, not silently honored. 

140 if sector_neutral and sector_max_net_weight > 0.0: 

141 _shrink_sectors_to_cap(weights, sector_by_symbol, sector_max_net_weight) 

142 steps_applied.append("sector_neutral") 

143 elif sector_neutral: 

144 steps_applied.append("sector_neutral_skipped_invalid_max_net_weight") 

145 

146 # Step 3: dollar neutrality - scale the larger leg down only. 

147 if dollar_neutral: 

148 long_sum = sum(weight for weight in weights.values() if weight > 0.0) 

149 short_sum = sum(-weight for weight in weights.values() if weight < 0.0) 

150 if long_sum > 0.0 and short_sum > 0.0: 

151 if long_sum > short_sum: 

152 factor = short_sum / long_sum 

153 weights = { 

154 symbol: (weight * factor if weight > 0.0 else weight) for symbol, weight in weights.items() 

155 } 

156 elif short_sum > long_sum: 

157 factor = long_sum / short_sum 

158 weights = { 

159 symbol: (weight * factor if weight < 0.0 else weight) for symbol, weight in weights.items() 

160 } 

161 steps_applied.append("dollar_neutral") 

162 else: 

163 steps_applied.append("dollar_neutral_skipped_one_sided_book") 

164 

165 if reapply_sector_cap_after_dollar_neutral and sector_neutral and sector_max_net_weight > 0.0: 

166 _shrink_sectors_to_cap(weights, sector_by_symbol, sector_max_net_weight) 

167 steps_applied.append("sector_cap_reapplied") 

168 

169 # Step 4: gross exposure cap. A non-positive cap is a misconfiguration - 

170 # V5.4.5 (#117 family): the old `gross > cap` comparison happily scaled 

171 # the whole book by 0/cap == 0 when cap <= 0, silently erasing it 

172 # (the same #81-class failure the sector step already guarded against). 

173 # Skip with a diagnostic instead. 

174 gross = sum(abs(weight) for weight in weights.values()) 

175 if gross_exposure_cap > 0.0 and gross > gross_exposure_cap: 

176 factor = gross_exposure_cap / gross 

177 weights = {symbol: weight * factor for symbol, weight in weights.items()} 

178 steps_applied.append("gross_cap") 

179 elif gross_exposure_cap <= 0.0: 

180 steps_applied.append("gross_cap_skipped_nonpositive_cap") 

181 

182 per_sector_net: dict[str, float] = {} 

183 for symbol, weight in weights.items(): 

184 sector = sector_by_symbol.get(symbol, "Unknown") 

185 per_sector_net[sector] = per_sector_net.get(sector, 0.0) + weight 

186 

187 post_gross = sum(abs(weight) for weight in weights.values()) 

188 net_after = sum(weights.values()) 

189 

190 diagnostics = { 

191 "pre_gross": sum(abs(weight) for weight in raw_weights_by_symbol.values()), 

192 "post_gross": post_gross, 

193 "net_before": net_before, 

194 "net_after": net_after, 

195 "per_sector_net": per_sector_net, 

196 "steps_applied": steps_applied, 

197 } 

198 return weights, diagnostics