Add a daily return series for a set of investment accounts

JA
7d ago
+24042-1359

Part of #121 (IP2, the performance engine, under epic #118). Part of we-promise/sure#4078 and we-promise/sure#3494.

Fork pre-flight for we-promise/sure#5088 (same commits), which replaces we-promise/sure#4197.

Replaces jaysbeekay/sure#443 (same changes, rebased and native-stacked).

Bottom of a fork native stack, against mirror/upstream-main.

Rebased 2026-11-15 onto main at dbeebf14c. Its 17 commits replayed onto main unchanged. test/models/portfolio and test/models/balance at this slice: 234 runs, 0 failures. Full suite at the top of the stack: 16,441 runs, 0 failures (8 ReleaseNotesWorkflowTest errors: no node in the test image). Rubocop and Brakeman clean.

Problem

Sure has no daily series of what a set of investment accounts was worth, what moved in and out, and what the market did. So it cannot compute a return that separates the owner's deposits from performance. period_return_trend treats a deposit as a gain and converts currencies at parity when a rate is missing. we-promise/sure#4078 sets out the model-layer engine that fixes this. This PR is its base layer.

Change

Adds Portfolio::DailyReturns (app/models/portfolio/daily_returns.rb, new). 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.

The rules:

  • 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 whatever they do not explain shows in Row#unexplained rather than being defined away.
  • Missing rates.
    • Rates are carried forward, then 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, rather than dividing by zero or flipping a gain's sign.
  • 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 a composition_flow, not a gain or a loss.
  • Carried-forward rows. Market and adjustment components come only from a balance row dated that day, so a gap does not repeat yesterday's market move.
  • What counts as a flow. External flows, income and fees come from Portfolio::FlowClassifier (we-promise/sure#3557), with the series' own accounts as the inside of the scope.

test/support/portfolio_returns_test_helper.rb (new): builders that refuse a balance day whose components do not add up to its closing figure, so a test cannot absorb its own arithmetic error.

Nothing on main calls the class yet. Known interim state: with this PR 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 next PR, journal flows, closes that before anything reads the series.

Size. 452 non-test 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 on why each join and rate is the one it is. Splitting the query would ship pieces that cannot be tested on their own.

Classifier SQL is spliced in after binding (0fe5578bb). Portfolio::DailyReturns#raw_rows used to pass the whole daily query, with FlowClassifier#sql_case and #sql_joins already interpolated, through sanitize_sql_array. Rails reads every :word in that string as a bind, so a classifier label or literal containing one would raise ActiveRecord::PreparedStatementInvalid before the query ran; it was safe only because no label contains one today. Now only the template's own binds are sanitized: the template carries a comment marker where each fragment belongs, and bind_and_splice replaces the markers with the already-sanitized fragments afterwards. The test "a colon word inside the classifier's sql is not read as a bind" stubs sql_case with a ':probe' literal and asserts the rows come back unchanged; it raised before the fix, and raises again if the fragments are spliced in before sanitizing.

A cash-settled Contribution or Withdrawal trade is internal (0087facd0). This changes the classifier's default path, not only the opt-in one. A Contribution- or Withdrawal-labelled trade whose amount is signed like its quantity (qty × amount > 0, as the trades form and API write qty × price) now classifies internal in classify, classify_ids and sql_case, whatever include_excluded and active_until_dates are. The balance calculators apply such a trade as a buy or a sale, cash for units at the same value, so nothing crosses the scope; read as a flow, a 500 trade on a flat 1,000 day was +100%. An in-kind (amount 0) or cash-only (qty 0) Contribution or Withdrawal is still external by direction, and a Transfer-labelled trade carrying cash is unchanged. Tests: "a contribution trade that settles in cash is not an external flow" and "a Contribution or Withdrawal trade that settles in cash is internal in both forms". Portfolio::DailyReturns is the classifier's only production caller; InvestmentStatement::Totals has its own SQL.

Updated 2026-11-02: a bound value that spells a fragment marker stays a literal (11bb8a1bd, 0e334559a); main merged in at 823265070. Full suite: 14,293 runs, 0 failures, 0 errors.

Updated 2026-10-14: review fixes (51c7d69c5).

  • One row per entry. Portfolio::FlowClassifier#sql_joins now reads transfers through LEFT JOIN LATERAL (... ORDER BY created_at, id LIMIT 1); since 6dc9f693f it prefers the transfer the entry is the inflow of first (see 2026-10-15 below). Two transfers sharing one leg (possible, because the only unique index is on the pair) no longer make DailyReturns sum that entry twice. classify_ids is the only other reader of the join. The writer-side root cause, per-leg unique indexes, is we-promise/sure#4225.
  • Flow FX follows the balance. A foreign entry converts into the account's currency on its own date, preferring the entry's extra["exchange_rate"] as Balance::SyncCache does, and then into the family currency at the previous day's rate. The old test that laid a balance no sync writes is corrected.
  • Missing-rate checks. A carried-forward row's start_balance is no longer checked, because value_open reads its end_balance. A zero-amount flow cannot be missing a rate.
  • Excluded entries count as flows. SyncCache still applies them, so they moved the balance. FlowClassifier gains include_excluded: (default off; both forms; parity test). Split parents are skipped, because SyncCache skips them and their children carry the amount. This reverses the earlier test "an excluded entry contributes no flow".
  • Known limit, documented. The classifier's scope ignores active_until_dates, and no caller passes them yet. The change that first does must make it window-aware.
  • FlowClassifier is touched, an upstream file from we-promise/sure#3557: sql_joins and an opt-in include_excluded:. These fixes left the default behaviour of classify, classify_ids and sql_case unchanged; 0087facd0 later changed one default case (below).

Updated 2026-10-15: review fixes.

  • 949c79511, excluded security-transfer legs. Under include_excluded: true, the opposite-leg lookup for a security transfer (Ruby and SQL) no longer requires the other leg to be live, so both legs of a move with one excluded leg are internal. Default behaviour is unchanged.
  • 6dc9f693f, one transfer for both forms. The transfers lateral in sql_joins now prefers the transfer a transaction is the inflow of, then the earliest, matching transfer_counterpart_account_id. Only reachable through writes that skip validations.
  • 943c160f6. The scope-widening test is pinned to unknown keyword: :scope_account_ids, so another ArgumentError cannot pass it.
  • 0f371528f, liabilities refused. Portfolio::DailyReturns raises ArgumentError the first time it queries a series that holds a liability account, because its flows are not multiplied by flows_factor. The check runs once per instance from bind_and_splice, so building an instance costs no query. Callers pass investment and crypto accounts.

Validation

On dc22ad370, cut from main at 3e35aaa07:

  • Full suite (bin/rails test): 11,818 runs, 54,491 assertions, 0 failures, 0 errors, 34 skips. Run locally on PostgreSQL 16.
  • After the bind fix, on 0fe5578bb (2026-10-14): full suite 11,819 runs, 0 failures, 0 errors, 34 skips. CI is green.
  • After the review fixes, on 51c7d69c5 (2026-10-14): full suite 11,866 runs, 0 failures, 0 errors, 34 skips. Rubocop is clean and Brakeman reports 0 warnings.
  • After the review fixes, on 0f371528f (2026-10-15): full suite 11,870 runs, 0 failures, 0 errors, 34 skips. Rubocop is clean and Brakeman reports 0 warnings.
  • Lint and security: bin/rubocop -f github on the changed files reports no offenses, and bin/brakeman --no-pager -q reports 0 warnings. No ERB, JS or system-test surface.

Tests

test/models/portfolio/daily_returns_test.rb (new), on dc22ad370: 35 runs, 100 assertions, 0 failures.

Fail-first. Four review findings were each fixed test-first, and each test failed before its fix:

  • an over-withdrawal suppresses the day rather than reversing its sign;
  • an all-zero foreign account does not flag a missing rate;
  • the flow scope cannot be widened beyond the series' accounts, so a transfer to an account outside it is a flow out, not a loss;
  • the balance builder refuses an amount finer than balances store.

Review fixes (51c7d69c5). 9 new or rewritten tests, each failing on b054f4de9; 8 mutations, all caught.

Review fixes (2026-10-15, 949c79511 to 0f371528f). 4 new tests and 1 tightened, each failing first (the tightened one by mutation, a required family: keyword); 7 mutations, all caught.

Mutations. Each was run against this file's tests, then restored, on the fork pre-flight. All were caught:

MutationTests that catch it
flow left out of the denominator9
no composition flow8
departures ignored2
components at today's rate1
flows at the entry date's rate1
parity fallback added to the rate lookup2
no carry-back rate1
no suppression2
flows not windowed by cut-off1
bare excluded = false (the pre-flight's COALESCE(entries.excluded, false) filter; 51c7d69c5 removes it, because excluded entries now count as flows and only split parents are skipped)1
missing flow rate not flagged1
carried-forward row opening at start_balance1
market read from a carried-forward row2
first-day row counted as an arrival2

Re-run on this branch, cut from current main:

  • deposit left out of the denominator: 2 failures;
  • suppression removed: 3;
  • flow rate_missing never raised: 1.

The code was byte-identical to the fork pre-flight it supersedes when rebuilt. The bind fix above (0fe5578bb) was added afterwards.

Migration notes

None. No schema change. It reads existing balances, entries, trades, transactions, holdings and exchange_rates columns.