Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Count dividend and interest income in investment totals (#4082)

jaysbeekaybc14f6993547
diff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rb
index e78b4bbb20..31046e5b03 100644
--- a/app/models/investment_statement.rb
+++ b/app/models/investment_statement.rb
@@ -387,7 +387,7 @@ class InvestmentStatement
account_ids_hash = Digest::MD5.hexdigest(account_ids.sort.join(","))
Rails.cache.fetch([
- "investment_statement", "totals_query", family.id, user&.id,
+ "investment_statement", "totals_query/v2", family.id, user&.id,
account_ids_hash, date_range.begin, date_range.end, family.entries_cache_version
]) { Totals.new(family, account_ids: account_ids, date_range: date_range).call }
end
diff --git a/app/models/investment_statement/totals.rb b/app/models/investment_statement/totals.rb
index 9d8efffa15..cd44bfa0b9 100644
--- a/app/models/investment_statement/totals.rb
+++ b/app/models/investment_statement/totals.rb
@@ -13,8 +13,8 @@ class InvestmentStatement::Totals
{
contributions: result["contributions"]&.to_d || 0,
withdrawals: result["withdrawals"]&.to_d || 0,
- dividends: 0, # Dividends come through as transactions, not trades
- interest: 0, # Interest comes through as transactions, not trades
+ dividends: result["dividends"]&.to_d || 0,
+ interest: result["interest"]&.to_d || 0,
trades_count: result["trades_count"]&.to_i || 0
}
end
@@ -40,19 +40,49 @@ class InvestmentStatement::Totals
# Aggregate trades by direction (buy vs sell)
# Buys (qty > 0) = contributions (cash going out to buy securities)
# Sells (qty < 0) = withdrawals (cash coming in from selling securities)
+ #
+ # Investment income (dividends, interest) is aggregated by activity label
+ # rather than by direction. Since #1311 these are recorded as Trades with
+ # qty: 0 and price: 0 (Trade::CreateForm#create_income_trade).
+ #
+ # Several providers store the same income as a Transaction carrying the
+ # same label instead (Trading212, IBKR, Questrade, SnapTrade, Indexa
+ # Capital, Kraken's fiat staking and earn rows), so income reads the label
+ # from whichever of the two the entry is. Only those labelled
+ # Transactions are joined in, and pending ones are left out until they
+ # post. A Transaction has no trades row, so it never reaches the
+ # direction branches or trades_count.
+ #
+ # Income is summed signed and then negated, as Portfolio::FlowClassifier
+ # requires: a negative amount is money in, so a margin-interest charge or
+ # a dividend reversal carrying an income label reduces the total instead
+ # of adding to it.
+ #
+ # The direction branches additionally exclude income labels rather than
+ # relying on qty: 0 to keep the buckets disjoint. Without this guard such
+ # a row would be counted twice: once by direction and once as income.
+ #
# Missing FX rates preserve InvestmentStatement's existing 1:1 fallback.
#
# account_ids is already scoped to the family's visible (draft/active)
# investment accounts, so the query trusts that input and skips a join back
# to accounts for family/status filtering.
+ # COALESCE keeps an unlabeled trade (NULL) out of the set.
+ def income_label_sql
+ "COALESCE(trades.investment_activity_label, '') IN ('Dividend', 'Interest')"
+ end
+
def aggregation_sql
<<~SQL
SELECT
- COALESCE(SUM(CASE WHEN trades.qty > 0 THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as contributions,
- COALESCE(SUM(CASE WHEN trades.qty < 0 THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as withdrawals,
+ COALESCE(SUM(CASE WHEN trades.qty > 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as contributions,
+ COALESCE(SUM(CASE WHEN trades.qty < 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as withdrawals,
+ COALESCE(-SUM(CASE WHEN #{label_sql} = 'Dividend' THEN entries.amount * COALESCE(er.rate, 1) ELSE 0 END), 0) as dividends,
+ COALESCE(-SUM(CASE WHEN #{label_sql} = 'Interest' THEN entries.amount * COALESCE(er.rate, 1) ELSE 0 END), 0) as interest,
COUNT(trades.id) as trades_count
FROM entries
- JOIN trades ON trades.id = entries.entryable_id AND entries.entryable_type = 'Trade'
+ LEFT JOIN trades ON trades.id = entries.entryable_id AND entries.entryable_type = 'Trade'
+ LEFT JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'
LEFT JOIN exchange_rates er ON (
er.date = entries.date AND
er.from_currency = entries.currency AND
@@ -61,9 +91,25 @@ class InvestmentStatement::Totals
WHERE entries.account_id IN (:account_ids)
AND entries.date BETWEEN :start_date AND :end_date
AND entries.excluded = false
+ AND (
+ entries.entryable_type = 'Trade'
+ OR (
+ entries.entryable_type = 'Transaction'
+ AND #{income_transaction_sql}
+ #{Transaction.pending_providers_sql("transactions")}
+ )
+ )
SQL
end
+ def label_sql
+ "COALESCE(trades.investment_activity_label, transactions.investment_activity_label)"
+ end
+
+ def income_transaction_sql
+ "transactions.investment_activity_label IN ('Dividend', 'Interest')"
+ end
+
def sql_params
{
target_currency: @family.currency,
diff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rb
index e28f37f867..2f1182965e 100644
--- a/test/models/investment_statement_test.rb
+++ b/test/models/investment_statement_test.rb
@@ -486,7 +486,7 @@ class InvestmentStatementTest < ActiveSupport::TestCase
aggregate_queries = queries.grep(/SUM\(CASE WHEN trades\.qty > 0/)
assert_equal 1, aggregate_queries.size
- assert_includes aggregate_queries.first, "FROM entries JOIN trades"
+ assert_includes aggregate_queries.first, "FROM entries LEFT JOIN trades"
assert_includes aggregate_queries.first, "entries.entryable_type = 'Trade'"
assert_includes aggregate_queries.first, "entries.account_id IN"
assert_includes aggregate_queries.first, "entries.excluded = false"
@@ -496,6 +496,201 @@ class InvestmentStatementTest < ActiveSupport::TestCase
assert_no_match(/JOIN accounts/, aggregate_queries.first)
end
+ test "totals aggregate dividend and interest income from income trades" do
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ create_income_trade(account: account, label: "Dividend", amount: 50, date: period.start_date)
+ create_income_trade(account: account, label: "Dividend", amount: 25, date: period.start_date + 1.day)
+ create_income_trade(account: account, label: "Interest", amount: 10, date: period.start_date)
+ # Outside the period, must not be counted
+ create_income_trade(account: account, label: "Dividend", amount: 999, date: period.start_date - 1.day)
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(75, "USD"), totals.dividends
+ assert_equal Money.new(10, "USD"), totals.interest
+ assert_equal Money.new(85, "USD"), totals.total_income
+ end
+
+ test "income trades are not counted as contributions or withdrawals" do
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ create_trade(account: account, qty: 2, amount: 120, date: period.start_date)
+ create_income_trade(account: account, label: "Dividend", amount: 50, date: period.start_date)
+
+ totals = @statement.totals(period: period)
+
+ # qty: 0 keeps income out of both direction branches
+ assert_equal Money.new(120, "USD"), totals.contributions
+ assert_equal Money.new(0, "USD"), totals.withdrawals
+ assert_equal Money.new(50, "USD"), totals.dividends
+ end
+
+ test "a buy relabeled to Dividend is counted as income only, not also as a contribution" do
+ # The activity-label quick editor permits changing the label on its own and
+ # leaves qty untouched, so an income-labeled trade can carry qty > 0. It must
+ # not land in both the direction bucket and the income bucket.
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ trade_entry = create_trade(account: account, qty: 2, amount: 120, date: period.start_date)
+ trade_entry.trade.update!(investment_activity_label: "Dividend")
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(0, "USD"), totals.contributions
+ # Income is signed (Portfolio::FlowClassifier): the 120 left the account,
+ # so the relabeled row nets against income rather than adding to it.
+ assert_equal Money.new(-120, "USD"), totals.dividends
+ assert_equal Money.new(-120, "USD"), totals.total_income
+ end
+
+ test "a sell relabeled to Interest is counted as income only, not also as a withdrawal" do
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ trade_entry = create_trade(account: account, qty: -1, amount: -40, date: period.start_date)
+ trade_entry.trade.update!(investment_activity_label: "Interest")
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(0, "USD"), totals.withdrawals
+ assert_equal Money.new(40, "USD"), totals.interest
+ end
+
+ test "labeled non-income trades still count by direction" do
+ # Only Dividend/Interest are excluded from the direction buckets; Buy, Sell
+ # and Reinvestment keep their existing contribution/withdrawal treatment.
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ buy = create_trade(account: account, qty: 2, amount: 120, date: period.start_date)
+ buy.trade.update!(investment_activity_label: "Buy")
+ reinvest = create_trade(account: account, qty: 1, amount: 30, date: period.start_date)
+ reinvest.trade.update!(investment_activity_label: "Reinvestment")
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(150, "USD"), totals.contributions
+ # Reinvestment is deliberately not folded into dividend income; doing so
+ # would require removing it from contributions too.
+ assert_equal Money.new(0, "USD"), totals.dividends
+ end
+
+ test "totals convert foreign-currency dividends into family currency" do
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500, currency: "EUR")
+
+ ExchangeRate.create!(
+ from_currency: "EUR",
+ to_currency: "USD",
+ date: period.start_date,
+ rate: 1.1
+ )
+
+ create_income_trade(account: account, label: "Dividend", amount: 100, date: period.start_date)
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(110, "USD"), totals.dividends
+ end
+
+ test "total_dividends and total_interest expose all-time income" do
+ account = create_investment_account(balance: 500)
+
+ create_income_trade(account: account, label: "Dividend", amount: 40, date: 2.years.ago.to_date)
+ create_income_trade(account: account, label: "Interest", amount: 5, date: Date.current)
+
+ assert_equal 40, @statement.total_dividends
+ assert_equal 5, @statement.total_interest
+ end
+
+ test "dividends and interest count the transaction shapes providers write" do
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ create_income_trade(account: account, label: "Dividend", amount: 50, date: period.start_date)
+ create_income_transaction(account: account, label: "Dividend", amount: 12.5, date: period.start_date, extra_shape: :flat)
+ create_income_transaction(account: account, label: "Interest", amount: 4, date: period.start_date, extra_shape: :none)
+ # PlaidAccount::Investments::TransactionsProcessor writes a dividend as
+ # a qty-0 trade with amount 0 * price, so its cash is not recoverable
+ # here (its `price` is a per-share figure, not the payment). It is
+ # income with amount 0 until the processor is fixed; the 62.5 below
+ # deliberately excludes it.
+ create_plaid_dividend_trade(account: account, date: period.start_date)
+ # Pending income is not counted until it posts
+ create_labelled_transaction(account: account, label: "Dividend", amount: -99, date: period.start_date, extra: { "plaid" => { "pending" => true } })
+ # A labelled transaction outside the period is not counted
+ create_income_transaction(account: account, label: "Dividend", amount: 999, date: period.start_date - 1.day, extra_shape: :flat)
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(62.5, "USD"), totals.dividends
+ assert_equal Money.new(4, "USD"), totals.interest
+ assert_equal Money.new(66.5, "USD"), totals.total_income
+ assert_equal Money.new(0, "USD"), totals.contributions
+ end
+
+ test "income nets by sign, so a charge or reversal labelled as income reduces it" do
+ # Portfolio::FlowClassifier decides income by label, not sign, and says to
+ # sum signed amounts: a margin-interest charge labelled "Interest" is money
+ # out and must lower interest, not add to it.
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ create_income_trade(account: account, label: "Dividend", amount: 100, date: period.start_date)
+ create_income_trade(account: account, label: "Interest", amount: 50, date: period.start_date)
+ reversal = create_income_trade(account: account, label: "Dividend", amount: 30, date: period.start_date)
+ reversal.update_columns(amount: 30)
+ create_labelled_transaction(account: account, label: "Interest", amount: 10, date: period.start_date)
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(70, "USD"), totals.dividends
+ assert_equal Money.new(40, "USD"), totals.interest
+ assert_equal Money.new(110, "USD"), totals.total_income
+ end
+
+ test "trades_count counts trades, not the income transactions read beside them" do
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+
+ create_trade(account: account, qty: 2, amount: 120, date: period.start_date)
+ create_income_transaction(account: account, label: "Dividend", amount: 10, date: period.start_date)
+ create_income_transaction(account: account, label: "Interest", amount: 3, date: period.start_date)
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(13, "USD"), totals.total_income
+ assert_equal 1, totals.trades_count
+ end
+
+ test "contributions and withdrawals count trades only, not external cash transactions" do
+ # None of the non-trade entries below is income, so reading labelled
+ # transactions for income must not let them move the direction buckets.
+ # Totals#contributions is the cash committed to buying securities:
+ # counting the 800 deposit and the 1 000 buy it funded would count that
+ # money twice.
+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)
+ account = create_investment_account(balance: 500)
+ checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)
+
+ create_portfolio_trade(account: account, qty: 10, price: 100, fee: 0, date: period.start_date)
+ create_portfolio_trade(account: account, qty: -2, price: 100, fee: 0, date: period.start_date)
+ create_labelled_transaction(account: account, label: "Contribution", amount: -300, date: period.start_date)
+ create_labelled_transaction(account: account, label: "Withdrawal", amount: 50, date: period.start_date)
+ create_labelled_transaction(account: account, label: nil, kind: "investment_contribution", amount: -200, date: period.start_date)
+ create_linked_transfer(family: @family, from: checking, to: account, amount: 800, date: period.start_date)
+
+ totals = @statement.totals(period: period)
+
+ assert_equal Money.new(1000, "USD"), totals.contributions, "only the buy is a contribution"
+ assert_equal Money.new(200, "USD"), totals.withdrawals, "only the sale is a withdrawal"
+ assert_equal 2, totals.trades_count
+ end
+
test "current_holdings memoizes so repeated dashboard-style calls issue a single query" do
account = create_investment_account(balance: 2100, currency: "USD")
security = Security.create!(ticker: "AAPL", name: "Apple")
@@ -554,6 +749,110 @@ class InvestmentStatementTest < ActiveSupport::TestCase
)
end
+ # Investment income (dividends, interest) is recorded as a Trade with
+ # qty: 0 and price: 0, matching Trade::CreateForm#create_income_trade.
+ # A negative amount means cash coming in.
+ def create_income_trade(account:, label:, amount:, date:)
+ account.entries.create!(
+ name: "#{label} #{SecureRandom.hex(3)}",
+ amount: -amount.to_d.abs,
+ date: date,
+ currency: account.currency,
+ entryable: Trade.new(
+ security: Security.create!(ticker: "T#{SecureRandom.hex(8)}", name: "Test Security"),
+ qty: 0,
+ price: 0,
+ currency: account.currency,
+ investment_activity_label: label
+ )
+ )
+ end
+
+ def create_portfolio_security(ticker: "T#{SecureRandom.hex(6)}")
+ Security.create!(ticker: ticker, name: "Test #{ticker}")
+ end
+
+ # Manual buy/sell (Trade::CreateForm) and provider trades. The manual form
+ # folds the fee into the entry amount; pass `fee_in_amount: false` for the
+ # Kraken / Binance-spot shape whose amount excludes it.
+ def create_portfolio_trade(account:, security: create_portfolio_security, qty:, price:, fee: 0, label: nil, date: Date.current, fee_in_amount: true, excluded: false)
+ label ||= qty.negative? ? "Sell" : "Buy"
+ amount = qty.to_d * price.to_d
+ amount += fee.to_d if fee_in_amount
+
+ account.entries.create!(
+ name: "#{label} #{security.ticker}",
+ date: date,
+ amount: amount,
+ currency: account.currency,
+ excluded: excluded,
+ entryable: Trade.new(
+ qty: qty,
+ price: price,
+ fee: fee,
+ currency: account.currency,
+ security: security,
+ investment_activity_label: label
+ )
+ )
+ end
+
+ # Trading212 / IBKR / Questrade: a Transaction with the label and the
+ # security id in extra. Negative amount = cash in.
+ def create_income_transaction(account:, label:, amount:, security: create_portfolio_security, date: Date.current, extra_shape: :flat)
+ extra = case extra_shape
+ when :flat then { "security_id" => security.id }
+ when :nested then { "security" => { "id" => security.id } }
+ else {}
+ end
+
+ account.entries.create!(
+ name: "#{label} from #{security.ticker}",
+ date: date,
+ amount: -amount.to_d.abs,
+ currency: account.currency,
+ entryable: Transaction.new(investment_activity_label: label, extra: extra)
+ )
+ end
+
+ # PlaidAccount::Investments::TransactionsProcessor routes a cash dividend
+ # through the trade path with quantity 0, so the amount is 0 * price = 0.
+ def create_plaid_dividend_trade(account:, security: create_portfolio_security, price: 100, date: Date.current)
+ account.entries.create!(
+ name: "Dividend #{security.ticker}",
+ date: date,
+ amount: 0,
+ currency: account.currency,
+ entryable: Trade.new(qty: 0, price: price, fee: 0, currency: account.currency, security: security, investment_activity_label: "Dividend")
+ )
+ end
+
+ def create_labelled_transaction(account:, label:, amount:, kind: "standard", date: Date.current, extra: {}, excluded: false)
+ account.entries.create!(
+ name: "#{label || 'Transaction'} #{SecureRandom.hex(2)}",
+ date: date,
+ amount: amount,
+ currency: account.currency,
+ excluded: excluded,
+ entryable: Transaction.new(investment_activity_label: label, kind: kind, extra: extra)
+ )
+ end
+
+ # A linked Transfer exactly as Transfer::Creator writes it: the outflow leg
+ # is investment_contribution when the destination is an investment account,
+ # the inflow leg is funds_movement, and optional fee legs point back at the
+ # transfer through transfer_id.
+ def create_linked_transfer(family:, from:, to:, amount:, date: Date.current, source_fee_amount: nil)
+ Transfer::Creator.new(
+ family: family,
+ source_account_id: from.id,
+ destination_account_id: to.id,
+ date: date,
+ amount: amount,
+ source_fee_amount: source_fee_amount
+ ).create
+ end
+
def create_trade(account:, qty:, amount:, date:)
account.entries.create!(
name: "Trade #{SecureRandom.hex(3)}",