Replay the cost-basis tracker in Holding's fallback
Closes #3566
What: a holding with no stored cost basis now shows the same average cost the holding calculators store for it. Holding#calculate_avg_cost replays the security's trades through Holding::LotBook, the calculators' own engine, instead of a separate SQL average: sells and outbound transfers are relieved, splits apply at the open of their ex-date, and a transfer in stops making the position unknown once the position closes. The replay is seeded from the holding's quantity walked back (opening shares on reverse-synced accounts), rounded to cost_basis's scale, and kept per instance. Trade#calculate_realized_gain_loss prices a closing sale with the new Holding#avg_cost_before(entry).
Why: the old SQL fallback ignored sells, splits and closed transfers, so it disagreed with the calculators (buy 10 @ 100, sell 10, buy 10 @ 200: 150 where the calculators store 200). This takes the issue's "one engine" direction.
Start reading: Holding#calculate_avg_cost, #opening_position and #avg_cost_trade_rows in app/models/holding.rb, then #avg_cost_before and its use in Trade#calculate_realized_gain_loss.
Key tests (test/models/holding_test.rb, test/models/trade_test.rb):
- "the fallback agrees with the forward calculator"
- "the fallback relieves a full sell, so a rebuy starts a clean basis"
- "the fallback stays unknown while transferred-in units are held"
- "a sale that closes the position realises its gain against the cost before the sale"
- "the fallback replays the trades once per holding instance"
Behaviour change: holdings with no stored basis show the calculators' figure (table in the details); a closing sale's realised gain is unchanged in value but now computed from the replay. Stored cost bases are untouched. No UI change, no migration.
Size: +247 / −115 outside tests, in holding.rb and trade.rb.
Fork pre-flight: jaysbeekay/sure#421 (the same branch, merged on the fork at da347b926; later commits are on this branch only).
Full description and evidence
What changed
-
5b617ff60Replay the cost-basis tracker in Holding's fallback -
ebea5a944Correct the fallback's outbound-transfer rule in a test comment -
15c92edefPin the fallback to the calculator for foreign-currency trades -
1ca63dfb8Price a closing sale at the average cost before it -
f6aeb1b52Seed the average-cost replay from the holding's quantity (from review: a reverse-synced account's opening shares) -
7e537c993Replay the history once when pricing a closing sale (from review: a closing sale replayed the history twice) -
da347b926Test the walk-back stops at the snapshot's date -
7d037ca17Replay the fallback's cost in the holding's own currency -
03083c1c9Replay a holding's fallback cost once per instance (the same efficiency concern raised on #4154) -
e15992553Merge upstream main2250ba801; the PR's own diff is unchanged (samegit patch-id --stable) -
25a0a46e4Bound a numeric trade rate before the cost replay casts it (from review: an oversized JSON number overflowed the query) -
d411d150aCount cost replay queries with the query cache off (from review) -
Holding#calculate_avg_cost: replays this security's trades up to the holding's date, inEntry.chronologicalorder, throughHolding::LotBook, followingHolding::ForwardCalculator#apply_trades:- a split applies at the open of its ex-date;
- a transfer in makes the cost unknown until the position crosses down through zero;
- a transfer out is relieved like a sell.
The replay starts from the opening position: the holding's own quantity walked back through the trades and splits up to its date (new private
Holding#opening_position), asHolding::ReverseCalculator#precompute_cost_basisseeds from the provider's snapshot. For forward-synced and manual accounts it is zero.The result is rounded to
cost_basis's stored scale (4). -
New private
Holding#avg_cost_trade_rows: one query, which keeps the existing rate SQL and computes the fee-inclusive unit cost in SQL. It returns the trades for both the walk-back and the replay, with a flag marking the replayed ones. Splits take a second query. -
New public
Holding#stored_avg_cost: the stored-basis read, split out ofavg_cost(which is nowstored_avg_cost || replayed_avg_cost). It never queries. -
New private
Holding#replayed_avg_cost:calculate_avg_costthrough the holding's own date, kept on the instance (nil included), so repeatedavg_costcalls on one holding replay once.Holding#reloaddrops it. Only that default cut-off is kept:avg_cost_before(entry)replays to the sale's own cut-off on every call, so a kept figure never answers for another date. The stored basis is still read live. -
New public
Holding#avg_cost_before(entry)and a fallback inTrade#calculate_realized_gain_loss(below). -
test/models/holding_test.rb: 22 new tests; 4 existing ones adjusted (below). -
test/models/trade_test.rb: 8 new tests. -
test/migrations/clear_transferred_position_cost_bases_migration_test.rb: one comment corrected.
| Trades (no stored basis) | Calculators store | Before | After |
|---|---|---|---|
| buy 10 @ 100, sell 10, buy 10 @ 200 | 200 | 150 | 200 |
| buy 10 @ 100, sell 5, buy 5 @ 200 | 150 | 133.33 | 150 |
| transfer in 10, sell 10, buy 10 @ 200 | 200 | nil | 200 |
| buy 10 @ 100, 2:1 split, buy 10 @ 60 | 53.3333 | 80 | 53.3333 |
Realized gain on a closing sale. Trade#calculate_realized_gain_loss prices a sale at the avg_cost of the latest holding on or before the sale date. When the sale closes the position, that row holds nothing and has no stored basis, so avg_cost falls to the fallback. The old fallback ignored sells and gave the right gain by accident. The replay relieves the sale and returns nil, so the gain disappeared, and the SnapTrade option buy-and-sell test failed. The new Holding#avg_cost_before(entry) replays the trades strictly before the sale, ordered by (entries.date, created_at, id), and applies splits with an ex-date on or before the sale's date. It shares calculate_avg_cost's replay, rounding and currency. Trade prices the sale at stored_avg_cost || avg_cost_before(entry), so partial sales and stored costs are unchanged, and a sale with no stored basis replays the history once, not once through the holding's date and again up to the sale. Where trades fall between the holding's date and the sale, the replay up to the sale is the right figure. New tests in test/models/trade_test.rb cover a closing sale, a buy and sale on the same day, and a closing sale on a split's ex-date; each fails before the change. A partial sale against a stored basis that differs from the replay passes before and after.
Opening shares on reverse-synced accounts. A reverse-synced account can hold shares from before its first imported trade. Starting the replay at zero, a sale that empties the imported trades looked like a full close, released a transfer in and reported the rebuy's price, where Holding::ReverseCalculator stores no basis and the old fallback returned nil. Seeding the replay from the holding's quantity walked back keeps those positions unknown (buy 10, transfer in 5, sell 15, rebuy 8 at 150, holding 10: nil; holding 8: 150).
Demo data
No demo data needed: the change only affects holdings with no stored basis, which demo accounts materialize past.
Screenshots
No UI change: the same cells and pages read Holding#avg_cost, and only the figure differs.
Migration notes
No migration. Stored cost bases are untouched; the fallback is computed on read.
Verification
- Fail-first on
upstream/maind55eac220. Every new positive test failed for the stated reason: 150 not 200, nil not 200, no split scaling, and no match with the calculator. The negative case (the fallback stays unknown while transferred-in units are held) passed before and after, as it should. - Mutations, each caught: sell relief removed (5 tests); transfer release removed (2); outbound transfer treated as a transfer in (2); split application removed (2); trailing splits ignored (the parity test); rounding removed (5); fee dropped (2);
avg_cost_before's cutoff made inclusive (4);Tradeback toavg_costalone (4); splits ignored inavg_cost_before(1); the replay preferred over a stored basis (3). bin/rails test test/models/holding_test.rb test/models/holding test/models/investment_statement_test.rb test/models/trade_test.rb: 220 runs, 0 failures.test/migrations/clear_transferred_position_cost_bases_migration_test.rb: 3 runs, 0 failures.- Review fixes, fail-first on
afdbed5e3:avg_cost stays unknown while opening shares keep transferred units in the position(150, not nil),a sale after opening shares kept transferred units held realises no gain(a gain against 150) andrealized gain on a closing sale with no stored basis replays the history once(2 trades and 2 splits queries, not 1).avg_cost is known again after a real close when the history explains the whole positionpasses before and after, as it should. - Review-fix mutations, each caught: seed back to zero (2 tests); split unscale skipped in the walk-back (2: the split walk-back test and the forward parity test); walk-back past the holding's date (1:
a sale after the snapshot's date walks back only the snapshot's trades); the replay cutoff ignored (4);Tradeback toavg_cost(1, the query count); unlocked zero trusted as a stored basis (1). bin/rails test(full) onda347b926: 11,841 runs, 54,606 assertions, 0 failures, 0 errors, 34 skips.SnaptradeAccount::ActivitiesProcessorTest#test_calculates_realized_gain/loss_for_option_buy_and_sell_using_per-contract_prices, which this branch broke atebea5a944, passes again (realized gain, above).- Memo (
03083c1c9), fail-first one15992553:the fallback replays the trades once per holding instance(4 trades queries for 4 calls, not 1) andthe fallback remembers an unknown cost too(3, not 1), counted with the query cache off.reload forgets the remembered fallback, so a later trade countsandthe remembered fallback never answers for a sale's earlier cut-offpass before and after, as guards on the memo. Mutations, each caught: memo removed (the 2 count tests);reloadno longer clearing it (the reload test); a memo that ignores the cut-off (the cut-off test and the reload test). bin/rails test(full) on03083c1c9: 13,192 runs, 60,627 assertions, 0 failures, 0 errors, 36 skips.- Rate bound (
25a0a46e4), fail-first on03083c1c9:the fallback ignores a numeric rate too large to convertraisedPG::NumericValueOutOfRange(a10**131071rate written toextradirectly).the fallback converts at a small numeric rate with many decimal placesguards against bounding by the string pattern, which would drop a small Float rate. Mutation caught: bound loosened to<= 1e20. The rate-string test now reloads the holding for each case, because the per-instance memo had answered its second case from the first. - Query counts (
d411d150a): the closing-sale count and the single-call holding count now run uncached. With the query cache forced on, a double-replay mutation fails the hardened count; the old count passes it. bin/rails test(full) ond411d150a: 13,194 runs, 60,630 assertions, 0 failures, 0 errors, 36 skips.bin/rubocop(changed files): no offenses.bundle exec erb_lint,npm run lint: not applicable, no ERB or JS changed.bin/brakeman --no-pager: 0 warnings.
Currency parity. A second parity test covers trades in a currency other than the account's. A USD account holds CAD trades, with a rate stored on every trade date, a fee, a split, a trade that carries its own rate and a USD trade. The fallback matches the stored cost_basis on every day, and the first day's basis is the converted figure. The test fails if the fallback skips the conversion, joins the wrong date, ignores the trade's own rate or leaves the fee unconverted. A separate test pins the known gap from #2012 and leaves it unfixed. When a trade's own date has no rate, Money#exchange_to uses the nearest earlier rate and the calculator stores a basis, while the fallback's exact-date lookup reports the cost as unknown. That gap is out of scope for this PR.
Blast radius
- Who calls it.
calculate_avg_costhas two callers,Holding#avg_costandHolding#avg_cost_before; onlyTrade#calculate_realized_gain_losscalls the second.avg_costruns it only when the storedcost_basisis nil, or zero and unlocked. Readers ofavg_cost:holdings/_cost_basis_cell,holdings/show,InvestmentStatement(investment_statement.rb:154) andHolding's trend helpers. Holdings with a stored basis are unaffected. - Siblings.
Holding::ForwardCalculator,Holding::ReverseCalculator,Holding::LotBookandHolding::Materializerare unchanged. The replay does not use theHolding::CostBasisTrackername, which #4904 removes. The newthe fallback agrees with the forward calculatortest holds the fallback to the materialized basis day by day, over a sell, a transfer in, a transfer out, a split and fees. - Exchange rates, deliberately unchanged. The calculators convert through
Money#exchange_to; the fallback still reads the trade's own rate, then the exact-date table rate. Aligning those is the open #2012, and doing it here would add a query per trade. - Query count. Two queries per holding, as before, and now once per holding instance however often
avg_costis asked. Theexists?check is gone and a splits query added. The existing test now pins one trades query and one splits query, and a new trade test pins the same for a closing sale's realized gain. - Existing tests adjusted.
calculates average cost basisand... from another currencyexpect the quotient at 4 places, the scale the calculators' figure is stored at; before, the fallback returned the unrounded quotient. The migration test's comment described the old outbound rule; its assertions are unchanged.a transfer in stops making the fallback unknown once the position is closedused a holding of 15 for trades netting 10; under the seed those 5 opening shares correctly keep it unknown, so it now holds the 10 its trades explain.
Since review
7d037ca17: the fallback replays cost in the holding's own currency. Trades in another currency convert throughexchange_ratesinto it, and a trade's carried rate applies only when the holding is in the account's currency. Calculator-built holdings, all in the account's currency, are unchanged. Full suite: 12,670 runs, 0 failures.03083c1c9: the fallback's replay is kept per holding instance and cleared onreload, so a page that asks a holding for its average cost several times replays its history once. Full suite: 13,192 runs, 0 failures.e15992553: merged upstreammainat2250ba801, no conflicts.25a0a46e4: a rate stored inextraas a JSON number is held to the 20 integer digits a rate string may have, by size, so one written directly cannot overflow the replay query. Full suite: 13,194 runs, 0 failures.d411d150a: the replay query-count tests run with the query cache off.
Summary by CodeRabbit
- Bug Fixes
- Average-cost calculations now account for purchases, sales, transfers, stock splits, and opening positions in chronological order.
- Shares remaining after an outbound transfer retain their purchase cost; transferred-in shares remain unknown-cost when their basis cannot be determined.
- Realized gains and losses on closing sales now use available cost-basis history, including when no stored average cost is present.
- Foreign-currency calculations handle missing or invalid exchange rates, and cost-basis values are rounded consistently.
- Historical cost calculations respect the relevant transaction date and account for same-day purchases and stock splits.