Convert a disposal's proceeds before subtracting its cost basis

Merged
JA
3mo ago
+421-20

Fork pre-flight: jaysbeekay/sure#174 — same branch and same commit as this PR, where the fork's CI and review gates run first.

Summary

Realised gain/loss subtracts a cost basis denominated in the holding's currency from proceeds denominated in the trade's currency, as bare numbers — Money#- keeps the left operand's currency and takes the right one's amount without converting or raising — and the difference is then labelled with the disposal's currency. A USD account holding a EUR-listed security reports 150.00 USD of gain where the true figure is 250.00 USD, and at a rate below parity the same defect overstates instead: 70.00 against a true 10.00. The error is unbounded in both directions because the whole wrong difference is scaled by the rate.

Fixes #3615.

The proceeds are converted into the basis's currency before the subtraction, at the disposal's own date, with no parity fallback — a missing rate means no figure rather than a figure at 1.0.

Why this conversion direction

MarketDataImporter#required_exchange_rate_pairs takes every entry currency against its account's as its first required pair, so a EUR disposal in a USD account has a EUR→USD row for the day it happened. USD→EUR is only ever present by accident of another account, so converting the basis into the trade's currency instead would lose disposals to rates the sync never fetches. Same figure, fewer unmeasurable disposals.

What changed

  • app/models/trade.rb — converted_to_basis_currency, exact date and exact direction, nil when there is no rate. Plus Trade.preload_exchange_rates, which answers a page of disposals' rates in one query instead of one per foreign disposal. A preload miss falls back to the single lookup rather than being authoritative: the preload keys the basis side on the account's currency, and a holding carried in a third currency would otherwise be excluded though its rate is on file.
  • app/controllers/reports_controller.rb — converts from the currency the figure actually carries, adds the holdings' own currencies to the list it enumerates (a third currency previously fell through the || 1 parity fallback), and hands the partial a per-trade converted figure.
  • app/views/reports/_investment_performance.html.erb — the per-trade line was taking the number out of the Trend and re-labelling it family currency with no conversion at all. It now renders the controller's converted figure, so the line and the card total are the same arithmetic. Conversion stays out of the template.

A rate that is present but not usable

ExchangeRate validates presence only — validates :rate, presence: true, with a plain decimal, null: false column — so neither the model nor the database requires a rate to be a positive number, and a provider, an import or a hand-written row can leave a 0 or a negative behind. The conversion multiplied by whatever was there.

Neither result is distinguishable from a real one. At a rate of 0, 300 EUR of proceeds against a 200 USD basis reports a 200 USD total loss the user never took; at −1.5 the proceeds go negative and it reports a 650 USD loss. Both figures are tax-relevant.

A rate that cannot convert is the missing-rate case wearing a number, so it takes the same exit as an absent one — no figure, rather than a fabricated one. rate.to_d.positive? covers nil, zero and negative in one place.

Migration notes

No migration. No schema change, no data rewritten.

Demo data

No demo data needed: the existing generator already produces foreign-currency trades, and the fix changes figures rather than adding a surface.

Screenshots

No visual change beyond the figures themselves — the per-trade line renders the same markup with a correctly converted amount.

Verification

  • bin/rails test: 9249 runs, 37391 assertions, 0 failures. One error, RecurringTransaction::PipelineTest, is a local database.yml user:/username: issue that opens a second connection as the OS user; it reproduces on main unchanged. ci / test_unit and ci / test_system are green on this head.
  • bin/rubocop, bundle exec erb_lint, bin/brakeman: clean.

Mutations checked, each failing a named test:

mutationcaught by
drop the conversion entirelythe cross-currency disposal tests
fall back to 1.0 on a missing ratethe missing-rate test
restore the view's re-labellingthe Reports rendering test
drop the holdings' currencies from the card's currency listthe third-currency test
replace the batched where in preload_exchange_rates with a per-trade find_bythe query-count test
drop the positivity guard back to nil if rate.nil?the non-positive-rate test, with the fabricated 200 USD loss

Two of those are worth naming because the first version of the test passed the mutation it was written to catch, which is why they were rewritten rather than trusted:

  • The query-count test called Trade.preload_exchange_rates outside capture_sql_queries and asserted no rate queries remained. True, but it says nothing about what the preload itself costs — a preload issuing one query per trade satisfied it. The preload now runs inside the capture and the assertion is one query for the whole set.
  • The Reports rendering test matched on the ticker alone and found the holdings line above, whose unrealised figure is 250 in the same fixture. The line now carries a data-testid.

The positivity guard has a positive control beside it: a real rate of 0.7, below parity, still converts. The guard rejects what cannot convert, not everything under 1.

Blast radius

Trade#realized_gain_loss has exactly two consumers, both in this diff. Trend is used widely, but this current/previous pairing is constructed in one place. holding.avg_cost also feeds Holding#trend for unrealised gains — untouched, and still in the holding's currency there.

Single-currency users see no figure move. Cross-currency users see corrected figures on Reports, which is the point.

The ExchangeRate.rates_for(...) || 1 parity fallback on the statement-conversion leg, and convert_current's Date.current holding conversion, are not touched here: they belong to the card rather than to this method, and both predate this change.

Summary by CodeRabbit

  • Bug Fixes
    • Corrected realized gain and loss calculations for trades involving different currencies.
    • Investment performance reports now display realized gains in the correct family currency.
    • Improved handling of multi-currency conversions, including conversions involving a third currency.
    • Trades without an available exchange rate no longer produce incorrect converted values.
    • Invalid or non-positive exchange rates are no longer used to calculate realized gains or losses.
    • Improved accuracy when reporting realized gains across foreign accounts, holdings, and trades.