Count dividend and interest income in investment totals
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. |
Net investment income by sign | @jaysbeekay | Sums income signed, so a charge or reversal labelled as income reduces it (review feedback). |
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 first commit, 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.
My second commit, from review: dividends and interest were summed as ABS(amount), so an outflow carrying an income label (a margin-interest charge, a dividend reversal) was added to income. Portfolio::FlowClassifier decides income by label, not sign, and requires a signed sum. The two columns are now -SUM(amount * rate): income is stored as a negative amount, so the negation keeps ordinary income positive and nets a charge against it. A $100 dividend and a $30 reversal report $70. Contributions and withdrawals keep ABS; they split by trade direction and are unchanged from main. The relabelled-buy test now expects -120 income for a buy relabelled Dividend: it is still kept out of contributions, and its cash left the account.
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. -
Fail first (signs).
income nets by sign, so a charge or reversal labelled as income reduces itfailed on5ea4c4dba: dividends came out at 130 (100 + 30 underABS) instead of 70. -
Mutations of my commits, 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 contributiondividendsback toSUM(ABS(...))income nets by sign, ...and the relabelled-buy testinterestback toSUM(ABS(...))income nets by sign, ...Dropping 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, so the change to signed sums moves no figure a user sees; PeriodTotals#total_income is dividends + interest and nets the same way.
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.
Summary by CodeRabbit
- Bug Fixes
- Investment statement totals now include dividend and interest income from eligible trades and transactions.
- Income-labeled trades are excluded from contribution and withdrawal totals; other trades remain classified by direction.
- Income in other currencies is converted using available exchange-rate data.
- Only posted, in-period income is included, and cash transactions and transfers do not affect trade contribution or withdrawal totals.