Attribute a portfolio's income to the securities that paid it
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:
ef3ae45cdAttribute a portfolio's income to the securities that paid it201243fd0Pin the cut-off and the unattributed-only case for attributionb3a5792c8Lock attribution to the daily rows' total with a partition testc2ffeb711Look a Security up by its id in IncomeBySecurity#amount_for42d2ea086Move the performance cache version past the by-security shape3711b51cdSplice classifier SQL into income attribution after binding14b956621Attribute income by security from the rows' own entries4d6909c07Hold 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 (since14b956621; 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 keysTransaction#activity_security_idreads. - 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, andunattributed = total - attributed. So the table always adds up to the income total, and a reversal with no security can make the remainder negative. amount_fortakes a Security or its id.
app/models/portfolio/income.rb.#to_hcarries the raw{ security_id => amount }asby_security, as plain values, so they survive the cache. The query runs only when income is asked for.app/models/portfolio/performance.rb.CACHE_VERSIONgoes from v8 to v9, so an income entry cached beforeby_securityexisted 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 githubon the changed files reports no offenses, andbin/brakeman --no-pager -qreports 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 throughbind_and_splice, and moving the check intoraw_rowsfails it.
Mutations. Each was run on the fork pre-flight, then restored. All were caught:
| Mutation | Tests that catch it |
|---|---|
| Trade security ignored | 9 |
flat extra key ignored | 2 |
| nested key ignored | 1 |
| attribution at the payment date's rate | 1 |
| unconvertible income kept | 1 |
| fees counted as income | 1 |
unattributed forced to zero | 3 |
| rows not sorted | 1 |
by_security dropped from the cached hash | 2 |
| the cut-off ignored | 1 |
any? ignoring the unattributed remainder | 1 |
Re-run on this branch:
CACHE_VERSIONkept at v8: 1 failure;amount_forwithout the id extraction: 1;unattributedforced to zero: 5;by_securitydropped 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.