Add a monthly realised gains model for investment accounts
Part of #4078
What: adds Portfolio::RealizedGains, which groups a set of accounts' disposals in a period by the month they were realised, in a given currency: gains, losses (as a magnitude) and trade count per month, plus totals. A disposal it cannot measure is excluded and counted (excluded_trades: gain_unknown, missing_exchange_rate), never folded in as zero. Under fifo a sale's gain is the cost of the lots it consumed, and a fifo sale with no readable lot record is excluded as gain_unknown. Adds Trade.preload_realized_gains, which reads what Trade#realized_gain_loss needs for a whole set of sales in a fixed number of queries; RealizedGains and ReportsController both call it.
Why: Sure reports realised gains only as one period total by tax treatment, computed in the controller, and nothing says when a gain was realised. That total also counts an unmeasurable disposal as zero without saying so.
Start reading: Portfolio::RealizedGains#measure!, #converted and #target_rates in app/models/portfolio/realized_gains.rb, then Trade.preload_realized_gains in app/models/trade.rb.
Key tests (test/models/portfolio/realized_gains_test.rb, test/models/trade_test.rb):
- "a sale is bucketed in the month it was realised"
- "a transfer out is not a realised sale"
- "a gain with no exchange rate on or before its trade date is excluded and counted"
- "a gain on a day with no rate converts at the nearest earlier one"
- "the query count does not grow with the number of disposals"
- "a fifo sale whose lots do not add up to its position is excluded as gain unknown"
Behaviour change: none for users; the model has no caller and no UI. A gain converts from its basis currency at the sale date's rate (or the nearest earlier one within 5 days), so the FX move on the cost while held is not in it. The Reports total's zero fold is deliberately left for its own PR. No migration.
Independent: branched from main; depends on no open PR. The InvestmentStatement#realized_gains wrapper that reads it waits for #4087.
Builds on #4900 and #4903 (merged): main has Trade#preloaded_holdings=, Trade.preload_basis_holdings (which runs Holding.preload_avg_costs), Trade#preloaded_lot_disposals= and HoldingLotDisposal.readable_by_sale. The branch merges main at fc524ae19 and reuses them. Preloading the fifo lot disposals, which arnaurodondev noted, is part of this PR rather than a follow-up.
Size: +289 / −29 outside tests, across 4 files (+862 / −29 with tests).
Fork pre-flight: jaysbeekay/sure#534, from the same branch.
Full description and evidence
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.
Branched from main at 3ae36a699. It depends on nothing open: not on the returns engine PRs (the returns stack that replaced #4197: #5129 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, 236 lines including comments). 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: oneBucket(month, gains, losses, trade_count)per month that had a disposal, oldest first.lossesis a positive amount and#netcarries 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.
It applies four rules, each one already in the codebase:
- A transfer out is not a sale. It has a negative
qtytoo. Disposals with aTrade::INTERNAL_MOVEMENT_LABELSlabel are filtered out in SQL. That list leaves out "Exchange", unlikeTransaction's, because exchanging one security for another can be a real disposal.Trade#realized_gain_lossalso returns nil for these, so neither check is needed alone. - 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_lossputs 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. - A missing rate is not a rate of 1.
ExchangeRate.rates_forends inrate&.rate || 1, so it is not used. A gain converts at the rate stored for its sale date, else the nearest earlier one up toExchangeRate::Provided::NEAREST_RATE_LOOKBACK_DAYS(5) before it, the windowExchangeRate.find_or_fetch_ratereuses; never a later day's. One query, bounded to those days. A gain with no rate in that window is excluded asmissing_exchange_rate. (The proceeds-to-basis rate insideTrade#realized_gain_lossis unchanged: it still reads the exact entry date.) - A disposal with no measurable gain is excluded, not counted as zero. When
Trade#realized_gain_lossis nil because the cost basis is unknown or the proceeds have no rate, the disposal is excluded asgain_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.
A disabled account's disposals after its cut-off date are left out. active_until_dates has the same shape as Balance::ChartSeriesBuilder's account_active_until_dates.
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, thenHoldingLotDisposal.readable_by_saleassigned throughpreloaded_lot_disposals=, thenTrade.preload_exchange_rates. The snapshots go first because the rate preload keys on the currency each position is carried in. All three are onmain; this gathers them so the two callers cannot drift apart.Trade.preload_exchange_ratesnow 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 ownfind_by. A missing rate still leaves the gain unknown; it no longer costs a query per disposal.snapshot_costreadsbasis_holding&.avg_costonce. The comments onpreloaded_lot_disposals=andHoldingLotDisposal.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. 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.
- Any UI, and the
InvestmentStatementwrapper (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.
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 foreign-disposal query-count test was added after mutation 14 below got through. Its fail-first evidence is that mutation: 6 queries against 10.
Mutations. Each was applied to the committed code alone, run against both test files, then reverted with git checkout HEAD -- app.
| # | Mutation | Caught by |
|---|---|---|
| 1 | drop the internal movement label filter | a transfer out is not a realised sale |
| 2 | filter Transaction::INTERNAL_MOVEMENT_LABELS instead of Trade's | a security exchange is still a disposal |
| 3 | convert at today's rate | a foreign currency gain converts at its own trade date; a gain converts from the currency its basis is carried in |
| 4 | parity when the rate is missing | a gain with no exchange rate on or before its trade date is excluded and counted |
| 5 | count an unmeasurable disposal as a zero gain | 3 tests (no cost basis; proceeds not convertible; all excluded still reports) |
| 6 | convert from the trade's currency instead of the basis currency | a disposal priced in another currency is measured in its basis currency; a gain converts from the currency its basis is carried in |
| 7 | no holdings preload | the query count does not grow with the number of disposals |
| 8 | ignore the cut-off date | a disposal after an account's cut-off date does not count |
| 9 | any? reads buckets only | a period whose only disposals are all excluded still reports itself |
| 10 | losses keep their sign | a disposal below cost is a loss; gains and losses in one month are reported separately |
| 12 | no period filter | a disposal outside the period does not count |
| 13 | no account filter | another account's disposals do not count |
| 14 | no Trade.preload_exchange_rates | got through at first; now caught by "the query count does not grow with foreign-priced disposals" (6 against 10) |
| 15 | exact 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 |
| 16 | window one day too long | the nearest earlier rate is used only within the lookback window |
| 17 | a later day's rate allowed | a gain with no exchange rate on or before its trade date is excluded and counted |
| 18 | oldest rate in the window instead of nearest | a gain on a day with no rate converts at the nearest earlier one |
Validation
- Full suite (
bin/rails test) onc5a487dfa, after the missing-rate preload fix (2bedc7dff,506b1bff6) and mergingmain: 14,260 runs, 65,729 assertions, 0 failures, 0 errors, 37 skips. - Full suite (
bin/rails test) on26ffe9a76: 12,665 runs, 58,505 assertions, 0 failures, 0 errors, 36 skips. - Lint:
bin/rubocopon the five changed files finds no offenses. There are no ERB, JS or system-test changes. - Brakeman:
bin/brakeman --no-pager -qreports 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.
Summary by CodeRabbit
- New Features
- Added monthly realized gains and losses reporting, with gain and loss totals, net results, trade counts, and counts of trades excluded because gains or exchange rates could not be determined.
- Reports use the sale-date exchange rate for foreign-currency gains and respect the selected period, account limits, and cutoff dates. Internal-movement trades are excluded.
- Bug Fixes
- Realized gain and loss figures now recalculate when holdings change, avoiding outdated results.