Add a monthly realised gains model for investment accounts

Closed
JA
11d ago
+889-29

Part of jaysbeekay/sure#121, drop 2.6 of the fork's investment portfolio programme (jaysbeekay/sure#118). The model layer of jaysbeekay/sure#166; the hub UI stays on the fork.

Updated 2026-11-21. Merged upstream main (fc524ae19) into the branch rather than rebasing, so its commits are kept. main now carries Trade#preloaded_holdings=, Trade.preload_basis_holdings and the fifo lot disposals (#4900, #4903), so this PR no longer adds the writer or changes that ReportsController line. A new Trade.preload_realized_gains reads each sale's basis snapshot, the lots a fifo sale consumed and the proceeds rates for a whole set; RealizedGains and ReportsController both call it. Under fifo a gain is the cost of the consumed lots, and a fifo sale with no readable lot record is excluded as gain_unknown. Full suite on 405fa1d1a: 18,060 runs, 0 failures; 8 errors in ReleaseNotesWorkflowTest from node missing in the test image. Diff: +862/−29, non-test +289/−29.

Upstream pre-flight for the programme coordinated in we-promise/sure#4078, on a branch cut from upstream main. Upstream PR: we-promise/sure#4405 (ready for review), from the same branch and commit.

Branched from main at 3ae36a699. It depends on nothing open: not on the returns engine PRs (#4197 and the PRs stacked on it), and not on the historical series PR (#4087). It is model layer only, with no caller and no UI. The fork's portfolio page reads it through InvestmentStatement#realized_gains, which needs historical_scope from #4087, so that one-method wrapper is left for after #4087 merges.

Problem

Sure reports realised gains only as one total for a period, grouped by tax treatment. ReportsController#build_gains_by_tax_treatment computes it inside the controller, and reports/_investment_performance.html.erb renders it. Nothing says when a gain was realised. There is no realised profit and loss by month, and no model a portfolio view could read one from.

The Reports total also treats a disposal it cannot measure as zero: gain ? ... : 0. A disposal with no cost basis, or with no rate for its proceeds, lowers the total, and nothing says a disposal was left out.

Change

app/models/portfolio/realized_gains.rb (new). Portfolio::RealizedGains.new(accounts:, period:, currency:, active_until_dates: {}) reads the accounts' disposals in the period and groups them by the month they happened, in currency.

  • #buckets: one Bucket(month, gains, losses, trade_count) per month that had a disposal, oldest first. losses is a positive amount and #net carries the sign. A month with no disposals is left out, not shown as zero.
  • #total_gains, #total_losses, #net, #trade_count.
  • #excluded_trades: { gain_unknown: n, missing_exchange_rate: n }, and #excluded_trade_count.
  • #any?: true when there is a bucket or an excluded disposal. Without the second half, a period where every disposal was excluded would look empty.

A disposal is a sell trade on an entry that is not excluded. An excluded entry is left out of reports: InvestmentStatement::Totals filters entries.excluded = false, and so does the Reports card's realised list in we-promise/sure#4409 (fork pre-flight jaysbeekay/sure#536). The two therefore agree on what a disposal is.

It applies four rules, each one already in the codebase:

  1. A transfer out is not a sale. It has a negative qty too. Disposals with a Trade::INTERNAL_MOVEMENT_LABELS label are filtered out in SQL. That list leaves out "Exchange", unlike Transaction's, because exchanging one security for another can be a real disposal. Trade#realized_gain_loss also returns nil for these, so neither check is needed alone.
  2. A gain converts at the rate on its trade date, never today's rate. It converts from the currency its basis is held in, which is the holding's currency. That is where Trade#realized_gain_loss puts it since #3616, and it is not always the trade's currency. So the figure is the gain in the holding's currency at the sale date's rate: the exchange-rate move on the cost while the position was held is not in it. It is not a home-currency cost-basis gain, and can differ from a tax figure computed that way. This PR has no user-facing copy; the model comment says so, and the card that reads it should too.
  3. A missing rate is not a rate of 1. ExchangeRate.rates_for ends in rate&.rate || 1, so it is not used. A gain converts at the rate stored for its sale date, else the nearest earlier one up to ExchangeRate::Provided::NEAREST_RATE_LOOKBACK_DAYS (5) before it, the window ExchangeRate.find_or_fetch_rate reuses; never a later day's. One query, bounded to those days. A gain with no rate in that window is excluded as missing_exchange_rate. (The proceeds-to-basis rate inside Trade#realized_gain_loss is unchanged: it still reads the exact entry date.)
  4. A disposal with no measurable gain is excluded, not counted as zero. When Trade#realized_gain_loss is nil because the cost basis is unknown or the proceeds have no rate, the disposal is excluded as gain_unknown.

The gain is Trade#realized_gain_loss: in an account that sells by fifo, the cost of the lots the sale consumed; otherwise the holding's average cost at the time of the sale. A fifo sale whose stored lots do not add up to its position (HoldingLot.in_partition) has no readable record of what it consumed. main already gives it a nil gain rather than pricing it off the snapshot, and this class counts it as gain_unknown. The class header says so.

A disabled account's disposals after its cut-off date are left out. active_until_dates takes the same values as Balance::ChartSeriesBuilder's account_active_until_dates, a Date or an ISO string (the builder hands them to SQL as JSON, so it accepts both). They are normalised with to_date and keyed by string id.

Queries: Trade.preload_realized_gains reads, once for the whole set, each sale's basis snapshot (with the average-cost fallback for a snapshot that has no stored basis), the lots each fifo sale consumed, and the proceeds-to-basis rates. Then one query reads the target rates. The query count does not grow with the number of disposals, average or fifo.

app/models/trade.rb (+31 / −16):

  • Trade.preload_realized_gains(trades): Trade.preload_basis_holdings, then HoldingLotDisposal.readable_by_sale assigned through preloaded_lot_disposals=, then Trade.preload_exchange_rates. The snapshots go first because the rate preload keys on the currency each position is carried in. All three are on main; this gathers them so the two callers cannot drift apart.
  • Trade.preload_exchange_rates now stores a pair it looked for and did not find as nil, and the proceeds conversion takes a stored nil as the answer instead of running its own find_by. A missing rate still leaves the gain unknown; it no longer costs a query per disposal.
  • snapshot_cost reads basis_holding&.avg_cost once. The comments on preloaded_lot_disposals= and HoldingLotDisposal.readable_by_sale (+3 / −2, comment only) now say a fifo sale with no record has an unknown gain.

app/controllers/reports_controller.rb (+3 / −11): #build_gains_by_tax_treatment replaces its three preload steps (basis snapshots, lot disposals, rates) with one Trade.preload_realized_gains call. The reads and their order are the same, so the card's figures do not change.

Blast radius. Portfolio::RealizedGains is new and has no callers. Trade.preload_realized_gains has two: RealizedGains#sell_trades and ReportsController#build_gains_by_tax_treatment. Both pass sell trades with entry and account loaded, which readable_by_sale expects. The nil entries preload_exchange_rates now writes are read only by the proceeds conversion (Trade#exchange_rate_on_entry_date), and in app code preload_exchange_rates is called only from the new helper. A pair the preload did not ask about is still absent and still takes its own lookup ("a disposal whose pair the preload did not ask about still takes its lookup").

Siblings. A grep for qty < 0 finds one other reader of realised gains: ReportsController#build_gains_by_tax_treatment, which already filters Trade::INTERNAL_MOVEMENT_LABELS, and which #4409 makes filter entries.excluded = false too, the rule this class now applies. Its zero fold is deliberately not changed here: that is a Reports behaviour change and needs its own PR. The other matches do not compute gains. InvestmentStatement::Totals and Portfolio::FlowClassifier use qty < 0 for cash-flow direction.

Left out on purpose:

  • Tax-treatment grouping, which Reports already does, and wash-sale accounting. Which lots a sale consumed comes from the account's cost basis method: the stored lot disposals under fifo, the average cost otherwise.
  • Pre-existing behaviour in Trade and Holding, unchanged here: in an average-cost account, a sale larger than the position is measured as avg_cost × qty against a basis that does not cover it, and a computed basis is not adjusted for a split.
  • Any UI, and the InvestmentStatement wrapper (see above).

Tests

test/models/portfolio/realized_gains_test.rb (30 tests), and three tests added to test/models/trade_test.rb. They use the families(:empty) fixture and build their own records.

Added after the adversarial review, on a446d5fc3:

  • an excluded disposal is not realised: an excluded sale of 2 at 150 against a basis of 100, and a kept sale of 1 at 130 in April. Net is 30 (not 130), only April has a bucket, and nothing is reported excluded.
  • a cut-off date given as an ISO string is honoured: the cut-off test with @march.iso8601; net 50. It raised ArgumentError: comparison of Date with String failed before.
  • a holding with no stored cost basis measures its gain from the buys behind it: 5 bought at 100, a snapshot with cost_basis: nil, 2 sold at 150. Net 100, nothing gain_unknown.

Fail-first. The branch's two test files, run against current main (11441f354) without the change: 62 runs, 1 failure, 30 errors. All 30 tests in realized_gains_test.rb error with NameError: uninitialized constant Portfolio::RealizedGains. In trade_test.rb, "preloading answers a disposal whose date has no rate without a lookup of its own" fails with Expected 1, Actual 5 ("four disposals with no rate cost one query, not five"). The other two added Trade tests pass on main: "a disposal whose pair the preload did not ask about still takes its lookup" pins a fallback this PR keeps, and main already has the preloaded_holdings= writer that "assigning preloaded holdings re-derives a realised figure already taken" checks. The errors show only that the class is missing; the mutation table below is the evidence that each test checks behaviour. Of the three added tests, the excluded and ISO-string tests failed on 26ffe9a76 (a failure and an ArgumentError). The no-basis test passed there, as it should: it covers a path that already worked and had no test; mutation 17 shows it catches a break.

Mutations. Each was applied to the committed code alone, run against the test file(s), then reverted.

#MutationCaught by
1drop the internal movement label filtera transfer out is not a realised sale
2filter Transaction::INTERNAL_MOVEMENT_LABELS instead of Trade'sa security exchange is still a disposal
3convert at today's ratea foreign currency gain converts at its own trade date; a gain converts from the currency its basis is carried in
4parity when the rate is missinga gain with no exchange rate on or before its trade date is excluded and counted
5count an unmeasurable disposal as a zero gain3 tests (no cost basis; proceeds not convertible; all excluded still reports)
6convert from the trade's currency instead of the basis currencya disposal priced in another currency is measured in its basis currency; a gain converts from the currency its basis is carried in
7no holdings preloadthe query count does not grow with the number of disposals
8ignore the cut-off datea disposal after an account's cut-off date does not count
9any? reads buckets onlya period whose only disposals are all excluded still reports itself
10losses keep their signa disposal below cost is a loss; gains and losses in one month are reported separately
12no period filtera disposal outside the period does not count
13no account filteranother account's disposals do not count
14no Trade.preload_exchange_ratesgot through at first; now caught by "the query count does not grow with foreign-priced disposals" (6 against 10)
15drop excluded: falsean excluded disposal is not realised
16only compact the cut-offs (no to_date)a cut-off date given as an ISO string is honoured (ArgumentError)
17preload only holdings with a stored cost_basisa holding with no stored cost basis measures its gain from the buys behind it
18exact date only (no lookback)a gain on a day with no rate converts at the nearest earlier one; the nearest earlier rate is used only within the lookback window; the query count does not grow with gains converted at an earlier day's rate
19window one day too longthe nearest earlier rate is used only within the lookback window
20a later day's rate alloweda gain with no exchange rate on or before its trade date is excluded and counted
21oldest rate in the window instead of nearesta gain on a day with no rate converts at the nearest earlier one

Validation

  • Full suite (bin/rails test) on c5a487dfa, after the missing-rate preload fix (2bedc7dff, 506b1bff6) and merging main: 14,260 runs, 65,729 assertions, 0 failures, 0 errors, 37 skips.
  • Full suite (bin/rails test) on 26ffe9a76: 12,665 runs, 58,505 assertions, 0 failures, 0 errors, 36 skips. On a446d5fc3: realized_gains_test.rb, trade_test.rb and reports_controller_test.rb together, 0 failures; CI's test_unit is the full-suite run for this head.
  • Lint: bin/rubocop on the changed files finds no offenses. There are no ERB, JS or system-test changes.
  • Brakeman: bin/brakeman --no-pager -q reports 0 warnings.
  • AGENTS.md: the logic is a model PORO under app/models/portfolio/, beside the other programme classes. The tests use Minitest with a fixture family. There are no new dependencies, no UI, no user-facing strings and no API changes. The commit subjects are imperative and at most 72 characters.

Migration notes

None. No schema change.