Add a fifo cost basis method with stored lot disposals

Merged
JA
1mo ago
+584-21

Part of jaysbeekay/sure#551 (PR 2 of the stack: PR 0 #577 ← 1a #578 ← 1b #579 ← PR 2 ← 3 ← 4 ← 5). Its base is main, because #579 merged as 283b62f6a.

Problem

Today a sale is always measured at the position's blended average. Under any other method that figure is wrong: the snapshot after a sale holds the mean of what remains, not the cost of what was sold. On the Example in #551, 60 units were bought at $12 and 40 at $20, then 40 sold at $25. Under fifo the sale's basis is 40 × $12 = $480. The snapshot after it says $17.33 a share, which gives $693.33.

What this changes

  • accounts.cost_basis_method {average, fifo}, default average (owner decision 1(c)), enforced by a check constraint. Every existing account keeps average, and its figures are unchanged.
  • holding_lot_disposals: one row per lot a sale took from. It holds the sale's entry, the source entry of the lot consumed (nil for the opening lot and for units sold beyond what was held), the qty, the unit cost and the currency (the account's, like derived lots).
  • Holding::LotBook takes the method. Under fifo a sale consumes the oldest open lot first and records a disposal for each lot it touches. average_cost becomes the mean of the open lots a trade acquired. The opening lot stays out of it, as it stays out of the pool (decision 8). A transfer-in stops making the position unknown once its lot has been sold, where under average it is unknown until the position closes. Under average the book records nothing and behaves exactly as before.
  • Both calculators build their books with the account's method. The materializer stores the disposals beside the lots, filtered to security_ids on a scoped run, because the calculators replay every security.
  • Trade#realized_gain_loss reads the stored disposals when the account sells by fifo and the stored record covers the whole sale. A consumed lot with no cost (the opening lot, or units sold beyond what was held) makes the basis unknown, giving :missing_cost_basis. Without a covering record it reads the snapshot exactly as before. Proceeds conversion is unchanged, so :missing_exchange_rate still names a missing sale-date rate.
  • Partition guard (owner decision 12, from nightly review 6376564566 on #579). Before reading disposals, HoldingLotDisposal.readable_by_sale checks that the position's open lot quantity equals the holding's quantity on its latest date (HoldingLot.in_partition). If it doesn't, the trade falls back to the snapshot figure. After an unlink, a forward sync keeps opening lots it cannot rebuild, and this is the state the guard keeps out.
  • Portfolio::RealizedGains preloads the disposals and the partition check: three queries for the whole set, and none when no account in it sells by fifo.

Not in this PR, and why:

  • A settings control for the method. It comes in PR 2b, the next slice (owner decision 13 on jaysbeekay/sure#551). It adds the account form select and starts a re-sync when the method changes, which is what restates the figures.
  • Named-lot selection. That is PR 4.
  • Counting the opening lot in the mean. Decision 8 keeps it out, and it gets its own slice later.

Example (from #551), as tested

MethodBasis of the 40 soldRealized gainRemaining avg
average$608$392$15.20
fifo$480$520$17.33

Blast radius

Who else hits these lines, and what do they pass?

  • LotBook.new is called by the two calculators, which now pass method:. The 1a byte-identity test stubs LotBook.new with its reference tracker, and the stub now accepts that keyword. The reverse calculator asks the book unknown_cost? only under fifo, so the reference tracker is never asked.
  • The reverse calculator now records a cost-basis snapshot after a transfer-in as well. Under average that snapshot repeats the previous figure: add_unknown leaves the pool untouched, and the transfer span still gates the date. So the stored figures are the same, and the 1a byte-identity test still passes.
  • Trade#calculate_realized_gain_loss is reached only through Portfolio::RealizedGains, which preloads, and through the reports view, which reads RealizedGains' trades.

What else reads what changed (siblings):

  • basis_holding: Trade only, kept as the fallback.
  • Holding#calculate_avg_cost and preload_avg_costs: unchanged. They serve rows with no stored basis, which under fifo are rows with an open lot of unknown cost, and they answer nil there too.
  • cost_basis_unknown: Gapfillable passes it through, unchanged.
  • holding_lots readers: this PR adds the first one (in_partition). Remap and reset need no change for disposals. These are keyed by sale entry, and store! deletes by the sales in scope, so a sale moved to another security is restated with it at the next materialization.
  • Family::DataExporter exports account.as_json, so the new column is exported automatically. Import of the method is left to PR 5, with the other lot data.

Tests

test/models/holding_lot_disposal_test.rb (new); the bracket says what each assertion catches.

  • fifo consumes the oldest lot first: the Example under both methods [gain $392 vs $520; remaining avg $15.20 vs $17.33].
  • fifo sale crossing two lots: sell 70 [stored basis 60×12 + 10×20 = $920].
  • average account figures unchanged after the method column exists [default average; no disposals written; $392 / $15.20].
  • realized gain reads the persisted consumption, not the post-sale snapshot [the snapshot gives $306.67; the gain is $520].
  • foreign-currency lot: basis at acquisition-date rate, proceeds at sale-date rate [basis $1,500 at 1.5; gain $1,100; not $600, which is the basis at the sale-date rate].
  • missing sale-date rate still reports :missing_exchange_rate [the lot side is known; the reason is unchanged].
  • a sale that consumes the opening lot has an unknown basis [:missing_cost_basis; disposals of 2 opening units and 2 from the first buy].
  • a materialization scoped to one security restates only that security's disposals [the other security's rows keep their ids; this one's are restated].
  • unlink, forward sync, then read: lots out of partition fall back to the snapshot figure. A reverse fifo account holds 6 units before its trades; its sale takes 4, leaving 2 opening units open. After unlinking and a forward sync, the stored lots add up to 18 against a holding of 16, and the forward run's record says $400. The gain reads the snapshot's $650.
  • lots in partition are read. This is the control for the test above: the same trades with no pre-history give $400 from the record, not the snapshot's $650. A guard that always falls back fails it.
  • lots short of the holding fall back to the snapshot figure. The other side of the guard: one lot is set 2 units short, so lots add up to 14 against a holding of 16. The gain reads the snapshot's $650, not the record's $400. Added at 55956c636 for the light review: before it, a >= guard passed both tests above.
  • realized gains preload reads stored disposals without a query per disposal [one query on holding_lot_disposals for two sales; figures from the record].
  • Book-level: under fifo the book consumes the oldest lot first and records what each sale took, under fifo a sale beyond the open lots records the excess at an unknown cost, under average the book records no disposals, under fifo a consumed transfer-in lot no longer makes the cost unknown.

PR 0's pins and 1a's byte-identity test (test/models/holding/lot_book_test.rb) still pass unchanged under average.

Evidence

Fail first. The tests were written before the code. On main (283b62f6a) all 14 initial tests error for the expected reasons: unknown attribute 'cost_basis_method' for Account, undefined method 'disposals' for Holding::LotBook, and wrong number of arguments for LotBook.new(method:).

The tests also caught two defects of my own on the way:

  • account.holding_lot_disposals.delete_all on the bare association nullified account_id instead of deleting the rows. It now uses a relation.
  • A materialization scoped to one security re-inserted the other securities' disposals, because the calculators replay every security. They are now filtered to security_ids.

Mutations (18, all caught). I broke each change in turn and ran the holding, lot, trade and realized-gains tests:

#MutationCaught by
P1fifo relieves pro rataoldest-first book test, persisted-consumption test, in-partition control
P2fifo consumes newest firstoldest-first book test, opening-lot test, preload test
P3fifo average comes from the poolpersisted-consumption test, Example test
P4opening lot counted in the fifo meanopening-lot test, unlink test
P5shortfall not recordedsale-beyond-open-lots test
P6forward fifo uses the transfer gatetransfer-in-sold test (forward)
P7reverse fifo uses the transfer spanstransfer-in-sold test (reverse)
P8disposals not persisted5 tests
P9scoped run keeps every security's disposalsscoped-materialization test
P10store! not scoped by salesscoped-materialization test
P11no partition guardunlink test
P12guard always falls backin-partition control, preload test, Example test
P13trade ignores disposals5 tests
P14unknown lot cost treated as zeroopening-lot test, unlink test
P15no preloadpreload test
P16partition compared against all dates, not the latestunlink test, Example test
P17disposals recorded under averageaverage book test, average-unchanged test
P18guard reads held >= lots instead of equalitylots-short test (added at 55956c636)

P6 and P7 survived the first run, and P18 was found by the light review (6380805199); because only the book-level test covered them. a transfer-in sold under fifo leaves the remaining position's basis known, forward and reverse was added in 246ad21f7, and both are now caught. P18 survived until the lots-short test.

Migration. I ran it on a scratch test database on beastpc, never a real one: up, then db:rollback STEP=2, then up again. Every step was clean. Abridged:

== 20261024090000 AddCostBasisMethodToAccounts: migrated
== 20261024090100 CreateHoldingLotDisposals: migrated
== 20261024090100 CreateHoldingLotDisposals: reverted
== 20261024090000 AddCostBasisMethodToAccounts: reverted
== 20261024090000 AddCostBasisMethodToAccounts: migrated
== 20261024090100 CreateHoldingLotDisposals: migrated

db/schema.rb carries only this PR's hunks. The regenerated file also rewrote four unrelated check constraints, which is Postgres-version formatting noise, and those hunks were left out.

Full suite at 246ad21f7: 14366 runs, 66764 assertions, 0 failures, 0 errors, 38 skips. After 55956c636 the full suite ran on #581's head 9a03e91dd, which contains it: 14373 runs, 66786 assertions, 0 failures, 0 errors, 38 skips. bin/rubocop: no offences. bin/brakeman: 0 warnings.

AGENTS.md

I checked the change against the current we-promise/sure AGENTS.md:

  • Code placement: the logic lives in models and POROs.
  • Comments: they describe intent, with no history.
  • Tests: Minitest, with fixtures created in each test.
  • Migrations: both use the current Migration[8.1], are schema-only and reversible, and the run-and-rollback transcript is above.
  • Commit: the subject is ≤72 characters.
  • UI, API, i18n: none touched, so no screenshots.

Migration notes: accounts.cost_basis_method is added with a constant default, which is a metadata-only change on PG 11+. holding_lot_disposals is a new, empty table. There is no backfill. Disposals come from the next materialization, and only for accounts set to fifo.