Add a daily return series for a set of investment accounts
Part of #121
This is the upstream pre-flight for slice 1 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 1 of 7 of the portfolio returns engine; we-promise/sure#4078 is the issue (part 3, returns engine).
Fork pre-flight PR: jaysbeekay/sure#372 (https://github.com/jaysbeekay/sure/pull/372), same branch, same commit.
Stacked on we-promise/sure#3557 (up/pending-sql-parity). Until that merges, GitHub shows its commits here as well; this PR's own commits are the ones after up/pending-sql-parity. 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.
Within this stack, nothing calls these classes until Portfolio::Performance (the fifth PR). Outside it, the net contributions series (jaysbeekay/sure#343 (upstream we-promise/sure#4028)) reads Portfolio::DailyReturns for its flows, so a change to the daily rows also reaches that series. No page, job or API response in this stack changes before Performance.
Known interim state: with the first PR alone, a security journalled in from another broker (a Transfer-labelled trade with amount: 0) is valued at its cash amount, nothing, so the arriving position reads as a gain. The second PR (journal flows) closes that. Nothing calls the class in between, so no user sees it.
Summary
Adds Portfolio::DailyReturns: for a set of investment accounts over a period, one row per calendar day in the family's currency, with the day's opening and closing value, external flows, income, fees, market movement, revaluations and currency effect, and the daily return r_t = V_close / (V_open + F) - 1.
It is the series every return figure in this stack is built on. It is computed in one SQL query and finished in BigDecimal in Ruby, where the arithmetic can be unit-tested.
What changed
app/models/portfolio/daily_returns.rb (new):
- Start-of-day flows. A deposit or withdrawal joins the day's denominator, so moving your own money is not a return.
- Currency. Each local component converts at the previous day's rate and the currency effect is measured as the closing local balance times the rate change, so the parts add up to the day's change and anything they do not explain shows up in
Row#unexplainedrather than being defined away. - Missing rates. Rates are carried forward, then back (an account older than the family's rate history converts at the earliest rate on file). A pair with no rate at all is flagged in
rate_missing?, never converted at 1. Only accounts that hold a balance, and flows that feed a figure, can raise it. - Suppression. A day whose denominator is zero or negative contributes 0 and is listed in
suppressed_rows, rather than dividing by zero or flipping the sign of a gain. - Accounts entering and leaving. With
active_until_dates, an account stops contributing after its cut-off; the value it carries out, and the opening value an account brings in mid-period, are acomposition_flow, not a gain or a loss. - Carried-forward rows. Market and adjustment components come from a balance row dated that day only, so a gap does not repeat yesterday's market move; a row carried in from before the period opens at its closing level.
- What counts as an external flow, income or a fee comes from
Portfolio::FlowClassifier(we-promise/sure#3557), with the series' own accounts as the inside of the scope (the earlierscope_account_idsoption is removed; see the fix round below).
test/support/portfolio_returns_test_helper.rb (new): builders that refuse to lay a balance day whose components do not add up to its closing figure, so a test cannot absorb its own arithmetic error.
Size. 447 non-test lines, over the ~300 guideline. About 270 are code, and most of that is one SQL query whose parts (balances, flows, arrivals, departures) only mean anything together; the rest is comments on why each join and rate is the one it is. Splitting the query would ship pieces that cannot be tested on their own.
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
bin/rails test test/models/portfolio/daily_returns_test.rb: 29 runs, 85 assertions, 0 failures.- Mutations, each run against this file's tests (restored with
git checkoutafter each). Every one is caught:- flow left out of the denominator: 9 tests;
- no composition flow: 8;
- departures ignored: 2;
- components at today's rate: 1;
- flows at the entry date's rate: caught by the new "a foreign currency flow converts at the previous day's rate";
- a parity fallback added to the rate lookup: 2;
- no carry-back rate: caught by the new "a balance before the first stored rate converts at the earliest rate after it";
- no suppression: 2;
- flows not windowed by cut-off: 1;
- bare
excluded = false: 1; - missing flow rate not flagged: 1;
- carried-forward row opening at
start_balance: 1; - market read from a carried-forward row: 2;
- first-day row counted as an arrival: 2.
- Fail-first: the two new tests were written after the first mutation run showed both mutants surviving, and each now fails under its mutant.
- Full suite after the engine fix round, at the top of the stack (
up/portfolio-income-by-securityat d33443696): 10,777 runs, 45,964 assertions, 0 failures, 0 errors, 33 skips (local, PostgreSQL 16, 4 workers). bin/rubocopon 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 one: the class is new and has no caller in this PR. It reads Portfolio::FlowClassifier#sql_case / #sql_joins, built on the series' own account_ids, and the balances, entries, trades, transactions and exchange_rates tables, all unchanged.
What else reads what I just changed the reading of? Nothing is changed. grep -rn "Portfolio::DailyReturns" app lib returns only this file.
Engine fix round (2026-10-09)
These commits come after the light Gatekeeper review and the cubic review. Each behavioural fix was written test first and then broken deliberately to show the test catches it.
| Commit | Finding | Test | Fail-first / mutation |
|---|---|---|---|
| b895dd963 | cubic Vbqq: no negative-denominator case | "an over-withdrawal suppresses the day rather than reversing its sign" | coverage gap, passes on the code as is; suppressed: denominator.zero? caught (:87) |
| ec08ea164 | cubic Vbqu: all-zero foreign rows flag rate_missing | "a foreign account whose balance rows are all zero does not flag a missing rate", plus control "a foreign account that opened the period holding a balance still flags a missing rate" | failed at :459; reverting to end_balance IS NOT NULL caught (:459); dropping the start_balance half caught (:472) |
| 6b5f0d850 | cubic Vbq1: a wider scope_account_ids reads a transfer out as a loss | "the flow scope cannot be widened beyond the accounts in the series", "a transfer to an account outside the series is a flow out, not a loss" | owner decision: option removed; failed at :593 (no ArgumentError); classifier on every account caught (:585) |
| 69236dc31 | cubic VYFF (on #375): lay_balance accepts sub-4dp amounts | "the balance builder refuses an amount finer than balances store" | failed at :608; skipping the scale check caught (:608) |
- Gatekeeper recommendation (re-run this file once journal flows lands): on #373's head, all 49
daily_returns_test.rbtests pass, the journal tests included. A security journalled in now reads as an external flow, not a gain. - Corrected claim. The earlier description said nothing calls
DailyReturnsuntil Performance. That is not so: the net contributions series (#343, upstream we-promise/sure#4028) readsPortfolio::DailyReturnsfor its flows. daily_returns_test.rb: 35 runs, 95 assertions, 0 failures.