Report time- and money-weighted returns for a set of accounts
Part of #4078 (part 3, returns engine)
Part of #3494
Fork pre-flight: jaysbeekay/sure#452 (pull/452), same branch, same commit. Its CI and review history are there. The earlier evidence for this code is on jaysbeekay/sure#376, the pre-flight it supersedes.
Updated 2026-11-05. #4213's head and #4212's head are merged down, bringing #4197's bound-value marker fix (11bb8a1bd, 0e334559a) and upstream main (529d7de76). No change to this PR's own files. The link also shows #4212's three files, since this branch merges that one in too. To review this slice alone: up/portfolio-drivers-v2...up/portfolio-performance-v2. Merge bottom-up; main is merged down after each one. Full suite on ab3689a64: 14,837 runs, 0 failures, 0 errors.
Stacked on the drivers PR, #4213, and the return scope PR, #4212. The branch is cut from up/portfolio-drivers-v2 (itself on #4198 and #4197) and merges up/portfolio-return-scope-v2 in with one merge commit, fddc431de. Until those merge, GitHub shows their commits here as well. This PR's own commits are the eleven after fddc431de:
8a480fc12Report time- and money-weighted returns for a set of accounts3cd8dd837Count eligibility queries past the query cache73d62112bDrop the flow scope option from Performancee03d9f67bLay the period money-weighted fixture at the stored scaledccc88b9dResolve return eligibility over the accounts' cut-offs580260c2cWithhold time-weighted figures when the scope held nothingb6409a222Remove the fee fixture no test in this slice usese286b57cbCarry the money-weighted return's ambiguity with its rate0b89e78c7Drive a real journal from the balance calculator to Performancec71989936Round each chained return level to 20 significant digits7fc5ba1e0Check the bounded-precision test against a non-zero return
After 1c035deb9: 402b306a2 merges #4212 at 20716ccd1, which removes ReturnScope#valuations? and the batch :valuations key. e7925cfbb is a comment-only change to performance.rb (four eligibility queries becomes three). 297cb9a3f merges #4213 at cc334ffab (with #4197's and #4198's review fixes). 88fdbd232 merges #4212 at b07e2bcee (only quantity trades count as trade tracking). fce8b6868 (2026-10-15) merges #4213 at f9b99fd45 (with #4197's and #4198's review fixes); no change to this PR's own files. The eligibility query-count tests here caught a first version of #4197's liability check that queried in DailyReturns#initialize; it now runs at query time. resolve_all's signature and return shape are unchanged.
The income PR stacks on this one.
Problem
The daily return series, the drivers and the return scope give the raw material for portfolio performance, but nothing turns them into the figures a portfolio view needs: a time-weighted and a money-weighted return, their annualised forms, volatility, drawdown and an index series, each withheld when the data cannot support it.
Change
app/models/portfolio/performance.rb (new, 388 lines). For a set of accounts over a period, in the family's currency:
- Time-weighted return. It chains every day's return. It is never chained at a coarser interval, which would change the answer whenever a flow lands mid-interval.
- Annualisation. Only from 365 days up, for both returns. A shorter period's figure is reported unannualised, never withheld.
- Money-weighted return. It is solved with the existing
Portfolio::Xirrover the period's own span. The closing value is dated at the end of the last day, and composition flows are included.money_weighted_return_ambiguous?carriesXirr#ambiguous?beside the rate. - Volatility. The sample standard deviation of calendar-daily returns, annualised by √365, because the balance rows include weekends and holidays.
- Withholding.
- A missing rate withholds every ratio, though the drivers are still reported.
- A scope where no account holds two balance days withholds every time-weighted figure.
- Any account that cannot support a money-weighted return withholds it. That is
Portfolio::ReturnScope, resolved once per instance over the accounts' cut-offs.
- Precision. Each chained level goes through one helper,
compound, which multiplies withBigDecimal#multat 20 significant digits. Unrounded, two years of daily returns grew each figure to about 28,000 digits and the cached metrics to 10.5 MB. - Caching. It uses
Family#build_cache_key(..., invalidate_on_data_updates: true), because a price sync changes balances without touching an entry. The key adds the family currency and the cut-off dates.
Nothing calls this class yet. Size: 388 non-test lines, over the ~300 guideline, because each figure carries the reasoning for its convention.
Validation
On 7fc5ba1e0, which merges the drivers branch (cut from main at 3e35aaa07) with the return scope branch (cut from main at a3bb5d991):
- Full suite (
bin/rails test): 11,942 runs, 54,949 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16. - 2026-10-14: the head moved to
1c035deb9only by merging the bind fix down the stack. The portfolio model tests pass (183 runs, 0 failures) and CI is green; the stack tip3f622bb8f, which contains this head, ran the full suite: 11,978 runs, 0 failures, 0 errors, 34 skips. - On
88fdbd232(2026-10-14): portfolio model and investment statement tests: 231 runs, 0 failures. The full suite on the stack's top (#4218 at14b956621, which contains this head) gave 11,993 runs, 0 failures, 0 errors. - On
fce8b6868(2026-10-15): portfolio model and investment statement tests: 238 runs, 0 failures. The full suite on the stack's top (#4218 at4d6909c07, which contains this head) gave 12,001 runs, 0 failures, 0 errors. - 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/performance_test.rb, on 7fc5ba1e0: 36 runs, 117 assertions, 0 failures.
Fail-first:
- The two-year precision test failed at 17,192 digits before
compoundexisted. Its oracle is the telescoped return, which does not use the chain. - The empty-scope, cut-off and ambiguity tests each failed before their fix.
Mutations. Each was run against this file's tests on the fork pre-flight, then restored. All were caught:
| Mutation | Tests that catch it |
|---|---|
| TWR summed rather than chained | 2 |
| annualised below a year | 2 |
| √252 | 1 |
| population variance | 1 |
| MWR ignoring flows | 6 |
| MWR ignoring composition | 2 |
| closing value dated on the last row | 1 |
| missing rate not withholding | 1 |
| MWR allowed for valuation-tracked | 1 |
| drawdown never resetting its peak | 1 |
| cache key without the sync time, currency or cut-offs | 1 each |
| ambiguity flag dropped or hard-coded | 2 |
compound unrounded, or bypassed by chain, rebased_index or drawdown | 1 each |
Re-run on this branch, cut from current main:
compoundunrounded: 1 failure;- a missing rate not withholding the time-weighted figures: 1;
- the ambiguity flag hard-coded false: 2;
CACHE_VERSIONback at v7: 1;- √252: 1;
resolve_allcalled without the cut-offs: 1.
performance.rb and its test were byte-identical to the fork pre-flight it supersedes when rebuilt. e7925cfbb (a one-line comment change to performance.rb) was added afterwards; the test is unchanged.
Migration notes
None. No schema change.
Summary by CodeRabbit
- New Features
- Added portfolio performance reporting with time- and money-weighted returns, annualized returns, volatility, drawdown, and an indexed performance series.
- Added a breakdown of portfolio changes, including contributions and withdrawals, account-scope changes, income, fees, market movement, revaluations, and currency effects.
- Added account-level return eligibility and support for account cut-off dates.
- Improvements
- Missing exchange rates and unvalued activity are surfaced; affected return figures are withheld when they cannot be calculated reliably.
- Added reconciliation and completeness indicators, including dates where returns could not be calculated.
- Linked transfers now respect counterpart transaction dates and account cut-off dates.