Coverage for risk/futures_risk.py: 100%

63 statements  

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

1"""Futures position sizing - margin-utilization-targeted, not the 

2volatility-of-notional model risk/position_sizing.py uses for equity/crypto/ 

3bond. 

4 

5Margin, contract count, and mark-to-market are fundamentally different from 

6a portfolio-weight-scaled sizing model: Lean trades futures in whole 

7contracts (not fractional weights), and the real constraint is how much of 

8the account's margin budget a position consumes, not how much daily-return 

9volatility it contributes. This module is deliberately separate from 

10risk/position_sizing.py rather than a new branch inside it - see 

11risk/asset_class_router.py for how its FuturesSizingDecision output gets 

12adapted onto the shared PositionSizingDecision shape everything downstream 

13(portfolio/book_construction.py, liquidity, analyzer, _apply_signal()) 

14consumes. 

15 

16Continuous-futures rollover/mark-to-market itself is NOT reimplemented here 

17- that's entirely delegated to Lean's native add_future() + continuous- 

18contract SetFilter() mapping (main.py::_add_asset()). rollover_due() below 

19is a diagnostic/logging signal only, never a trade trigger - a second, 

20hand-rolled rollover state machine racing against Lean's own would be a bug 

21class, not a feature. 

22""" 

23 

24from __future__ import annotations 

25 

26import json 

27import logging 

28from dataclasses import asdict, dataclass 

29from datetime import date 

30from pathlib import Path 

31from typing import Any 

32 

33logger = logging.getLogger(__name__) 

34 

35DEFAULT_CONTRACT_SPECS_PATH = Path(__file__).resolve().parents[1] / "data" / "reference" / "futures_contract_specs.json" 

36 

37 

38@dataclass(frozen=True) 

39class FuturesSizingDecision: 

40 """One futures order's size: contracts, notional, margin and the caps that bound it.""" 

41 contract_count: int 

42 notional_value: float 

43 margin_required: float 

44 margin_utilization: float 

45 target_weight: float 

46 base_target_weight: float 

47 confidence_multiplier: float 

48 max_margin_utilization: float 

49 sizing_reason: str 

50 

51 def to_dict(self) -> dict[str, Any]: 

52 return asdict(self) 

53 

54 

55def load_futures_contract_specs(path: Path = DEFAULT_CONTRACT_SPECS_PATH) -> dict[str, Any]: 

56 """Defensive load - returns {} (not a raised exception) on a missing or 

57 unparseable specs file, same convention as train.py::load_sector_mapping(). 

58 A missing spec for a given ticker means build_futures_position_sizing() 

59 can't size it - callers must treat that as "no position", not a crash.""" 

60 try: 

61 with path.open("r", encoding="utf-8") as handle: 

62 data = json.load(handle) 

63 except (OSError, json.JSONDecodeError) as exc: 

64 logger.warning("load_futures_contract_specs(%s): unreadable — %s", path, exc) 

65 return {} 

66 return {key: value for key, value in data.items() if not key.startswith("_")} 

67 

68 

69def build_futures_position_sizing( 

70 base_target_weight: float, 

71 confidence: float, 

72 price: float, 

73 contract_spec: dict[str, Any] | None, 

74 portfolio_value: float, 

75 target_margin_utilization: float = 0.20, 

76 max_margin_utilization: float = 0.40, 

77) -> FuturesSizingDecision: 

78 """Margin-utilization-targeted sizing: computes the max contracts 

79 affordable at max_margin_utilization (the hard ceiling), then scales 

80 toward target_margin_utilization by confidence using the same 

81 "0.5 + 0.5*confidence" shape as 

82 risk/position_sizing.py::build_dynamic_position_sizing()'s 

83 confidence_multiplier, and floors to an integer contract_count (Lean 

84 trades futures in whole contracts, never fractional weights). 

85 

86 target_weight is a DERIVED reconciliation value for downstream weight- 

87 based consumers (exposure caps, book construction) - contract_count is 

88 the source of truth and is what main.py::_apply_signal() actually 

89 executes via MarketOrder(), never fed back into SetHoldings(). 

90 

91 Returns an all-zero decision (contract_count=0) when contract_spec is 

92 missing/empty, confidence is 0, base_target_weight is 0, or 

93 portfolio_value/price/multiplier/margin are non-positive - never 

94 raises, matching risk/position_sizing.py's "no active signal -> zero 

95 weight" convention.""" 

96 confidence = max(0.0, min(float(confidence), 1.0)) 

97 base_target_weight = float(base_target_weight) 

98 portfolio_value = max(float(portfolio_value), 0.0) 

99 price = max(float(price), 0.0) 

100 max_margin_utilization = max(float(max_margin_utilization), 0.0) 

101 target_margin_utilization = max(0.0, min(float(target_margin_utilization), max_margin_utilization)) 

102 

103 contract_spec = contract_spec or {} 

104 multiplier = float(contract_spec.get("multiplier", 0.0)) 

105 margin_per_contract = float(contract_spec.get("initial_margin_usd", 0.0)) 

106 

107 if ( 

108 base_target_weight == 0.0 

109 or confidence == 0.0 

110 or portfolio_value <= 0.0 

111 or price <= 0.0 

112 or multiplier <= 0.0 

113 or margin_per_contract <= 0.0 

114 ): 

115 return FuturesSizingDecision( 

116 contract_count=0, 

117 notional_value=0.0, 

118 margin_required=0.0, 

119 margin_utilization=0.0, 

120 target_weight=0.0, 

121 base_target_weight=base_target_weight, 

122 confidence_multiplier=0.0, 

123 max_margin_utilization=max_margin_utilization, 

124 sizing_reason="no_active_signal_or_missing_contract_spec", 

125 ) 

126 

127 confidence_multiplier = 0.5 + 0.5 * confidence 

128 max_contracts_affordable = int(portfolio_value * max_margin_utilization // margin_per_contract) 

129 contracts_at_target = int(portfolio_value * target_margin_utilization // margin_per_contract) 

130 contract_count = min(int(contracts_at_target * confidence_multiplier), max_contracts_affordable) 

131 contract_count = max(contract_count, 0) 

132 

133 direction = 1.0 if base_target_weight >= 0.0 else -1.0 

134 notional_value = contract_count * multiplier * price 

135 margin_required = contract_count * margin_per_contract 

136 margin_utilization = margin_required / portfolio_value if portfolio_value > 0.0 else 0.0 

137 target_weight = direction * (notional_value / portfolio_value) if portfolio_value > 0.0 else 0.0 

138 

139 sizing_reason = "no_active_signal_or_missing_contract_spec" if contract_count == 0 else "margin_utilization_scaled_sizing" 

140 

141 return FuturesSizingDecision( 

142 contract_count=int(direction) * contract_count, 

143 notional_value=notional_value, 

144 margin_required=margin_required, 

145 margin_utilization=margin_utilization, 

146 target_weight=target_weight, 

147 base_target_weight=base_target_weight, 

148 confidence_multiplier=confidence_multiplier, 

149 max_margin_utilization=max_margin_utilization, 

150 sizing_reason=sizing_reason, 

151 ) 

152 

153 

154def resolve_futures_margin_source(raw_value: str) -> str: 

155 """Validates phase_v2.futures_risk.margin_source - "static" (default, 

156 the offline data/reference/futures_contract_specs.json file) or 

157 "live" (Lean's own IB-calibrated BuyingPowerModel, resolved once per 

158 security at add-time and queried per sizing call - see main.py:: 

159 _resolve_futures_contract_spec()). "live" here means Lean's own 

160 LOCAL margin-model calculation (InteractiveBrokersBrokerageModel's 

161 bundled margin rules), never a live network round-trip to IB's 

162 servers - that would be far too slow inside on_data() and is not 

163 what this option does. Any unrecognized value (a config typo) falls 

164 back to "static" rather than raising - never crashes the algorithm 

165 over a bad string.""" 

166 normalized = str(raw_value).strip().lower() 

167 return normalized if normalized in ("static", "live") else "static" 

168 

169 

170def build_live_contract_spec( 

171 multiplier: float, 

172 initial_margin_usd: float, 

173 description: str = "", 

174 exchange: str = "", 

175) -> dict[str, Any]: 

176 """Constructs a contract_spec dict in the exact shape 

177 build_futures_position_sizing() already consumes (same keys 

178 load_futures_contract_specs() produces from the static JSON file), 

179 from live values main.py resolves via Lean's own 

180 Security.SymbolProperties/BuyingPowerModel. Pure - no Lean coupling 

181 itself; only main.py's caller touches self.Securities. description/ 

182 exchange default to "" (informational only, never read by 

183 build_futures_position_sizing()'s own sizing math) since Lean's 

184 BuyingPowerModel query has no equivalent of either - callers 

185 typically pass the static spec's own values through for display 

186 continuity when a live spec replaces it.""" 

187 return { 

188 "description": description, 

189 "multiplier": float(multiplier), 

190 "initial_margin_usd": float(initial_margin_usd), 

191 "exchange": exchange, 

192 } 

193 

194 

195def rollover_due(current_date: date, contract_expiry_date: date | None, rollover_days_before_expiry: int = 5) -> bool: 

196 """Pure date comparison - a diagnostic/logging signal only. Actual 

197 contract rollover is entirely delegated to Lean's native add_future() + 

198 continuous-contract SetFilter() mapping (main.py::_add_asset()); this 

199 function must never itself trigger a trade. Returns False when 

200 contract_expiry_date is unknown (e.g. Lean's continuous-contract 

201 subscription hasn't surfaced the mapped contract's expiry yet).""" 

202 if contract_expiry_date is None: 

203 return False 

204 return (contract_expiry_date - current_date).days <= rollover_days_before_expiry