Break a period's change in value into its drivers

Draft
JA
2mo ago
+414-0

Part of #121

This is the upstream pre-flight for slice 3 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 3 of 7 of the portfolio returns engine; we-promise/sure#4078 is the issue (part 3, returns engine).

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

Stacked on the journal flows PR. Until that merges, GitHub shows its commits here as well; this PR's own commits are the ones after up/portfolio-journal-flows. 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.

Nothing calls these classes until Portfolio::Performance (the fifth PR in this stack). Every PR before it adds a model with its tests and no caller, so it changes no page, job or API response.

Summary

Adds Portfolio::Drivers, which says where a period's change in value came from: net external flows, composition (accounts entering or leaving), income, fees, market movement, revaluations and the currency effect, with the residual reported as unexplained.

What changed

app/models/portfolio/drivers.rb (new): sums the daily rows' components.

  • external_net + composition + income - fees + market + revaluations + fx_effect == change.
  • fx_effect is measured per day by DailyReturns, not taken as the residual, so reconciles? can return false and unexplained is a real figure.
  • revaluations is reported apart from market: on a valuation day the whole move lands in the balance adjustments, so a manually valued account would otherwise show a flat zero market move.
  • RECONCILE_TOLERANCE is one minor unit, because a multi-currency family accumulates sub-cent dust from converting entries and balance rows by different paths. A known limitation for zero-decimal currencies (JPY) is noted in the code.

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

  • drivers_test.rb: 9 runs, 34 assertions, 0 failures.
  • Mutations, all caught:
    • fees added instead of subtracted: 2 tests;
    • composition left out of unexplained: 1;
    • fx_effect taken as the residual: 1 ("reconciles is falsifiable");
    • revaluations folded into market: 2;
    • reconciles? always true: 1;
    • value_open from the last row: 2;
    • an empty scope raising: 1.
  • The tolerance mutants (0, 0.02, and < in place of <=) survived the original tests. They are caught by the new "reconciles allows a residual of up to one minor unit", which checks 0.004, the 0.01 boundary and 0.015.
  • Full suite after the engine fix round, at the top of the stack (up/portfolio-income-by-security at d33443696): 10,777 runs, 45,964 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. It reads only daily_returns.rows.

What else reads what I just changed the reading of? Nothing is changed outside the new file.

Engine fix round (2026-10-09)

The branch first merges up/portfolio-journal-flows down: a --no-ff merge, clean, no force push.

Contract: drivers over a suppressed day

This answers the light review's observation.

  • What happens on a suppressed journal day. DailyReturns suppresses a day carrying a journal it cannot value: no holding row (journal_holdings.currency NULL), a zero price, or no rate for the holding's currency. On that day the journal is not an external flow, so its value stays wherever the balance row booked it, in market.
  • So the identity still holds. unexplained is 0 and reconciles? is true, while market reports a gain the holdings never earned. This corrects the review's expectation of a non-zero unexplained: the test below shows the residual is zero in this shape. That makes it worse, not better, because nothing in unexplained or reconciles? can flag it. When no holding row exists, rate_missing? is not set either, so Performance withholds nothing.
  • Chosen: Drivers reports suppression explicitly. It gains suppressed_dates, complete? (false when any day in the period was suppressed) and to_h[:suppressed_days] (a count, so the cached hash stays plain values). reconciles? is documented as speaking only to the rows as recorded, to be read together with complete?. Anything presenting the drivers reads complete? / suppressed_days and says a day was left out.
  • Rejected: Performance withholds the drivers on any suppressed day. Suppression also covers a non-positive denominator (an over-withdrawal), whose drivers are complete. Row#suppressed does not record which kind of day it was, so withholding would blank correct figures. Performance already reports the drivers when a rate is missing, on the grounds that they are money.
CommitChangeTestFail-first / mutation
7598762acDrivers exposes suppression"a suppressed journal day still reconciles, so the drivers say a day was suppressed" (journal with no holding row; asserts suppressed, rate_missing? false, external_net 0, market 500, unexplained 0, reconciles? true, complete? false, suppressed_dates, suppressed_days 1). Control added to "an ordinary period leaves nothing unexplained".failed on the missing complete? while every pre-existing assertion above it passed; complete? → true caught (:185); suppressed_days: 0 caught (:187)
  • drivers_test.rb: 10 runs, 45 assertions, 0 failures. All portfolio model tests on this head: 118 runs, 0 failures.