Add a fifo cost basis method and its account setting
Part of #4449.
Replaces #4497, closed so the stack can be a native GitHub stack (heads in this repo). Its review history, including jjmata's threads and their answers, stays there.
What: adds a per-account cost basis method, accounts.cost_basis_method (average, the default, or fifo). Under fifo, Holding::LotBook relieves the oldest open lots first and the materializer stores each sale's consumption in a new holding_lot_disposals table; Trade#realized_gain_loss reads it. A "Cost basis method" select on the edit form of an account that trades sets it, and a change re-syncs the account.
Why: a sale is always measured at the blended average, which is wrong under FIFO because the snapshot after a sale holds the mean of what remains. On #4449's example (60 at $12, 40 at $20, sell 40 at $25), FIFO's basis is $480, not $693.33.
Start reading: Holding::LotBook (app/models/holding/lot_book.rb), HoldingLotDisposal.readable_by_sale, Trade#realized_gain_loss, then Account::Syncer (restates on a method change).
Key tests (test/models/holding_lot_disposal_test.rb, test/controllers/investments_controller_test.rb):
- "fifo sale crossing two lots"
- "realized gain reads the persisted consumption, not the post-sale snapshot"
- "average account figures unchanged after the method column exists"
- "unlink, forward sync, then read: lots out of partition leave a fifo gain unknown"
- "changing the method starts one sync of the account"
Behaviour change: every existing account stays on average with its figures unchanged, except where a sale exceeded the position: the purchase that covers it no longer joins the average pool. Trading accounts gain the method select. Two migrations: a column with a constant default (metadata-only) and a new empty table; both reversible, no backfill.
Stack: bottom of the lot stack (slice 3 of #4449; 1 of 5 open), based on main. Next: #4901 (lot cost editor). Merge order: #4900 → #4901 → #4902 → #4903 → #4904 (slice 2, #4899, is merged).
Size: +369 / −29 outside tests (about 305 excluding schema and locale), slightly over the guide: the method and its setting ship together so the slice doesn't add a method nobody can select.
Fork pre-flight: jaysbeekay/sure#601 (same commits, on the fork's copy of this branch). It ports the merged fork PRs jaysbeekay/sure#580 and jaysbeekay/sure#581.
Screenshots
Edit investment account, rendered headless by a throwaway system test with fixture data. Before is slice 2's head, after is this branch.
| Before | After | |
|---|---|---|
| Desktop (1400px) | ![]() | ![]() |
| Phone (390px) | ![]() | ![]() |
Full description and evidence
Problem
A sale is always measured at the position's blended average. Under any other method that figure is wrong, because the snapshot after a sale holds the mean of what remains, not the cost of what was sold. On #4449's Example (60 bought at $12, 40 at $20, then 40 sold at $25), the FIFO basis is 40 × $12 = $480. The snapshot after the sale says $17.33 a share, which gives $693.33.
What this changes
accounts.cost_basis_method{average,fifo}, defaultaverage, with a check constraint. Every existing account keepsaverage, and its figures are unchanged.holding_lot_disposals: one row per lot a sale took from. It holds the sale's entry, the consumed lot's source entry (nil for the opening lot, and for units sold beyond what was held until a purchase covers them), the qty, the unit cost and the currency.Holding::LotBooktakes the method.- Under
fifoa sale consumes the oldest open lot first and records a disposal for each lot it touches. average_costbecomes the mean of the open lots a trade acquired. The opening lot stays out, as it stays out of the pool.- A transfer-in stops making the position unknown once its lot has been sold.
- A sale beyond the position leaves a shortfall. The acquisition that fills it prices that part of the sale under
fifo, oldest shortfall first, and its units stay out of the average pool under either method. - Under
averagethe book records nothing. Its figures change only where a sale exceeded the position (see Blast radius).
- Under
- Both calculators build their books with the account's method. The materializer stores the disposals, filtered to
security_idson a scoped run. Trade#realized_gain_lossreads the stored disposals when the account sells byfifoand the record covers the whole sale. A consumed lot with no cost makes the gain unknown. Without a covering record, anaverageaccount reads the snapshot as before. Afifoaccount's gain is unknown instead, because its snapshot after the sale holds the mean of the open lots, not the cost of what was sold. The proceeds conversion is unchanged.- Partition guard. Before reading disposals,
HoldingLotDisposal.readable_by_salechecks that the position's open lots equal the holding's latest quantity (HoldingLot.in_partition). Otherwise the sale has no readable record, and underfifoits gain is unknown. After an unlink, a forward sync keeps opening lots it cannot rebuild, and this is the state the guard keeps out. - The reports card preloads each sale's disposals beside its holdings: one disposals query for the whole set, and none when no account sells by
fifo. - A "Cost basis method" select (Average cost / First in, first out (FIFO)) on the edit form of an account that supports trades, with a hint. All strings go through
t().- Changing the method starts a sync, which restates the stored figures. Resubmitting the same method starts none.
- A change made while a sync is already running is restated afterwards:
Account::Syncerrecords the method each run used, and post-sync starts another sync if it has changed since. - The shared update path drops the method for an account without trades, judged after the subtype in the same submission is applied.
createdrops it too: a new account starts onaverage.
| Method | Basis of the 40 sold | Realized gain | Remaining avg |
|---|---|---|---|
average | $608 | $392 | $15.20 |
fifo | $480 | $520 | $17.33 |
Not in this slice: the lot cost editor (U4), named-lot selection (U6), and counting the opening lot in the mean.
Blast radius
Who else hits these lines, and what do they pass?
-
LotBook.newis called by the two calculators, which now passmethod:. -
The reverse calculator now records a cost-basis snapshot after a transfer-in. Under
averageit repeats the previous figure, and slice 1's byte-identity test still passes. -
Trade#calculate_realized_gain_lossis reached from the reports card (which preloads) and from a single trade. -
AccountableResource#updateserves every account type's controller, andaccounts/_formis rendered by every type's form. A non-trade account never shows the select and drops the param (tested on a depository). -
Stored averages and gains change only where a sale exceeded the position. Under
average, a purchase that covers such a sale no longer joins the cost pool, so a later purchase is not averaged against it: a sale entered before the same day's purchase from a flat position, then 10 at $300 the next day, now averages $300 where it averaged $250. Underfifothe part of a sale beyond the lots is priced at the acquisition that covers it instead of unknown. A short across a split keeps its unknown cost. The order of a day's trades is unchanged (#4495's rule: entry order decides when created_at differs).
Siblings:
basis_holdingis kept as the fallback.Holding's SQL average fallback (avg_cost_from_totals) still sums every purchase, a sale beyond the position included; we-promise/sure#4151 replaces it with the replay.Holding#calculate_avg_costis unchanged: it serves rows with no stored basis, and answers nil where an open lot's cost is unknown.cost_basis_unknownpasses throughGapfillableunchanged.- Disposals are keyed by sale entry, so a sale moved to another security is restated with it.
Family::DataExporterexportsaccount.as_json, so the new column is exported.
Tests
test/models/holding_lot_disposal_test.rb(new):- the Example under both methods;
- a sale crossing two lots;
averageunchanged;- the persisted consumption beating the post-sale snapshot;
- a foreign-currency lot (basis at the acquisition-date rate, proceeds at the sale-date rate);
- a missing sale-date rate;
- a sale consuming the opening lot;
- a scoped materialization;
- the partition guard both ways, with a control: an unlink then a forward sync leaves the gain unknown, lots in partition are read, and lots short of the holding leave it unknown;
- book-level oldest-first, shortfall,
averageand transfer-in cases; - a sale beyond the position: entered before the same day's purchase (+500 under both methods), the same entered after it, older lots still sold first, an intraday short covered higher (−500), a short covered on a later day, a transfer out's shortfall filled before a later sale's, and the next day's average after a same-day round trip (300, not 250).
test/controllers/reports_controller_test.rb: the card reads two FIFO sales' disposals in one query and shows the oldest-lot gain ($130).investments_controller_test.rb:- changing the method starts one sync, and resubmitting starts none;
- an unknown method gets a 422;
- the select appears only on accounts that trade;
- a depository ignores the method;
- a new account starts on
average.
cryptos_controller_test.rb: an exchange↔wallet switch in the same submission.account/syncer_test.rb: a method changed mid-sync starts one more sync, with the unchanged control.- Mutations: 18 on the model side and 10 on the setting, all caught. For the shortfall, 4 more, all caught: no shortfall pricing, covering units entering the pool, the shortfall priced at the sale price, and a transfer out left out of the queue. The reports preload was checked both ways at this head: without it, 2 queries; with
Tradeignoring it, 3.
Validation
- Full suite at
08b8c1cd7(the tree it ran on, before a commit-message-only rewrite):13504 runs, 62152 assertions, 0 failures, 0 errors, 36 skips. test/system/accounts_test.rb(headless Chromium): 9 runs, 0 failures.bin/rubocop,erb_lintandbin/brakeman(0 warnings) are clean.
Migration notes
accounts.cost_basis_methodis added with a constant default, which is metadata-only on PG 11+.holding_lot_disposalsis a new, empty table.- Both migrations are schema-only and reversible, with no backfill. Disposals come from the next materialization, and only for accounts set to
fifo. - Verified: up,
db:rollback STEP=2, up on a scratch test database.
AGENTS.md
- Code placement: model logic. The controller adds a param guard and a sync call.
- Design system: the select is the styled form builder's own, and the hint uses
text-secondary. No new styles. - Copy: strings go through
t(). - Other: screenshots above; current-version migrations with notes; commit subjects ≤72 characters, with no fork references.
Summary by CodeRabbit
- New Features
- Choose average-cost or FIFO accounting for eligible investment and crypto accounts. New accounts use average cost by default.
- FIFO accounting tracks the lots used for sales, supporting lot-based cost basis and realized-gain calculations.
- Changing an account’s cost-basis method recalculates historical realized gains and current holdings’ average cost.
- Imported account data can restore a recognized cost-basis method.
- Improvements
- Reports use available lot details to calculate realized gains for FIFO sales; gains remain unknown when required cost information is unavailable.



