Attribute a portfolio's income to the securities that paid it

Closed
JA
21d ago
+6867-36

Part of #4078 (part 3, returns engine)
Part of #3494

Fork pre-flight: jaysbeekay/sure#454 (pull/454), same branch, same commit. Its CI and review history are there. The earlier evidence for this code is on jaysbeekay/sure#378, the pre-flight it supersedes.

Updated 2026-11-05. #4217's head is merged down, bringing #4197's bound-value marker fix (11bb8a1bd, 0e334559a) and upstream main (529d7de76). No change to this PR's own files. To review this slice alone: up/portfolio-income-v2...up/portfolio-income-by-security-v2. Merge bottom-up; main is merged down after each one. Full suite on d22f3f3ae: 14,874 runs, 0 failures, 0 errors.

Stacked on the income PR, #4217 (up/portfolio-income-v2), the top of the returns engine stack below it. Until those merge, GitHub shows their commits here as well. This PR's own commits are the eight after 62281704a:

  • ef3ae45cd Attribute a portfolio's income to the securities that paid it
  • 201243fd0 Pin the cut-off and the unattributed-only case for attribution
  • b3a5792c8 Lock attribution to the daily rows' total with a partition test
  • c2ffeb711 Look a Security up by its id in IncomeBySecurity#amount_for
  • 42d2ea086 Move the performance cache version past the by-security shape
  • 3711b51cd Splice classifier SQL into income attribution after binding
  • 14b956621 Attribute income by security from the rows' own entries
  • 4d6909c07 Hold income by security to the liability refusal

Problem

The income PR reports a portfolio's income by month, but not which holdings paid it. A provider records the paying security in different places depending on how it shapes a dividend, and some dividends name no security at all, so a per-security table either has to say what it could not attribute or it will not add up.

Change

  • app/models/portfolio/daily_returns.rb (+58): #income_by_security. One grouped query over the same entries as the daily rows. It goes through the same classifier, FX conversion, cut-off window and split-parent rule (since 14b956621; excluded entries count, as in the rows).
    • A Trade-shaped dividend names its security in a column.
    • A Transaction-shaped one names it only when the provider recorded it in extra, under the two keys Transaction#activity_security_id reads.
    • Ids are compared lower-cased. An entry with no rate is dropped, as the rows drop it.
  • app/models/portfolio/income_by_security.rb (new, 65 lines).
    • Rows are sorted largest first, then by ticker.
    • An id that matches no security joins unattributed, and unattributed = total - attributed. So the table always adds up to the income total, and a reversal with no security can make the remainder negative.
    • amount_for takes a Security or its id.
  • app/models/portfolio/income.rb. #to_h carries the raw { security_id => amount } as by_security, as plain values, so they survive the cache. The query runs only when income is asked for.
  • app/models/portfolio/performance.rb. CACHE_VERSION goes from v8 to v9, so an income entry cached before by_security existed is not served.

Income attribution binds the same way (3711b51cd). DailyReturns#income_by_security sanitized income_by_security_query, with the classifier's CASE and joins interpolated, as one string, the same hazard. It now goes through bind_and_splice like the daily query, which arrives here from #4197 through the stack. The test "a colon word inside the classifier's sql is not read as a bind" in income_by_security_test.rb stubs sql_case with a ':probe' literal and asserts the attribution is unchanged; it raised before the fix, and raises again if the query is sanitized whole.

Updated 2026-10-14. be56fa0d8 merges #4217 at b786df777, which includes #4197's one-row-per-entry join and so covers this slice's own SUM over the classifier joins. 14b956621 then makes income_by_security_query share the rows' FX joins (entry_fx_joins) and split-parent predicate (not_split_parent_sql), so attribution still partitions the rows' income now that it counts excluded entries and converts through the account's currency.

Updated 2026-10-15. 31c7e31d8 merges #4217 at 52031186f; 4d6909c07 then adds "income by security refuses a liability account too": income_by_security runs its own query, so #4197's liability refusal is asserted on it as well (it holds because the check sits in bind_and_splice; moving the check into raw_rows fails it).

Validation

On 42d2ea086, stacked on 62281704a:

  • Full suite (bin/rails test): 11,974 runs, 55,042 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16.
  • After the bind fix, on 3f622bb8f (2026-10-14): full suite 11,978 runs, 0 failures, 0 errors, 34 skips. CI is green.
  • On 14b956621 (2026-10-14): full suite 11,993 runs, 55,099 assertions, 0 failures, 0 errors, 34 skips. Rubocop is clean and Brakeman reports 0 warnings.
  • On 4d6909c07 (2026-10-15): full suite 12,001 runs, 55,132 assertions, 0 failures, 0 errors, 34 skips. Brakeman reports 0 warnings.
  • 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_by_security_test.rb, income_test.rb and performance_test.rb, on 42d2ea086: 68 runs, 206 assertions, 0 failures.

Fail-first:

  • "amount_for takes a Security as readily as its id" failed before the id extraction.
  • "an income entry cached before by_security existed is not served" failed at v8.
  • "attributed and unattributed income partition the daily rows' total" is a lock. It covers every storage shape, a fee on a security and a foreign dividend.
  • "income attributed to a security counts once when its transaction is a leg of two transfers" (14b956621): with the join reverted, it reads 60, not 30.
  • "an excluded dividend and one carrying its own rate partition the daily rows' total" failed before 14b956621. 3 mutations of that change, all caught.
  • "income by security refuses a liability account too" (4d6909c07) is a lock: the refusal already holds through bind_and_splice, and moving the check into raw_rows fails it.

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

MutationTests that catch it
Trade security ignored9
flat extra key ignored2
nested key ignored1
attribution at the payment date's rate1
unconvertible income kept1
fees counted as income1
unattributed forced to zero3
rows not sorted1
by_security dropped from the cached hash2
the cut-off ignored1
any? ignoring the unattributed remainder1

Re-run on this branch:

  • CACHE_VERSION kept at v8: 1 failure;
  • amount_for without the id extraction: 1;
  • unattributed forced to zero: 5;
  • by_security dropped from the cached hash: 3.

There is one equivalent mutant: fetch with a default in #rows changes nothing, because the rows are built only from securities that exist. The fork pre-flight recorded a second, dropping the excluded filter, which changed nothing then because the classifier returned NULL for excluded entries. Since 14b956621 the query has no excluded filter: it counts excluded entries through the classifier's include_excluded: true and skips split parents with not_split_parent_sql.

The code was byte-identical to the fork pre-flight it supersedes when rebuilt. The bind fix above (3711b51cd) was added afterwards.

Migration notes

None. No schema change.

Summary by CodeRabbit

  • New Features
    • Added portfolio performance metrics, including time- and money-weighted returns, annualized returns, volatility, and maximum drawdown.
    • Added return breakdowns for deposits and withdrawals, account changes, income, fees, market movement, revaluations, and currency effects, with checks for unexplained changes.
    • Added monthly income summaries and income attribution by security, including unattributed amounts.
    • Return calculations account for account eligibility and cutoff dates, and identify suppressed days or missing exchange rates that may affect results.
    • Added indicators for incomplete performance data and whether return calculations are available for an account.
  • Bug Fixes
    • Improved classification of linked transfers and trade activity, including excluded entries and account cutoff dates.