Count dividend and interest income in investment totals

Closed
JA
2mo ago
+352-7

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 head c639ed665 and upstream main. Nothing here is left to send.
  • Fork main gets it through the next upstream sync. Fork main's own InvestmentStatement::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-totals is 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 fees column. Fees go in a separate PR.
  • The income labels are the literal list ('Dividend', 'Interest') rather than Portfolio::FlowClassifier.labels_for(:income), because the classifier is unmerged upstream (we-promise/sure#3557). This list matches labels_for(:income) on origin/up/pending-sql-parity, which is %w[Dividend Interest].
  • Pending is Transaction.pending_providers_sql("transactions"), upstream main's raw-SQL predicate, not FlowClassifier.pending_sql. The non-boolean pending-flag hardening arrives with we-promise/sure#3557.
  • The direction guard is vdusart's income_label_sql, which reads trades only. Fork main's is income_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's v4.
  • Tests: dividends and interest count the transaction shapes providers write and contributions and withdrawals count trades only, not external cash transactions are ported with their names unchanged. The first drops a fork issue reference from a comment. The second drops its totals.fees assertion and has its comment rewritten without FlowClassifier/contract references. Their helpers are private methods in the test file, with bodies identical to fork main's PortfolioFlowTestHelper. One new test, trades_count counts trades, not the income transactions read beside them, is not on fork main; it was added because the COUNT(entries.id) mutation survived without it. totals aggregate directly from trade entries gets the same FROM entries LEFT JOIN trades string 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

CommitAuthorWhat it does
fix(investments): report real dividend and interest totals (1 of 2)@vdusartAggregates 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)@vdusartExcludes the income labels from the contribution and withdrawal branches, so a buy relabelled Dividend is counted once.
Count investment income stored as a Transaction@jaysbeekayReads 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 trades becomes LEFT JOIN trades, plus LEFT JOIN transactions. A WHERE clause keeps every trade, as before. Of the transactions, it admits only those labelled Dividend or Interest that are not pending.
  • The dividends and interest columns 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 predicate IncomeStatement's raw SQL already uses, so "pending" means the same thing here as there.
  • Nothing else changes. A transaction has no trades row, so trades.qty is NULL and it never reaches the contribution or withdrawal branches. vdusart's income-label guard on those branches is unchanged, and trades_count still counts trades.id.
  • The cache key stays at vdusart's v2. v2 has never been released, so no cache holds a v2 entry built from the trades-only query.

These providers write income as a labelled Transaction; I checked each processor on current main:

ProviderWhereShape
Trading212Trading212Account::ActivitiesProcessor#process_dividend, #process_cash_transactionimport_transaction with investment_activity_label: "Dividend" / "Interest", security id in extra
IBKRIbkrAccount::ActivitiesProcessor#process_cash_transactionimport_transaction, Dividend / Interest, extra.security_id
QuestradeQuestradeAccount::ActivitiesProcessor#process_cash_activity"Dividends" => "Dividend", "Interest" => "Interest", extra.security_id
SnapTradeSnaptradeAccount::ActivitiesProcessor#process_cash_activityDIVIDEND, DIV, DISTRIBUTION, ... → Dividend; INTEREST → Interest
Indexa CapitalIndexaCapitalAccount::ActivitiesProcessor#process_cash_activityDIVIDEND / DIV → Dividend, INTEREST → Interest
KrakenKrakenAccount::LedgerProcessor#process_ledger_entryfiat 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::TransactionsProcessor writes a cash dividend as a qty-0 trade with amount 0 * 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 ::boolean cast in pending_providers_sql raises on a pending flag PostgreSQL cannot parse, for example "maybe". This aggregation now reads transactions, so it is exposed to that the way IncomeStatement already 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)

  1. How should pre-#1311 dividend transactions be treated? Instances that upgraded across #1311 have dividend history split in two: Transaction rows before the upgrade, Trade rows 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_label plus extra["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?

  1. 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::TransactionsProcessor is 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?

  2. Should dividends appear in IncomeStatement too?
    All three IncomeStatement stat classes hard-join entryable_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?

  3. Should Reinvestment count as dividend income, and if so what happens to contributions? Per the reasoning above, the two are coupled: counting reinvested distributions as income requires deciding whether contributions means all buys or only external inflows. If contributions are meant to be external only, then Reinvestment (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 to total_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 write failed 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:

    MutationCaught by
    drop the pending exclusiondividends and interest count the transaction shapes providers write
    read the label from trades onlysame
    LEFT JOIN trades back to JOIN tradessame, and totals aggregate directly from trade entries
    let a transaction reach the contribution branch (COALESCE(trades.qty, 1) > 0)same two
    the above, plus admitting every transactionadds contributions and withdrawals count trades only, not external cash transactions
    trades_count as COUNT(entries.id)trades_count counts trades, not the income transactions read beside them
    drop Interest from the transaction label listthe transaction-shapes and trades_count tests
    remove vdusart's income-label guard from the contribution brancha buy relabeled to Dividend is counted as income only, not also as a contribution

    Dropping the label narrowing on its own changes no figure, and no test catches it. That is by design: the CASE checks the label again, and a transaction's trades.qty is NULL. The narrowing only limits which rows are scanned.

  • bin/rails test on c639ed665 (upstream main at 275f2f994): 11361 runs, 48408 assertions, 0 failures, 0 errors, 34 skips.

  • test/models/investment_statement_test.rb: 35 runs, 0 failures.

  • bin/rubocop on 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_totals reads Contribution / Withdrawal transactions, never Dividend / Interest, and excludes pending with excluding_pending, the same ::boolean IS DISTINCT FROM true family of predicate. It is left alone, and its figures do not overlap these.
  • IncomeStatement (ScopedTransactionsQuery#investment_activity_label_sql) excludes only Transfer, Sweep In, Sweep Out and Exchange. A dividend stored as a Transaction is therefore already counted there as ordinary income, while one stored as a Trade is not. This PR leaves IncomeStatement untouched. Whether the two should agree is vdusart's question 3.
  • InvestmentStatement::Totals itself: income_label_sql (vdusart's guard) still reads trades only. That is deliberate, because only a trade can reach the direction branches.