From 094fb17357af0aebd4d4f4d4432d3d331424a8ea Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:37:50 +0800 Subject: [PATCH 1/2] fix(reconciliation): explain broker-assisted fees and valuation basis Split broker-assisted sell and regulatory fees out of statement reconciliation residuals using a dated Firstrade fee schedule, and report the balances-versus-positions valuation basis difference separately. The TAF increase is deferred to 2029 per SR-FINRA-2026-020. --- application/firstrade_fee_schedule.py | 166 ++++++++++++ application/statement_reconciliation.py | 302 +++++++++++++++++++++ docs/statement-reconciliation.md | 87 ++++++ docs/statement-reconciliation.zh-CN.md | 41 +++ tests/test_statement_reconciliation.py | 337 ++++++++++++++++++++++++ 5 files changed, 933 insertions(+) create mode 100644 application/firstrade_fee_schedule.py create mode 100644 application/statement_reconciliation.py create mode 100644 docs/statement-reconciliation.md create mode 100644 docs/statement-reconciliation.zh-CN.md create mode 100644 tests/test_statement_reconciliation.py diff --git a/application/firstrade_fee_schedule.py b/application/firstrade_fee_schedule.py new file mode 100644 index 00000000..ba483a38 --- /dev/null +++ b/application/firstrade_fee_schedule.py @@ -0,0 +1,166 @@ +"""Fee schedule configuration for Firstrade statement reconciliation. + +All rates are data, not logic. Each table is a list of segments keyed by the +first trade date on which the segment applies; a lookup picks the latest +segment whose ``effective_from`` is on or before the trade date. Dates before +the first segment, and dates after ``verified_through`` (the last day the +rates below were checked against the published sources), are unsupported and +fail closed (``FeeScheduleError``) so a reconciliation never silently applies +a rate that was not verified. In particular the SEC fiscal year 2027 Section 31 +rate has not been published yet; the FY2026 rate stays in effect until 60 days +after the FY2027 appropriation is enacted, so no date past ``verified_through`` +is assumed to keep the FY2026 rate. + +Sources (checked 2026-11-01): +- Broker-assisted order fee: https://www.firstrade.com/trading/pricing +- SEC Section 31 rate advisories (charge date is the trade date): + FY2024 $27.80/M from 2024-05-22, FY2025 $0.00/M from 2025-05-14, + FY2026 $20.60/M from 2026-04-04. +- FINRA Trading Activity Fee (TAF), covered equity securities: + SR-FINRA-2024-019 (2025 fee adjustment schedule: $0.000166/share, max $8.30 + until 2025-12-31; $0.000195/share, max $9.79 from 2026-01-01), + SR-FINRA-2026-021 (rate $0 for 2026-10-01..2026-12-31, Release 34-106409) and + SR-FINRA-2026-020 (Release 34-106410, filed 2026-09-15, immediately + effective) which defers the remaining increases by two years: 2027 and 2028 + stay at $0.000195/share (max $9.79), 2029 is $0.000232/share (max $11.61), + 2030 is $0.000240 (max $12.05) and 2031 is $0.000249 (max $12.50). +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from datetime import date +from decimal import Decimal, InvalidOperation +from typing import Any + + +class FeeScheduleError(ValueError): + """The fee schedule is malformed or does not cover the requested date.""" + + +DEFAULT_FEE_SCHEDULE_CONFIG: dict[str, Any] = { + "schema_version": "firstrade_fee_schedule.v1", + # Last trade date for which every rate below was verified against the + # published sources. Later trade dates are unsupported (fail closed). + "verified_through": "2026-11-01", + # Matched case-insensitively against the transaction description. + "broker_assisted_markers": ["BROKER/DEALER ORDER"], + "broker_assisted_fee": [ + {"effective_from": "2000-01-01", "amount": "19.95"}, + ], + # Dollars per $1,000,000 of covered sale proceeds. + "sec_rate_per_million": [ + {"effective_from": "2024-05-22", "rate": "27.80"}, + {"effective_from": "2025-05-14", "rate": "0.00"}, + {"effective_from": "2026-04-04", "rate": "20.60"}, + ], + # FINRA TAF for covered equity securities (stocks and ETFs). + "taf_per_share": [ + {"effective_from": "2024-01-01", "rate": "0.000166", "max_per_trade": "8.30"}, + {"effective_from": "2026-01-01", "rate": "0.000195", "max_per_trade": "9.79"}, + {"effective_from": "2026-10-01", "rate": "0", "max_per_trade": "0"}, + # SR-FINRA-2026-021 pause ends; SR-FINRA-2026-020 keeps 2026 rates. + {"effective_from": "2027-01-01", "rate": "0.000195", "max_per_trade": "9.79"}, + {"effective_from": "2029-01-01", "rate": "0.000232", "max_per_trade": "11.61"}, + {"effective_from": "2030-01-01", "rate": "0.000240", "max_per_trade": "12.05"}, + {"effective_from": "2031-01-01", "rate": "0.000249", "max_per_trade": "12.50"}, + ], + "minimum_regulatory_fee": "0.01", + "explained_residual_tolerance": "0.01", +} + + +@dataclass(frozen=True) +class FeeSchedule: + broker_assisted_markers: tuple[str, ...] + broker_assisted_fee: tuple[tuple[date, Decimal], ...] + sec_rate_per_million: tuple[tuple[date, Decimal], ...] + taf_per_share: tuple[tuple[date, Decimal, Decimal], ...] + minimum_regulatory_fee: Decimal + explained_residual_tolerance: Decimal + verified_through: date + + def _lookup(self, table: tuple[tuple[Any, ...], ...], trade_date: date, name: str): + if trade_date > self.verified_through: + raise FeeScheduleError( + f"{name}_not_verified_after_{self.verified_through.isoformat()}") + selected = None + for row in table: + if row[0] <= trade_date: + selected = row + if selected is None: + raise FeeScheduleError(f"{name}_not_defined_for_{trade_date.isoformat()}") + return selected + + def broker_assisted_fee_on(self, trade_date: date) -> Decimal: + return self._lookup(self.broker_assisted_fee, trade_date, "broker_assisted_fee")[1] + + def sec_rate_on(self, trade_date: date) -> Decimal: + return self._lookup(self.sec_rate_per_million, trade_date, "sec_rate")[1] + + def taf_on(self, trade_date: date) -> tuple[Decimal, Decimal]: + row = self._lookup(self.taf_per_share, trade_date, "taf_rate") + return row[1], row[2] + + def is_broker_assisted(self, description: object) -> bool: + text = str(description or "").upper() + return any(marker.upper() in text for marker in self.broker_assisted_markers) + + +def _decimal(value: object, field: str) -> Decimal: + if isinstance(value, bool) or not isinstance(value, (str, int)): + raise FeeScheduleError(f"{field}_invalid") + try: + number = Decimal(str(value)) + except InvalidOperation: + raise FeeScheduleError(f"{field}_invalid") from None + if not number.is_finite() or number < 0: + raise FeeScheduleError(f"{field}_invalid") + return number + + +def _date(value: object, field: str) -> date: + try: + return date.fromisoformat(str(value)) + except ValueError: + raise FeeScheduleError(f"{field}_invalid") from None + + +def _segments(raw: object, field: str, value_keys: tuple[str, ...]) -> tuple[tuple[Any, ...], ...]: + if not isinstance(raw, list) or not raw: + raise FeeScheduleError(f"{field}_missing") + rows = [] + for item in raw: + if not isinstance(item, Mapping): + raise FeeScheduleError(f"{field}_invalid") + rows.append((_date(item.get("effective_from"), field), + *(_decimal(item.get(key), f"{field}.{key}") for key in value_keys))) + dates = [row[0] for row in rows] + if dates != sorted(dates) or len(set(dates)) != len(dates): + raise FeeScheduleError(f"{field}_not_strictly_ordered") + return tuple(rows) + + +def load_fee_schedule(config: Mapping[str, Any] | None = None) -> FeeSchedule: + """Validate a schedule mapping (default: the packaged one).""" + + data = DEFAULT_FEE_SCHEDULE_CONFIG if config is None else config + if data.get("schema_version") != "firstrade_fee_schedule.v1": + raise FeeScheduleError("schema_version_unsupported") + markers = data.get("broker_assisted_markers") + if (not isinstance(markers, list) or not markers + or any(not isinstance(m, str) or not m.strip() for m in markers)): + raise FeeScheduleError("broker_assisted_markers_invalid") + if data.get("verified_through") in (None, ""): + raise FeeScheduleError("verified_through_missing") + return FeeSchedule( + broker_assisted_markers=tuple(markers), + broker_assisted_fee=_segments(data.get("broker_assisted_fee"), "broker_assisted_fee", ("amount",)), + sec_rate_per_million=_segments(data.get("sec_rate_per_million"), "sec_rate", ("rate",)), + taf_per_share=_segments(data.get("taf_per_share"), "taf_rate", ("rate", "max_per_trade")), + minimum_regulatory_fee=_decimal(data.get("minimum_regulatory_fee"), "minimum_regulatory_fee"), + explained_residual_tolerance=_decimal( + data.get("explained_residual_tolerance"), "explained_residual_tolerance"), + verified_through=_date(data.get("verified_through"), "verified_through"), + ) diff --git a/application/statement_reconciliation.py b/application/statement_reconciliation.py new file mode 100644 index 00000000..2d317ee3 --- /dev/null +++ b/application/statement_reconciliation.py @@ -0,0 +1,302 @@ +"""Pure, offline helpers that explain Firstrade statement reconciliation gaps. + +Nothing here performs I/O, reads credentials or calls a broker. Inputs are +statement/CSV rows and the read-only account facts already collected. + +Two gap classes are modelled explicitly instead of being left "unexplained": + +* ``decompose_sell_fees`` - a desk-executed (``BROKER/DEALER ORDER``, which + includes ``MARGIN SELLOUT``) sell nets less than quantity x price because of + the broker-assisted order fee and the regulatory pass-through fee. +* ``valuation_basis_difference`` - the balances endpoint and the positions + endpoint value the same shares from different quote bases, so + ``balance long_stock_value`` and ``positions market_value`` can differ by a + few cents without any cash or quantity discrepancy. The tolerance has an + absolute cap and the share counts are cross-checked when available. +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Mapping +from datetime import date, datetime +from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal, InvalidOperation +from typing import Any + +from application.firstrade_fee_schedule import FeeSchedule, FeeScheduleError, load_fee_schedule + +_CENT = Decimal("0.01") +_MILLION = Decimal("1000000") + +VALUATION_TOLERANCE_FLOOR = Decimal("0.10") +VALUATION_TOLERANCE_RATE = Decimal("0.001") +# Absolute ceiling so 0.1% of a large account can never hide a real break. +VALUATION_TOLERANCE_CAP = Decimal("25.00") + +_EXEC_TIME_RE = re.compile(r"EXEC TIME:\s*(\d{4}-\d{2}-\d{2})", re.IGNORECASE) +_SETTLEMENT_RE = re.compile(r"S/D:\s*(\d{1,2}/\d{1,2}/\d{4})", re.IGNORECASE) + + +def _to_decimal(value: object) -> Decimal: + if isinstance(value, bool) or value is None: + raise ValueError("amount_invalid") + try: + number = Decimal(str(value).replace(",", "").strip()) + except InvalidOperation: + raise ValueError("amount_invalid") from None + if not number.is_finite(): + raise ValueError("amount_invalid") + return number + + +def _trade_date(value: object) -> date: + if isinstance(value, datetime): + return value.date() + if isinstance(value, date): + return value + text = str(value or "").strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y"): + try: + return datetime.strptime(text, fmt).date() + except ValueError: + continue + raise ValueError("trade_date_invalid") + + +def _resolve_dates(csv_date: object, description: object) -> tuple[date, date | None]: + """Return ``(trade_date, settlement_date)`` for a history row. + + In the Firstrade history CSV the ``Date`` column is the trade date: for the + 2026-08-28 IBIT sell it is ``8/28/2026`` while the description carries + ``EXEC TIME: 2026-08-28 ...`` and ``S/D: 08/31/2026`` (T+1 settlement). + SEC Section 31 and FINRA TAF are charged on the trade date, so the + settlement date must never select a rate. The row fails closed when the + ``Date`` column disagrees with ``EXEC TIME`` or equals/precedes ``S/D``, + which would mean an export that carries settlement dates. + """ + + trade_date = _trade_date(csv_date) + text = str(description or "") + executed = _EXEC_TIME_RE.search(text) + if executed and _trade_date(executed.group(1)) != trade_date: + raise ValueError("date_column_not_trade_date") + settled = _SETTLEMENT_RE.search(text) + settlement_date = _trade_date(settled.group(1)) if settled else None + if settlement_date is not None and settlement_date <= trade_date: + raise ValueError("date_column_not_trade_date") + return trade_date, settlement_date + + +def _row_value(row: Mapping[str, Any], *keys: str) -> Any: + lowered = {str(k).lower(): v for k, v in row.items()} + for key in keys: + if key.lower() in lowered: + return lowered[key.lower()] + return None + + +def _round_up_cent(value: Decimal) -> Decimal: + return value.quantize(_CENT, rounding=ROUND_CEILING) + + +def _money(value: Decimal) -> str: + return format(value.quantize(_CENT, rounding=ROUND_HALF_UP), "f") + + +def _exact(value: Decimal) -> str: + return format(value.normalize(), "f") if value != 0 else "0" + + +def regulatory_fee( + *, proceeds: Decimal, quantity: Decimal, trade_date: date, schedule: FeeSchedule +) -> dict[str, Decimal]: + """SEC Section 31 plus FINRA TAF on a sale, collapsed to one cent-rounded fee. + + Firstrade shows a single ``FEES`` line, so the unrounded SEC and TAF + amounts are summed, rounded up to the next cent, and floored at the + configured minimum (``$0.01``) whenever any fee is owed. A rate of zero + (e.g. the SEC rate between 2025-05-14 and 2026-04-03) yields no fee. + """ + + sec_raw = proceeds * schedule.sec_rate_on(trade_date) / _MILLION + taf_rate, taf_max = schedule.taf_on(trade_date) + taf_raw = min(abs(quantity) * taf_rate, taf_max) if taf_rate > 0 else Decimal(0) + total_raw = sec_raw + taf_raw + if total_raw <= 0: + fee = Decimal("0.00") + else: + fee = max(_round_up_cent(total_raw), schedule.minimum_regulatory_fee) + return {"sec_raw": sec_raw, "taf_raw": taf_raw, "fee": fee} + + +def decompose_sell_fees( + row: Mapping[str, Any], *, schedule: FeeSchedule | None = None +) -> dict[str, Any]: + """Explain the gap between ``quantity x price`` and the reported net proceeds. + + ``row`` uses the Firstrade history CSV shape: Date (the trade date, not the + settlement date), Transaction, Quantity, Description, Symbol, Price, Amount + (case-insensitive keys). Quantity and price must be positive. Returns a plain + dict with fixed keys; ``status`` is one of ``explained``, ``unexplained``, + ``not_applicable`` or ``unsupported``. The schedule is applied by trade + date and fails closed (``unsupported``) when a rate is not defined. + """ + + schedule = schedule or load_fee_schedule() + transaction = str(_row_value(row, "transaction") or "").strip().lower() + description = _row_value(row, "description") + base = {"status": "not_applicable", "reason": None} + if transaction not in {"sold", "sell"}: + return {**base, "reason": "not_a_sell"} + if not schedule.is_broker_assisted(description): + return {**base, "reason": "not_broker_assisted_order"} + try: + trade_date, settlement_date = _resolve_dates( + _row_value(row, "date", "trade_date"), description) + quantity = abs(_to_decimal(_row_value(row, "quantity"))) + price = _to_decimal(_row_value(row, "price")) + reported_net = _to_decimal(_row_value(row, "amount", "net_amount")) + if quantity <= 0: + raise ValueError("quantity_not_positive") + if price <= 0: + raise ValueError("price_not_positive") + except ValueError as exc: + return {"status": "unsupported", "reason": str(exc)} + gross = quantity * price + try: + broker_fee = schedule.broker_assisted_fee_on(trade_date) + reg = regulatory_fee( + proceeds=gross, quantity=quantity, trade_date=trade_date, schedule=schedule) + except FeeScheduleError as exc: + return {"status": "unsupported", "reason": str(exc)} + expected_net = (gross - broker_fee - reg["fee"]).quantize(_CENT, rounding=ROUND_HALF_UP) + residual = (reported_net - expected_net).quantize(_CENT) + explained = abs(residual) <= schedule.explained_residual_tolerance + return { + "status": "explained" if explained else "unexplained", + "reason": None if explained else "residual_exceeds_tolerance", + "trade_date": trade_date.isoformat(), + "settlement_date": settlement_date.isoformat() if settlement_date else None, + "gross_proceeds": _exact(gross), + "gross_minus_reported_net": _exact(gross - reported_net), + "broker_assisted_fee": _money(broker_fee), + "regulatory_fee": _money(reg["fee"]), + "sec_fee_unrounded": _exact(reg["sec_raw"]), + "taf_unrounded": _exact(reg["taf_raw"]), + "expected_net": _money(expected_net), + "reported_net": _money(reported_net), + "residual": _money(residual), + "residual_tolerance": _money(schedule.explained_residual_tolerance), + } + + +def _quantity_map(raw: Mapping[str, object] | None) -> dict[str, Decimal] | None: + if raw is None: + return None + result: dict[str, Decimal] = {} + for symbol, quantity in raw.items(): + key = str(symbol or "").strip().upper() + if not key or key in result: + raise ValueError("quantity_invalid") + value = _to_decimal(quantity) + if value <= 0: + raise ValueError("quantity_invalid") + result[key] = value + return result + + +def valuation_basis_difference( + *, + balance_long_stock_value: object, + positions_market_values: Iterable[object], + position_quantities: Mapping[str, object] | None = None, + expected_quantities: Mapping[str, object] | None = None, + tolerance_cap: Decimal = VALUATION_TOLERANCE_CAP, +) -> dict[str, str]: + """Compare balances-endpoint stock value with the sum of positions market values. + + A non-zero gap within ``min(max($0.10, 0.1% of market value), cap)`` (cap + ``$25.00``) is reported as ``valuation_basis_difference`` (two endpoints, + two quote bases) and is not an unexplained reconciliation break. A gap + above the tolerance is ``unexplained``. The gap is signed + ``positions - balance``. + + A price-basis gap is only credible when the share counts agree, so the + position quantities are cross-checked against ``expected_quantities`` (for + example the previous snapshot or the ledger) when both are supplied: any + difference makes the result ``unexplained`` (``quantity_mismatch``). + ``quantity_check`` is ``not_performed`` when either side is missing, so a + caller can see the quantities were not verified. An empty positions list + only matches a zero balance value. + """ + + try: + balance_value = _to_decimal(balance_long_stock_value) + values = [_to_decimal(v) for v in positions_market_values] + actual = _quantity_map(position_quantities) + expected = _quantity_map(expected_quantities) + except ValueError: + return {"status": "unavailable", "reason": "valuation_input_missing"} + if balance_value < 0 or any(v < 0 for v in values): + return {"status": "unavailable", "reason": "valuation_input_negative"} + positions_value = sum(values, Decimal(0)) + difference = positions_value - balance_value + reference = max(abs(balance_value), abs(positions_value)) + tolerance = min( + max(VALUATION_TOLERANCE_FLOOR, reference * VALUATION_TOLERANCE_RATE), tolerance_cap) + quantity_check = "not_performed" + if actual is not None and expected is not None: + quantity_check = "matched" if actual == expected else "mismatch" + reason = None + if not values and balance_value != 0: + status, reason = "unexplained", "positions_empty_balance_nonzero" + elif quantity_check == "mismatch": + status, reason = "unexplained", "quantity_mismatch" + elif difference == 0: + status = "match" + elif abs(difference) <= tolerance: + status = "valuation_basis_difference" + else: + status, reason = "unexplained", "difference_exceeds_tolerance" + report = { + "status": status, + "balance_long_stock_value": _exact(balance_value), + "positions_market_value": _exact(positions_value), + "difference_positions_minus_balance": _exact(difference), + "tolerance": _exact(tolerance), + "quantity_check": quantity_check, + } + if reason: + report["reason"] = reason + return report + + +def valuation_basis_report( + observation: Mapping[str, Any], *, expected_quantities: Mapping[str, object] | None = None +) -> dict[str, str]: + """Build the report from a ``collect_firstrade_account_facts`` observation.""" + + balances = observation.get("balances") + positions = observation.get("positions") + if not isinstance(balances, Mapping) or not isinstance(positions, list): + return {"status": "unavailable", "reason": "observation_incomplete"} + if balances.get("long_stock_value") is None: + return {"status": "unavailable", "reason": "balance_long_stock_value_missing"} + rows = [row for row in positions if isinstance(row, Mapping)] + values = [row.get("market_value") for row in rows] + if any(v is None for v in values): + return {"status": "unavailable", "reason": "position_market_value_missing"} + quantities: dict[str, object] | None = None + if expected_quantities is not None: + quantities = {} + for row in rows: + symbol = str(row.get("symbol") or "").strip().upper() + if not symbol or symbol in quantities or row.get("quantity") is None: + return {"status": "unavailable", "reason": "position_quantity_missing"} + quantities[symbol] = row["quantity"] + return valuation_basis_difference( + balance_long_stock_value=balances["long_stock_value"], + positions_market_values=values, + position_quantities=quantities, + expected_quantities=expected_quantities, + ) diff --git a/docs/statement-reconciliation.md b/docs/statement-reconciliation.md new file mode 100644 index 00000000..d20f0624 --- /dev/null +++ b/docs/statement-reconciliation.md @@ -0,0 +1,87 @@ +# Statement reconciliation: fee split and valuation basis + +Two reconciliation gaps looked unexplained but have fixed, documented causes. +`application/statement_reconciliation.py` models them as pure, offline helpers. +Nothing in it calls a broker, reads credentials, or writes data. + +## Desk-executed sells: broker-assisted fee plus regulatory fee + +A sell whose description contains `BROKER/DEALER ORDER` (this includes +`MARGIN SELLOUT`) nets less than `quantity x price`: + +``` +expected net = quantity x price - broker-assisted fee - regulatory fee +``` + +- Broker-assisted fee: `$19.95` per order (Firstrade pricing page). +- Regulatory fee: SEC Section 31 (`rate per $1M x proceeds`) plus FINRA TAF + (`rate per share`, capped per trade). The unrounded amounts are summed, + rounded up to the next cent, with a `$0.01` minimum whenever any fee is owed. +- A residual within `+/- $0.01` after this split is reported as `explained`. + Larger residuals are `unexplained`. A trade date outside the configured + schedule is `unsupported` (fail closed), never guessed. +- Quantity and price must both be greater than zero; otherwise the row is + `unsupported` (`quantity_not_positive` / `price_not_positive`). +- The CSV `Date` column is the **trade date**, not the settlement date. In the + 2026-08-28 IBIT row `Date` is `8/28/2026`, the description has + `EXEC TIME: 2026-08-28 ...` and `S/D: 08/31/2026` (T+1). SEC Section 31 and + FINRA TAF are charged on the trade date, so rates are selected by `Date` and + `settlement_date` is only reported. A row whose `Date` disagrees with + `EXEC TIME`, or is not before `S/D`, is `unsupported` + (`date_column_not_trade_date`). + +Worked case, 2026-08-28 IBIT: `2 x 43.7724 = 87.5448`, minus `19.95` and +`0.01` gives `67.58`, which matches the reported amount. The earlier +"unexplained `19.96`" is the sum of the two fees. + +Rates live in `application/firstrade_fee_schedule.py` as effective-dated +segments (SEC `0.00` from 2025-05-14, `20.60` per million from 2026-04-04). +TAF for covered equities: `0.000195` per share (max `$9.79`) in 2026, paused +2026-10-01 to 2026-12-31 (SR-FINRA-2026-021), then `0.000195` / `$9.79` again +for 2027 and 2028 because SR-FINRA-2026-020 postpones the remaining increases +by two years: `0.000232` / `$11.61` from 2029-01-01, `0.000240` / `$12.05` from +2030-01-01 and `0.000249` / `$12.50` from 2031-01-01. Update the segments when +SEC or FINRA publish a new rate; `load_fee_schedule()` validates ordering and +values. + +`verified_through` (currently `2026-11-01`) is the last trade date the rates +were checked against the published sources. Trade dates after it are +`unsupported` (`..._not_verified_after_`), because the SEC fiscal year +2027 Section 31 rate has not been published (the FY2026 rate stays in effect +until 60 days after the FY2027 appropriation is enacted) and the FINRA filings +above are immediately effective but still open to SEC suspension. Re-verify the +sources and move `verified_through` forward in the same change. + +## Valuation basis difference + +The balances endpoint and the positions endpoint price the same shares from +different quote bases, so `long_stock_value` (balances) and the sum of +position `market_value` can differ by a few cents with identical quantities and +cash. `valuation_basis_difference` reports this as its own status: + +| Status | Meaning | +| --- | --- | +| `match` | Exactly equal. | +| `valuation_basis_difference` | Non-zero, within `min(max($0.10, 0.1% of market value), $25.00)`. | +| `unexplained` | Larger than the tolerance, a position quantity mismatch, or an empty positions list with a non-zero balance value. | +| `unavailable` | An input was missing or negative. | + +The `$25.00` absolute cap keeps 0.1% of a large account from hiding a real +break. Pass `expected_quantities` (for example from the previous snapshot or +the ledger) to cross-check share counts: a price-basis gap is only credible when +quantities agree, so any quantity difference is `unexplained` +(`quantity_mismatch`). `quantity_check` reports `matched`, `mismatch` or +`not_performed`; an empty positions list only matches a zero balance value. + +Worked case, 2026-10-31: balance `130.56` against positions `130.6232` is a +`0.0632` gap, within the `0.1306` tolerance. + +The read-only collector now keeps `long_stock_value` as a distinct balance fact +(`balances.long_stock_value`, coverage flags `long_stock_value_available` and +`long_stock_value_ambiguous`). If the top-level and `result` values conflict, the +value is withheld and flagged ambiguous; the rest of the collection (cash, +equity, positions) is still returned. +`build_firstrade_account_snapshot(..., include_valuation_basis=True)` can persist +it next to `net_assets`. This is off by default because the QRS console +currently accepts exactly `currency` and `net_assets` in Firstrade balance rows +and rejects additional keys; extend that schema before enabling it. diff --git a/docs/statement-reconciliation.zh-CN.md b/docs/statement-reconciliation.zh-CN.md new file mode 100644 index 00000000..b727e4a3 --- /dev/null +++ b/docs/statement-reconciliation.zh-CN.md @@ -0,0 +1,41 @@ +# 对账:费用拆分与估值口径 + +有两类对账差异看起来无法解释,但原因固定且已记录。 +`application/statement_reconciliation.py` 用纯离线函数对它们建模,不调用券商、不读取凭据、不写入数据。 + +## 人工委托卖单:经纪人协助费 + 监管费 + +描述中含 `BROKER/DEALER ORDER`(包括 `MARGIN SELLOUT`)的卖单,到账金额小于 `数量 x 价格`: + +``` +预期净额 = 数量 x 价格 - 经纪人协助费 - 监管费 +``` + +- 经纪人协助费:每笔 `$19.95`(Firstrade 费率页面)。 +- 监管费:SEC Section 31(`每百万美元费率 x 成交额`)加 FINRA TAF(每股费率,单笔设上限)。未取整金额相加后向上取整到分,只要产生费用最低 `$0.01`。 +- 拆分后残差在 `+/- $0.01` 内记为 `explained`;更大为 `unexplained`;交易日期超出费率表范围记为 `unsupported`(失败即关闭,不猜测)。 +- 数量和价格必须大于 0,否则该行为 `unsupported`(`quantity_not_positive` / `price_not_positive`)。 +- CSV 的 `Date` 列是**交易日**而非结算日。2026-08-28 IBIT 一行中 `Date` 为 `8/28/2026`,描述含 `EXEC TIME: 2026-08-28 ...` 与 `S/D: 08/31/2026`(T+1)。SEC Section 31 与 FINRA TAF 以交易日计费,因此按 `Date` 选择费率,`settlement_date` 仅作展示;`Date` 与 `EXEC TIME` 不一致或不早于 `S/D` 时记为 `unsupported`(`date_column_not_trade_date`)。 + +示例,2026-08-28 IBIT:`2 x 43.7724 = 87.5448`,减去 `19.95` 和 `0.01` 得 `67.58`,与实际到账一致。此前的“无法解释 `19.96`”即这两项费用之和。 + +费率以带生效日期的分段形式放在 `application/firstrade_fee_schedule.py`(SEC 自 2025-05-14 起 `0.00`,自 2026-04-04 起每百万 `20.60`)。TAF(普通股/ETF)2026 年每股 `0.000195`(单笔上限 `$9.79`),2026-10-01 至 2026-12-31 暂停(SR-FINRA-2026-021);因 SR-FINRA-2026-020 将剩余涨幅推迟两年,2027、2028 年仍为 `0.000195` / `$9.79`,2029-01-01 起 `0.000232` / `$11.61`,2030-01-01 起 `0.000240` / `$12.05`,2031-01-01 起 `0.000249` / `$12.50`。SEC 或 FINRA 发布新费率时更新分段;`load_fee_schedule()` 会校验顺序和取值。 + +`verified_through`(当前 `2026-11-01`)是费率最后一次对照公开来源核实的交易日。之后的交易日为 `unsupported`(`..._not_verified_after_<日期>`):SEC 2027 财年 Section 31 费率尚未公布(FY2026 费率在 2027 财年拨款法案生效后 60 天内继续有效),上述 FINRA 备案虽即时生效但仍可能被 SEC 暂停。更新来源核实时需在同一变更中推进 `verified_through`。 + +## 估值口径差异 + +余额接口与持仓接口对同一批股票使用不同报价口径,因此在数量和现金一致时,`long_stock_value`(余额接口)与持仓 `market_value` 之和可能相差几分钱。`valuation_basis_difference` 把它单独报告: + +| 状态 | 含义 | +| --- | --- | +| `match` | 完全相等。 | +| `valuation_basis_difference` | 非零,且在 `min(max($0.10, 市值的 0.1%), $25.00)` 之内。 | +| `unexplained` | 超过容差、持仓数量不一致,或持仓为空但余额股票价值非零。 | +| `unavailable` | 缺少输入或输入为负。 | + +`$25.00` 绝对上限避免大账户的 0.1% 掩盖真实差异。传入 `expected_quantities`(例如上一份快照或账本)可交叉核对股数:只有数量一致时价格口径差异才可信,数量不一致一律 `unexplained`(`quantity_mismatch`)。`quantity_check` 取值 `matched`、`mismatch` 或 `not_performed`;持仓为空只与零余额股票价值匹配。 + +示例,2026-10-31:余额 `130.56` 对持仓 `130.6232`,差 `0.0632`,在 `0.1306` 容差内。 + +只读采集器现在把 `long_stock_value` 作为独立的余额事实保留(`balances.long_stock_value`,覆盖标记 `long_stock_value_available` 与 `long_stock_value_ambiguous`)。顶层与 `result` 中的值冲突时,该值被置空并标记为 ambiguous,其余采集结果(现金、权益、持仓)照常返回。`build_firstrade_account_snapshot(..., include_valuation_basis=True)` 可把它与 `net_assets` 一并持久化。该选项默认关闭:QRS 控制台目前只接受 Firstrade 余额行中的 `currency` 和 `net_assets`,会拒绝额外字段;启用前需先扩展该 schema。 diff --git a/tests/test_statement_reconciliation.py b/tests/test_statement_reconciliation.py new file mode 100644 index 00000000..474441a3 --- /dev/null +++ b/tests/test_statement_reconciliation.py @@ -0,0 +1,337 @@ +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from application.firstrade_fee_schedule import ( + DEFAULT_FEE_SCHEDULE_CONFIG, + FeeScheduleError, + load_fee_schedule, +) +from application.statement_reconciliation import ( + decompose_sell_fees, + valuation_basis_difference, + valuation_basis_report, +) + +# Shape of the Firstrade history CSV row for the 2026-08-28 margin sellout. +# ``Date`` is the trade date (matches EXEC TIME); S/D is the T+1 settlement date. +AUG_28_IBIT_SELL = { + "Date": "8/28/2026", + "Transaction": "Sold", + "Quantity": "-2", + "Description": ( + "ISHARES BITCOIN TR ISHARES BITCOIN TRUST ETF BROKER/DEALER ORDER MARGIN SELLOUT " + "UNSOLICITED EXEC TIME: 2026-08-28 14:50:14 S/D: 08/31/2026"), + "Symbol": "IBIT", + "Price": "43.7724", + "Amount": "67.58", +} + + +def sell_on(trade_date: str, **overrides): + """The Aug 28 sell re-dated to ``trade_date`` (YYYY-MM-DD), EXEC TIME kept in step.""" + + return {**AUG_28_IBIT_SELL, "Date": trade_date, + "Description": f"BROKER/DEALER ORDER EXEC TIME: {trade_date} 10:00:00", **overrides} + + +def test_aug_28_ibit_margin_sellout_is_explained_by_two_fees(): + result = decompose_sell_fees(AUG_28_IBIT_SELL) + + assert result["status"] == "explained" + assert result["gross_proceeds"] == "87.5448" + assert result["broker_assisted_fee"] == "19.95" + assert result["regulatory_fee"] == "0.01" + assert result["expected_net"] == "67.58" + assert result["reported_net"] == "67.58" + assert result["residual"] == "0.00" + # The statement gap that used to look like an unexplained $19.96. + assert result["gross_minus_reported_net"] == "19.9648" + + +def test_residual_within_one_cent_is_explained_and_beyond_is_not(): + off_by_cent = decompose_sell_fees({**AUG_28_IBIT_SELL, "Amount": "67.59"}) + off_by_two = decompose_sell_fees({**AUG_28_IBIT_SELL, "Amount": "67.60"}) + + assert off_by_cent["status"] == "explained" and off_by_cent["residual"] == "0.01" + assert off_by_two["status"] == "unexplained" + assert off_by_two["reason"] == "residual_exceeds_tolerance" + + +def test_sec_rate_is_segmented_by_effective_date(): + # 2026-04-03 is the last day of the $0.00/M segment: no SEC fee at all, and + # TAF on 2 shares (0.00039) still rounds up to the one-cent minimum. + before = decompose_sell_fees(sell_on("2026-04-03")) + after = decompose_sell_fees(sell_on("2026-04-04")) + assert before["sec_fee_unrounded"] == "0" + assert before["regulatory_fee"] == "0.01" + assert after["sec_fee_unrounded"] == "0.00180342288" + assert after["regulatory_fee"] == "0.01" + + large = {"Quantity": "-1000", "Price": "100", "Amount": "99977.79"} + # 100,000 x 20.60/M = 2.06; TAF 1000 x 0.000195 = 0.195; sum 2.255 -> 2.26. + result = decompose_sell_fees(sell_on("2026-08-28", **large)) + assert result["regulatory_fee"] == "2.26" + assert result["expected_net"] == "99977.79" + # Rate was zero before 2026-04-04: only TAF, 0.195 -> 0.20. + zero_sec = decompose_sell_fees(sell_on("2026-01-15", **large)) + assert zero_sec["sec_fee_unrounded"] == "0" + assert zero_sec["regulatory_fee"] == "0.20" + + +def test_taf_pause_and_cap_follow_the_schedule(): + schedule = load_fee_schedule() + taf_195 = (Decimal("0.000195"), Decimal("9.79")) + assert schedule.taf_on(date(2025, 12, 31)) == (Decimal("0.000166"), Decimal("8.30")) + assert schedule.taf_on(date(2026, 1, 1)) == taf_195 + assert schedule.taf_on(date(2026, 9, 30)) == taf_195 + # SR-FINRA-2026-021: TAF is $0 from 2026-10-01 to 2026-12-31. + assert schedule.taf_on(date(2026, 10, 1)) == (Decimal(0), Decimal(0)) + assert schedule.taf_on(date(2026, 11, 1)) == (Decimal(0), Decimal(0)) + capped = decompose_sell_fees(sell_on( + "2026-02-02", Quantity="-100000", Price="1", Amount="0")) + assert capped["taf_unrounded"] == "9.79" + + +def test_taf_increase_is_deferred_to_2029_by_sr_finra_2026_020(): + # Verify with a schedule whose verified_through covers the later years. + config = {**DEFAULT_FEE_SCHEDULE_CONFIG, "verified_through": "2031-12-31"} + schedule = load_fee_schedule(config) + taf_195 = (Decimal("0.000195"), Decimal("9.79")) + assert schedule.taf_on(date(2027, 1, 1)) == taf_195 + assert schedule.taf_on(date(2027, 12, 31)) == taf_195 + assert schedule.taf_on(date(2028, 1, 1)) == taf_195 + assert schedule.taf_on(date(2028, 12, 31)) == taf_195 + assert schedule.taf_on(date(2029, 1, 1)) == (Decimal("0.000232"), Decimal("11.61")) + assert schedule.taf_on(date(2030, 1, 1)) == (Decimal("0.000240"), Decimal("12.05")) + assert schedule.taf_on(date(2031, 1, 1)) == (Decimal("0.000249"), Decimal("12.50")) + + +def test_dates_after_verified_through_are_unsupported(): + schedule = load_fee_schedule() + assert schedule.verified_through == date(2026, 11, 1) + assert schedule.sec_rate_on(date(2026, 11, 1)) == Decimal("20.60") + for lookup in (schedule.sec_rate_on, schedule.taf_on, schedule.broker_assisted_fee_on): + with pytest.raises(FeeScheduleError, match="not_verified_after_2026-11-01"): + lookup(date(2026, 11, 2)) + # SEC FY2027 Section 31 rate is not published: a later sale must not borrow FY2026's. + late = decompose_sell_fees(sell_on("2026-11-02")) + assert late["status"] == "unsupported" + assert "not_verified_after_2026-11-01" in late["reason"] + assert decompose_sell_fees(sell_on("2026-11-01"))["status"] != "unsupported" + + +def test_verified_through_is_required_and_must_be_a_date(): + config = {k: v for k, v in DEFAULT_FEE_SCHEDULE_CONFIG.items() if k != "verified_through"} + with pytest.raises(FeeScheduleError, match="verified_through_missing"): + load_fee_schedule(config) + with pytest.raises(FeeScheduleError, match="verified_through_invalid"): + load_fee_schedule({**config, "verified_through": "tomorrow"}) + + +def test_non_broker_assisted_or_non_sell_rows_are_not_applicable(): + online = decompose_sell_fees({**AUG_28_IBIT_SELL, "Description": "SOLD IBIT ONLINE"}) + buy = decompose_sell_fees({**AUG_28_IBIT_SELL, "Transaction": "Bought"}) + assert online == {"status": "not_applicable", "reason": "not_broker_assisted_order"} + assert buy == {"status": "not_applicable", "reason": "not_a_sell"} + + +def test_dates_outside_the_schedule_and_bad_input_fail_closed(): + early = decompose_sell_fees(sell_on("2020-01-02")) + assert early["status"] == "unsupported" + assert "not_defined_for_2020-01-02" in early["reason"] + assert decompose_sell_fees({**AUG_28_IBIT_SELL, "Amount": "n/a"})["status"] == "unsupported" + assert decompose_sell_fees({**AUG_28_IBIT_SELL, "Date": "soon"})["status"] == "unsupported" + + +def test_schedule_loader_rejects_malformed_config(): + bad = {**DEFAULT_FEE_SCHEDULE_CONFIG, "sec_rate_per_million": [ + {"effective_from": "2026-04-04", "rate": "20.60"}, + {"effective_from": "2025-05-14", "rate": "0.00"}, + ]} + with pytest.raises(FeeScheduleError, match="not_strictly_ordered"): + load_fee_schedule(bad) + with pytest.raises(FeeScheduleError, match="schema_version_unsupported"): + load_fee_schedule({**DEFAULT_FEE_SCHEDULE_CONFIG, "schema_version": "x"}) + with pytest.raises(FeeScheduleError, match="rate_invalid"): + load_fee_schedule({**DEFAULT_FEE_SCHEDULE_CONFIG, "sec_rate_per_million": [ + {"effective_from": "2026-04-04", "rate": "-1"}]}) + + +def test_schedule_is_overridable_from_config(): + custom = {**DEFAULT_FEE_SCHEDULE_CONFIG, + "broker_assisted_fee": [{"effective_from": "2000-01-01", "amount": "25.00"}]} + result = decompose_sell_fees(AUG_28_IBIT_SELL, schedule=load_fee_schedule(custom)) + assert result["broker_assisted_fee"] == "25.00" + assert result["status"] == "unexplained" + + +def test_130_56_vs_130_6232_is_a_valuation_basis_difference_not_unexplained(): + result = valuation_basis_difference( + balance_long_stock_value="130.56", positions_market_values=["130.6232"]) + + assert result == { + "status": "valuation_basis_difference", + "balance_long_stock_value": "130.56", + "positions_market_value": "130.6232", + "difference_positions_minus_balance": "0.0632", + "tolerance": "0.1306232", + "quantity_check": "not_performed", + } + + +def test_valuation_tolerance_is_floor_or_tenth_of_a_percent(): + small = valuation_basis_difference( + balance_long_stock_value="10", positions_market_values=["10.10"]) + assert small["status"] == "valuation_basis_difference" and small["tolerance"] == "0.1" + just_over = valuation_basis_difference( + balance_long_stock_value="10", positions_market_values=["10.11"]) + assert just_over["status"] == "unexplained" + big = valuation_basis_difference( + balance_long_stock_value="10000", positions_market_values=["10010"]) + assert big["status"] == "valuation_basis_difference" and big["tolerance"] == "10.01" + assert valuation_basis_difference( + balance_long_stock_value="5", positions_market_values=["5"])["status"] == "match" + + +def test_valuation_report_uses_collector_observation_and_fails_closed(): + observation = { + "balances": {"long_stock_value": "130.56"}, + "positions": [{"symbol": "IBIT", "market_value": "130.6232"}], + } + assert valuation_basis_report(observation)["status"] == "valuation_basis_difference" + missing = {"balances": {"long_stock_value": None}, "positions": []} + assert valuation_basis_report(missing) == { + "status": "unavailable", "reason": "balance_long_stock_value_missing"} + no_mv = {"balances": {"long_stock_value": "1"}, "positions": [{"symbol": "X", "market_value": None}]} + assert valuation_basis_report(no_mv)["reason"] == "position_market_value_missing" + assert valuation_basis_report({})["reason"] == "observation_incomplete" + + +def test_csv_date_is_trade_date_and_settlement_date_never_selects_the_rate(): + result = decompose_sell_fees(AUG_28_IBIT_SELL) + assert result["trade_date"] == "2026-08-28" + assert result["settlement_date"] == "2026-08-31" + + # Trade on the last day of a rate segment, settlement after the boundary: + # the rate follows the trade date (SEC FY2026 rate starts 2026-04-04). + last_zero_day = sell_on( + "2026-04-03", Description="BROKER/DEALER ORDER EXEC TIME: 2026-04-03 10:00:00 S/D: 04/06/2026") + assert decompose_sell_fees(last_zero_day)["sec_fee_unrounded"] == "0" + # And the TAF pause: a 2026-09-30 trade settling 2026-10-01 still pays TAF. + pause_edge = sell_on( + "2026-09-30", Quantity="-100000", Price="1", Amount="0", + Description="BROKER/DEALER ORDER EXEC TIME: 2026-09-30 10:00:00 S/D: 10/01/2026") + assert decompose_sell_fees(pause_edge)["taf_unrounded"] == "9.79" + + +def test_date_column_that_is_not_the_trade_date_fails_closed(): + exported_settlement = {**AUG_28_IBIT_SELL, "Date": "8/31/2026"} + wrong = decompose_sell_fees(exported_settlement) + assert wrong == {"status": "unsupported", "reason": "date_column_not_trade_date"} + same_day = {**AUG_28_IBIT_SELL, "Description": AUG_28_IBIT_SELL["Description"].replace( + "S/D: 08/31/2026", "S/D: 08/28/2026")} + assert decompose_sell_fees(same_day)["reason"] == "date_column_not_trade_date" + # Without EXEC TIME or S/D the Date column is used as the trade date. + plain = {**AUG_28_IBIT_SELL, "Description": "BROKER/DEALER ORDER"} + assert decompose_sell_fees(plain)["trade_date"] == "2026-08-28" + + +@pytest.mark.parametrize( + ("overrides", "reason"), + [ + ({"Quantity": "0"}, "quantity_not_positive"), + ({"Quantity": "-0"}, "quantity_not_positive"), + ({"Price": "0"}, "price_not_positive"), + ({"Price": "-1"}, "price_not_positive"), + ({"Price": "0.00"}, "price_not_positive"), + ], +) +def test_non_positive_quantity_or_price_is_unsupported(overrides, reason): + result = decompose_sell_fees({**AUG_28_IBIT_SELL, **overrides}) + assert result == {"status": "unsupported", "reason": reason} + + +def test_smallest_positive_quantity_and_price_are_accepted(): + tiny = decompose_sell_fees({ + **AUG_28_IBIT_SELL, "Quantity": "-0.00001", "Price": "0.0001", "Amount": "-19.96"}) + assert tiny["status"] == "explained" + assert tiny["gross_proceeds"] == "0.000000001" + assert tiny["regulatory_fee"] == "0.01" + one_share = decompose_sell_fees({**AUG_28_IBIT_SELL, "Quantity": "1", "Price": "0.01", + "Amount": "-19.96"}) + assert one_share["status"] == "explained" + + +def test_valuation_tolerance_has_an_absolute_cap(): + # 0.1% of 100,000 would be 100; the cap holds it at 25. + inside = valuation_basis_difference( + balance_long_stock_value="100000", positions_market_values=["100025"]) + assert inside["status"] == "valuation_basis_difference" and inside["tolerance"] == "25" + outside = valuation_basis_difference( + balance_long_stock_value="100000", positions_market_values=["100025.01"]) + assert outside["status"] == "unexplained" + assert outside["reason"] == "difference_exceeds_tolerance" + assert outside["tolerance"] == "25" + custom = valuation_basis_difference( + balance_long_stock_value="100000", positions_market_values=["100050"], + tolerance_cap=Decimal("50")) + assert custom["status"] == "valuation_basis_difference" + + +def test_empty_positions_only_match_a_zero_balance_value(): + assert valuation_basis_difference( + balance_long_stock_value="0", positions_market_values=[])["status"] == "match" + # A small non-zero balance with no positions must not pass as a basis difference. + stale = valuation_basis_difference(balance_long_stock_value="0.05", positions_market_values=[]) + assert stale["status"] == "unexplained" + assert stale["reason"] == "positions_empty_balance_nonzero" + report = valuation_basis_report({"balances": {"long_stock_value": "130.56"}, "positions": []}) + assert report["status"] == "unexplained" + zero = valuation_basis_report({"balances": {"long_stock_value": "0"}, "positions": []}) + assert zero["status"] == "match" + + +def test_negative_valuation_inputs_are_unavailable(): + assert valuation_basis_difference( + balance_long_stock_value="-1", positions_market_values=["1"])["reason"] == "valuation_input_negative" + assert valuation_basis_difference( + balance_long_stock_value="1", positions_market_values=["-1"])["status"] == "unavailable" + + +def test_position_quantity_cross_check_blocks_a_basis_explanation(): + kwargs = dict(balance_long_stock_value="130.56", positions_market_values=["130.6232"]) + matched = valuation_basis_difference( + **kwargs, position_quantities={"ibit": "2.98909"}, expected_quantities={"IBIT": "2.98909"}) + assert matched["status"] == "valuation_basis_difference" + assert matched["quantity_check"] == "matched" + changed = valuation_basis_difference( + **kwargs, position_quantities={"IBIT": "2.98909"}, expected_quantities={"IBIT": "3"}) + assert changed["status"] == "unexplained" and changed["reason"] == "quantity_mismatch" + extra = valuation_basis_difference( + **kwargs, position_quantities={"IBIT": "2.98909", "SPY": "1"}, + expected_quantities={"IBIT": "2.98909"}) + assert extra["reason"] == "quantity_mismatch" + # Quantities not supplied: the result says so instead of implying a check. + assert valuation_basis_difference(**kwargs)["quantity_check"] == "not_performed" + bad = valuation_basis_difference( + **kwargs, position_quantities={"IBIT": "0"}, expected_quantities={"IBIT": "0"}) + assert bad["status"] == "unavailable" + + +def test_valuation_report_cross_checks_collector_quantities(): + observation = { + "balances": {"long_stock_value": "130.56"}, + "positions": [{"symbol": "IBIT", "quantity": "2.98909", "market_value": "130.6232"}], + } + ok = valuation_basis_report(observation, expected_quantities={"IBIT": "2.98909"}) + assert ok["status"] == "valuation_basis_difference" and ok["quantity_check"] == "matched" + assert valuation_basis_report( + observation, expected_quantities={"IBIT": "2"})["reason"] == "quantity_mismatch" + no_qty = {"balances": observation["balances"], + "positions": [{"symbol": "IBIT", "quantity": None, "market_value": "130.6232"}]} + assert valuation_basis_report( + no_qty, expected_quantities={"IBIT": "2.98909"})["reason"] == "position_quantity_missing" From 754cf3031d52b1d5de36fec897dc81c31985b6d6 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:37:51 +0800 Subject: [PATCH 2/2] fix(account-facts): flag conflicting long_stock_value instead of failing Collect the balance-endpoint long_stock_value as a distinct fact. When the top-level and result values conflict, withhold the value and mark it ambiguous instead of discarding the whole collection. The publisher persists it only when include_valuation_basis is enabled, because the console schema does not yet accept the extra key. --- application/account_facts_publisher.py | 19 ++++++++- application/account_facts_readonly.py | 18 ++++++++ tests/test_account_facts_publisher.py | 42 ++++++++++++++++++ tests/test_account_facts_readonly.py | 59 ++++++++++++++++++++++++++ 4 files changed, 137 insertions(+), 1 deletion(-) diff --git a/application/account_facts_publisher.py b/application/account_facts_publisher.py index 1fc74404..1d991022 100644 --- a/application/account_facts_publisher.py +++ b/application/account_facts_publisher.py @@ -191,8 +191,18 @@ def build_firstrade_account_snapshot( config: AccountFactsPublishConfig, *, account_scope: str, + include_valuation_basis: bool = False, ) -> dict[str, Any]: - """Build native facts; optional positions require an explicit currency setting.""" + """Build native facts; optional positions require an explicit currency setting. + + ``include_valuation_basis`` additionally persists the balance-API + ``long_stock_value`` next to ``net_assets`` so the balance-vs-positions + valuation basis difference can be reconciled from stored history. It is + off by default: the QRS/console Firstrade schema currently accepts exactly + ``currency`` and ``net_assets`` per balance row + (QuantRuntimeSettings ``IBKR_BALANCE_FIELDS``) and rejects extra keys, so + enable it only after that schema is extended. + """ if ( observation.get("status") != "available" or observation.get("platform") != "firstrade" @@ -255,6 +265,13 @@ def build_firstrade_account_snapshot( }], "cash": cash, } + if include_valuation_basis: + long_stock_value = balances.get("long_stock_value") + if long_stock_value is None: + ambiguous = (observation.get("coverage") or {}).get("long_stock_value_ambiguous") + raise AccountFactsPublishError( + "long_stock_value_ambiguous" if ambiguous is True else "long_stock_value_unavailable") + payload["broker_reported_balances"][0]["long_stock_value"] = _amount(long_stock_value) if config.position_currency is not None: rows = observation.get("positions") if observation.get("positions_status") != "available" or not isinstance(rows, list) or len(rows) > 64: diff --git a/application/account_facts_readonly.py b/application/account_facts_readonly.py index d537462a..06643aa3 100644 --- a/application/account_facts_readonly.py +++ b/application/account_facts_readonly.py @@ -260,6 +260,21 @@ def collect_firstrade_account_facts( raise AccountFactsUnavailable("balances_ambiguous") if cash_balance is None: cash_balance = result_cash + # Balance-endpoint value of long stock. It is priced on a different quote + # basis than the positions endpoint, so keep it as a distinct fact instead + # of folding it into provider_equity (see statement_reconciliation). + # Conflicting top-level and ``result`` values only flag this auxiliary fact + # as ambiguous (value withheld); it must not discard the rest of the + # collection, so cash/equity/positions stay available. + long_stock_value = _exact_balance_value(balances, ("long_stock_value",)) + long_stock_value_ambiguous = False + if isinstance(provider_result, Mapping): + result_long = _exact_balance_value(provider_result, ("long_stock_value",)) + if long_stock_value is not None and result_long is not None and long_stock_value != result_long: + long_stock_value = None + long_stock_value_ambiguous = True + elif long_stock_value is None: + long_stock_value = result_long available_cash = _exact_balance_value(balances, ("available_cash",)) buying_power = _exact_balance_value(balances, ("buying_power",)) balance_currency = _currency_code(balances) @@ -274,6 +289,7 @@ def collect_firstrade_account_facts( "balances": { "provider_equity": provider_equity, "cash_balance": cash_balance, + "long_stock_value": long_stock_value, "available_cash": available_cash, "buying_power": buying_power, "currency": balance_currency, @@ -287,6 +303,8 @@ def collect_firstrade_account_facts( "positions_missing_identity_fields": missing_identity if include_positions else None, "provider_equity_available": provider_equity is not None, "cash_balance_available": cash_balance is not None, + "long_stock_value_available": long_stock_value is not None, + "long_stock_value_ambiguous": long_stock_value_ambiguous, "available_cash_available": available_cash is not None, "buying_power_available": buying_power is not None, "balance_currency_available": balance_currency is not None, diff --git a/tests/test_account_facts_publisher.py b/tests/test_account_facts_publisher.py index 52fb79af..c3a16913 100644 --- a/tests/test_account_facts_publisher.py +++ b/tests/test_account_facts_publisher.py @@ -341,3 +341,45 @@ def test_empty_position_page_does_not_claim_complete_inventory(): cfg = load_account_facts_publish_config(config(FIRSTRADE_ACCOUNT_FACTS_POSITION_CURRENCY="USD")) payload = build_firstrade_account_snapshot(data, cfg, account_scope="us") assert "broker_reported_positions" not in payload + + +def test_default_snapshot_never_carries_long_stock_value(): + cfg = load_account_facts_publish_config(config()) + data = observation() + data["balances"]["long_stock_value"] = "130.56" + + payload = build_firstrade_account_snapshot(data, cfg, account_scope="us") + + assert payload["broker_reported_balances"] == [{"currency": "USD", "net_assets": "1234.50"}] + assert "long_stock_value" not in repr(payload) + + +def test_opt_in_persists_balance_long_stock_value_next_to_net_assets(): + cfg = load_account_facts_publish_config(config()) + data = observation() + data["balances"]["long_stock_value"] = "130.56" + + payload = build_firstrade_account_snapshot( + data, cfg, account_scope="us", include_valuation_basis=True) + + assert payload["broker_reported_balances"] == [ + {"currency": "USD", "net_assets": "1234.50", "long_stock_value": "130.56"}] + + +def test_opt_in_fails_closed_without_long_stock_value(): + cfg = load_account_facts_publish_config(config()) + + with pytest.raises(AccountFactsPublishError, match="long_stock_value_unavailable"): + build_firstrade_account_snapshot( + observation(), cfg, account_scope="us", include_valuation_basis=True) + + +def test_opt_in_reports_ambiguous_long_stock_value_distinctly(): + cfg = load_account_facts_publish_config(config()) + data = observation() + data["balances"]["long_stock_value"] = None + data["coverage"] = {"long_stock_value_ambiguous": True} + + with pytest.raises(AccountFactsPublishError, match="long_stock_value_ambiguous"): + build_firstrade_account_snapshot( + data, cfg, account_scope="us", include_valuation_basis=True) diff --git a/tests/test_account_facts_readonly.py b/tests/test_account_facts_readonly.py index d522cbe1..ab4e4015 100644 --- a/tests/test_account_facts_readonly.py +++ b/tests/test_account_facts_readonly.py @@ -80,6 +80,7 @@ def clock(): "balances": { "provider_equity": "1234.5", "cash_balance": "200.25", + "long_stock_value": None, "available_cash": None, "buying_power": "150", "currency": "USD", @@ -96,6 +97,8 @@ def clock(): "positions_missing_identity_fields": 0, "provider_equity_available": True, "cash_balance_available": True, + "long_stock_value_available": False, + "long_stock_value_ambiguous": False, "available_cash_available": False, "buying_power_available": True, "balance_currency_available": True, @@ -194,6 +197,7 @@ def test_keeps_provider_cash_and_buying_power_fields_distinct(): assert result["balances"] == { "provider_equity": None, "cash_balance": None, + "long_stock_value": None, "available_cash": "75", "buying_power": "90", "currency": "USD", @@ -258,6 +262,7 @@ def test_does_not_mix_margin_cash_with_cash_or_buying_power(): assert result["balances"] == { "provider_equity": None, "cash_balance": "100", + "long_stock_value": None, "available_cash": "90", "buying_power": "80", "currency": "USD", @@ -455,3 +460,57 @@ def test_accepts_firstrade_total_value_as_provider_equity(field): ) assert result["balances"]["provider_equity"] == "1234.5" + + +def test_collects_long_stock_value_from_provider_result_envelope(): + client = CachedReadOnlyClient() + client.balances = { + "account_list_total_value": "132.83", + "result": {"cash_balance": "2.27", "long_stock_value": "130.56"}, + } + client.positions = {"items": [{"symbol": "IBIT", "quantity": "2.98909", "market_value": "130.6232"}]} + + result = collect_firstrade_account_facts( + client, + expected_account="synthetic-account-a", + clock=lambda: datetime(2026, 10, 31, 21, tzinfo=timezone.utc), + ) + + assert result["balances"]["long_stock_value"] == "130.56" + assert result["coverage"]["long_stock_value_available"] is True + + +def test_conflicting_long_stock_value_is_flagged_without_failing_collection(): + client = CachedReadOnlyClient() + client.balances = { + "account_list_total_value": "132.83", + "long_stock_value": "1.00", + "result": {"cash_balance": "2.27", "long_stock_value": "2.00"}, + } + client.positions = {"items": [{"symbol": "IBIT", "quantity": "2.98909", "market_value": "130.6232"}]} + + result = collect_firstrade_account_facts( + client, + expected_account="synthetic-account-a", + clock=lambda: datetime(2026, 10, 31, 21, tzinfo=timezone.utc), + ) + + assert result["status"] == "available" + assert result["balances"]["long_stock_value"] is None + assert result["balances"]["cash_balance"] == "2.27" + assert result["balances"]["provider_equity"] == "132.83" + assert result["coverage"]["long_stock_value_available"] is False + assert result["coverage"]["long_stock_value_ambiguous"] is True + assert len(result["positions"]) == 1 + + +def test_conflicting_cash_balance_still_fails_closed(): + client = CachedReadOnlyClient() + client.balances = {"cash_balance": "1.00", "result": {"cash_balance": "2.00"}} + + with pytest.raises(AccountFactsUnavailable, match="balances_ambiguous"): + collect_firstrade_account_facts( + client, + expected_account="synthetic-account-a", + clock=lambda: datetime(2026, 10, 31, 21, tzinfo=timezone.utc), + )