Value a journalled security as the flow it is
Part of #121
This is the upstream pre-flight for slice 2 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 2 of 7 of the portfolio returns engine; we-promise/sure#4078 is the issue (part 3, returns engine).
Fork pre-flight PR: jaysbeekay/sure#373 (https://github.com/jaysbeekay/sure/pull/373), same branch, same commit.
Stacked on the daily returns PR. Until that merges, GitHub shows its commits here as well; this PR's own commits are the ones after up/portfolio-daily-returns. 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.
Summary
A security moved into an account from a broker outside the scope is written as a Transfer-labelled trade with amount: 0 (Questrade writes price: 0, amount: 0). Valued at its cash amount it moved nothing, so the arriving position landed in the closing value with the denominator unchanged: a position worth half the account read as a 50% day.
This values such a journal from the position instead, and takes the same value back out of the market component so the day still reconciles.
What changed
app/models/portfolio/daily_returns.rb:
- A journal is a Transfer-labelled trade with no cash amount. Its external flow is
qty xthat day's holding price, converted from the holding's currency at the previous day's rate. It isqty, not the holding row'samount, because a top-up would otherwise count units already held. - The holding row is chosen with
LIMIT 1, preferring the entry's currency, becauseholdingsis unique per currency and a plain join valued the journal once per row. - The same value is subtracted from
market, becauseBalance::BaseCalculatorbooks the arriving position there; counting it in both leftunexplainedat minus the journal. - A journal with no usable price (none, zero, or no rate for the holding's currency) suppresses the day and raises
rate_missing?where the rate is what is missing.Holding::PortfolioCachewrites a zero-price row on a date with no price, so keying on "no row" would never fire. - Unchanged: a Transfer-labelled trade that carries a cash amount, and a Contribution or Withdrawal labelled trade, flow at their cash amount.
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
daily_returns_test.rb: 42 runs, 119 assertions, 0 failures.- Fail-first: with the previous PR's
daily_returns.rbin place, 6 of the new tests fail (journal in, journal out, top-up, two suppression cases, several currencies). The others are negative controls that hold either way. - Mutations, all caught:
- journal valued at its cash amount: 4 tests;
- not taken out of market: 4;
- valued from the holding amount: 4;
- predicate ignores the amount: 1;
- predicate ignores the label: new test "a contribution labelled trade with no cash amount is not valued as a journal";
- unpriced journal not suppressed: 2;
- zero price counted as priced: 1;
- holding join without
LIMIT 1: 1; - journal rate not flagged: new test "a journal priced in a currency with no rate is flagged as a missing rate";
- journal rate at the journal date: new test "a journal priced in a foreign currency converts at the previous day's rate".
- 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 caller yet; Portfolio::DailyReturns is new in the parent PR. The predicate reads Portfolio::FlowClassifier::TRANSFER_LABEL, the same constant the classifier keys its journal rule on.
What else reads what I just changed the reading of? holdings.price is also read by Balance::BaseCalculator#market_value_change_on_date, which this reads from on purpose so the flow and the market move are one number. No other reader changes.
Engine fix round (2026-10-09)
The branch first merges up/portfolio-daily-returns down: a --no-ff merge, clean, no force push. That brings the fix round from #372.
| Commit | Finding | Test | Fail-first / mutation |
|---|---|---|---|
| a9b41ff98 | cubic Vczd: a journal valued from a rated holding flags its entry currency's missing rate | "a journal valued from a holding in a rated currency does not flag the entry currency's missing rate" | failed at :866; dropping the AND NOT COALESCE((journal_predicate), false) line caught (:866). Dropping only the COALESCE survives. That is an equivalent mutant: a trade with no label classifies internal. |
- Gatekeeper observation (the two valuation paths agree): the end-to-end test through the real
Balance::Materializeris added in the Performance slice (#376, e46098f9b), where the real path first exists. - Corrected claim. The earlier description said nothing calls these classes until Performance. The net contributions series (#343, branched from this one) reads
Portfolio::DailyReturns. daily_returns_test.rb: 49 runs, 137 assertions, 0 failures. All portfolio model tests on this head: 108 runs, 0 failures.
Updated 2026-10-13. 351d120b7 answers the code-master review 6105957389. A journal with no quantity (trades.qty IS NULL, reachable only by bypassing Trade's validation) now suppresses the day like an unpriced journal. A second test pins that one unpriced journal suppresses a day that also carries a priced one.