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

JA
7d ago
+1427-0

Updated 2026-11-20 (head e3fb17b34). Two test comments now describe the checks actually made (the one-day MWR case and the time-weighted withholding rule). Comments only.

Part of #4078 (part 3, returns engine)

Part of #3494

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

What: adds Portfolio::Performance: for a set of accounts over a period, a time-weighted return chained daily, a money-weighted return through the existing Portfolio::Xirr, their annualised forms (from 365 days up), volatility (√365 over calendar days), max drawdown, an index series and the drivers. Each figure is withheld when the data cannot support it: a missing rate withholds every ratio, and an account ReturnScope rules out withholds the money-weighted return. Results are cached under Family#build_cache_key(..., invalidate_on_data_updates: true).
Why: the daily series, drivers and return scope are raw material; this turns them into the figures a portfolio view needs.
Start reading: #time_weighted_return, #money_weighted_return and the compound helper in app/models/portfolio/performance.rb.
Key tests (test/models/portfolio/performance_test.rb):

  • "twr matches the hand computed textbook case"
  • "mwr differs from twr when flows are unevenly timed"
  • "every ratio is withheld when an exchange rate is missing"
  • "mwr is withheld when an account in the scope is valuation tracked"
  • "two years of daily returns keep a bounded precision and a small cached payload"

Worked examples. Four tests assert figures worked by hand in their comments (test/models/portfolio/performance_test.rb at d5f08522e):

TestLineFixtureExpected
"twr matches the hand computed textbook case":23, worked at :14-221,000 grows to 1,100; 1,000 is deposited; 2,100 grows to 2,310TWR 1.10 × 1.10 − 1 = 21.0% (with the deposit let through it would read 131%)
"volatility annualises calendar daily returns by sqrt 365":53daily returns +10%, −10%, 0: sample standard deviation 0.10.1 × √365 ≈ 1.9105, and asserted not 0.1 × √252
"mwr differs from twr when flows are unevenly timed":711,000 on 1 Jan, 1,000 deposited on 2 Jul, 2,000 grows to 2,200 by 31 DecTWR 10.0%, MWR ≈ 13.46%
"max drawdown measures the largest peak to trough fall":1281,000 → 1,200 → 900 → 1,000index peaks at 1.20 and falls to 0.90: 25%

Behaviour change: none; nothing calls this class yet. No migration.

Stack: 6 of 11 in the portfolio returns stack, on #5091. GitHub shows only this slice's diff. Next: #5093 (income). Merge order: #5129 → #5088 → #5089 → #5090 → #5091 → #5092 → #5093 → #5094 → #5285 → #5296 → #5297.
Size: +443 outside tests, in one new file; over the ~300 guideline because each figure carries the reasoning for its convention.
Fork pre-flight: jaysbeekay/sure#711 (same commits, against a mirror of upstream main). Earlier evidence: jaysbeekay/sure#452.

Full description and evidence

Rebased 2026-11-15 onto main at dbeebf14c. Its 15 own commits replayed onto the slice below unchanged. test/models/portfolio and test/models/balance at this slice: 352 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 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. Family#build_cache_key already includes the currency on main; naming it again means this key does not rely on that (the code comment saying otherwise was corrected in 6001fefaf).

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 metrics for selected accounts and date ranges, including time- and money-weighted returns, annualized returns, volatility, maximum drawdown, and a rebased performance index.
    • Performance calculations reflect account eligibility and activity over the selected period. When exchange rates are missing, affected return figures and series are withheld; available drivers and suppressed dates remain accessible.
  • Tests
    • Added coverage for performance calculations, account eligibility, caching, and scenarios with missing rates or unsupported activity.