Count positions held at an account's first row open as arriving
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. A linked account writes this when its history starts after its holdings were bought. The daily return series read those positions as a market gain: one such row (opening at 0.0006, closing at 1,188.11) chained to a time-weighted return of 722,137,312%. The Period return card and Reports read them as gain too: 10,000 gaining 200, beside an account arriving with 5,000 of positions, read +5,300 instead of +300.
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.
Closes #5965
Fork pre-flight: jaysbeekay/sure#1019 (same commits: same branch, same head).
What changed
Portfolio::DailyReturns- The flows CTE is grouped per account first (
flows_by_account_date), then summed by day as before. It getstraded_value(every trade's units at the day's price, from the holdings row it moved, converted as a journal's value is) andtraded_rate_missing. For a security with no holdings row that day (a sale emptied it), the day's trades in it are netted first: each sale is valued at its own price for its share of the units sold on net, so a same-day round trip opens nothing, and a buy with no holdings row is in neither side. That sale converts as the balance converts its entry (Portfolio::DailyReturns.entry_rate_lookup: the entry's stored rate if positive, else a rate on its date or up toNEAREST_RATE_LOOKBACK_DAYSbefore). The netting runs only on an account's first row, the one row the opening reads. - The carried-journal settlement is kept per account as well (
carried_journal_rows). - A new
openings_by_dateCTE: on each account's first-ever row withstart_non_cash_balance0, the opening 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 that row. - The opening leaves
market. It joinscomposition_flowafter the period's first day andvalue_openon it. It flagscontribution_rate_missingandrate_missingwhen it has no rate or a traded leg can't be converted, andcontribution_rate_missingwhen the first row's holdings are valued at parity, on the period's first day too.
- The flows CTE is grouped per account first (
InvestmentStatement#period_return_trend: on that rowabsolute_returnreads the traded units at the day's price less the day's net buys, notnet_market_flows, with the same netting and rate lookup for a sale with no holdings row. An account whose first-row traded units are priced in a currency with no rate into the account's is left out and counted, as one whose balances have no rate is.Portfolio::Performance::CACHE_VERSIONv16 → v19.lay_balance(test helper) getsstart_non_cash:,bought:andsold:. Existing fixtures whose first-row market move came from a held position, or from a same-day buy, now say so (with the buy's trade and holdings row), and their assertions are unchanged. Two tests that pinned the old reading each get a twin atstart_non_cash0 that asserts the new one.
Non-test diff: +342 / −61 in 3 files. It is over the usual size because both readers of the same row (the series and the Period return card) change together; splitting them would leave the card and the Performance section disagreeing on the Portfolio page.
Demo data
No demo data needed. The demo generator writes forward-calculated accounts, whose first row is an opening anchor with no market move.
Migration notes
No migration. Cached performance metrics are recomputed once, because of the cache version bump. period_return_trend is not cached.
Verification
bin/rails teston 7111d2209 (this branch merged withup/portfolio-performance-section-stackedat a55855a50): 20112 runs, 0 failures, 8 errors. All 8 areReleaseNotesWorkflowTest, fromnodemissing in the test image. ThePortfolio::,InvestmentStatement, chartable and chart series tests on the same commit: 736 runs, 0 failures.bin/rubocop(changed files): no offenses.bin/brakeman: 0 warnings.- No ERB or JavaScript change, so erb_lint and Biome don't apply.
- Each changed line was broken on its own, and a named test caught each one. The table is on the fork pre-flight.
Blast radius
The DailyReturns rows feed Portfolio::Performance, Portfolio::Drivers, Portfolio::Income (unchanged columns) and the net contributions line in Balance::ChartSeriesBuilder, which now counts such opening positions as put in. period_return_trend feeds the Portfolio Period return card (Portfolio::SectionRegistry#kpis) and Reports (reports/_investment_performance, reports/print). Only an account's first-ever row with nothing in start_non_cash_balance changes. In the series its opening moves from market to composition_flow or value_open by the same amount, so Row#unexplained is unchanged. A first row whose start_non_cash_balance is not 0 keeps today's reading.
Summary by cubic
Fixes portfolio returns counting an account's opening holdings as a market gain, which inflated daily and time-weighted returns when a linked account's history started after its positions were bought (one account read a time-weighted return of 722,137,312%). Positions an account held at its first row's open are now treated as money arriving with the account.
Bug Fixes
- Positions held at an account's first-ever row's open now count as composition flow (after the period's first day) or value_open (on it), not as market return; the opening is the close's holdings less the day's traded units, at the day's price.
- A sale of a security with no holdings row that day is valued from the day's net trades at its own price, so a same-day round trip opens nothing; gains on units bought that day still count as returns.
period_return_trend(Period return card and Reports) applies the same rule, so the card and the Performance section agree; accounts whose opening values have no exchange rate are left out and counted.- Performance cache version bumped to v19, so cached metrics recompute once;
period_return_trendis not cached.
Summary by CodeRabbit
- Bug Fixes
- Improved portfolio and investment return calculations when an account’s first recorded balance includes existing holdings, so those positions count as opening value rather than market gains.
- Better account for purchases, sales, and other flows on the first balance date, including applicable exchange rates.
- Exclude accounts from affected return calculations when required currency conversions are unavailable.
- Updated contribution and performance calculations to reflect opening positions consistently across charts and reports.