Portfolio returns engine: TWR, MWR, volatility, drivers (#121)
Summary
Draft delivery of the model layer of #121 (IP2, performance engine), part of #118. It adds:
- time-weighted and money-weighted returns;
- annualised return, volatility and max drawdown;
- a drivers breakdown that must reconcile.
All of it sits behind a normative contract (docs/portfolio/returns-contract.md, R1–R17, with flow table F1–F14 and a precedence note) that a CI step keeps bound to live tests.
No UI. Reconciled onto #133 and ready. This branch was built before #133 (IP0 foundations) existed and carried its own Portfolio::FlowClassifier, which #133 also delivered. #133 merged on 2026-09-14, the reconciliation is complete, and the branch now adopts main's classifier, one coverage task that checks both contracts, and the historical account scope. What the reconciliation decided, and why, is in "Reconciliation with #133" below rather than left as an open question.
CI is green at d2cfa5a5a: 14/14 check runs success, including ci/test_unit, ci/test_system, ci/lint, CodeQL, Codacy and CodeRabbit. Review 5208066665 found two financial-correctness defects; both are fixed in d2cfa5a5a together with a third that shared their cause, per the owner's decisions on #121 (see "Decisions" and "Validation"). The evidence that is still missing is named in the checklist and in "Risks and follow-up"; it is evidence, not code.
Scope and dependencies
-
Parent PR/branch, if stacked: none. Branched from fork
mainatea8627183and rebased onto currentmainafter #133 merged. Both dependencies are now merged: #133 (the flow classifier it consumes) and #134 (the hub that will render 2.4/2.6). -
Delivered:
Issue PR Content Where 2.1 Portfolio::DailyReturns: dailyr_t = V_end / (V_open + F_t) − 1frombalances, FX-converted per datedaily_returns.rb, R1, R2, R6, R132.2 Portfolio::Performance(TWR, annualised TWR, MWR, volatility, max drawdown) andPortfolio::Xirr;Portfolio::Driverswith measuredfx_effectand an explicitunexplainedtermperformance.rb,xirr.rb,drivers.rb, R3–R5, R7–R12, R142.3 Portfolio::ReturnScope: value return vs money-weighted per account; insufficient historyreturn_scope.rb, R15, R162.5 Period keys already satisfied by Period::PERIODS(last_day,current_week,current_month,current_year,last_5_years,all_time); no change -
Intentionally out of scope:
Decisions (D1–D9 from the readiness review on #121)
| Decision | Contract row | |
|---|---|---|
| D1 | Start-of-day flow timing | R1 |
| D2 | Family currency, FX inside the return, attributed by fx_effect | R2, R11 |
| D3 | Calendar-daily volatility annualised by √365, not √252 | R5 |
| D4 | Annualise only periods of 365 days or more | R4 |
| D5 | A non-positive denominator suppresses the day (return 0, recorded) | R6 |
| D6 | The loan payoff chart controller is not generalised | no code here; applies to 2.4 |
| D7 | Comparison chart: top five accounts plus "all" | not built; applies to 2.4 |
| D8 | Cache on build_cache_key(invalidate_on_data_updates: true), not entries_cache_version | R14 |
| D9 | Returns net of fees; fees reported separately | R7 |
| D5b (amended) | An account entering or leaving the scope is a composition flow, not a return: its opening value arrives, its closing value departs, at the previous day's rate (Option A). Replaces suppressing the departure day | R17, R1, R8, R12 |
| P1a gate | An account with exactly one balance day withholds every time-weighted figure; an account with none does not block | R15 |
As on #119 and #120, these are the readiness review's recommended assumptions. No owner confirmation is recorded on #121.
Evidence checklist
-
Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
-
Contract rows touched by this change name existing tests (
docs/portfolio/returns-contract.mdR1–R17, checked byportfolio:verify_contract_coverage, added to CI beside the loans gate). -
Any gate test has an observed failing mutation transcript attached. Re-run against the adopted classifier and attached in https://github.com/jaysbeekay/sure/pull/148#issuecomment-5677123001: of M1–M13, twelve killed and M11 is not applicable (its code is now
main's classifier); of the six later fixes, five killed and X5 (Newton's residual check) survived, now killed by the test added ine9ef327ef.Re-running them against the adopted classifier requires executing the suite, and the environment this branch is being worked in cannot boot Rails:
.ruby-versionpins 3.4.9 and the machine has 3.3.6, sobin/railsandbin/rubocopdo not start. This is stated plainly rather than deferred to a date: the transcripts need a machine that can run the suite, and every "green" claim below rests on CI, not on a local run. -
Fixtures used as evidence assert internal consistency (the textbook TWR case and the drivers reconciliation are hand-computable).
-
Financial calculations use
BigDecimaland documented rounding points (returns are ratios, never rounded in the model layer). -
De-identification uses token-shape allowlists; no personal data is included.
-
Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Exit criteria from #121
| Assertion | Test |
|---|---|
| Deposit 1 000 → 1 100, deposit 1 000 → 2 310 gives TWR 21.0 % and a different MWR | Portfolio::PerformanceTest "twr matches the hand computed textbook case", "mwr differs from twr when flows are unevenly timed" |
| A dividend paid to cash leaves TWR unchanged | Portfolio::DailyReturnsTest "a dividend is income rather than an external flow", "a transaction shaped dividend is income too" |
An FX-only move shows in fx_effect, not market | Portfolio::DriversTest "fx effect carries a rate only move and market stays zero" |
| Drivers sum to end − start to the cent, and can fail to | Portfolio::DriversTest "drivers reconcile to the period change for every account shape", "reconciles is falsifiable and reports an unexplained move" (R12: unexplained is measured, not a residual) |
Xirr converges on a sign-changing series and raises on one with no sign change | Portfolio::XirrTest "raises when the series never changes sign" |
Validation
Current evidence is a local run plus CI. The suite now runs locally in the dev container (Ruby 3.4.9, which .ruby-version pins); the earlier machine had 3.3.6 and could not boot bin/rails. The mutation evidence for this branch is in https://github.com/jaysbeekay/sure/pull/148#issuecomment-5677123001, and the measurements behind R9's accuracy wording are in https://github.com/jaysbeekay/sure/pull/148#discussion_r4013643194.
| Head | Result |
|---|---|
d2cfa5a5a (current: composition flows (R17) and the R15 aggregate gate, on f48e77277) | 14/14 CI check runs success, including ci/test_unit, ci/test_system, ci/lint, CodeQL, Codacy and CodeRabbit. Locally: full bin/rails test 8,963 runs, 37,225 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest's second PG.connect reads config[:username] while database.yml sets user:, so it fails authentication in the container; not touched by this PR), 30 skips, no out-of-memory kills; portfolio tests, investment statement, coverage gate and task tests, 196 runs, 0 failures; portfolio:verify_contract_coverage verified 40 methodology and 17 returns rows. Tests written first: 13 failures and 2 negative-test errors on the original engine. Mutations: all 12 killed, each by a named test, with the working tree byte-identical afterwards. N1 arrivals dropped (8 tests), N2 departures dropped (3), N3 MWR ignores composition (2), N4 unexplained ignores composition (1), N5 arrival from end_balance (only an account arriving and gaining on its first day keeps that day's gain), N6 same-day rate on arrival (1), N7 a first row on the period's first day counted as an arrival (19), N8 R15 gate removed (2), N9 gate blocks empty accounts (1), N10 departure day suppressed again, re-running X1 (1), N11 departures counted rather than measured, re-running X2 (5), N12 arrival ignores the cut-off window (only an account whose first balance row falls after its cut off never arrives) |
f48e77277 (R9 accuracy wording only, on fa520720f) | 14/14 CI check runs success, including ci/test_unit, ci/test_system, ci/lint, CodeQL, Codacy and CodeRabbit. portfolio:verify_contract_coverage verified 40 methodology and 16 returns rows locally before the push |
fa520720f (e9ef327ef plus a merge of main, which changes only CLAUDE.md and .coderabbit.yaml) | 14/14 CI check runs success, including ci/test_unit, ci/test_system, ci/lint, CodeQL, Codacy and CodeRabbit. Locally, on the merged tree: this PR's tests and ContractCoverageTest, 151 runs, 462 assertions, 0 failures; the contract gate verified 40 methodology and 16 returns rows |
e9ef327ef | Local full bin/rails test: 8,948 runs, 37,170 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest's second PG.connect reads config[:username] while database.yml sets user:, so it fails authentication in the container; not touched by this PR), 30 skips. bin/rubocop on the changed test: no offenses |
f5a5ee4b | 13/13 CI check runs success, including ci/test_unit, ci/test_system, ci/lint, CodeQL, Codacy (0 new issues) |
| b04c8195 | 13/13 CI check runs success |
Earlier local runs, retained as history:
| Command | Result |
|---|---|
bin/rails test | 8770 runs, 36300 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect, which fails password auth on this machine on every branch), 30 skips |
bin/rails portfolio:verify_contract_coverage | Verified 16 returns-contract rows against existing tests. Now reports both contracts: 40 methodology and 16 returns contract rows, after the task was unified with #133's |
bin/rails test at a2b44874d (SHA-256 cache-key digest; CodeQL and Codacy MD5 alerts) | 8770 runs, 36300 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect, which fails password auth on this machine on every branch), 30 skips |
bin/rails test at 548ceb2a1 (review round: cubic's 17 findings) | 8784 runs, 36324 assertions, 0 failures, 1 error (environmental: RecurringTransaction::PipelineTest opens its own PG.connect, which fails password auth on this machine on every branch), 30 skips |
test/models/portfolio, InvestmentStatementTest at 548ceb2a1 | 86 runs, 214 assertions, 0 failures |
bin/rubocop (changed Ruby files) | 15 files, no offenses |
bin/brakeman --no-pager | 0 security warnings, 0 errors |
erb_lint, npm run lint, system tests | not applicable: no ERB, JS or view change |
| Migrations, OpenAPI | none |
Blast radius
InvestmentStatementgains two methods,performance(period:)(aPortfolio::Performanceover the statement's investment accounts) andreturn_scopes(period:)(aPortfolio::ReturnScopeper account, keyed by account id). Both default toPeriod.current_month_for(family). No existing method changes behaviour, and nothing inapp/calls either yet..github/workflows/ci.ymlgains one step,portfolio:verify_contract_coverage, beside the loans gate.- The engine only reads (
balances,entries,exchange_rates,transfers) and never writes, so it is safe from a GET. Portfolio::Performance#cache_keydigests its account and scope ids with SHA-256 (a2b44874d); the key is not a security boundary, and the change only moves every performance key once.
Reconciliation with #133
#133 merged on 2026-09-14 and this branch was rebased onto it. The four files that both branches added are now one set, and the three semantic forks have answers rather than options.
| File | Resolution |
|---|---|
app/models/portfolio/flow_classifier.rb | Main's, adopted. No longer in this branch's changed files. ReturnScope and DailyReturns both consume its sql_case / sql_joins, so there is one flow-semantics definition |
test/models/portfolio/flow_classifier_test.rb | Main's. The two parity corpora merged into one |
lib/tasks/portfolio.rake | One task. portfolio:verify_contract_coverage checks the methodology P-rows and these R-rows in a single pass |
.github/workflows/ci.yml | One step, beside the loans gate |
The shared declared_tests and class_body helpers were lifted to Portfolio::ContractCoverage so both contract readers use the same Ripper token-stream check, rather than a second reader reintroducing the regex hole #133 closed.
The three semantic forks, resolved to main's rules:
| Fork | This branch had | Resolution |
|---|---|---|
| Security transfers | F3: a Transfer-labelled trade is internal | Main's P16. External unless its opposite leg is in scope |
| Excluded entries | F9: excluded reads as internal through COALESCE | Main's P18. Left unclassified (nil / NULL) |
| Account scope | Visible investment accounts, so a closed account's history dropped out | Main's P5. InvestmentStatement#historical_scope, used by both performance and return_scopes; active_until_dates was already plumbed through DailyReturns |
The contract carries the tiebreak in its own words: if the table and the classifier ever disagree, the classifier and the P-rows are right and the table is stale.
Risks and follow-up
Open evidence, not open code:
- Mutation transcripts — see the checklist above. Measured against a deleted classifier, and not re-runnable in an environment that cannot boot Rails.
- Owner decisions are recorded on #121: D1–D6, D8 and D9 confirmed and D7 deferred (https://github.com/jaysbeekay/sure/issues/121#issuecomment-5677780796). D5b amended to Option A (composition flows), the P1a aggregate gate, and short-period MWR tracked in #156 (triage plan: https://github.com/jaysbeekay/sure/issues/121#issuecomment-5678035407). The contract still reads "draft for engineering and product sign-off"; that line is updated separately.
- Residual composition shapes not exercised: an incremental forward sync (
window_start_date) and a QIF import that moves the opening anchor. The rule reads the first balance row'sstart_balance, which all three calculator paths tested write as the opening position; these two paths were not run. - #156: money-weighted return is annualised even for periods of a few days (a two-day gain reported 603). Tracked separately by owner decision.
Known limitations, each pinned by a test or an issue rather than left as trivia:
- #151 — a security journalled in from outside the scope reads as return, not flow. The entry carries
amount: 0, so the classification is correct and the consequence is not. Written into the contract's Known Limitations as F10 and guarded by a test that fails if the behaviour silently changes. - #152 — the contract-coverage gate accepts a
testthe named class does not declare. The defect is inmain'scontract_coverage.rbfrom #133; this branch only promoted two of its methods to singletons, which widens the blast radius rather than causing it. - #154 —
Portfolio::ReturnScoperesolves one account at a time, so eligibility costs up to four queries per account andPerformanceandInvestmentStatementeach build their own. Raised by Codacy on this PR; deliberately not fixed here because the fix is a batch resolver, and a second path deriving eligibility is the defect classCLAUDE.mdwarns about on this epic. all_timeand wide scopes are UNVERIFIED. Therate_lookupsubquery is O(N×D) and no benchmark or query plan is attached. A deliberate deferral with a specification on its thread; worth a number before #134's UI calls these on wide scopes.
Review rounds, for the record: cubic's 17 findings, CodeRabbit's 7 on the pre-reconciliation head plus 1 after (the composition-change signal, fixed in f5a5ee4b), Codacy's 4, and two gatekeeper passes. Every finding is either fixed with a regression test, or answered on its thread with the reason and an issue.
- Next unblocked once this merges: the 2.4 dashboard and 2.6 realised P&L on the hub, then #124 (benchmarks), #127 (FIRE planner) and #131 (assistant tools).
Summary by CodeRabbit
-
New Features
- Added portfolio performance metrics, including time-weighted and money-weighted returns, annualization, volatility, drawdown, and XIRR.
- Added daily return breakdowns for flows, income, fees, market movement, revaluations, currency effects, and unexplained changes.
- Added return scopes, historical cutoffs, missing-rate detection, suppressed-return handling, reconciliation, and performance caching.
- Integrated performance and return scopes into investment statements, including custom family periods.
-
Documentation
- Added a comprehensive returns contract covering calculations, account scenarios, flow classification, and limitations.
-
Tests
- Expanded coverage for portfolio returns, currency conversion, flow handling, valuation changes, and contract verification.
Generated by Claude Code