Coverage for risk/forex_risk.py: 100%
65 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Forex position sizing - leverage-utilization-targeted, the FX sibling
2of risk/futures_risk.py's margin-utilization-targeted model (not the
3volatility-of-notional model risk/position_sizing.py uses for equity/
4crypto/bond).
6Forex trades in whole LOTS (this module follows futures' own "whole
7units, never fractional weights" convention for consistency, rather than
8supporting fractional/micro lots), and the real constraint is how much of
9the account's margin a position consumes at the pair's max leverage - the
10same "budget, not volatility" shape risk/futures_risk.py already
11established for futures, adapted to lot_size/leverage_max/margin_pct
12instead of a fixed per-contract multiplier/margin (forex margin scales
13with the pair's CURRENT price, unlike futures' fixed initial_margin_usd
14per contract - "one lot" is a fixed base-currency notional, not a fixed
15dollar margin).
17V4.6 (development/Problems.md, Roadmap "Assets") - code-complete,
18IB/Lean-backtest-unverified, the exact same status futures/options
19shipped with: main.py::_add_asset() wires self.add_forex(), but zero
20forex tickers are configured in phase1.universe.assets and
21phase_v2.forex_risk.enabled defaults False.
23Confirmed via direct Lean source inspection that Forex is fully
24first-class in this Lean version (SecurityType.Forex,
25Common/Securities/Forex/Forex.cs, real pip-size/lot-size symbol
26properties) - unlike individual bonds (see features/bond_features.py's
27own module docstring), there is no native-support question here."""
29from __future__ import annotations
31import json
32import logging
33from dataclasses import asdict, dataclass
34from pathlib import Path
35from typing import Any
37logger = logging.getLogger(__name__)
39DEFAULT_PAIR_SPECS_PATH = Path(__file__).resolve().parents[1] / "data" / "reference" / "forex_pair_specs.json"
42@dataclass(frozen=True)
43class ForexSizingDecision:
44 """One forex order's size: lots, notional, margin and the caps that bound it."""
45 lot_count: int
46 notional_value: float
47 margin_required: float
48 margin_utilization: float
49 target_weight: float
50 base_target_weight: float
51 confidence_multiplier: float
52 max_leverage_utilization: float
53 sizing_reason: str
55 def to_dict(self) -> dict[str, Any]:
56 return asdict(self)
59def load_forex_pair_specs(path: Path = DEFAULT_PAIR_SPECS_PATH) -> dict[str, Any]:
60 """Defensive load - returns {} (not a raised exception) on a missing or
61 unparseable specs file, same convention as
62 risk/futures_risk.py::load_futures_contract_specs(). A missing spec
63 for a given pair means build_forex_position_sizing() can't size it -
64 callers must treat that as "no position", not a crash."""
65 try:
66 with path.open("r", encoding="utf-8") as handle:
67 data = json.load(handle)
68 except (OSError, json.JSONDecodeError) as exc:
69 logger.warning("load_forex_pair_specs(%s): unreadable — %s", path, exc)
70 return {}
71 return {key: value for key, value in data.items() if not key.startswith("_")}
74def build_forex_position_sizing(
75 base_target_weight: float,
76 confidence: float,
77 price: float,
78 pair_spec: dict[str, Any] | None,
79 portfolio_value: float,
80 target_leverage_utilization: float = 0.20,
81 max_leverage_utilization: float = 0.40,
82) -> ForexSizingDecision:
83 """Leverage-utilization-targeted sizing: computes the max lots
84 affordable at max_leverage_utilization (the hard ceiling), then scales
85 toward target_leverage_utilization by confidence using the same
86 "0.5 + 0.5*confidence" shape as
87 risk/futures_risk.py::build_futures_position_sizing()'s
88 confidence_multiplier, and floors to an integer lot_count.
90 Per-lot margin is `lot_size * price * margin_pct` (equivalently
91 `lot_size * price / leverage_max`, since margin_pct and leverage_max
92 are reciprocals by construction in forex_pair_specs.json).
94 target_weight is a DERIVED reconciliation value for downstream
95 weight-based consumers (exposure caps) - lot_count is the source of
96 truth and is what main.py::_apply_signal() actually executes via
97 MarketOrder(), never fed back into SetHoldings().
99 Returns an all-zero decision (lot_count=0) when pair_spec is
100 missing/empty, confidence is 0, base_target_weight is 0, or
101 portfolio_value/price/lot_size/margin_pct are non-positive - never
102 raises, matching risk/futures_risk.py's "no active signal -> zero
103 position" convention."""
104 confidence = max(0.0, min(float(confidence), 1.0))
105 base_target_weight = float(base_target_weight)
106 portfolio_value = max(float(portfolio_value), 0.0)
107 price = max(float(price), 0.0)
108 max_leverage_utilization = max(float(max_leverage_utilization), 0.0)
109 target_leverage_utilization = max(0.0, min(float(target_leverage_utilization), max_leverage_utilization))
111 pair_spec = pair_spec or {}
112 lot_size = float(pair_spec.get("lot_size", 0.0))
113 margin_pct = float(pair_spec.get("margin_pct", 0.0))
115 if (
116 base_target_weight == 0.0
117 or confidence == 0.0
118 or portfolio_value <= 0.0
119 or price <= 0.0
120 or lot_size <= 0.0
121 or margin_pct <= 0.0
122 ):
123 return ForexSizingDecision(
124 lot_count=0,
125 notional_value=0.0,
126 margin_required=0.0,
127 margin_utilization=0.0,
128 target_weight=0.0,
129 base_target_weight=base_target_weight,
130 confidence_multiplier=0.0,
131 max_leverage_utilization=max_leverage_utilization,
132 sizing_reason="no_active_signal_or_missing_pair_spec",
133 )
135 margin_per_lot = lot_size * price * margin_pct
136 confidence_multiplier = 0.5 + 0.5 * confidence
137 max_lots_affordable = int(portfolio_value * max_leverage_utilization // margin_per_lot)
138 lots_at_target = int(portfolio_value * target_leverage_utilization // margin_per_lot)
139 lot_count = min(int(lots_at_target * confidence_multiplier), max_lots_affordable)
140 lot_count = max(lot_count, 0)
142 direction = 1.0 if base_target_weight >= 0.0 else -1.0
143 notional_value = lot_count * lot_size * price
144 margin_required = lot_count * margin_per_lot
145 margin_utilization = margin_required / portfolio_value if portfolio_value > 0.0 else 0.0
146 target_weight = direction * (notional_value / portfolio_value) if portfolio_value > 0.0 else 0.0
148 sizing_reason = "no_active_signal_or_missing_pair_spec" if lot_count == 0 else "leverage_utilization_scaled_sizing"
150 return ForexSizingDecision(
151 lot_count=int(direction) * lot_count,
152 notional_value=notional_value,
153 margin_required=margin_required,
154 margin_utilization=margin_utilization,
155 target_weight=target_weight,
156 base_target_weight=base_target_weight,
157 confidence_multiplier=confidence_multiplier,
158 max_leverage_utilization=max_leverage_utilization,
159 sizing_reason=sizing_reason,
160 )
163def cap_forex_target_to_book_weight(target_weight: float, book_weight: float) -> float:
164 """V5.5.0 (Problems.md #128) - forex sizing above is margin-driven: a
165 pair's target_weight is lots * lot_size * price / NAV, i.e. several
166 TIMES NAV at 20% margin utilization and 1:50 leverage, and the book's
167 own weight only chose the direction. Only the exposure caps limited it
168 (shorts shared one 30% budget with equities), so the 2026-08-27 run held
169 up to 60% of NAV short in forex while the book wanted ~8% a name.
171 Caps |target_weight| at |book_weight| (the weight the book assigned this
172 pair), keeping the sign. Margin sizing stays as an upper bound, never a
173 target. Non-finite input -> 0.0 (no trade).
174 """
175 try:
176 target = float(target_weight)
177 cap = abs(float(book_weight))
178 except (TypeError, ValueError):
179 return 0.0
180 if target != target or cap != cap or abs(target) == float("inf") or cap == float("inf"):
181 return 0.0
182 if abs(target) <= cap:
183 return target
184 return cap if target > 0.0 else -cap