Report time- and money-weighted returns for a set of accounts

Closed
JA
21d ago
+5849-36

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:

  • 8a480fc12 Report time- and money-weighted returns for a set of accounts
  • 3cd8dd837 Count eligibility queries past the query cache
  • 73d62112b Drop the flow scope option from Performance
  • e03d9f67b Lay the period money-weighted fixture at the stored scale
  • dccc88b9d Resolve return eligibility over the accounts' cut-offs
  • 580260c2c Withhold time-weighted figures when the scope held nothing
  • b6409a222 Remove the fee fixture no test in this slice uses
  • e286b57cb Carry the money-weighted return's ambiguity with its rate
  • 0b89e78c7 Drive a real journal from the balance calculator to Performance
  • c71989936 Round each chained return level to 20 significant digits
  • 7fc5ba1e0 Check 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::Xirr over 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? carries Xirr#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 with BigDecimal#mult at 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 1c035deb9 only by merging the bind fix down the stack. The portfolio model tests pass (183 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 88fdbd232 (2026-10-14): portfolio model and investment statement tests: 231 runs, 0 failures. The full suite on the stack's top (#4218 at 14b956621, 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 at 4d6909c07, which contains this head) gave 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/performance_test.rb, on 7fc5ba1e0: 36 runs, 117 assertions, 0 failures.

Fail-first:

  • The two-year precision test failed at 17,192 digits before compound existed. 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:

MutationTests that catch it
TWR summed rather than chained2
annualised below a year2
√2521
population variance1
MWR ignoring flows6
MWR ignoring composition2
closing value dated on the last row1
missing rate not withholding1
MWR allowed for valuation-tracked1
drawdown never resetting its peak1
cache key without the sync time, currency or cut-offs1 each
ambiguity flag dropped or hard-coded2
compound unrounded, or bypassed by chain, rebased_index or drawdown1 each

Re-run on this branch, cut from current main:

  • compound unrounded: 1 failure;
  • a missing rate not withholding the time-weighted figures: 1;
  • the ambiguity flag hard-coded false: 2;
  • CACHE_VERSION back at v7: 1;
  • √252: 1;
  • resolve_all called 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.