Coverage for execution/reconciliation.py: 100%
52 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"""V5.1 Phase 6 (production safety): position reconciliation - compares
2the book's INTENDED per-symbol weights against what the broker (Lean's
3own `self.Portfolio`, or an IB snapshot once Problems.md #72 clears)
4actually holds, and classifies every discrepancy.
6Pure, Lean-free - no QCAlgorithm/self.Portfolio dependency here at all, so
7this is fully unit-testable with plain dicts (same "compute the math in a
8pure module, let the live caller supply real data" split every other
9risk/execution module in this codebase already follows) and directly
10reusable against a future IB portfolio snapshot with zero changes.
11"""
13from __future__ import annotations
15import math
16from dataclasses import asdict, dataclass, field
17from typing import Any
20@dataclass(frozen=True)
21class ReconciliationReport:
22 """Expected against actual holdings: matched names, drifts, orphan and missing positions, the largest drift and whether it breaches."""
23 matched: list[str] = field(default_factory=list)
24 drifted: list[dict] = field(default_factory=list)
25 orphan_broker: list[dict] = field(default_factory=list)
26 missing_broker: list[dict] = field(default_factory=list)
27 max_abs_weight_drift: float = 0.0
28 breach: bool = False
30 def to_dict(self) -> dict[str, Any]:
31 return asdict(self)
34def reconcile_positions(
35 expected_by_symbol: dict[str, float],
36 actual_by_symbol: dict[str, float],
37 *,
38 weight_tolerance: float,
39 value_tolerance_usd: float,
40 portfolio_value: float,
41 max_tolerated_drift: float | None = None,
42) -> ReconciliationReport:
43 """Classifies every symbol appearing in EITHER dict:
44 - "matched": both expected and actual are present and within
45 weight_tolerance (as a fraction of portfolio weight) AND within
46 value_tolerance_usd (the dollar-value equivalent of that weight
47 difference) - both must hold, since a large-value portfolio can
48 have a tiny weight_tolerance breach that is still a huge dollar
49 drift, and a small-value portfolio can have a huge weight_tolerance
50 breach that is a trivial dollar amount.
51 - "drifted": both present, but outside tolerance - full per-symbol
52 delta detail (expected_weight, actual_weight, delta_weight,
53 delta_usd).
54 - "orphan_broker": held by the broker but not in the expected book at
55 all (expected_weight treated as 0.0) - e.g. a position main.py's
56 book no longer wants but the broker never closed.
57 - "missing_broker": expected by the book but the broker holds nothing
58 for it (actual_weight treated as 0.0) - e.g. an order that never
59 filled.
61 max_abs_weight_drift is the single largest |delta_weight| across every
62 NON-matched symbol (drifted + orphan_broker + missing_broker combined -
63 a symbol classified "matched" is, by construction, already within both
64 tolerances, so including it could only ever pull the max down toward a
65 value the genuine drifts already exceed - excluding it keeps this
66 field's value exactly matching what its name and this docstring claim).
67 breach is that value compared against max_tolerated_drift (typically
68 phase_v2.reconciliation.max_tolerated_drift) - the one field a caller
69 checks to decide whether this reconciliation should trip the kill
70 switch (risk/kill_switch.py's "reconciliation_breach" trigger) without
71 re-deriving the comparison itself. max_tolerated_drift=None (the
72 default) always reports breach=False - an unconfigured caller gets a
73 strict no-op, matching every other fail-open contract in this codebase.
75 Tolerance is checked BEFORE presence: a symbol held/expected only on
76 one side but within weight_tolerance/value_tolerance_usd of the other
77 side's implicit 0.0 (a dust position - a fractional share leftover, a
78 rounding remainder) is "matched", never "orphan_broker"/"missing_broker".
79 Without this, every dust amount was a permanent, unfixable "orphan" no
80 matter how negligible, even though it could never move max_abs_weight_drift
81 past a real drift either - pure report-quality noise.
83 Pure dict-in/dict-out - result does not depend on either dict's
84 insertion order (both are iterated via a sorted union of keys). Empty
85 inputs (both dicts empty) return an all-empty, non-breaching report,
86 never raise.
88 V5.4.5 (development/Problems.md #117): a non-finite weight on either
89 side previously slipped through every comparison silently - `abs(nan)
90 <= tol` is False (so the symbol still classified drifted/orphan), but
91 `max(0.0, abs(nan))` kept 0.0, leaving max_abs_weight_drift at 0.0 and
92 breach False: a real blow-up reported as NaN was a false-clean. A
93 non-finite weight now forces max_abs_weight_drift to +inf, so any
94 configured max_tolerated_drift reports breach=True (fail-closed for a
95 safety trigger). An explicit None value no longer raises float(None)
96 either - it degrades through this same non-finite path."""
97 all_symbols = sorted(set(expected_by_symbol) | set(actual_by_symbol))
99 def _finite_weight(value) -> float | None:
100 if value is None:
101 return None
102 try:
103 as_float = float(value)
104 except (TypeError, ValueError):
105 return None
106 return as_float if math.isfinite(as_float) else None
108 matched: list[str] = []
109 drifted: list[dict] = []
110 orphan_broker: list[dict] = []
111 missing_broker: list[dict] = []
112 max_abs_weight_drift = 0.0
114 for symbol in all_symbols:
115 expected_weight = _finite_weight(expected_by_symbol.get(symbol, 0.0))
116 actual_weight = _finite_weight(actual_by_symbol.get(symbol, 0.0))
117 if expected_weight is None or actual_weight is None:
118 # Unreadable weight: count it as infinite drift (breach-worthy)
119 # rather than silently clean.
120 max_abs_weight_drift = math.inf
121 delta_usd: float | None = None
122 drifted.append(
123 {"symbol": symbol, "expected_weight": expected_weight, "actual_weight": actual_weight,
124 "delta_weight": None, "delta_usd": None}
125 )
126 continue
127 delta_weight = actual_weight - expected_weight
128 delta_usd = delta_weight * portfolio_value
130 within_tolerance = abs(delta_weight) <= weight_tolerance and abs(delta_usd) <= value_tolerance_usd
132 if within_tolerance:
133 matched.append(symbol)
134 elif symbol not in expected_by_symbol:
135 max_abs_weight_drift = max(max_abs_weight_drift, abs(delta_weight))
136 orphan_broker.append(
137 {"symbol": symbol, "expected_weight": 0.0, "actual_weight": actual_weight,
138 "delta_weight": delta_weight, "delta_usd": delta_usd}
139 )
140 elif symbol not in actual_by_symbol:
141 max_abs_weight_drift = max(max_abs_weight_drift, abs(delta_weight))
142 missing_broker.append(
143 {"symbol": symbol, "expected_weight": expected_weight, "actual_weight": 0.0,
144 "delta_weight": delta_weight, "delta_usd": delta_usd}
145 )
146 else:
147 max_abs_weight_drift = max(max_abs_weight_drift, abs(delta_weight))
148 drifted.append(
149 {"symbol": symbol, "expected_weight": expected_weight, "actual_weight": actual_weight,
150 "delta_weight": delta_weight, "delta_usd": delta_usd}
151 )
153 breach = max_tolerated_drift is not None and max_abs_weight_drift > max_tolerated_drift
155 return ReconciliationReport(
156 matched=matched,
157 drifted=drifted,
158 orphan_broker=orphan_broker,
159 missing_broker=missing_broker,
160 max_abs_weight_drift=max_abs_weight_drift,
161 breach=breach,
162 )