Add a daily return series for a set of investment accounts
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#4197 (pull/4197), opened 2026-10-14 from this same branch, so it moves with this head (now 823265070; the upstream page was not re-read from this session).
Held for #463, in draft. The owner decided on 2026-10-16 that this stack does not merge until #463's trade-fee fix lands, and moved it back to draft on 2026-10-23.
Supersedes #372 as the upstream pre-flight for Portfolio::DailyReturns. #372 sits on up/pending-sql-parity, which upstream has since squash-merged as we-promise/sure#3557, and is 123 commits behind. This branch is cut from current upstream main, so its diff shows only this slice. #372 stays open until the owner decides; fork #374 to #378 are stacked on the old journal-flows branch and are untouched.
- Base:
mirror/upstream-mainatbf8d6cc39. - Head:
up/portfolio-daily-returns-v2at823265070, with upstreammainmerged in.
Updated 2026-11-02: a bound value that spells a fragment marker stays a literal (11bb8a1bd, 0e334559a), answering we-promise/sure#4197 comment 6497302056; upstream main merged in at 823265070. Full suite: 14,293 runs, 0 failures, 0 errors.
Updated 2026-10-22, adversarial review fixes: the head moved from 150964275 to c285e4a49. Answers adversarial review 6342799973; the reply is comment 6349441118.
fa8abcc30, "Find a flow's rate as SyncCache does and respect cut-offs in the classifier":- The entry→account conversion uses the window
ExchangeRate::Provided#find_or_fetch_rateuses (exact date, else up to 5 days back, never a later rate). Otherwise the flow israte_missing. FlowClassifiertakesactive_until_dates:, so a transfer to an account after its cut-off is external, in both forms. The "known limit" from 2026-10-14 is gone.- The header states the tenancy contract: the caller scopes the ids. #452 does that scoping.
- The entry→account conversion uses the window
c285e4a49mergesmirror/upstream-mainatbf8d6cc39, cleanly.150964275(2026-10-18, before this round) made#classifyread a leg's transfer in the order the SQL does, with four classifier tests.- 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): 13,138 runs, 1 failure, 0 errors, 36 skips. The one failure isProvider::OpenaiTest's Ruby 3.4Hash#inspectassertion, because the local run used Ruby 3.3.6. Rubocop is clean. CI onc285e4a49is green.
Updated 2026-10-15, overnight review fixes: the head moved from 51c7d69c5 to 0f371528f. Four commits answer CodeRabbit threads PRRT_kwDOPRMXr86sdtD0 and PRRT_kwDOPRMXr86sdtD9 (raised on we-promise/sure#4213, code from this PR) and jjmata's comment 6182190180 on we-promise/sure#4197:
949c79511: underinclude_excluded: true, the security-transfer opposite-leg lookup (Ruby and SQL) counts an excluded leg, so both legs of a mixed excluded/live move are internal. The default is unchanged.6dc9f693f: the transfers lateral insql_joinsprefers the transfer a transaction is the inflow of, then the earliest, matchingtransfer_counterpart_account_id.943c160f6: the scope-widening test is pinned tounknown keyword: :scope_account_ids.0f371528f:DailyReturnsraisesArgumentErrorthe first time it queries a series holding a liability account (checked once per instance inbind_and_splice). Callers at the stack tips (Portfolio::Performance, the net contributions line) pass investment or crypto accounts.- Evidence. 4 new tests and 1 tightened, each failing first (the tightened one by a required-keyword mutation); 7 mutations, all caught. Full suite on
0f371528f: 11,870 runs, 54,699 assertions, 0 failures, 0 errors, 34 skips. Rubocop clean, Brakeman 0 warnings.
Updated 2026-10-14: the head moved from dc22ad370 to 0fe5578bb, which splices the flow classifier's SQL into the daily query after binding instead of re-sanitizing it (full review 6168438106; answered in 6169481206). Fail-first probe test, mutation and full suite (11,819 runs, 0 failures, 0 errors) are in 6169481206. The verification below is from dc22ad370.
Updated 2026-10-14 (2), stack fix pass: the head moved from b054f4de9 (a merge of mirror a3bb5d991) to 51c7d69c5, "Count each flow once and convert it as the balance did". It answers nightly review 6172428805 and the Codex threads on we-promise/sure#4197 and #4198:
-
Transfer fan-out (nightly blocker, option A).
Portfolio::FlowClassifier#sql_joinsreads transfers through aLEFT JOIN LATERAL ... ORDER BY created_at, id LIMIT 1, so it gives one row per entry by construction, and its contract comment says so. The root cause (per-leg unique indexes ontransfers) is raised separately as jaysbeekay/sure#459 / we-promise/sure#4225. -
Flow FX. A foreign entry converts into the account's currency on its own date, using the entry's
extra["exchange_rate"]first asBalance::SyncCachedoes, and then into the family currency at the previous day's rate. -
Missing-rate checks. A carried-forward row's
start_balanceis not checked, and a zero-amount flow cannot be missing a rate. -
Excluded entries (owner decision). They count as flows, because SyncCache still applies them.
FlowClassifiergainsinclude_excluded:. Split parents are skipped, as SyncCache skips them. This reverses the pinned test "an excluded entry contributes no flow". -
Known limit, documented. The classifier's scope ignores
active_until_dates. (Fixed 2026-10-22 infa8abcc30.) -
Evidence. Every change was test-first: 9 new or rewritten tests failed on
b054f4de9, and 8 mutations were all caught. Full suite on51c7d69c5: 11,866 runs, 54,680 assertions, 0 failures, 0 errors, 34 skips. Rubocop is clean and Brakeman reports 0 warnings. Reply: see the comment on this PR. -
Stacked above it: journal flows, #444 (
up/portfolio-journal-flows-v2), then net contributions, #343 (we-promise/sure#4028) and #344 (we-promise/sure#4029). The net contributions series readsPortfolio::DailyReturnsfor its flows. That series answers we-promise/sure#4008.
Commits
Cherry-picked from the rebased up/net-contributions-model (at 0ca4e5360), where they interleave by date with the journal-flows and net-contributions commits. The original #372 commits are in brackets. Each patch is identical to its original (same git patch-id), except 6655845de, whose context lines moved because the journal commits came first on the model branch. The resulting files were byte-identical to #372's head 69236dc31 (as rebuilt; later changes are in the updates above): git diff 69236dc31 HEAD -- <the three files> is empty.
| Commit | Rebased source | #372 original | Subject |
|---|---|---|---|
730baa513 | def7c1a27 | 8e31e65b4 | Add a daily return series for a set of investment accounts |
0063581e0 | a7d635280 | 08d694b89 | Pin the previous-day rate for flows and the rate carry-back |
e182a405e | e25f99f2a | b895dd963 | Pin that an over-withdrawal suppresses the day |
56de6dcf2 | becbcdb31 | ec08ea164 | Flag a missing rate only for a balance that needs converting |
6655845de | 74ead4aa3 | 6b5f0d850 | Classify flows against the accounts the series values |
dc22ad370 | 1a3f8f8b7 | 69236dc31 | Refuse balance fixture amounts finer than the stored scale |
0fe5578bb | (new) | (new) | Splice classifier SQL into daily returns after binding |
51c7d69c5 | (new) | (new) | Count each flow once and convert it as the balance did |
150964275 | (new) | (new) | Read a leg's transfer in classify in the order the SQL does |
fa8abcc30 | (new) | (new) | Find a flow's rate as SyncCache does and respect cut-offs in the classifier |
Summary
Adds Portfolio::DailyReturns. For a set of investment accounts over a period, it gives one row per calendar day in the family's currency, with:
- the day's opening and closing value;
- external flows, income and fees;
- market movement, revaluations and the currency effect;
- the daily return
r_t = V_close / (V_open + F) - 1.
Every return figure in the portfolio engine is built on this series. 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, 569 lines at c285e4a49):
- 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.
- 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 in
Row#unexplained.
- Missing rates.
- Balance rates are carried forward, then back. A flow's entry→account rate uses SyncCache's window (exact date, else up to 5 days back).
- 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. - Accounts entering and leaving. With
active_until_dates, an account stops contributing after its cut-off, and a transfer to it after that date is an external flow. The value it carries out, and the opening value an account brings in mid-period, are acomposition_flow. - Carried-forward rows. Market and adjustment components come only from a balance row dated that day.
- What counts as a flow. External flows, income and fees come from
Portfolio::FlowClassifier(merged in we-promise/sure#3557), with the series' own accounts as the inside of the scope. - Tenancy. The caller scopes the ids to one family, as
FlowClassifierrequires.
test/support/portfolio_returns_test_helper.rb (new): builders that refuse a balance day whose components do not add up to its closing figure.
Size. 569 lines, over the ~300 guideline. Most of the code is one SQL query whose parts (balances, flows, arrivals, departures) only mean anything together. The rest is comments. Splitting the query would ship pieces that cannot be tested on their own.
Known interim state. With this slice alone, a security journalled in from another broker (a Transfer-labelled trade with amount: 0) is valued at its cash amount, which is nothing. The journal-flows slice stacked on this one closes that. Nothing upstream calls this class until then.
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 one on this branch: the class is new and nothing in app/ or lib/ calls it (git grep -n "Portfolio::DailyReturns" app lib finds only this file). Above it, Balance::ChartSeriesBuilder (#343) reads it for net contributions.
What else reads what I just changed the reading of? One upstream file changes: Portfolio::FlowClassifier. #sql_joins gives one transfer row per entry, and there are two new options, include_excluded: and active_until_dates:, both off by default. The only other reader of sql_joins is #classify_ids (grep -rn "sql_joins\|flow_transfers" app), and its parity tests pass. Otherwise the class reads existing balances, entries, trades, transactions, holdings and exchange_rates columns, and Portfolio::FlowClassifier.
Verification (on dc22ad370; later rounds are in the updates above)
test/models/portfolio/daily_returns_test.rb: 35 runs, 100 assertions, 0 failures.- Full suite: 11,818 runs, 54,491 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16.
- Lint and security:
bin/rubocop -f githubon the three files reports no offenses, andbin/brakeman --no-pager -qreports 0 warnings. No ERB or JS changed. - Mutations re-run on this base, each against
daily_returns_test.rband restored after. All are caught:- deposit left out of the denominator: 2 failures;
- suppression removed: 3;
- flow
rate_missingnever raised: 1.
- Carried from #372. The code was unchanged until
0fe5578bband51c7d69c5, so the full fail-first and mutation tables on #372 still apply, including the four fix-round findings. Each of those was written test-first and broken deliberately.