Convert a disposal's proceeds before subtracting its cost basis

Merged
JA
3mo ago
+650-78

What this fixes

Realised gain was proceeds minus cost basis as bare numbers. Trend#value is current - previous, and Money#- keeps the left operand's currency while taking the right one's amount without converting or raising — so a disposal priced in the security's currency had a basis denominated in the account's subtracted from it, and the difference was then labelled with the disposal's currency.

A USD account holding a EUR-listed security, basis 100 USD/share, 2 sold at 150 EUR/share, EUR→USD 1.5 that day:

reportedtrueerror
rate 1.5150.00 USD250.00 USDundercounts by 100
rate 0.770.00 USD10.00 USDovercounts by 60 — 7×

Because the subtraction happened before any conversion, the whole wrong difference was scaled by the rate. Whether it flattered or understated depended on which side of parity the rate sat.

Fixes #169.

What changed

  • 5e4ab672a Convert a disposal's proceeds before subtracting its cost basis
  • 82558dc76 Fetch the disposal rates in one query, not one per disposal
  • 0a8a9670b Measure a disposal whose position is carried in a third currency
  • f091f9b5b Treat a rate that cannot convert as a rate that is missing
  • 7a2428592 Key the rate preload on the currency the basis is actually carried in
  • 60e2d35ec Refuse a rate that cannot convert on the card, and batch the third leg

9 files, +650/−78. The first commit is the defect in the title; the other five came out of review and four of them fixed further live defects rather than tidying the first.

The fix

Convert the proceeds into the basis's currency first, at the disposal's own date.

That direction and not the other, because it is the direction the data holds: 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, while USD→EUR is only ever there by accident of another account. (The issue suggested converting the basis into the trade's currency, which needs the pair that is not guaranteed. Same final figure, fewer disposals lost to a missing rate.)

Exact date, exact direction, no parity fallback and no nearest-rate lookback — the same rule Portfolio::RealizedGains already applies. A missing rate means no figure, not a figure at 1.0.

nil now has two causes, and calling a missing rate a missing cost basis would send a user to fix something that is not broken — so Trade#realized_gain_loss_unavailable_reason names which fact is missing, and Portfolio::RealizedGains tallies the right one. Its :mixed_currency exclusion is gone, with its en/de strings: those disposals are measured now.

All three consumers are updated together, as the issue requires:

  1. ReportsController#build_gains_by_tax_treatment — converts from the currency the figure carries, not the trade's.
  2. 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. The controller now hands it a converted per-trade figure, so the line and the card total are the same arithmetic. Conversion stays out of the template.
  3. Portfolio::RealizedGains — measures what it used to decline.

Rates in one query, not one per disposal (82558dc76)

Converting per disposal made the fix its own N+1: a Reports page or a hub section with n cross-currency disposals issued n rate lookups. Trade.preload_exchange_rates(trades) fetches every rate a set can need in one query, keyed [from, to, date], and Portfolio::RealizedGains batches its own leg alongside it.

A miss is not authoritative, unlike preloaded_holdings. 7a2428592 keys the basis side on the holding's own currency as well as the account's — Holding#avg_cost is Money in the holding's currency, and that is what the proceeds are converted into — so the third-currency shape below now hits the preload rather than paying a lookup per disposal. It is answered from the preloaded holdings, so it costs no query to ask. A caller that preloads rates without preloading holdings still leaves the basis side unknowable without a query, and for that case a miss falls back to the single lookup rather than to a wrong answer.

A position carried in a third currency (0a8a9670b)

This one was a live defect, not documentation. Statement in USD, position carried in GBP, disposal priced in EUR: neither batch covers it. Trade's preload keys the basis side on the account's currency, so it misses; Portfolio::RealizedGains's own batch enumerates the disposals' and the accounts' currencies, and GBP is in neither. A disposal with every rate it needs on file was tallied as :missing_exchange_rate by the hub and printed at parity by the Reports card. Both fixed, both pinned by a three-currency test.

Both remaining legs of the third-currency shape (7a2428592, 60e2d35ec)

Two follow-ups the daily sweep found after the commits above, each the same defect one level out.

Trade.preload_exchange_rates keyed only on the account's currency, so the GBP-carried position — the exact shape 0a8a9670b was written for — missed the preload and paid a find_by per disposal. It now keys on Trade#preloaded_basis_currency too. Portfolio::RealizedGains#rates_by_date had the identical gap on the statement leg (GBP→USD, in neither of the two sets it enumerated), measured at 8 queries for 6 disposals against 4 for 2; it now enumerates the holdings' currencies as well.

ReportsController's own conversion lambda was the one place still multiplying by rates_for's || 1, which returns a stored 0 unchanged. A real 40 GBP gain rendered as $0.00 and entered the treatment total, while the hub excluded the same disposal — two views of one disposal disagreeing. It now leaves the trade out of the tally, which the partial already renders as "no data". This is CodeRabbit's Major on review 5233890804, which an earlier reply reported as "CodeRabbit returned clean"; that reply was wrong.

A rate that is present but not usable (f091f9b5b)

cubic's finding, valid on both conversion legs. 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. Both legs multiplied by whatever was there.

Neither result is distinguishable from a real one. On the disposal leg, 300 EUR against a 200 USD basis reports a 200 USD total loss at a rate of 0 and a 650 USD loss at −1.5. On the statement leg a real 40 GBP gain enters the tally as 0 USD, which nets out exactly like a disposal that broke even. Both figures are tax-relevant.

A rate that cannot convert is the missing-rate case wearing a number, so it takes the same exit — no figure, :missing_exchange_rate as the reason. rate.to_d.positive? covers nil, zero and negative in one place on both legs.

Deliberately not in this PR

The ExchangeRate.rates_for(...) || 1 parity fallback in ReportsController and its Date.current holding conversion. Both are #167, both are about the card rather than this method, and neither changes which accounts Reports counts. This PR moves no account scope.

Blast radius

Who else hits this line, and what do they pass? Trade#realized_gain_loss has exactly three consumers, all above. Trend is used widely but this current/previous pairing is built in one place. holding.avg_cost also feeds Holding#trend for unrealised gains — untouched, and still in the holding's currency there.

Conversion is batched: one query for every rate a set of disposals can need, plus one further lookup per disposal the batch misses. A same-currency disposal short-circuits before any lookup, so the P41 constant-query-count test is unaffected (and still green).

The per-miss fallback is also the path a genuinely missing rate takes, so a period with n unmeasurable disposals costs n queries on top of the batch. That is bounded by the disposals that produce no figure rather than by all of them, and the alternative is the third-currency exclusion defect above, so the code stays and the comment on converted now says so.

Single-currency users see no number move. Cross-currency users see corrected figures on Reports, and the hub starts showing disposals it previously excluded.

Verification

  • bin/rails test (in the dev container): 9030 runs, 37445 assertions, 0 failures, 1 environmental error (below). CI ci / test_unit and ci / test_system are also green on this head. One error, RecurringTransaction::PipelineTest, is the database.yml user:/username: defect tracked in #168 — it opens a second connection that falls back to the OS user. Unrelated to this change and present on main.
  • bin/rails portfolio:verify_contract_coverage: 41 methodology and 17 returns rows verified.
  • bin/rubocop on the six changed Ruby files: no offenses. erb_lint on the partial: no errors. bin/brakeman: 0 warnings.

Every assertion mutation-checked, not merely green:

mutationcaught by
drop the conversion entirely4 failures across trade + realized-gains
fall back to 1.0 on a missing rate2 failures
blame the cost basis for every nilthe missing-rate tally test
restore the view's re-labellingthe Reports rendering test
replace the batched where with a per-trade find_bythe query-count test
treat the third-currency miss as "no rate"the three-currency test
drop either positivity guard back to nil if rate.nil?its own test — the disposal leg with the fabricated 200 USD loss, the statement leg with a 0/0 bucket carrying a trade_count of 1
key the Trade preload on the account's currency onlythe third-currency preload test: 1 query becomes 5
drop the basis currency from the hub's rate batchthe third-currency flat-count test: 6 queries for 2 disposals becomes 10 for 6
restore the card's `

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.

The first version of that last test passed against the mutation it was written to catch: it 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 and the fixture uses a foreign account, so the assertion is on the disposal line and the re-labelling is visible.

Summary by CodeRabbit

  • Bug Fixes
    • Realized gains and losses for investments and accounts in different currencies are now converted using applicable exchange rates from the trade date.
    • Investment performance reports now display converted gain amounts in the correct currency, preventing misleading currency labels or understated gains.
    • Cross-currency disposals are no longer automatically excluded when conversion data is available.
    • Transactions remain excluded when cost-basis information or valid exchange rates are unavailable.