Count positions first priced on an account's first row as arriving
Fixes jaysbeekay/sure#999
Upstream issue: we-promise/sure#5965
Upstream PR: we-promise/sure#5966 (same branch, same commit), based on up/portfolio-performance-section-stacked above we-promise/sure#5818 in the returns stack.
Base: up/portfolio-performance-section-stacked, the head of the fork pre-flight jaysbeekay/sure#996 (we-promise/sure#5818), the top of the returns stack. Portfolio::DailyReturns exists only in that stack.
Summary
Some accounts start their balance history with nothing in start_non_cash_balance on the first row, yet close that row holding positions they held before the history starts. SnapTrade writes this when an account's history starts after its holdings were bought. Portfolio::DailyReturns read those positions as a market gain. On edge, one such row (opening at 0.0006, closing at 1,188.11) chained to a time-weighted return of 722,137,312%. InvestmentStatement#period_return_trend (the Period return card beside it on the Portfolio page, and Reports) read them as gain too.
Now, on that row, what the account held at the open is the units held at the close less the units traded that day, at the day's price. Those positions arrive with the account, like its opening cash. The gain on the units traded that day is still a return: 500 units held, 1 bought at 100 and a close at 110 arrive 55,000 and keep 10 of gain.
What changed
app/models/portfolio/daily_returns.rbflows_by_account_date: the flows CTE grouped by account and date, plustraded_value(every trade's units, buys, sales and journals, at the day's price from the holdings row it moved, converted as a journal's value is; a sale with no holdings row that day, one that emptied the position, at its own price, converted as its entry is; a buy with none is in neither the close's holdings nor here) andtraded_rate_missing.flows_by_datesums it by day, so its columns are unchanged.carried_journal_rows: the carried-journal settlement kept per account as well;carried_journals_by_datesums it by day as before.openings_by_date: each account's first-ever balance row withstart_non_cash_balance0, within the period and the account's window. The value isnet_market_flows + non_cash_inflows - non_cash_outflows(the close's holdings value) at the previous day's rate, less that account'straded_valueand any journal carried to the row.- Final SELECT: the opening leaves
market. It joinsarrived_value(composition_flow) after the period's first day andvalue_openon it.contribution_rate_missingandrate_missingfire for an opening with no rate or a traded leg that can't be converted, on the period's first day too, so the day's capital is never chained while it is unknown.
app/models/investment_statement.rb,#period_return_trend: on the same rowabsolute_returnreads the traded units at the day's price less the day's net buys, notnet_market_flows. The traded units come fromperiod_return_opening_trades_sql(holdings price; for a sale with no holdings row, the trade's own price converted from the entry's currency as DailyReturns andBalance::SyncCacheconvert the entry: the entry's stored rate through the sharedPortfolio::DailyReturns.entry_custom_rate_sql, else the table's).period_return_unconvertible_account_idsalso leaves out an account whose first-row traded units are worth something and priced in a currency with no rate into the account's (a sale with a positive stored rate needs none; one whose stored rate is not positive is left out), soperiod_return_unconvertible_countsays so.app/models/portfolio/performance.rb:CACHE_VERSIONv16 → v19.test/support/portfolio_returns_test_helper.rb:lay_balancegetsstart_non_cash:,bought:(cash out,non_cash_inflowsin) andsold:(non_cash_outflowsout, cash in). The defaults are unchanged.
Non-test diff: +342 / −61.
Behaviour change and reversed tests
The first Gatekeeper review (finding 2) named two tests that pinned the old reading. Each keeps its assertion, now with start_non_cash: so the gain is on a held position, and each gets a twin at start_non_cash 0 that asserts the reversal:
- "an account arriving and gaining on its first day keeps that day's gain" → twin "an arrival opening with nothing held brings its first day's market move with it" (r 0.0333 → 0,
composition_flow500 → 550) - "an account whose first balance row is the period's first day is not an arrival" → twin "a first row on the period's first day opening with nothing held opens at its close" (
value_open1,000 → 1,100, r 0.10 → 0)
Other existing fixtures had a first row whose lay_balance market move came from a position they held, or from a same-day buy, but they didn't say so. They now say so, and their assertions are unchanged:
daily_returns_test.rb: "start of day flow convention places the flow in the denominator" and "a carried forward balance does not repeat its market flow on later days" getstart_non_cash: 1_000. "an unpriced journal dated before the period is carried to the period's first day when priced there" gets a row before the journal. "a buy on an arrival's first row keeps its gain and its commission" gets the holdings row its 40 of market implies (10 at 105).performance_test.rb:build_textbook_case, "volatility annualises calendar daily returns by sqrt 365", "an account synced today with one balance day does not withhold the scope's time weighted figures" and "two years of daily returns keep a bounded precision and a small cached payload" getstart_non_cash:.drivers_test.rb: "drivers reconcile to the period change for every account shape" getsstart_non_cash:on the trade-tracked account.chartable_test.rb: the two "no prior history" tests getbought: 500with the buy and the holdings row behind it (5 at 100, closing at 120), because their 100 gain is on units bought that day. The two anchor tests getstart_non_cash: 1_000.
Tests
| Test | Before fix | After |
|---|---|---|
| DailyReturns "an arrival's positions first priced on its first row arrive rather than return" | r 1.198 (expected 0.00457) | pass |
| DailyReturns "positions first priced on the period's first day open the period rather than return" | value_open 0.0006 (expected 1188.1106) | pass |
| DailyReturns "an arrival opening with nothing held brings its first day's market move with it" | r 0.0333 (expected 0) | pass |
| DailyReturns "a first row on the period's first day opening with nothing held opens at its close" | value_open 1000 (expected 1100) | pass |
| DailyReturns "an arrival's first priced positions with no rate make contributions incomplete" | false | pass |
| DailyReturns "positions held at an arrival's first row open arrive beside a buy that day" | composition_flow 100 (expected 55100) | pass |
| DailyReturns "positions held at an arrival's first row open arrive beside a sale that day" | composition_flow 0 (expected 1000) | pass |
| DailyReturns "a journal carried to an arrival's first row is a flow once, not an arrival as well" | composition_flow 500 (expected 0) | pass |
| DailyReturns "an internal journal on an arrival's first row with no rate makes contributions incomplete" | false | pass |
| DailyReturns "positions held at a first row's open on the period's first day with no rate make contributions incomplete" | false | pass |
| InvestmentStatement "period_return_trend does not count an arriving account's opening positions as a return" | 15,300 (expected 10,300) | pass |
| InvestmentStatement "period_return_trend keeps the gain on units bought beside an arriving account's opening positions" | 65,210 (expected 10,210) | pass |
| InvestmentStatement "period_return_trend does not count an arriving account's opening positions as a return beside a sale" | 11,200 (expected 10,200) | pass |
| DailyReturns "a sale of a whole opening position on an arrival's first row is not a gain" | composition_flow 0 (expected 1000) | pass |
| DailyReturns "a traded unit with no rate on an arrival's first row marks the day's rate missing" | false | pass |
| DailyReturns "a sale with no holdings row and no rate on an arrival's first row makes contributions incomplete" | false | pass |
| InvestmentStatement "period_return_trend does not count the sale of a whole opening position as a return" | 11,200 (expected 10,200) | pass |
| InvestmentStatement "period_return_trend leaves out an account whose first-row traded units have no rate" | 10,100 (expected 10,200) | pass |
| DailyReturns "a buy with no holdings row on an arrival's first row leaves its opening positions whole" | composition_flow 55,000 (expected 55,100) | pass |
| InvestmentStatement "period_return_trend leaves the opening positions whole beside a buy with no holdings row" | 10,200 (expected 10,100) | pass |
| InvestmentStatement "period_return_trend values a sale with no holdings row at the trade's own exchange rate" | unconvertible count 1 (expected 0) | pass |
| InvestmentStatement "period_return_trend keeps an account whose first-row traded units are worth nothing" | unconvertible count 1 (expected 0) | pass |
| Performance "twr does not count an arriving account's first priced positions as a gain" | TWR 1.188 (expected 0) | pass |
| Drivers "positions first priced on an arrival's first row are composition, not market" | composition 0 (expected 500) | pass |
| ChartSeriesBuilder "positions first priced on an account's first row count as put in" | [20, 20] (expected [1020, 1020]) | pass |
Performance "the cached metrics carry the ambiguity flag" (adds refute_equal "v16" and "v17") | fails at v17 | pass |
Guards that pass before and after, and catch a wrong fix (see Mutations): "a journal on an arrival's first row is a flow once, not an arrival as well", "a journal on a first row on the period's first day does not open the period as well", "an internal journal on an arrival's first row does not arrive", "a buy on an arrival's first row keeps its gain and its commission", "a zero-priced journal on an arrival's first row with no rate leaves the opening complete", "a buy with no holdings row and no rate on an arrival's first row leaves contributions complete", and the InvestmentStatement guards "ignores an exchange rate on a sale in the account's currency", "does not apply a non-positive exchange rate on a sale", "converts a sale with no holdings row from the entry's currency", "period_return_trend and the daily returns agree on whether a sale with no holdings row converts" (entry EUR / trade USD with no rate; a stored rate written as the string "2"; a stored rate of 0 beside a table rate), "keeps an account whose later traded units have no rate", "keeps a first row's market move on positions it opened holding", "counts a later row opening with nothing held" and "counts a first row in a currency other than the account's".
Mutations
Each mutation was applied on its own to a copy of the tree and run against the daily_returns, drivers, performance, chart_series_builder and chartable tests (331 runs), or the investment_statement tests (176 runs).
| Mutation | Caught by |
|---|---|
traded_value not subtracted from the opening | 8 failures, e.g. "a buy on an arrival's first row keeps its gain and its commission" |
non_cash_inflows left out of the opening | 4 failures, e.g. "positions held at an arrival's first row open arrive beside a buy that day" |
non_cash_outflows left out of the opening | "positions held at an arrival's first row open arrive beside a sale that day" |
| Carried journal not subtracted from the opening | "a journal carried to an arrival's first row is a flow once, not an arrival as well" |
traded_rate_missing not in opening_rate_missing | "an internal journal on an arrival's first row with no rate makes contributions incomplete" |
First-day opening kept out of contribution_rate_missing | "positions held at a first row's open on the period's first day with no rate make contributions incomplete" |
start_non_cash_balance = 0 condition dropped | 12 failures, e.g. "an account arriving and gaining on its first day keeps that day's gain" |
traded_value for journals only | 5 failures, e.g. "positions held at an arrival's first row open arrive beside a buy that day" |
price > 0 dropped from traded_rate_missing | "a zero-priced journal on an arrival's first row with no rate leaves the opening complete" |
Non-zero-opening clause dropped from opening_rate_missing | "an empty arrival with no rate leaves contributions complete" |
period_return_trend first-row rule off | 3 failures, e.g. "does not count an arriving account's opening positions as a return" |
…its start_non_cash_balance = 0 dropped | "keeps a first row's market move on positions it opened holding" |
…its first-row (NOT EXISTS) check dropped | "counts a later row opening with nothing held" |
…its non_cash_inflows dropped | "keeps the gain on units bought beside an arriving account's opening positions" |
…its non_cash_outflows dropped | "does not count … as a return beside a sale" |
| …its traded value dropped | 2 failures |
| …its account-currency check dropped | "counts a first row in a currency other than the account's" |
…its b0.date < b.date made <= | 3 failures |
Opening not taken out of market | 7 failures, e.g. "an arrival's positions first priced on its first row arrive rather than return" |
Opening not added to arrived_value | 6 failures, e.g. "an arrival opening with nothing held brings its first day's market move with it" |
Opening not added to first-day value_open | 4 failures, e.g. "a first row on the period's first day opening with nothing held opens at its close" |
CACHE_VERSION back to v17 | "the cached metrics carry the ambiguity flag" |
| Trade-price fallback for a sale with no holdings row removed | "a sale of a whole opening position on an arrival's first row is not a gain" |
Fallback's missing rate not in traded_rate_missing | "a sale with no holdings row and no rate on an arrival's first row makes contributions incomplete" |
| Fallback widened from sales to buys | "a buy with no holdings row on an arrival's first row leaves its opening positions whole" |
| …and its missing-rate twin widened to buys | "a buy with no holdings row and no rate on an arrival's first row leaves contributions complete" |
period_return_trend fallback widened to buys | "leaves the opening positions whole beside a buy with no holdings row" |
| …zero-value filter dropped from the unconvertible check | "keeps an account whose first-row traded units are worth nothing" |
| …stored-rate rows checked against the table / stored rate not applied | "values a sale with no holdings row at the trade's own exchange rate" |
| …trade currency in place of the entry's | "converts a sale with no holdings row from the entry's currency", and the paired DailyReturns/InvestmentStatement test |
| …stored rate applied in the account's own currency | "ignores an exchange rate on a sale in the account's currency" |
| …a non-positive stored rate not refused / a stored rate checked against the table / a string rate not read | the paired test "period_return_trend and the daily returns agree on whether a sale with no holdings row converts" |
opening_rate_missing not in rate_missing | "a traded unit with no rate on an arrival's first row marks the day's rate missing" |
period_return_trend trade-price fallback removed | "does not count the sale of a whole opening position as a return" |
| …unconvertible traded units not counted / priced in the account's currency / currency filter off | "leaves out an account whose first-row traded units have no rate" |
| …first-row filter dropped from the traded units | "keeps an account whose later traded units have no rate" |
Verification
- Full unit suite (beastpc, ruby image) on 7111d2209: 20112 runs, 0 failures, 8 errors. All 8 errors are
ReleaseNotesWorkflowTest, fromnodemissing in the image. - System tests
test/system/portfolios_test.rbandtest/system/reports_test.rb: 20 runs, 0 failures. bin/rubocopon the changed files: no offenses.bin/brakeman: 0 warnings.- No UI, view or JavaScript change, so no screenshots. No migration.
- I haven't yet run the read-only before/after TWR on edge's House family.
Blast radius
DailyReturns#rows feeds Portfolio::Performance (TWR, MWR through external_flow + composition_flow, volatility, drawdown, index), Portfolio::Drivers (market and composition), Portfolio::Income (income and fees, unchanged) and Balance::ChartSeriesBuilder's net contributions line (rows.first.value_open plus flows) and its incomplete flag; an opening that can't be valued also sets rate_missing, so Performance withholds its ratios. InvestmentStatement#period_return_trend feeds Portfolio::SectionRegistry#kpis (the Period return card, portfolios/_kpi_row) and ReportsController (reports/_investment_performance, reports/print); it is not cached. Only an account's first-ever row with nothing in start_non_cash_balance changes. In the series the positions it held at the open move from market to composition_flow (or value_open) by the same amount, so Row#unexplained is unchanged; the gain on that day's traded units stays in market. In period_return_trend the same positions leave absolute_return; start_value is unchanged. The net contributions line now counts such opening positions as put in. Grouping the flows and the carried journals by account first doesn't change any flows_by_date or carried_journals_by_date column: each is a sum or a BOOL_OR of the same rows. A first row whose start_non_cash_balance is not 0 keeps today's reading. Goal contributions read raw net_market_flows and are not changed here (follow-up).