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

Closed
JA
21d ago
+5849-36

Part of #118 (IP2, the performance engine; its tracking issue #121 is closed)
Part of we-promise/sure#4078 (returns engine, part 3; under we-promise/sure#3494)

Upstream draft PR: we-promise/sure#4214 (pull/4214), opened 2026-10-14 from this same branch, so it moves with this head (now c80ba2311; the upstream page was not re-read from this session).

Stacked on #450 (drivers) and #451 (return scope). The branch is cut from up/portfolio-drivers-v2 (#450, itself on #444 and #443) and merges in up/portfolio-return-scope-v2 (#451) with one --no-ff merge, fddc431de. The base here is mirror/upstream-main, so until those merge, GitHub shows their commits here as well.

Held for #463, in draft. The owner decided on 2026-10-16 (comment 6207728111) that this stack does not merge until #463's trade-fee fix lands, and moved it back to draft on 2026-10-23.

Supersedes #376 as the upstream pre-flight for Portfolio::Performance. #376 sits on the old up/portfolio-drivers and is over 120 commits behind. #376 carried the return scope commits as its own cherry-picks; this branch merges #451 instead, so the return scope code has one source. #376 stays open until the owner decides.

  • Base: mirror/upstream-main at bf8d6cc39.
  • Head: up/portfolio-performance-v2 at c80ba2311.

Updated 2026-10-23, merge-down: the head moved from dc325b25a to c80ba2311, a clean merge of #450 at db414ee31. That brings #444's fc400f58f (with #443's c285e4a49 under it) and upstream main at 2250ba801. No change to this PR's own files. Portfolio tests on c80ba2311: 233 runs, 0 failures. Full suite on the stack top (#454 at 58d469e77): 13,375 runs, 61,229 assertions, 0 failures, 0 errors, 36 skips, on Ruby 3.4.9.

Updated 2026-10-22, adversarial review fixes: the head moved from ab71cf6e3 to dc325b25a. This answers adversarial review 6342842357 and nightly review 6328554675. The reply is comment 6349447249.

  • A merge brings in #450 at de2be1a7f, which carries #443's and #444's fixes and mirror bf8d6cc39.
  • 64403720b, "Scope performance to the family and stop a one-day account blanking it":
    • Family scoping. Accounts are loaded once through family.accounts.where(id: account_ids) and shared by DailyReturns and ReturnScope.resolve_all. A foreign id contributes nothing and is left out of the cache key. The query count is unchanged.
    • The one-day veto. time_weighted_supported? no longer withholds for one account with a single balance day. It needs any scope with two or more. MWR still withholds there, because ReturnScope returns INSUFFICIENT.
    • Suppressed days. MWR is withheld when a day is suppressed for an unvalued journal (#444's Row#unvalued_journal).
    • Comments. Added on suppressed_dates, on the use of Float in annualising, and on user in the cache key.
  • dc325b25a bumps CACHE_VERSION to v9, because those changes alter what a cached figure means.
  • Declined: LOCF eligibility (should fix 2), with the reasoning in the reply.
  • ab71cf6e3 (2026-10-18, before this round) merged #450's f283f3587.
  • Evidence. The new tests failed first, and each mutation failed its test. Portfolio tests: 259 runs, 0 failures. Full suite at the top of the stack (145e36d15, before the cache bump): 13,138 runs, 1 failure, 0 errors, 36 skips. The one failure is Provider::OpenaiTest's Ruby 3.4 Hash#inspect assertion; the local run used Ruby 3.3.6. CI on dc325b25a is green.

Updated 2026-10-15: the head moved from 88fdbd232 to fce8b6868, a clean merge of #450 at f9b99fd45 (the overnight review fixes on #443 and #444). No change to this PR's own files. This PR's eligibility query-count tests caught a first, unpushed version of the liability check that queried in DailyReturns#initialize; it now runs at query time. Portfolio model and investment statement tests on fce8b6868: 238 runs, 0 failures. Full suite on #454 at 4d6909c07: 12,001 runs, 0 failures, 0 errors.

Updated 2026-10-14: the head moved from 7fc5ba1e0 to 1c035deb9, with merges only: d21d823f9 merges drivers (6525686e0), and 1c58a3b35 and 1c035deb9 merge return scope at 9cd1395af and 603257ae2. Together they bring in the classifier-SQL bind fixes in DailyReturns and ReturnScope#external_transactions? (full review 6168438106 on #443; see #451). This slice's own files were unchanged at that head, and the portfolio model tests passed (183 runs, 0 failures). Later heads change files, listed below.
Updated 2026-10-14 (2): what changed after 1c035deb9 (full review 6171788835, finding 1).

  • 402b306a2 merges return scope at 20716ccd1, which removes ReturnScope#valuations? and the batch :valuations key (#451; return_scope.rb 38 lines, return_scope_test.rb 45 lines).

  • e7925cfbb is a comment-only change to performance.rb ("four" per-account eligibility queries becomes "three").

  • Stack fix pass, head 88fdbd232: 297cb9a3f merges drivers at cc334ffab. That brings #443's one-row-per-entry transfer join (the nightly 6172426146 blocker), the flow FX and excluded-entry changes, #444's journal carry, and #450's Drivers#fees comment. 88fdbd232 merges return scope at b07e2bcee, so zero-quantity dividend, interest and fee trades no longer count as trade tracking.

  • Evidence. Portfolio model and investment statement tests on 88fdbd232: 231 runs, 0 failures. Brakeman reports 0 warnings. The full suite ran on the top of the stack, #454 at 14b956621, which contains this head: 11,993 runs, 0 failures, 0 errors. The root cause (per-leg unique indexes on transfers) is raised separately as jaysbeekay/sure#459 / we-promise/sure#4225.

  • Stacked above it: income, #453 (up/portfolio-income-v2), then income by security, #454.

Commits (this PR's own)

Cherry-picked from #376. Every patch is identical to its original (same git patch-id), with no conflicts.

Commit#376 originalSubject
8a480fc12b9cc535a7Report time- and money-weighted returns for a set of accounts
3cd8dd8379cd02d1e8Count eligibility queries past the query cache
73d62112bd57b5808cDrop the flow scope option from Performance
e03d9f67b78faaf8aaLay the period money-weighted fixture at the stored scale
dccc88b9db033f1acbResolve return eligibility over the accounts' cut-offs
580260c2cd0470cedcWithhold time-weighted figures when the scope held nothing
b6409a2228c89fcc0fRemove the fee fixture no test in this slice uses
e286b57cbe24b386f2Carry the money-weighted return's ambiguity with its rate
0b89e78c7e46098f9bDrive a real journal from the balance calculator to Performance
c71989936dba9fcb3bRound each chained return level to 20 significant digits
7fc5ba1e0274f314f9Check the bounded-precision test against a non-zero return
e7925cfbb(new)Count three per-account eligibility queries, not four
64403720b(new)Scope performance to the family and stop a one-day account blanking it
dc325b25a(new)Bump the performance cache version for the scoping and TWR change

Arriving by merge from #451: 9cd1395af, 603257ae2, 20716ccd1 (merge 402b306a2) and b07e2bcee (merge 88fdbd232).

  • One message edited. dba9fcb3b's last line named this fork's review and PR number ("Answers the code master review ... on #376 ..."). c71989936 drops that line; the patch and the rest of the message are unchanged.
  • Not carried: #376's four cherry-picks of the return scope commits (1f55292ef, 5cd594f9e, bbd5e9ace, 164e38dcd), which the merge of #451 replaces, and #376's three --no-ff merges of the drivers branch.
  • Files against #376's head 07b10a112: performance.rb, performance_test.rb, return_scope.rb, drivers.rb, daily_returns.rb and the helper were byte-identical before the 2026-10-22 round. The one difference is deliberate: return_scope_test.rb gains the 18-line test "the balance builder refuses an amount finer than balances store", from #375's 3d2392d16. #376 never carried it because its cherry-picks skipped that commit; it now comes in with #451.

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), its annualised form and whether the solve was ambiguous;
  • volatility, maximum drawdown and a rebased index series;
  • the drivers breakdown.

What changed

app/models/portfolio/performance.rb (new, 415 lines):

  • Tenancy. The requested ids are resolved through family.accounts, so another family's account contributes nothing.
  • TWR chains every day's return.
  • Annualisation only from 365 days up, for both TWR and MWR.
  • 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. money_weighted_return_ambiguous? carries Xirr#ambiguous?.
  • Volatility is the sample standard deviation of calendar-daily returns, annualised by √365.
  • Withholding.
    • A missing rate withholds every ratio, though the drivers are still reported.
    • A scope with no account holding two balance days withholds every time-weighted figure. One new account with a single day does not.
    • Any account that cannot support a money-weighted return withholds MWR (Portfolio::ReturnScope, resolved once per instance over the accounts' cut-offs), and so does a day suppressed for an unvalued journal.
  • Precision. Each chained level goes through compound, BigDecimal#mult at 20 significant digits, so two years of daily returns stay small.
  • Caching on Family#build_cache_key(..., invalidate_on_data_updates: true), plus the family currency and the cut-off dates. CACHE_VERSION v9.

Size. 415 non-test lines, over the guideline because each figure carries the reasoning for its convention.

Demo data

None needed: model only, no UI.

Migration notes

None. No schema change.

Blast radius

Who else hits this line, and what do they pass? No caller yet: git grep -n "Portfolio::Performance" app lib finds the new file and comments in daily_returns.rb and return_scope.rb.

What else reads what I just changed the reading of? This slice's own change is the new performance.rb. It builds Portfolio::Xirr.new(flows, days_per_unit:) (merged in we-promise/sure#3611) and reads rate and ambiguous? together. It also reads Portfolio::Drivers#to_h, Portfolio::ReturnScope.resolve_all, Portfolio::DailyReturns::Row#unvalued_journal and Family#build_cache_key. ReturnScope has changed in #451 (20716ccd1 drops valuations?, b07e2bcee counts only quantity trades), and it arrives here by merge. resolve_all's signature and return shape are the same.

Verification (on 7fc5ba1e0; later rounds are in the updates above)

  • test/models/portfolio/performance_test.rb: 36 runs, 117 assertions, 0 failures. All portfolio model tests: 180 runs, 731 assertions, 0 failures.
  • Full suite: 11,942 runs, 54,949 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16.
  • 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 or JS changed.
  • Mutations re-run on this base, each against performance_test.rb and restored after. All are caught:
    • compound unrounded (the precision fix reverted): 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 in place of √365: 1;
    • resolve_all called without the cut-offs: 1.
  • Carried from #376. performance.rb was unchanged apart from e7925cfbb's comment until the 2026-10-22 round, so its full mutation list, the fix-round table and the precision follow-up still apply.

Review history carried from #376

Every review on #376 is answered there: the light review 6066668857 (6074650227), the code-master review 6105957659 and the nightly review 6120599740 (6141125217), and three cubic threads, all resolved. The nightly review 6157135071 (2026-10-13, MEDIUM: merge the dependencies first, retarget to the resulting base and rerun the precision test and full CI) is what this rebuild does. The precision test passes here, on current main, inside the 36 runs above.