Replace the cost-basis tracker with an in-memory lot book

Merged
JA
1mo ago
+909-96

Part of #4449.

Slice 1 (U1) of the per-lot cost basis series that #4449 proposes. Each later slice builds on the one before it. This one has no dependency.

Fork pre-flight: jaysbeekay/sure#599 (https://github.com/jaysbeekay/sure/pull/599), which holds this slice's CI and review history. Same branch, same commit. It ports two merged fork PRs, jaysbeekay/sure#577 and jaysbeekay/sure#578, onto current main. Their review history is there too.

Problem

Cost basis is a running weighted average per position (Holding::CostBasisTracker). There is no notion of a lot, so nothing can say what each acquisition cost, which a FIFO method, a per-lot cost or a transferred-in parcel's own cost all need (#4449).

What this changes

Behaviour does not change. This slice adds the lot structure under today's figures. No stored figure moves, and there is no schema change, UI or new param.

  • Characterisation tests first. They pin today's figures before anything moves:
    • the remap merge's weighted cost_basis, and its unknown-side fallback;
    • InvestmentStatement's unrealized figures and the sale's realized gain on #4449's two-parcel Example (15.20, 888, 608, 392);
    • the same Example with the first parcel transferred in (unknown throughout, and the sale has no realized gain).
  • Holding::LotBook replaces the tracker's internals: an in-memory book of lots per security, used by both holding calculators.
    • One lot per acquisition, keyed by its source entry, with its own acquired_on, open quantity and per-unit cost. A transfer-in is a lot of unknown cost.
    • A sale relieves every open lot pro rata (the average method), so each lot keeps its own cost.
    • A split restates every lot: more units at a lower cost, with the same money. For any history that never goes negative, the lots sum exactly to the position, because the last open lot takes the rounding.
    • The figure still comes from the running pool of priced acquisitions. That equals the lots' weighted mean, but pro-rata quantities carry BigDecimal rounding the pool does not, so the pool keeps every stored cost_basis byte-identical.
    • The unknown gate is unchanged: a position holding transferred-in units is still reported unknown, as before.
  • Holding::CostBasisTracker stays as a subclass with the same interface (apply, buy, sell, split, average_cost), so code written against it keeps working, including the fallback replay proposed in #4151.

Blast radius

Who else hits these lines, and what do they pass? The tracker was constructed only by ForwardCalculator and ReverseCalculator#precompute_cost_basis. Both pass a converted, fee-adjusted price (or nil) and a signed quantity to #apply, a Rational ratio to #split, and read #average_cost after each event. apply's new source_id: and acquired_on: keywords are optional. The materializer consumes the same HoldingData fields and is unchanged.

Siblings, unchanged: the label checks (INTERNAL_MOVEMENT_LABELS, TRANSFER_LABEL), Trade#basis_holding, Holding.preload_avg_costs and the remap/reset writes all read snapshot rows or labels, never the tracker.

Tests

  • Characterisation (holding_test.rb, investment_statement_test.rb): four tests that pass on main by design. Run at this head, each of these mutations fails at least one of them: a plain mean in the remap merge, the merge's fallback keeping the moved row's basis, the sale's basis using the holding's quantity, unrealized_gains summing the current value, and the fallback's transfer guard removed. Sale relief and the transfer gate inside the calculators are covered by the lot book tests below.
  • test/models/holding/lot_book_test.rb (new, 19 tests). It keeps today's tracker verbatim as ReferenceTracker, the oracle.
    • Equivalence: the book under average matches the tracker exactly at every step over four sequences (liquidation and repurchase, the two-parcel Example, 1/3 relief with 3:1 and 1:7 splits, unknown prices with an oversell and transfers).
    • Byte identity: forward and reverse materialization write identical holdings rows (date, security, qty, cost basis, source, lock, currency) with the oracle and with the book, on fixtures of more than 20 rows covering a locked manual row, a transfer sold out and bought back, a split with fees, a provider-only position and units held before the first trade.
    • Lots: one per acquisition, keyed by its entry; pro-rata relief keeps each lot's cost; a split restates them; a transfer-in is an unknown lot that does not move the average.
    • Partition: open lots sum to the position after every step, and on every date of the forward calculator.
  • Fail-first: before the book existed, 15 of its 17 original tests errored on the missing constant; the other two are interface and lock guards that pass by design.
  • Mutations (11, all caught): figure from the lots' mean instead of the pool; a transfer counted in the pool; splits not scaling lots, or keeping the unit cost; a sale not relieving lots; rounding not absorbed; either calculator dropping a transfer lot or a lot's source entry; a pool reset clearing the lots.

Validation

  • Full suite at 727a6778c: 13456 runs, 61989 assertions, 0 failures, 0 errors, 36 skips.
  • bin/rubocop: no offenses. bin/brakeman: no warnings.
  • No ERB, JS, migration, API or UI change.

AGENTS.md

I checked the change against the current AGENTS.md:

  • Code placement: model POROs, with Minitest and fixtures. minitest/mock's stub is used only to swap in the oracle.
  • Comments: they describe current behaviour, not history.
  • Commits: subjects are ≤72 characters, with no fork references.
  • Dependencies: none added.

Summary by CodeRabbit

  • Improvements
    • Cost basis reflects acquisition lots, partial sales, and stock splits for more consistent average-cost calculations.
    • Transfers without a known purchase cost remain marked as unknown rather than receiving an inferred cost.
    • Investment statements show blended cost basis and related gain calculations for holdings with multiple purchase parcels.
    • When holdings are merged, known cost bases are combined by quantity, while unknown bases remain unknown.
    • Same-day trades are ordered with purchases before sales when their timestamps match; trades with different timestamps retain their entry order.