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

Draft
JA
2mo ago
+1880-0

Part of #121

This is the upstream pre-flight for slice 5 of 7 of the portfolio return engine (drop 2 of #118). The upstream PR on we-promise/sure is NOT YET OPENED (awaiting owner approval). When it is opened it will be from this branch: same branch, same commit.

Base is the parent slice's branch, so this diff shows only this slice's commits. Fork stack: #372 daily returns → #373 journal flows → #374 drivers → #376 performance (carrying #375 return scope, which is also based on up/pending-sql-parity) → #377 income → #378 income by security.


Part of we-promise/sure#4078
Part of we-promise/sure#3494

Slice 5 of 7 of the portfolio returns engine; we-promise/sure#4078 is the issue (part 3, returns engine).

Fork pre-flight PR: jaysbeekay/sure#376 (https://github.com/jaysbeekay/sure/pull/376), same branch, same commit.

Stacked on the drivers PR, with the return scope PR's commits on top. Until that merges, GitHub shows its commits here as well; this PR's own commits are the ones after up/portfolio-drivers. I will rebase onto main as each parent merges.

Stack, in merge order: we-promise/sure#3557 (flow classifier) → daily returns → journal flows → drivers → return scope → performance → income → income by security. Return scope also stands alone on we-promise/sure#3557.

Summary

Adds Portfolio::Performance, the figures a portfolio view needs for a set of accounts over a period, in the family's currency:

  • time-weighted return and its annualised form;
  • money-weighted return (XIRR, via the already-merged Portfolio::Xirr) and its annualised form;
  • volatility, maximum drawdown and a rebased index series;
  • the drivers breakdown.

This is the first class in the stack meant to be called. Nothing calls it yet; a follow-up exposes it on InvestmentStatement.

What changed

app/models/portfolio/performance.rb (new):

  • TWR 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 TWR and MWR; a short period's figure is reported unannualised, never withheld.
  • MWR is solved over the period's own span, with the closing value dated at the end of the last day, and includes composition flows.
  • Volatility is 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. An account with a single balance day withholds every time-weighted figure. Any account that cannot support a money-weighted return withholds MWR (Portfolio::ReturnScope, resolved once per instance); an account with no balance rows in the period does neither.
  • Caching on 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, the flow scope and the cut-off dates as DailyReturns resolves them.

This branch carries the return scope PR's commits so the stack is linear; that PR also stands alone on we-promise/sure#3557.

Size. 342 non-test lines (about 180 code), over the guideline because each figure carries the reasoning for its convention.

Demo data

None needed: model only, no UI. Exercised by the tests below.

Migration notes

None. No schema change; reads existing balances, entries, trades, transactions, holdings and exchange_rates columns.

Verification

  • performance_test.rb: 29 runs, 73 assertions, 0 failures.
  • Mutations, all caught:
    • TWR summed rather than chained: 2 tests;
    • 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;
    • MWR on an annual basis: 2;
    • missing rate not withholding: 1;
    • MWR allowed for valuation-tracked: 1;
    • an empty account blocking MWR: 1;
    • a one-day account ignored: 3;
    • drawdown never resetting its peak: 1;
    • index series starting at the base: 1;
    • cache key without the sync time, currency, flow scope or cut-offs: 1 each;
    • a total loss annualised: 1.
  • Removing the eligibility memo was masked by the query cache. The test now counts uncached queries and catches it.
  • Equivalent mutant: the rows.size < 2 guard on MWR. A one-day period already leaves every account with one balance day or none, so eligibility withholds the figure first.
  • Full suite after the cut-off follow-up, at the top of the stack (up/portfolio-income-by-security at 1dc444d54): 10,782 runs, 45,992 assertions, 0 failures, 0 errors, 33 skips (local, PostgreSQL 16, 4 workers).
  • bin/rubocop on the changed files: no offenses. bin/brakeman --no-pager -q: 0 warnings.

Blast radius

Who else hits this line, and what do they pass? No caller yet.

What else reads what I just changed the reading of? Nothing outside the new file changes. It builds one Portfolio::Xirr.new(flows, days_per_unit:) (merged in we-promise/sure#3611) and reads its rate and ambiguous? together (it called rate_or_nil before the fix round), and Family#build_cache_key, unchanged.

Engine fix round (2026-10-09)

up/portfolio-drivers is merged down with a --no-ff merge, clean, no force push. The Performance-side flow scope removal is committed before that merge, so neither side is red.

CommitFindingTestFail-first / mutation
d57b5808ccubic Vbq1 (on #372), owner decision 4: remove scope_account_ids"the flow scope cannot be widened beyond the accounts measured"; the two flow-scope cache key tests and the scope: key part are removedfailed at :213 (no ArgumentError); re-adding the keyword caught
78faaf8aathe merged fixture scale check refused one fixture (1,035.714286)the fixture now uses 1,035.7143n/a
bbd5e9acecherry-pick -x of #375 ab4a52295 (ReturnScope cut-offs)see #375see #375
b033f1acbcubic VcEX: balance_days ignores the cut-off"a cut-off that leaves one in-window balance day withholds time weighted figures"failed at :393; dropping active_until_dates: from resolve_all caught (:393)
d0470cedccubic VcEL, owner decision 3: an all-empty scope reads 0% TWR"time weighted figures are withheld when no account holds a balance in the period"failed at :371; the any? { balance_days >= 2 } clause → true caught (:371)
8c89fcc0fcubic VcEb: unused eur_account_with_feeremoved here, re-added on #377n/a
e24b386f2jaysbeekay/sure#385 model half: MWR ambiguity discarded"an ambiguous money-weighted series is flagged", "a single-sign-change series is not flagged", "a withheld money-weighted return is not flagged" (ConvergenceError, NoSignChangeError, NoDurationError, a valuation-tracked scope, a missing rate), "the cached metrics carry the ambiguity flag"failed on the missing reader; flag dropped from compute caught (:561, :612); hard-coded false caught (:561, :612); CACHE_VERSION kept at v7 caught (:619); flag not gated on the rate caught (:588)
e46098f9bGatekeeper recommendation from #373: an end-to-end journal test"a journal through the real balance calculator is valued once, and the drivers reconcile" (real Balance::Materializer and security prices)a lock, passes as is; dropping - journal_flow from market caught (:653)
164e38dcdcherry-pick -x of #375 9d2d58028: the trade, valuation and transfer checks read only up to the cut-offsee #375see #375; return_scope.rb is byte-identical on both branches
  • Money-weighted ambiguity. money_weighted solves one Portfolio::Xirr and returns its rate together with ambiguous?. compute stores mwr_ambiguous, false whenever the rate is withheld. money_weighted_return_ambiguous? reads it, and CACHE_VERSION is now v8. The rate itself is unchanged. rate_or_nil keeps its signature and has no caller in this slice. The page hint is fork-only work.
  • :mwr readers: money_weighted_return and annualized_money_weighted_return, both in this class.
  • performance_test.rb: 35 runs, 0 failures. All portfolio model tests on this head: 171 runs, 0 failures.
  • After the cut-off follow-up (164e38dcd), all portfolio model tests: 176 runs, 715 assertions, 0 failures. The test file conflicted on the pick only because this branch never carried #375's helper test; the new tests are the same lines as there. Performance#return_scopes already passes DailyReturns' cut-offs to resolve_all, so money_weighted_supported? picks the fix up with no change here.

Precision follow-up (2026-10-13)

dba9fcb3b and 274f314f9 answer the code-master review 6105957659 (findings 3, 4 and 6). chain, drawdown and rebased_index multiplied BigDecimals without rounding. The digits of each chained level therefore grew every day: one account over two years cached 10.5 MB of metrics at about 28,500 digits a figure. They now compound through compound, which uses BigDecimal#mult at CHAIN_PRECISION = 20 significant digits.

  • Fail-first test: "two years of daily returns keep a bounded precision and a small cached payload". Its oracle is the telescoped return. It failed at 17,192 digits before the fix.
  • Four mutations, each caught: the helper unrounded, and each of chain, rebased_index and drawdown bypassing it.
  • Full suite at 274f314f9: 10,751 runs, 45,910 assertions, 0 failures, 0 errors, 33 skips. rubocop is clean and brakeman reports 0 warnings.
  • Merged down into #377 (0827b17f6) and #378 (456fd5542).
  • Fork main carries the same defect, tracked in jaysbeekay/sure#434.