Replay the cost-basis tracker in Holding's fallback

Merged
JA
2mo ago
+519-71

Summary

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 the shared Holding::CostBasisTracker instead of a separate SQL average, so sells and outbound transfers are relieved, splits are applied, and a transfer in stops making the position unknown once it is closed.

Fixes jaysbeekay/sure#419
Fork pre-flight for upstream we-promise/sure#3566. Upstream draft PR: we-promise/sure#4151 (https://github.com/we-promise/sure/pull/4151), the same branch and the same commit. Base is mirror/upstream-main at the same commit as upstream main (a3bb5d991), so the diff is what upstream will see.

What changed

  • 5b617ff60 Replay the cost-basis tracker in Holding's fallback

  • ebea5a944 Correct the fallback's outbound-transfer rule in a test comment

  • 15c92edef Pin the fallback to the calculator for foreign-currency trades

  • 1ca63dfb8 Price a closing sale at the average cost before it

  • f6aeb1b52 Seed the average-cost replay from the holding's quantity (from review: a reverse-synced account's opening shares)

  • 7e537c993 Replay the history once when pricing a closing sale (from review: a closing sale replayed the history twice)

  • da347b926 Test the walk-back stops at the snapshot's date

  • Holding#calculate_avg_cost: replays this security's trades up to the holding's date, in Entry.chronological order, through Holding::CostBasisTracker, following Holding::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), as Holding::ReverseCalculator#precompute_cost_basis seeds 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 of avg_cost (which is now stored_avg_cost || calculate_avg_cost). It never queries.

  • New public Holding#avg_cost_before(entry) and a fallback in Trade#calculate_realized_gain_loss (below).

  • test/models/holding_test.rb: 13 new tests; 4 existing ones adjusted (below).

  • test/models/trade_test.rb: 7 new tests.

  • test/migrations/clear_transferred_position_cost_bases_migration_test.rb: one comment corrected.

Trades (no stored basis)Calculators storeBeforeAfter
buy 10 @ 100, sell 10, buy 10 @ 200200150200
buy 10 @ 100, sell 5, buy 5 @ 200150133.33150
transfer in 10, sell 10, buy 10 @ 200200nil200
buy 10 @ 100, 2:1 split, buy 10 @ 6053.33338053.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/main d55eac220. 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); Trade back to avg_cost alone (4); splits ignored in avg_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) and realized 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 position passes 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); Trade back to avg_cost (1, the query count); unlocked zero trusted as a stored basis (1).
  • bin/rails test (full) on da347b926: 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 at ebea5a944, passes again (realized gain, above).
  • 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 we-promise/sure#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_cost has two callers, Holding#avg_cost and Holding#avg_cost_before; only Trade#calculate_realized_gain_loss calls the second. avg_cost runs it only when the stored cost_basis is nil, or zero and unlocked. Readers of avg_cost: holdings/_cost_basis_cell, holdings/show, InvestmentStatement (investment_statement.rb:154) and Holding's trend helpers. Holdings with a stored basis are unaffected.
  • Siblings. Holding::ForwardCalculator, Holding::ReverseCalculator, Holding::CostBasisTracker and Holding::Materializer are unchanged. The new the fallback agrees with the forward calculator test 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 we-promise/sure#2012, and doing it here would add a query per trade.
  • Query count. Two queries per holding, as before. The exists? 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 basis and ... from another currency expect 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 closed used 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.
  • Fork-only sibling. Holding.preload_avg_costs (fork main only) mirrors the old SQL. It is tracked as jaysbeekay/sure#420, to follow once this reaches fork main; it does not exist upstream.