Count dividend and interest income in investment totals
Closed as merged upstream, 2026-10-12, on the owner's instruction ("Close #379 and #360 as merged upstream"). we-promise/sure#4082 was merged into upstream main as bc14f6993 "Count dividend and interest income in investment totals (#4082)". It is on mirror/upstream-main at d55eac220.
- Checked before closing: every file this branch changes (
app/models/investment_statement.rb,app/models/investment_statement/totals.rb,test/models/investment_statement_test.rb) is identical between this PR's headc639ed665and upstreammain. Nothing here is left to send. - Fork
maingets it through the next upstream sync. Forkmain's ownInvestmentStatement::Totals(from #133) differs on purpose, as listed below, so that sync will need those differences resolved by hand. - #119 (drop 0.4) and #123 stay open: this PR was only "Part of" them.
- The branch
up/investment-income-totalsis left in place. This session cannot delete branches.
Part of #119 (drop 0.4)
Part of #123
Upstream pre-flight for drop 0.4 of #119: dividend and interest totals, adopting we-promise/sure#3350 by @vdusart, who agreed on 2026-10-08 to hand it over (https://github.com/we-promise/sure/pull/3350#issuecomment-6058213993). Upstream PR: we-promise/sure#4082 (opened 2026-10-09). Same branch, same commit. Base is mirror/upstream-main, which equals upstream main at 275f2f994, so the diff below is what upstream will see.
Commits: vdusart's two commits (b7c79c752, 87c8e6ea5), rebased unchanged with the author kept (range-diff =), then two of ours (5ea4c4dba, and c639ed665 from upstream review: income summed signed rather than as ABS, per Portfolio::FlowClassifier's contract, so a charge or reversal labelled as income reduces it). No fees, and Portfolio::FlowClassifier itself is not called.
Divergences from fork main's InvestmentStatement::Totals (from #133), all deliberate:
- No
feescolumn. Fees go in a separate PR. - The income labels are the literal list
('Dividend', 'Interest')rather thanPortfolio::FlowClassifier.labels_for(:income), because the classifier is unmerged upstream (we-promise/sure#3557). This list matcheslabels_for(:income)onorigin/up/pending-sql-parity, which is%w[Dividend Interest]. - Pending is
Transaction.pending_providers_sql("transactions"), upstreammain's raw-SQL predicate, notFlowClassifier.pending_sql. The non-boolean pending-flag hardening arrives with we-promise/sure#3557. - The direction guard is vdusart's
income_label_sql, which readstradesonly. Fork main's isincome_or_fee_sql. - Transactions are narrowed to income labels only, without fee labels or transfer fee legs.
- The cache key is
totals_query/v2(vdusart's), not fork main'sv4. - Tests:
dividends and interest count the transaction shapes providers writeandcontributions and withdrawals count trades only, not external cash transactionsare ported with their names unchanged. The first drops a fork issue reference from a comment. The second drops itstotals.feesassertion and has its comment rewritten without FlowClassifier/contract references. Their helpers are private methods in the test file, with bodies identical to fork main'sPortfolioFlowTestHelper. One new test,trades_count counts trades, not the income transactions read beside them, is not on fork main; it was added because theCOUNT(entries.id)mutation survived without it.totals aggregate directly from trade entriesgets the sameFROM entries LEFT JOIN tradesstring change fork main made.
Dependency. This has no prerequisite. It overlaps we-promise/sure#3983 (our missing-FX-rate PR), which rewrites the same COALESCE(er.rate, 1) lines in totals.rb. Whichever merges second needs a rebase.
Upstream issue: we-promise/sure#4078 (part 2). The upstream PR continues we-promise/sure#3350 and also names the coordination issue we-promise/sure#3494.
In the description below, a bare #N means we-promise/sure, as it will be posted there.
Part of #4078 (part 2). Programme: #3494.
Continues #3350 by @vdusart, who asked me to take it over (their comment). Their two commits are carried unchanged and still authored by them. One follow-up commit of mine closes the gap I described on #3350 on 10 September. Once this is open, #3350 can be closed in its favour.
Fork pre-flight: jaysbeekay/sure#379 (same branch, same commit).
Summary
InvestmentStatement::Totals reports dividends: 0 and interest: 0 for every family. That comment was accurate until #1311, which moved investment income to Trade records with qty: 0 and price: 0. vdusart's commits make the totals read those income trades. My follow-up also counts the same income when a provider stores it as a Transaction carrying the Dividend or Interest label, which several providers do.
Commits
| Commit | Author | What it does |
|---|---|---|
fix(investments): report real dividend and interest totals (1 of 2) | @vdusart | Aggregates dividends and interest by trades.investment_activity_label, and bumps the totals cache key to v2. |
fix(investments): report real dividend and interest totals (2 of 2) | @vdusart | Excludes the income labels from the contribution and withdrawal branches, so a buy relabelled Dividend is counted once. |
Count investment income stored as a Transaction | @jaysbeekay | Reads income from labelled Transaction entries too. |
Rebase. vdusart's commits were rebased onto current main with no change to their content: git range-diff reports both patches as identical (=). The only conflict was textual, in test/models/investment_statement_test.rb. Upstream main had added a private helper, create_trade_for, at the same spot where #3350 added create_income_trade. Both helpers are kept, upstream's first.
What changed
My commit only, in app/models/investment_statement/totals.rb:
JOIN tradesbecomesLEFT JOIN trades, plusLEFT JOIN transactions. AWHEREclause keeps every trade, as before. Of the transactions, it admits only those labelledDividendorInterestthat are not pending.- The
dividendsandinterestcolumns read the label from whichever of the two tables the entry belongs to:COALESCE(trades.investment_activity_label, transactions.investment_activity_label). - Pending transactions are excluded with
Transaction.pending_providers_sql("transactions"). That is the predicateIncomeStatement's raw SQL already uses, so "pending" means the same thing here as there. - Nothing else changes. A transaction has no
tradesrow, sotrades.qtyis NULL and it never reaches the contribution or withdrawal branches. vdusart's income-label guard on those branches is unchanged, andtrades_countstill countstrades.id. - The cache key stays at vdusart's
v2.v2has never been released, so no cache holds av2entry built from the trades-only query.
These providers write income as a labelled Transaction; I checked each processor on current main:
| Provider | Where | Shape |
|---|---|---|
| Trading212 | Trading212Account::ActivitiesProcessor#process_dividend, #process_cash_transaction | import_transaction with investment_activity_label: "Dividend" / "Interest", security id in extra |
| IBKR | IbkrAccount::ActivitiesProcessor#process_cash_transaction | import_transaction, Dividend / Interest, extra.security_id |
| Questrade | QuestradeAccount::ActivitiesProcessor#process_cash_activity | "Dividends" => "Dividend", "Interest" => "Interest", extra.security_id |
| SnapTrade | SnaptradeAccount::ActivitiesProcessor#process_cash_activity | DIVIDEND, DIV, DISTRIBUTION, ... → Dividend; INTEREST → Interest |
| Indexa Capital | IndexaCapitalAccount::ActivitiesProcessor#process_cash_activity | DIVIDEND / DIV → Dividend, INTEREST → Interest |
| Kraken | KrakenAccount::LedgerProcessor#process_ledger_entry | fiat staking → Dividend, earn → Interest, written as Transaction entryables |
(Kraken's crypto staking rewards are Trades with amount 0. They were already read by vdusart's commits and are unchanged here.)
The label list is literal, ('Dividend', 'Interest'), the same pair vdusart's guard uses.
Deliberately out of scope
- Fees. Investment fees are not part of this PR. They will come separately.
- Plaid dividends. As vdusart noted, these still report 0.
PlaidAccount::Investments::TransactionsProcessorwrites a cash dividend as a qty-0 trade with amount0 * price, so the cash is lost at import time and no reader can recover it. The fix belongs in the processor. Reinvestment. This label stays in contributions and out of dividends, which is vdusart's question 4 below.- Pending flags that are not booleans. The
::booleancast inpending_providers_sqlraises on a pending flag PostgreSQL cannot parse, for example"maybe". This aggregation now reads transactions, so it is exposed to that the wayIncomeStatementalready is. It uses the same predicate rather than a different one, and #3557 replaces that predicate for every reader at once.
Questions for maintainers (carried over unchanged from #3350)
- How should pre-#1311 dividend transactions be treated? Instances that upgraded across #1311 have dividend history split in two:
Transactionrows before the upgrade,Traderows after. #1311 deliberately left the transactions table untouched, so no backfill exists. Options as I see them:
- leave them as-is and accept that investment income aggregates cover only post-upgrade data;
- have the aggregate also read dividend-labelled Transactions (via
investment_activity_labelplusextra["security_id"]), which makes history complete but entrenches two storage shapes; - offer a migration path.
I've kept this PR to trades-only rather than pick one. Which direction do you prefer?
-
Should provider-delivered dividends be normalized to Trades? Trading212 has a ticker and could resolve a security; SimpleFIN structurally cannot (which is why
SimplefinAccount::Investments::TransactionsProcessoris a no-op). So full normalization isn't reachable for every provider — is forward-only normalization where a security is resolvable worth doing, or should the readers handle both shapes instead? -
Should dividends appear in
IncomeStatementtoo?
All threeIncomeStatementstat classes hard-joinentryable_type = 'Transaction', so dividend income is currently absent from reports, budgets and category breakdowns.
Is investment income intended to be reported separately from ordinary income, or should it flow into both? -
Should
Reinvestmentcount as dividend income, and if so what happens tocontributions? Per the reasoning above, the two are coupled: counting reinvested distributions as income requires deciding whethercontributionsmeans all buys or only external inflows. If contributions are meant to be external only, thenReinvestment(and arguably the internal-movement labels) should leave that bucket regardless of this PR, I can do that as a follow-up. If contributions are meant to be all buys, then reinvested distributions can only be surfaced as a separate figure rather than added tototal_dividends. Which is intended?
Note from @jaysbeekay on questions 1 and 3: the questions above are vdusart's original wording. The "trades-only" in question 1 describes their two commits. My follow-up commit takes question 1's second option for any Transaction carrying the Dividend or Interest label, because that is how the providers in the table above store income today. If you prefer another direction, that commit can be dropped on its own and vdusart's two still stand. On question 3, a dividend stored as a Transaction already reaches IncomeStatement (see Blast radius). Only the Trade shape is absent there.
Demo data
No new demo data. The values surface through InvestmentStatement#totals (dividends, interest, total_income) and through #total_dividends and #total_interest.
Migration notes
None. There is no schema change. The totals cache key is versioned (totals_query/v2), so no warm cache serves the old zeros.
Verification
-
Fail first.
dividends and interest count the transaction shapes providers writefailed on vdusart's head for the right reason: it counted 50, the income trade only, and missed the 12.50 dividend stored as a transaction. -
Mutations of my commit, each caught by a test:
Mutation Caught by drop the pending exclusion dividends and interest count the transaction shapes providers writeread the label from trades only same LEFT JOIN tradesback toJOIN tradessame, and totals aggregate directly from trade entrieslet a transaction reach the contribution branch ( COALESCE(trades.qty, 1) > 0)same two the above, plus admitting every transaction adds contributions and withdrawals count trades only, not external cash transactionstrades_countasCOUNT(entries.id)trades_count counts trades, not the income transactions read beside themdrop Interestfrom the transaction label listthe transaction-shapes and trades_counttestsremove vdusart's income-label guard from the contribution branch a buy relabeled to Dividend is counted as income only, not also as a contributionDropping the label narrowing on its own changes no figure, and no test catches it. That is by design: the
CASEchecks the label again, and a transaction'strades.qtyis NULL. The narrowing only limits which rows are scanned. -
bin/rails testonc639ed665(upstreammainat275f2f994): 11361 runs, 48408 assertions, 0 failures, 0 errors, 34 skips. -
test/models/investment_statement_test.rb: 35 runs, 0 failures. -
bin/rubocopon the changed files: no offences.bin/brakeman: no warnings. There are no ERB, JS or API changes.
Blast radius
Who else hits this line, and what do they pass? InvestmentStatement#totals_query is the only caller of Totals. It passes the family's visible investment account ids and a period range. Its readers are InvestmentStatement#totals, which feeds the dashboard's _investment_summary and ReportsController#build_investment_metrics, and #total_dividends / #total_interest, which read the all-time totals. The dashboard and reports read only contributions, withdrawals and trades_count. The tests above pin all three and they do not move. Today nothing in app/ renders dividends or interest.
What else reads what I just changed the reading of? grep -rn "investment_activity_label" app/models, looking for readers of labelled transactions in investment accounts:
InvestmentFlowStatement#period_totalsreadsContribution/Withdrawaltransactions, neverDividend/Interest, and excludes pending withexcluding_pending, the same::boolean IS DISTINCT FROM truefamily of predicate. It is left alone, and its figures do not overlap these.IncomeStatement(ScopedTransactionsQuery#investment_activity_label_sql) excludes onlyTransfer,Sweep In,Sweep OutandExchange. A dividend stored as aTransactionis therefore already counted there as ordinary income, while one stored as aTradeis not. This PR leavesIncomeStatementuntouched. Whether the two should agree is vdusart's question 3.InvestmentStatement::Totalsitself:income_label_sql(vdusart's guard) still readstradesonly. That is deliberate, because only a trade can reach the direction branches.