Group a portfolio's income by month, with its fees and fee ratio

JA
7d ago
+773-16

Closes #4229
Part of #4078 (part 3, returns engine)

Part of #3494

Replaces #4217 (same changes, rebased and native-stacked; its review history stays there).

What: adds Portfolio::Income, which groups the daily rows' dividend and interest income by month, reports fees apart, and gives a fee ratio over the period's average daily value. Portfolio::Performance#income caches it as its own entry, computed only when asked. A commission folded into a buy's or sell's amount now moves from market to fees in DailyReturns (the period change and returns do not move, only the split).
Why: nothing reports how much a portfolio paid out each month, what it was charged, and what that charge is as a share of the money invested. Without the commission change, a brokerage that charges per trade showed a 0% fee ratio.
Start reading: Portfolio::Income#buckets and #fee_ratio in app/models/portfolio/income.rb, then trade_commission_sql in app/models/portfolio/daily_returns.rb and Performance#income.
Key tests (test/models/portfolio/income_test.rb, drivers_test.rb, performance_test.rb):

  • "income is not a contribution or a withdrawal, and reconciles with the drivers"
  • "a month that nets negative keeps its sign, so the buckets still add up to the total"
  • "the fee ratio divides by the period's value, not by where it ended"
  • "a commission folded into a buy's amount is a fee, not a market loss"
  • "reading the income alone computes none of the returns"

Behaviour change: none for users; nothing calls these classes yet. In the model, fees now include commissions recorded on trades, and the performance cache version moves to v10. No migration.

Stack: 7 of 11 in the portfolio returns stack, on #5092. GitHub shows only this slice's diff. Next: #5094 (income by security). Merge order: #5129 → #5088 → #5089 → #5090 → #5091 → #5092 → #5093 → #5094 → #5285 → #5296 → #5297.
Size: +208 / −16 outside tests, across 4 files.
Fork pre-flight: jaysbeekay/sure#712 (same commits, against a mirror of upstream main). Earlier evidence: jaysbeekay/sure#453.

Full description and evidence

Rebased 2026-11-15 onto main at dbeebf14c. Its 6 own commits replayed onto the slice below unchanged, plus e82d3d780, which counts a commission folded into a trade's amount as a fee (see Commissions on trades). test/models/portfolio and test/models/balance at this slice: 373 runs, 0 failures. Full suite at the top of the stack: 16,441 runs, 0 failures (8 ReleaseNotesWorkflowTest errors: no node in the test image). Rubocop and Brakeman clean.

Problem

The daily rows carry each day's dividend and interest income and its fees, but nothing reports them over a period: how much a portfolio paid out each month, what it was charged, and what that charge is as a share of the money invested.

Change

app/models/portfolio/income.rb (new, 126 lines). It regroups the daily rows' income and fees by calendar month and re-derives nothing. What counts as income is the classifier's answer, already converted as the balance took it: into the account's currency on its own date (the entry's own rate first), then into the family's currency at the previous day's rate. That includes a Trade-shaped dividend since #1311, or a Transaction-shaped one. So the months add up to the drivers' income.

  • Months. A month that paid nothing is absent. A month whose payouts and reversals net to zero or below is kept, so the buckets always add up to the total.
  • Fees. Reported apart, as a positive magnitude, not netted out of income.
  • Fee ratio. Fees over the period's average daily value, so it does not shrink as the portfolio grows. It is nil when there was no value. A day before the portfolio's first balance counts as zero in the average (pinned since 6ab406c87: "a day before the portfolio's first balance counts as zero in the fee ratio", which fails against a mean over valued days only, 990 for 660).
  • Cached shape. Each bucket's month is an ISO 8601 string. A JSON-serialising cache store would turn a Date into a string anyway, so a caller would otherwise read a different type depending on the store.

app/models/portfolio/performance.rb (+23):

  • #income. It is a cache entry of its own, computed only when asked, so a caller that reads only the returns never pays for it.
  • The missing-rate flag. It reads the flag from the daily returns, so reading the income never runs the returns' computation.
  • Withholding. The fee ratio is withheld when a rate is missing. The money figures are not.

Updated 2026-10-14. b786df777 merges #4214 at 88fdbd232, which brings #4197's, #4198's, #4212's and #4213's review fixes. Portfolio::Income reads the rows' income, so the total now includes excluded income entries and converts foreign income as the balance did. This slice's own files are unchanged.

Updated 2026-10-15. 52031186f merges #4214 at fce8b6868 (with #4197's and #4198's review fixes below it). No change to this PR's own files.

Validation

On 62281704a, stacked on 7fc5ba1e0:

  • Full suite (bin/rails test): 11,957 runs, 54,994 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16.
  • 2026-10-14: the head moved to d835d5899 only by merging the bind fix down the stack, and this PR's own files are unchanged. The portfolio model tests pass (198 runs, 0 failures) and CI is green; the stack tip 3f622bb8f, which contains this head, ran the full suite: 11,978 runs, 0 failures, 0 errors, 34 skips.
  • On b786df777 (2026-10-14): portfolio model tests 246 runs, 0 failures. Brakeman reports 0 warnings.
  • On 52031186f (2026-10-15): portfolio model and investment statement tests 253 runs, 0 failures. Full suite: see #4218 (12,001 runs, 0 failures, 0 errors).
  • Lint and security: bin/rubocop -f github on the changed files reports no offenses, and bin/brakeman --no-pager -q reports 0 warnings. No ERB, JS or system-test surface.

Tests

test/models/portfolio/income_test.rb and test/models/portfolio/performance_test.rb, on 62281704a: 51 runs, 160 assertions, 0 failures.

Fail-first:

  • "reading the income alone computes none of the returns" failed with an unexpected Portfolio::Performance#compute invocation.
  • "the cached payload's months survive a JSON round trip unchanged" failed with a Date where the string belonged.

Mutations. Each was run on the fork pre-flight, then restored. All were caught:

MutationTests that catch it
empty months kept6
a net-zero month dropped1
a negative month dropped2
fees netted out of income1
fee ratio over the closing value2
fee ratio 0 instead of nil with no value1
buckets unsorted2
fee ratio not withheld on a missing rate1
the missing-rate flag not passed to income1
a Date month in the cached hash1

Re-run on this branch:

  • fee ratio not withheld on a missing rate: 2 failures;
  • a Date month: 1;
  • fee ratio 0 instead of nil: 1;
  • income reading the returns' flag instead of the daily returns': 1.

The code is byte-identical to the fork pre-flight it supersedes.

Commissions on trades (added 2026-11-15)

A commission recorded on a buy or sell (trades.fee) and folded into its entry amount -- amount = qty × price + fee, as the trade form, SnapTrade and IBKR write it -- was booked by the balance calculator as a market loss, so fees and the fee ratio read 0% for a brokerage that charges per trade. Portfolio::DailyReturns now moves such a commission from market to fees, converted as the trade's own amount is (e82d3d780). The change, the returns and unexplained do not move; only the split does. A fee kept out of the amount was never charged to the balance and is not counted. Fees include commissions recorded on trades; there is no UI copy in this PR, so the model comments say so.

  • Tests, each seen to fail first: a buy of 100 @ 50 with a fee of 5 gives fees 5 and market 0 (before: 0 and −5) and still reconciles; a sell's fee lands in fees; a fee kept out of the amount stays uncounted; no fee moves nothing; a EUR trade's 5 EUR fee is 5.5 USD at the previous day's 1.1.
  • Mutations, both caught: dropping the amount-includes-fee check; moving the fee without adding it back to market.
  • A commission on a valuation day is handled like any other: both balance calculators compute an investment account's market movement on a valuation day too, so the commission is in market and moves to fees (pinned through the real materializer: a reconciliation day at a flat price with a 5 commission gives market 0, fees 5, revaluations 0). A missing rate on a commission-bearing trade flags the series, via #5088's check on internal entries, and the cache version moves to v10 so warm entries stop serving the old split.

Migration notes

None. No schema change.

Summary by CodeRabbit

  • New Features
    • Added monthly portfolio income summaries with income totals, fees, average portfolio value, and fee ratios. Months without income are omitted; months with zero or negative net income remain included.
    • Income and fee figures remain available when exchange rates are missing, while the fee ratio is withheld.
  • Improvements
    • Eligible commissions included in buy or sell trade amounts are counted as fees rather than market value, including commissions in foreign currencies. Trades whose amounts exclude commissions remain unchanged.