fix(holdings): replay the cost-basis fallback through the calculators' tracker
Follow-up to #4033, as discussed in its review.
Problem
Holding#calculate_avg_cost is the cost basis of a holding with none materialized. It was an SQL average of every purchase the account ever made in the security: a second implementation of the rules the holding calculators apply through Holding::CostBasisTracker. The two disagreed:
- A full close did not reset it. A position sold in full and bought again still averaged in the first round's purchases. The tracker starts again from a clean basis.
- Splits were ignored. Purchases before and after a split were summed as they stood, mixing pre- and post-split units.
- An internal movement made it unknown for good. The calculators treat units moved in as unknown only until the position next crosses zero.
#4033 listed the first as a known limitation, and its review pointed out that the fee and missing-rate rules were now written twice.
Fix
Holding::CostBasisFallback replays the account's trades and splits in the security, up to the holding's date, through the tracker and the calculators' own helpers (Holding::TradeCalculatorHelpers). The order is the calculators': trades by date and creation, a split at the open of its ex-date. A buy's fee is part of its cost, a sell relieves at the running average, a full close resets it, and a foreign trade with no usable rate leaves it unknown.
A position closed on the holding's date keeps the cost of the units it last held. A sale's gain is measured against the holding on its own date, and after a full close that holding holds nothing and has no materialized basis. The SQL average answered that case by accident, since it never reset; a plain replay would reset and leave every sale that closes a position without a gain.
It stays two queries, the trades and the splits, and a holding replays once however often it is asked for its average cost. It orders trades and splits with the reverse calculator's own merge, now shared through Holding::TradeCalculatorHelpers. Each trade's rate is read with it: its own rate first, then the table's for that day, as before. The calculators look a rate up per trade; the fallback never does, so it never triggers a fetch either. The SQL fallback's rate pattern from #4033 goes away with it: a rate is accepted on the same terms as Trade's validation.
Behaviour change
A holding without a materialized basis can now show a different average, or none. The cases are the three above, and each now agrees with what the calculators materialize.
Not in this PR
The reverse calculator also counts units held before an account's first imported trade, at an unknown cost. The fallback starts from an empty position, as the forward calculator does. Counting those units here would turn the average of the known purchases, which the fallback has always shown for such a holding, into no figure at all. That is a visible change of its own. A sale of such units does not take the replay below zero: it closes what the replay holds, as the tracker does, so the purchases after it keep their basis.
Tests
New in Holding::CostBasisFallbackTest: the holding on the day a position closes keeps what its units cost; a position bought again after a full close starts from a clean basis; a sale of units held before the imported trades does not leave it short; the basis is known again once moved-in units are sold in full, and unknown while they are held; the cost carries across a split. In HoldingTest: the trades and splits are read once each, and a holding replays its history once however often it is asked. New in TradeTest: a sale that closes the position realizes its gain against what it held. Each new test fails without the change, except the unknown-while-held case and the closing-day cases, which main already gets right by accident and the replay must keep. The fee-inclusive average now compares within 1e-20, since the tracker carries a fee per unit, as the calculators do.
Also in KrakenAccount::ProcessorTest, pinning what #4086's review relied on: a sell whose fee came out in coins carries those units in its quantity, and price * qty - fee gives back what the fill brought in, so its gain is measured on every unit that left at its cost.
bin/rails test test/models: 7,453 runs, 1 failure, from this branch's base: SnaptradeAccount::ActivitiesProcessorTest expected option gains without fees, which #4145 has since fixed on main. Rubocop clean.
Summary by CodeRabbit
- Bug Fixes
- Average cost now accounts for stock splits, purchase fees, sales, position closures and reopenings, and transferred units. It remains unknown when available information is insufficient to determine it reliably.
- Sales that close a position now retain the correct realized gain.
- Kraken sales with fees deducted in the asset sold now account for all units removed when calculating trade quantity and realized gain.
- Repeated average-cost requests reuse the result, and reloading a holding refreshes it.