Portfolio returns engine: TWR, MWR, volatility, drivers (#121)

Merged
JA
3mo ago
+3141-46

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

  • Issue: #121 (part of #118).

  • Parent PR/branch, if stacked: none. Branched from fork main at ea8627183 and rebased onto current main after #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 PRContentWhere
    2.1Portfolio::DailyReturns: daily r_t = V_end / (V_open + F_t) − 1 from balances, FX-converted per datedaily_returns.rb, R1, R2, R6, R13
    2.2Portfolio::Performance (TWR, annualised TWR, MWR, volatility, max drawdown) and Portfolio::Xirr; Portfolio::Drivers with measured fx_effect and an explicit unexplained termperformance.rb, xirr.rb, drivers.rb, R3–R5, R7–R12, R14
    2.3Portfolio::ReturnScope: value return vs money-weighted per account; insufficient historyreturn_scope.rb, R15, R16
    2.5Period keysalready satisfied by Period::PERIODS (last_day, current_week, current_month, current_year, last_5_years, all_time); no change
  • Intentionally out of scope:

    • 2.4, the performance UI, which needs #134's section framework.
    • 2.6, the realised P&L timeline, which has no rendering surface until #134 merges.
    • Upstream delivery.

Decisions (D1–D9 from the readiness review on #121)

DecisionContract row
D1Start-of-day flow timingR1
D2Family currency, FX inside the return, attributed by fx_effectR2, R11
D3Calendar-daily volatility annualised by √365, not √252R5
D4Annualise only periods of 365 days or moreR4
D5A non-positive denominator suppresses the day (return 0, recorded)R6
D6The loan payoff chart controller is not generalisedno code here; applies to 2.4
D7Comparison chart: top five accounts plus "all"not built; applies to 2.4
D8Cache on build_cache_key(invalidate_on_data_updates: true), not entries_cache_versionR14
D9Returns net of fees; fees reported separatelyR7
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 dayR17, R1, R8, R12
P1a gateAn account with exactly one balance day withholds every time-weighted figure; an account with none does not blockR15

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.md R1–R17, checked by portfolio: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 in e9ef327ef.

    Re-running them against the adopted classifier requires executing the suite, and the environment this branch is being worked in cannot boot Rails: .ruby-version pins 3.4.9 and the machine has 3.3.6, so bin/rails and bin/rubocop do 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 BigDecimal and 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

AssertionTest
Deposit 1 000 → 1 100, deposit 1 000 → 2 310 gives TWR 21.0 % and a different MWRPortfolio::PerformanceTest "twr matches the hand computed textbook case", "mwr differs from twr when flows are unevenly timed"
A dividend paid to cash leaves TWR unchangedPortfolio::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 marketPortfolio::DriversTest "fx effect carries a rate only move and market stays zero"
Drivers sum to end − start to the cent, and can fail toPortfolio::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 changePortfolio::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.

HeadResult
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
e9ef327efLocal 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
f5a5ee4b13/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:

CommandResult
bin/rails test8770 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_coverageVerified 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 548ceb2a186 runs, 214 assertions, 0 failures
bin/rubocop (changed Ruby files)15 files, no offenses
bin/brakeman --no-pager0 security warnings, 0 errors
erb_lint, npm run lint, system testsnot applicable: no ERB, JS or view change
Migrations, OpenAPInone

Blast radius

  • InvestmentStatement gains two methods, performance(period:) (a Portfolio::Performance over the statement's investment accounts) and return_scopes(period:) (a Portfolio::ReturnScope per account, keyed by account id). Both default to Period.current_month_for(family). No existing method changes behaviour, and nothing in app/ calls either yet.
  • .github/workflows/ci.yml gains 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_key digests 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.

FileResolution
app/models/portfolio/flow_classifier.rbMain'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.rbMain's. The two parity corpora merged into one
lib/tasks/portfolio.rakeOne task. portfolio:verify_contract_coverage checks the methodology P-rows and these R-rows in a single pass
.github/workflows/ci.ymlOne 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:

ForkThis branch hadResolution
Security transfersF3: a Transfer-labelled trade is internalMain's P16. External unless its opposite leg is in scope
Excluded entriesF9: excluded reads as internal through COALESCEMain's P18. Left unclassified (nil / NULL)
Account scopeVisible investment accounts, so a closed account's history dropped outMain'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's start_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 test the named class does not declare. The defect is in main's contract_coverage.rb from #133; this branch only promoted two of its methods to singletons, which widens the blast radius rather than causing it.
  • #154 — Portfolio::ReturnScope resolves one account at a time, so eligibility costs up to four queries per account and Performance and InvestmentStatement each 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 class CLAUDE.md warns about on this epic.
  • all_time and wide scopes are UNVERIFIED. The rate_lookup subquery 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