The personal finance app for everyone (by everyone)
Ruby
Add a fifo cost basis method and its account setting (#4900)
jaysbeekay75a25f0cd962
diff --git a/app/controllers/concerns/accountable_resource.rb b/app/controllers/concerns/accountable_resource.rbindex da0e5c5060..3db1f8940f 100644--- a/app/controllers/concerns/accountable_resource.rb+++ b/app/controllers/concerns/accountable_resource.rb@@ -41,8 +41,9 @@ module AccountableResourcenilend || (Time.zone.today - 2.years)Account.transaction do+ # A new account has no sales to restate, so it starts on the default method.@account = Current.family.accounts.create_and_sync(- account_params.except(:return_to, :opening_balance_date).merge(owner: Current.user, logo_chosen: logo_chosen?),+ account_params.except(:return_to, :opening_balance_date, :cost_basis_method).merge(owner: Current.user, logo_chosen: logo_chosen?),opening_balance_date: opening_balance_date)@account.lock_saved_attributes!@@ -84,7 +85,12 @@ module AccountableResource# Assigning a balance can fail before the normal update path assigns the# other submitted fields. Keep them available for the 422 form without# persisting them.- update_params = account_params.except(:return_to, :balance, :opening_balance_date)+ update_params = account_params.except(:return_to, :balance, :opening_balance_date, :cost_basis_method)+ # Every account type posts through here; only one with trades has lots to+ # sell. Applied after the other fields, since the same form can change a+ # crypto account's subtype and with it whether the account trades.+ cost_basis_method = account_params[:cost_basis_method]+ previous_cost_basis_method = @account.cost_basis_method# An uploaded logo is meant to be seen, so it takes over from Brandfetch.update_params[:logo_selection] = "automatic" if account_params[:logo].present?@account.logo_chosen = logo_chosen?@@ -108,7 +114,11 @@ module AccountableResource# Update remaining account attributes. Note: currency is intentionally allowed# here so all account types (depositories, credit cards, loans, etc.) can# have their currency changed via this shared update path.- unless @account.update(update_params)+ # One save: lock_saved_attributes! below locks what this save changed,+ # and a second save would leave it nothing to lock.+ @account.assign_attributes(update_params)+ @account.cost_basis_method = cost_basis_method if cost_basis_method && @account.supports_trades?+ unless @account.save@error_message = @account.errors.full_messages.join(", ")raise ActiveRecord::Rollbackend@@ -130,6 +140,10 @@ module AccountableResourceendapply_logo_choice+ # The stored figures were worked out under the old method; a sync restates+ # them. Compared by hand: lock_saved_attributes! saves again, which clears+ # saved_change_to_cost_basis_method?.+ @account.sync_later if @account.cost_basis_method != previous_cost_basis_methodredirect_back_or_to account_path(@account), notice: t("accounts.update.success", type: accountable_type.name.underscore.humanize)end@@ -200,7 +214,7 @@ module AccountableResource:name, :balance, :subtype, :currency, :accountable_type, :return_to,:opening_balance_date,:institution_name, :institution_domain, :notes, :exclude_from_reports,- :enable_category_matcher, :logo,+ :enable_category_matcher, :cost_basis_method, :logo,accountable_attributes: self.class.permitted_accountable_attributes)enddiff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex de6a5a4f8f..e0d92836fe 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -656,6 +656,10 @@ class ReportsController < ApplicationControllertrade.instance_variable_set(:@preloaded_holdings, holdings_by_account[trade.entry.account_id] || [])end+ # What each fifo sale took from which lot, read once for the whole set.+ lot_disposals = HoldingLotDisposal.readable_by_sale(sell_trades)+ sell_trades.each { |trade| trade.preloaded_lot_disposals = lot_disposals[trade.entry.id] }+# The rates the proceeds conversion needs, in one query rather than one# per foreign disposal.Trade.preload_exchange_rates(sell_trades)diff --git a/app/models/account.rb b/app/models/account.rbindex ef1d35fcfc..799a5e7b47 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -24,6 +24,7 @@ class Account < ApplicationRecordhas_many :trades, through: :entries, source: :entryable, source_type: "Trade"has_many :holdings, dependent: :destroyhas_many :holding_lots+ has_many :holding_lot_disposalshas_many :balances, dependent: :destroyhas_many :recurring_transactions, dependent: :destroyhas_many :goal_accounts, dependent: :destroy@@ -79,6 +80,8 @@ class Account < ApplicationRecordendenum :classification, { asset: "asset", liability: "liability" }, validate: { allow_nil: true }+ # Which lots a sale consumes: pro rata (the default) or oldest first.+ enum :cost_basis_method, { average: "average", fifo: "fifo" }, prefix: :cost_basis, validate: trueVISIBLE_STATUSES = %w[draft active].freezeHISTORICAL_STATUSES = (VISIBLE_STATUSES + %w[disabled]).freezediff --git a/app/models/account/syncer.rb b/app/models/account/syncer.rbindex d7493701fd..635c1d3d46 100644--- a/app/models/account/syncer.rb+++ b/app/models/account/syncer.rb@@ -6,6 +6,11 @@ class Account::Syncerenddef perform_sync(sync)+ # This syncer is shared by every account type, and only investment and+ # crypto accounts keep lot books, so only their syncs record the method.+ if account.accountable_type.in?(%w[Investment Crypto])+ sync.update!(data: (sync.data || {}).merge("cost_basis_method" => account.cost_basis_method))+ endRails.logger.info("Processing balances (#{account.linked? ? 'reverse' : 'forward'})")import_market_datamaterialize_balances(window_start_date: sync.window_start_date)@@ -15,9 +20,25 @@ class Account::Syncerdef perform_post_syncaccount.family.auto_match_transfers!(account: account)+ restate_if_cost_basis_method_changedendprivate+ # A method saved while this run was calculating left its figures on the+ # old one, and the form's sync_later folded into this run. Once it has+ # completed, a new sync restates them. Post-sync also runs after a failed+ # sync; that one queues nothing, since each failure would queue another,+ # and the next sync to complete restates the figures.+ def restate_if_cost_basis_method_changed+ latest = account.syncs.ordered.first+ return unless latest&.completed?++ used = latest.data&.dig("cost_basis_method")+ return if used.nil? || used == Account.where(id: account.id).pick(:cost_basis_method)++ account.sync_later+ end+def materialize_balances(window_start_date: nil)strategy = account.linked? ? :reverse : :forwardBalance::Materializer.new(account, strategy: strategy, window_start_date: window_start_date).materialize_balancesdiff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 6988b0d11f..d787f0630d 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -377,6 +377,7 @@ class Family::DataImporter)# Older exports predate the choice and keep the account's own.account.logo_selection = data["logo_selection"] if Account.logo_selections.key?(data["logo_selection"])+ account.cost_basis_method = data["cost_basis_method"] if Account.cost_basis_methods.key?(data["cost_basis_method"])account.save!diff --git a/app/models/holding/cost_basis_tracker.rb b/app/models/holding/cost_basis_tracker.rbindex f15b17bdf6..a3e1521ff5 100644--- a/app/models/holding/cost_basis_tracker.rb+++ b/app/models/holding/cost_basis_tracker.rb@@ -1,5 +1,7 @@-# Weighted-average cost basis for a single security. The behaviour lives in-# Holding::LotBook; this name keeps its interface (#apply, #buy, #sell, #split,-# #average_cost) available to code that only needs the average.+# The pre-lot weighted-average tracker's name, kept only as the subject of the+# parity suite: cost_basis_tracker_test.rb and the oracle block in+# lot_book_test.rb assert Holding::LotBook reproduces its figures to the last+# digit. No production code constructs it — the calculators use LotBook+# directly.class Holding::CostBasisTracker < Holding::LotBookenddiff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rbindex 6c7c9b439c..480f0fef0f 100644--- a/app/models/holding/forward_calculator.rb+++ b/app/models/holding/forward_calculator.rb@@ -9,7 +9,7 @@ class Holding::ForwardCalculator# The lots of each security, which also give the weighted-average cost# basis, relieving sells so the figure stays correct after a position is# fully sold and repurchased.- @lot_books = Hash.new { |h, k| h[k] = Holding::LotBook.new }+ @lot_books = Hash.new { |h, k| h[k] = Holding::LotBook.new(method: account.cost_basis_method) }# Securities whose position has taken in a transfer. A coin moved in was# acquired at a price nothing here knows, and averaging the purchases alone# would apply their price to units that never cost it.@@ -21,6 +21,11 @@ class Holding::ForwardCalculatorlots_from(@lot_books)end+ # What each sale of each security took from which lot, once #calculate has run.+ def lot_disposals_by_security+ disposals_from(@lot_books)+ end+def clamped_security_idsSet.newend@@ -76,7 +81,7 @@ class Holding::ForwardCalculatorcurrency: price.currency,amount: qty * price.price,cost_basis: cost_basis_for(security_id, price.currency),- cost_basis_unknown: @transferred_security_ids.include?(security_id)+ cost_basis_unknown: cost_unknown?(security_id))end.compactend@@ -139,8 +144,16 @@ class Holding::ForwardCalculator# Returns the current cost basis for a security, or nil if nothing is held# or the position contains transferred-in units of unknown cost.def cost_basis_for(security_id, currency)- return nil if @transferred_security_ids.include?(security_id)+ return nil if cost_unknown?(security_id)@lot_books[security_id].average_costend++ # Under fifo a transfer-in stops mattering once its lot is sold, so the+ # book answers; under average it is unknown until the position closes.+ def cost_unknown?(security_id)+ return @lot_books[security_id].unknown_cost? if account.cost_basis_fifo?++ @transferred_security_ids.include?(security_id)+ endenddiff --git a/app/models/holding/lot_book.rb b/app/models/holding/lot_book.rbindex 2506d392fc..e2a7ded1d2 100644--- a/app/models/holding/lot_book.rb+++ b/app/models/holding/lot_book.rb@@ -5,7 +5,8 @@# quantity, acquisition date and per-unit cost. A transfer-in is a lot whose# cost nothing here knows. Under the average method a disposal relieves every# open lot pro rata, so each lot keeps its own cost and only its quantity-# shrinks.+# shrinks. Under fifo it consumes the oldest lot first, and each sale records+# what it took from which lot as a disposal.## The figure the calculators report, #average_cost, comes from a running pool# of priced acquisitions rather than from the lots. The two agree, but pro-rata@@ -15,7 +16,9 @@## Lot quantities are kept at the precision they are stored at, and a sale# beyond the open lots is a shortfall the next acquisitions fill before they-# open a lot, so the open lots always sum to the position.+# open a lot, so the open lots always sum to the position. Units that fill a+# shortfall stay out of the pool, and under fifo they price the part of the+# sale that went beyond the lots, oldest sale first.## Buys add to the running cost and quantity. Sells relieve quantity at the# current average cost (leaving the per-share average unchanged), and once the@@ -25,8 +28,15 @@## Prices are expected in the account's currency (callers convert before# applying), so the book itself is currency-agnostic.+#+# Under fifo the figure is the mean of the open lots a trade acquired rather+# than the pool, since what remains is no longer a pro-rata share of what was+# bought. The opening lot stays out of it, as it stays out of the pool.class Holding::LotBookLot = Data.define(:source_id, :acquired_on, :qty, :unit_cost)+ # `lot_source_id` and `unit_cost` are nil for the opening lot and for units+ # sold beyond what was held until an acquisition covers them.+ Disposal = Data.define(:sale_id, :lot_source_id, :qty, :unit_cost)# A drift this small is the 18-place rounding of a split that does not# divide evenly; anything wider is a real difference.@@ -34,13 +44,20 @@ class Holding::LotBookattr_reader :lots- def initialize+ def initialize(method: "average")+ @fifo = method.to_s == "fifo"@lots = []+ @disposals = []@closed = []@shortfall = BigDecimal("0")+ @uncovered = []resetend+ def disposals+ @disposals.select { |disposal| disposal.qty.positive? }+ end+# Applies a trade by its signed quantity: positive is a buy, negative a sell.def apply(price, qty, source_id: nil, acquired_on: nil)return if qty.nil?@@ -48,17 +65,22 @@ class Holding::LotBookqty = qty.to_dreturn if qty.zero?- qty.positive? ? buy(price, qty, source_id: source_id, acquired_on: acquired_on) : sell(qty)+ qty.positive? ? buy(price, qty, source_id: source_id, acquired_on: acquired_on) : sell(qty, sale_id: source_id)enddef buy(price, qty, source_id: nil, acquired_on: nil)qty = qty&.to_dreturn if qty.nil? || !qty.positive?+ # Units that cover a sale beyond what was held close that position; only+ # the rest is held, so only the rest joins the pool.+ held = qty - [ qty, @shortfall ].minadd_lot(source_id, acquired_on, qty, price&.to_d)+ return unless held.positive?+@unknown = true if price.nil?- @total_cost += price.to_d * qty unless price.nil?- @total_qty += qty+ @total_cost += price.to_d * held unless price.nil?+ @total_qty += heldend# Units that arrived by internal movement, at a cost nothing here knows.@@ -69,11 +91,13 @@ class Holding::LotBookadd_lot(source_id, acquired_on, qty, nil)end- def sell(qty)+ # A sale with no `sale_id` (a transfer out) consumes lots without recording+ # a disposal: it realises nothing.+ def sell(qty, sale_id: nil)qty = qty&.to_dreturn if qty.nil? || qty.zero?- relieve_lots(qty.abs)+ @fifo ? consume_oldest(qty.abs, sale_id) : relieve_lots(qty.abs)return if @total_qty.zero?# Relieve at the current average cost so the per-share average is unchanged.@@ -93,6 +117,9 @@ class Holding::LotBookdef split(ratio)@total_qty = Security::Split.scale(@total_qty, ratio)@shortfall = Security::Split.scale(@shortfall, ratio)+ # A cover after the split is in other shares than the sale it would price,+ # so a sale short across a split keeps its unknown cost.+ @uncovered.clearrescale_lots(Security::Split.scale(open_qty, ratio)) do |lot|lot.with(qty: Security::Split.scale(lot.qty, ratio),@@ -104,16 +131,23 @@ class Holding::LotBook# Current weighted-average cost per share, or nil when nothing is held or# the cost of what is held is unknown.def average_cost+ return lot_average_cost if @fiforeturn nil if @total_qty.zero? || @unknown@total_cost / @total_qtyend+ # An open lot a trade brought in at a cost nothing here knows.+ def unknown_cost?+ @lots.any? { |lot| lot.source_id && lot.unit_cost.nil? }+ end+# Gives an open lot the drift between the open lots and `target`, the# quantity they must add up to, when it is no more than `bound`: the opening# lot, whose split round trip made it, or the last open lot once a sale has# taken the opening one. The lot's quantity is restated, as #rescale_lots- # does, so no sale is recorded and no other lot moves.+ # does, so no sale or disposal is recorded and no other lot moves; a+ # disposal already taken from it stays as recorded, under 10^-12 apart.def settle_opening(target, bound:)drift = target.to_d - open_qtyreturn if drift.zero? || drift.abs > bound@@ -143,10 +177,65 @@ class Holding::LotBookdef add_lot(source_id, acquired_on, qty, unit_cost)filled = [ qty, @shortfall ].min@shortfall -= filled+ cover(filled, source_id, unit_cost) if filled.positive?lot = Lot.new(source_id: source_id, acquired_on: acquired_on, qty: qty - filled, unit_cost: unit_cost)lot.qty.positive? ? @lots << lot : @closed << lotend+ def lot_average_cost+ acquired = @lots.select(&:source_id)+ return nil if acquired.empty? || unknown_cost?++ acquired.sum(BigDecimal("0")) { |lot| lot.qty * lot.unit_cost } / acquired.sum(BigDecimal("0"), &:qty)+ end++ # Lots are booked in the order they were acquired, the opening lot first,+ # so the oldest is the first open one.+ def consume_oldest(qty, sale_id)+ left = qty+ open = []+ @lots.each do |lot|+ taken = [ left, lot.qty ].min+ left -= taken+ record_disposal(sale_id, lot.source_id, taken, lot.unit_cost) if taken.positive?+ rest = lot.with(qty: lot.qty - taken)+ rest.qty.positive? ? open << rest : @closed << rest+ end+ @lots = open+ return unless left.positive?++ @shortfall += left+ @uncovered << [ record_disposal(sale_id, nil, left, nil), left ]+ end++ # Returns the disposal's index, or nil when nothing was recorded.+ def record_disposal(sale_id, lot_source_id, qty, unit_cost)+ return unless sale_id++ @disposals << Disposal.new(sale_id: sale_id, lot_source_id: lot_source_id, qty: qty, unit_cost: unit_cost)+ @disposals.size - 1+ end++ # Moves `qty` of the oldest shortfall onto the acquisition that filled it,+ # at its cost. Each shortfall is queued with its disposal's index, or nil+ # for a transfer out, which recorded none but is still filled in turn. A+ # covered part leaves its disposal at a lower quantity, which #disposals+ # drops once it reaches zero.+ def cover(qty, source_id, unit_cost)+ left = qty+ while left.positive? && (pending = @uncovered.first)+ index, short = pending+ taken = [ left, short ].min+ if index+ @disposals[index] = @disposals[index].with(qty: @disposals[index].qty - taken)+ @disposals << @disposals[index].with(lot_source_id: source_id, qty: taken, unit_cost: unit_cost)+ end+ short -= taken+ short.positive? ? pending[1] = short : @uncovered.shift+ left -= taken+ end+ end+# Pro-rata relief across every open lot; an oversell closes them all and# leaves the excess as a shortfall.def relieve_lots(qty)diff --git a/app/models/holding/materializer.rb b/app/models/holding/materializer.rbindex 1964e62b0e..ab55569b0f 100644--- a/app/models/holding/materializer.rb+++ b/app/models/holding/materializer.rb@@ -67,6 +67,23 @@ class Holding::Materializer# Only the reverse walk knows the units held before the trades.HoldingLot.store!(account, rows, security_ids: security_ids, openings: strategy == :reverse)+ persist_lot_disposals+ end++ # Recorded only under fifo, so an account sold by average keeps none; its+ # disposal costs are in the account's currency, like its derived lots. The+ # calculators replay every security, so a scoped run keeps to its own.+ def persist_lot_disposals+ by_security = @calculator.lot_disposals_by_security+ by_security = by_security.slice(*security_ids) if security_ids+ rows = by_security.values.flatten.map do |disposal|+ {+ account_id: account.id, sale_entry_id: disposal.sale_id, lot_source_entry_id: disposal.lot_source_id,+ qty: disposal.qty, unit_cost: disposal.unit_cost, currency: account.currency+ }+ end++ HoldingLotDisposal.store!(account, rows, security_ids: security_ids)enddef lot_row(security_id, source_entry_id, qty:, acquired_on: nil, unit_cost: nil, currency: account.currency, clamped: false)diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rbindex e5cfd8a410..121ad38ca2 100644--- a/app/models/holding/reverse_calculator.rb+++ b/app/models/holding/reverse_calculator.rb@@ -14,6 +14,11 @@ class Holding::ReverseCalculatorlots_from(@lot_books)end+ # What each sale of each security took from which lot, once #calculate has run.+ def lot_disposals_by_security+ disposals_from(@lot_books)+ end+# Securities whose provider quantity is below what their trades add up to.attr_reader :clamped_security_ids@@ -135,7 +140,7 @@ class Holding::ReverseCalculator# Spans [start, end) during which a security still holds transferred-in units# of unknown cost. `end` is nil while a span is still open at the last trade.@unknown_spans = Hash.new { |h, k| h[k] = [] }- @lot_books = Hash.new { |h, k| h[k] = Holding::LotBook.new }+ @lot_books = Hash.new { |h, k| h[k] = Holding::LotBook.new(method: account.cost_basis_method) }open_unknown_start = {}# get_trades is already in replay order (date, created_at, acquisitions@@ -183,7 +188,7 @@ class Holding::ReverseCalculatorpositions[security_id] = Security::Split.scale(positions[security_id], event.ratio)@lot_books[security_id].split(event.ratio)- @cost_basis_snapshots[security_id] << [ event.ex_date, @lot_books[security_id].average_cost ]+ record_cost_basis(security_id, event.ex_date)nextend@@ -201,8 +206,8 @@ class Holding::ReverseCalculator@lot_books[security_id].add_unknown(trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)else@lot_books[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)- @cost_basis_snapshots[security_id] << [ trade_entry.date, @lot_books[security_id].average_cost ]end+ record_cost_basis(security_id, trade_entry.date)elsebook = @lot_books[security_id]# Buys raise the basis; sells relieve quantity at the running average, and a@@ -212,7 +217,7 @@ class Holding::ReverseCalculator# Record the basis after each trade — including nil once a position is fully# closed — so cost_basis_for returns nil for the sold-out span instead of a# stale figure carried forward from the last buy.- @cost_basis_snapshots[security_id] << [ trade_entry.date, book.average_cost ]+ record_cost_basis(security_id, trade_entry.date)end# Close an open unknown span only on a genuine downward crossing through@@ -265,21 +270,36 @@ class Holding::ReverseCalculatorevents.sort_by { |date, kind, index, _| [ date, kind, index ] }.map(&:last)end+ # [date, cost basis, whether an open lot's cost is unknown]. A transfer-in+ # leaves the average where it was, so its entry repeats the last figure.+ def record_cost_basis(security_id, date)+ book = @lot_books[security_id]+ @cost_basis_snapshots[security_id] << [ date, book.average_cost, account.cost_basis_fifo? && book.unknown_cost? ]+ end++ # Under fifo a transfer-in stops mattering once its lot is sold, so the+ # book's own answer on the day counts; under average it is unknown until+ # the position closes.def transferred_by?(security_id, date)+ return cost_basis_snapshot(security_id, date)&.last || false if account.cost_basis_fifo?+@unknown_spans[security_id].any? { |start, stop| start <= date && (stop.nil? || date < stop) }enddef cost_basis_for(security_id, date)return nil if transferred_by?(security_id, date)- snapshots = @cost_basis_snapshots[security_id]- return nil if snapshots.empty?+ cost_basis_snapshot(security_id, date)&.second+ end+ # The last entry on or before `date`.+ def cost_basis_snapshot(security_id, date)+ snapshots = @cost_basis_snapshots[security_id]lo, hi, result = 0, snapshots.size - 1, nilwhile lo <= himid = (lo + hi) / 2if snapshots[mid][0] <= date- result = snapshots[mid][1]+ result = snapshots[mid]lo = mid + 1elsehi = mid - 1diff --git a/app/models/holding/trade_calculator_helpers.rb b/app/models/holding/trade_calculator_helpers.rbindex 499b11dbdb..b7b8812183 100644--- a/app/models/holding/trade_calculator_helpers.rb+++ b/app/models/holding/trade_calculator_helpers.rb@@ -7,6 +7,10 @@ module Holding::TradeCalculatorHelpersbooks.filter_map { |security_id, book| [ security_id, book.ledger ] if book.respond_to?(:ledger) }.to_hend+ def disposals_from(books)+ books.filter_map { |security_id, book| [ security_id, book.disposals ] if book.respond_to?(:disposals) }.to_h+ end+# Converts a trade's price into the account's currency at the rate of the# day it was made, or nil when there is no rate for that day.def converted_trade_price(trade, date:)diff --git a/app/models/holding_lot.rb b/app/models/holding_lot.rbindex e8bb54df4a..b4eaa91c00 100644--- a/app/models/holding_lot.rb+++ b/app/models/holding_lot.rb@@ -41,6 +41,22 @@ class HoldingLot < ApplicationRecordendend+ # The [account_id, security_id] pairs among those given whose stored lots+ # add up to the holding's quantity on its latest date. A forward sync keeps+ # opening lots it cannot rebuild, so after an unlink the lots can hold more+ # than the position, and a reader trusts them only where the two agree.+ def in_partition(account_ids, security_ids)+ lots = where(account_id: account_ids, security_id: security_ids).group(:account_id, :security_id).sum(:qty)+ return Set.new if lots.empty?++ holdings = Holding.where(account_id: account_ids, security_id: security_ids)+ latest = holdings.group(:account_id, :security_id).select(:account_id, :security_id, "MAX(date)")+ held = holdings.where("(holdings.account_id, holdings.security_id, holdings.date) IN (#{latest.to_sql})")+ .group(:account_id, :security_id).sum(:qty)++ lots.filter_map { |key, qty| key if held[key] == qty }.to_set+ end+# Moves lots to another security with their trades. Lots are never merged:# derived lots keep their own rows, and an opening lot moves only where the# target has none, since the target's own is restated over the moved unitsdiff --git a/app/models/holding_lot_disposal.rb b/app/models/holding_lot_disposal.rbnew file mode 100644index 0000000000..e23840296d--- /dev/null+++ b/app/models/holding_lot_disposal.rb@@ -0,0 +1,44 @@+# What one sale took from one lot, under a lot method (fifo). Written by the+# holdings materializer from the calculators' lot books; a sale's realized+# gain is read back from these rather than from the snapshot after it, which+# holds the cost of what remains.+class HoldingLotDisposal < ApplicationRecord+ belongs_to :account+ belongs_to :sale_entry, class_name: "Entry"+ belongs_to :lot_source_entry, class_name: "Entry", optional: true++ class << self+ # Replaces the disposals of the account's sales, within `security_ids`+ # when given. Scoped by the sales themselves, so a sale that moved to+ # another security is restated with it.+ def store!(account, rows, security_ids: nil)+ # A relation, not the association: the association's delete_all would+ # nullify account_id rather than delete.+ scope = where(account: account)+ if security_ids+ sales = account.entries.where(entryable_type: "Trade", entryable_id: Trade.where(security_id: security_ids).select(:id))+ scope = scope.where(sale_entry_id: sales.select(:id))+ end++ transaction do+ scope.delete_all+ insert_all(rows) if rows.any?+ end+ end++ # The stored disposals of each of `trades`, by sale entry id, for the+ # trades whose account sells by fifo and whose position's lots can be read+ # (HoldingLot.in_partition). Any other trade is absent, and reads its basis+ # from the holding snapshot. Expects each trade's entry and account loaded.+ def readable_by_sale(trades)+ fifo = trades.select { |trade| trade.entry.account.cost_basis_fifo? }+ return {} if fifo.empty?++ readable = HoldingLot.in_partition(fifo.map { |trade| trade.entry.account_id }.uniq, fifo.map(&:security_id).uniq)+ sale_ids = fifo.select { |trade| readable.include?([ trade.entry.account_id, trade.security_id ]) }.map { |trade| trade.entry.id }+ return {} if sale_ids.empty?++ where(sale_entry_id: sale_ids).group_by(&:sale_entry_id)+ end+ end+enddiff --git a/app/models/trade.rb b/app/models/trade.rbindex f2490200d2..e3436da84e 100644--- a/app/models/trade.rb+++ b/app/models/trade.rb@@ -88,6 +88,15 @@ class Trade < ApplicationRecordTrend.new(current: current_value, previous: cost_basis)end+ # Set by callers that list many sales: what this sale took from each lot, as+ # HoldingLotDisposal.readable_by_sale gives it, or nil where there is no+ # readable record and the basis comes from the holding snapshot. Clears the+ # memo, so a sale measured before the preload does not keep its old figure.+ def preloaded_lot_disposals=(value)+ @preloaded_lot_disposals = value+ remove_instance_variable(:@realized_gain_loss) if defined?(@realized_gain_loss)+ end+# Set by callers that list many disposals, so the proceeds conversion below# reads one preloaded set instead of a query per foreign disposal. Keyed# `[from, to, date]`.@@ -217,6 +226,28 @@ class Trade < ApplicationRecordendend+ def lot_disposals+ return @preloaded_lot_disposals if defined?(@preloaded_lot_disposals)++ HoldingLotDisposal.readable_by_sale([ self ])[entry.id]+ end++ # The cost of the lots this sale consumed, :unknown when one of them has+ # no cost, or nil when there is no record covering the whole sale.+ def disposed_lots_cost+ disposals = lot_disposals+ return nil if disposals.blank? || disposals.sum(BigDecimal("0"), &:qty) != qty.abs+ return :unknown if disposals.any? { |disposal| disposal.unit_cost.nil? }++ Money.new(disposals.sum(BigDecimal("0")) { |disposal| disposal.qty * disposal.unit_cost }, disposals.first.currency)+ end++ # The position's average on the sale's day, applied to the units sold.+ def snapshot_cost+ holding = basis_holding+ holding.avg_cost * qty.abs if holding&.avg_cost+ end+def calculate_realized_gain_lossreturn nil unless sell?# Moving an asset to another account you own realises nothing. Without@@ -224,11 +255,13 @@ class Trade < ApplicationRecord# difference is booked as a gain the user never made.return nil if internal_movement?- holding = basis_holding+ # Under fifo the snapshot is the open lots' mean after the sale, not the+ # cost of the lots it consumed, so without a record covering the sale the+ # gain is unknown rather than priced off the snapshot.+ cost_basis = disposed_lots_cost || (snapshot_cost unless entry.account.cost_basis_fifo?)- return nil unless holding&.avg_cost+ return nil unless cost_basis.is_a?(Money)- cost_basis = holding.avg_cost * qty.abs# A disposal's fee is what selling cost, so it comes off the proceeds.sale_proceeds = converted_to_basis_currency(price_money * qty.abs - fee_money, cost_basis.currency)diff --git a/app/views/accounts/_form.html.erb b/app/views/accounts/_form.html.erbindex 35ae602c2d..5bbb710a4c 100644--- a/app/views/accounts/_form.html.erb+++ b/app/views/accounts/_form.html.erb@@ -36,6 +36,15 @@</div><% end %>+ <% if account.persisted? && account.supports_trades? %>+ <div class="space-y-1">+ <%= form.select :cost_basis_method,+ Account.cost_basis_methods.keys.map { |method| [ t(".cost_basis_methods.#{method}"), method ] },+ { label: t(".cost_basis_method_label") } %>+ <p class="text-secondary text-sm"><%= t(".cost_basis_method_hint") %></p>+ </div>+ <% end %>+<details class="group"><summary class="cursor-pointer text-sm text-secondary hover:text-primary flex items-center gap-1 py-2"><%= icon "chevron-right", size: "sm", class: "group-open:rotate-90 transition-transform" %>diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex c8ec78816d..cc31652b14 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -96,6 +96,11 @@ en:exclude_from_reports: Exclude from all reportsenable_category_matcher_label: Enable category matcherenable_category_matcher_hint: When enabled, the provider's suggested category is applied to imported transactions. Disable to leave new transactions uncategorized.+ cost_basis_method_label: Cost basis method+ cost_basis_method_hint: How a sale is matched to the shares it came from. Changing it recalculates past realized gains and the average cost of what you hold. A sale of shares whose cost is unknown shows its gain as unknown.+ cost_basis_methods:+ average: Average cost+ fifo: First in, first out (FIFO)index:accounts: Accountsfinancekit_accounts:diff --git a/db/migrate/20261024090000_add_cost_basis_method_to_accounts.rb b/db/migrate/20261024090000_add_cost_basis_method_to_accounts.rbnew file mode 100644index 0000000000..5ad24d46d3--- /dev/null+++ b/db/migrate/20261024090000_add_cost_basis_method_to_accounts.rb@@ -0,0 +1,6 @@+class AddCostBasisMethodToAccounts < ActiveRecord::Migration[8.1]+ def change+ add_column :accounts, :cost_basis_method, :string, null: false, default: "average"+ add_check_constraint :accounts, "cost_basis_method IN ('average', 'fifo')", name: "accounts_cost_basis_method_known"+ end+enddiff --git a/db/migrate/20261024090100_create_holding_lot_disposals.rb b/db/migrate/20261024090100_create_holding_lot_disposals.rbnew file mode 100644index 0000000000..7b23341ef7--- /dev/null+++ b/db/migrate/20261024090100_create_holding_lot_disposals.rb@@ -0,0 +1,19 @@+class CreateHoldingLotDisposals < ActiveRecord::Migration[8.1]+ def change+ create_table :holding_lot_disposals, id: :uuid do |t|+ t.references :account, null: false, type: :uuid, foreign_key: { on_delete: :cascade }+ t.references :sale_entry, null: false, type: :uuid, foreign_key: { to_table: :entries, on_delete: :cascade }+ # The trade that acquired the lot consumed; nil for the opening lot and+ # for units sold beyond what was held until an acquisition covers them.+ # Indexed: entries delete with :nullify must find matching disposals per+ # destroyed entry.+ t.references :lot_source_entry, type: :uuid, foreign_key: { to_table: :entries, on_delete: :nullify }+ t.decimal :qty, precision: 34, scale: 18, null: false+ t.decimal :unit_cost, precision: 25, scale: 10+ t.string :currency, null: false+ t.timestamps+ end++ add_check_constraint :holding_lot_disposals, "qty > 0", name: "holding_lot_disposals_qty_positive"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex d79998ad64..cd5fe27037 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -103,6 +103,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) dot.decimal "balance", precision: 19, scale: 4t.decimal "cash_balance", precision: 19, scale: 4, default: "0.0"t.virtual "classification", type: :string, as: "\nCASE\n WHEN ((accountable_type)::text = ANY (ARRAY[('Loan'::character varying)::text, ('CreditCard'::character varying)::text, ('OtherLiability'::character varying)::text])) THEN 'liability'::text\n ELSE 'asset'::text\nEND", stored: true+ t.string "cost_basis_method", default: "average", null: falset.datetime "created_at", null: falset.string "currency"t.datetime "disabled_at"@@ -136,6 +137,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) dot.index ["plaid_account_id"], name: "index_accounts_on_plaid_account_id"t.index ["simplefin_account_id"], name: "index_accounts_on_simplefin_account_id"t.index ["status"], name: "index_accounts_on_status"+ t.check_constraint "cost_basis_method::text = ANY (ARRAY['average'::character varying, 'fifo'::character varying]::text[])", name: "accounts_cost_basis_method_known"endcreate_table "active_storage_attachments", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -1191,6 +1193,21 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) dot.check_constraint "target_mode::text = ANY (ARRAY['fixed'::character varying::text, 'months_of_expenses'::character varying::text])", name: "chk_goals_target_mode_enum"end+ create_table "holding_lot_disposals", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|+ t.uuid "account_id", null: false+ t.datetime "created_at", null: false+ t.string "currency", null: false+ t.uuid "lot_source_entry_id"+ t.decimal "qty", precision: 34, scale: 18, null: false+ t.uuid "sale_entry_id", null: false+ t.decimal "unit_cost", precision: 25, scale: 10+ t.datetime "updated_at", null: false+ t.index ["account_id"], name: "index_holding_lot_disposals_on_account_id"+ t.index ["lot_source_entry_id"], name: "index_holding_lot_disposals_on_lot_source_entry_id"+ t.index ["sale_entry_id"], name: "index_holding_lot_disposals_on_sale_entry_id"+ t.check_constraint "qty > 0::numeric", name: "holding_lot_disposals_qty_positive"+ end+create_table "holding_lots", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|t.uuid "account_id", null: falset.date "acquired_on"@@ -3228,6 +3245,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) doadd_foreign_key "goal_pledges", "goals", on_delete: :cascadeadd_foreign_key "goal_pledges", "transactions", column: "matched_transaction_id", on_delete: :nullifyadd_foreign_key "goals", "families", on_delete: :cascade+ add_foreign_key "holding_lot_disposals", "accounts", on_delete: :cascade+ add_foreign_key "holding_lot_disposals", "entries", column: "lot_source_entry_id", on_delete: :nullify+ add_foreign_key "holding_lot_disposals", "entries", column: "sale_entry_id", on_delete: :cascadeadd_foreign_key "holding_lots", "accounts", on_delete: :cascadeadd_foreign_key "holding_lots", "entries", column: "source_entry_id", on_delete: :cascadeadd_foreign_key "holding_lots", "securities", column: "origin_security_id", on_delete: :nullifydiff --git a/test/controllers/cryptos_controller_test.rb b/test/controllers/cryptos_controller_test.rbindex 823930ac5d..0d00932988 100644--- a/test/controllers/cryptos_controller_test.rb+++ b/test/controllers/cryptos_controller_test.rb@@ -50,4 +50,26 @@ class CryptosControllerTest < ActionDispatch::IntegrationTestassert_equal "exchange", @account.accountable.subtypeassert @account.supports_trades?end++ test "a method sent with a switch from exchange to wallet is dropped and starts no sync" do+ @account.accountable.update!(subtype: "exchange")+ Account.any_instance.expects(:sync_later).never++ patch crypto_path(@account), params: { account: { subtype: "wallet", cost_basis_method: "fifo" } }++ @account.reload+ assert_equal "wallet", @account.accountable.subtype+ assert @account.cost_basis_average?+ end++ test "a method sent with a switch from wallet to exchange is kept and starts one sync" do+ @account.accountable.update!(subtype: "wallet")+ Account.any_instance.expects(:sync_later).once++ patch crypto_path(@account), params: { account: { subtype: "exchange", cost_basis_method: "fifo" } }++ @account.reload+ assert_equal "exchange", @account.accountable.subtype+ assert @account.cost_basis_fifo?+ endenddiff --git a/test/controllers/investments_controller_test.rb b/test/controllers/investments_controller_test.rbindex e9caf260ff..63ab9b9189 100644--- a/test/controllers/investments_controller_test.rb+++ b/test/controllers/investments_controller_test.rb@@ -7,4 +7,84 @@ class InvestmentsControllerTest < ActionDispatch::IntegrationTestsign_in @user = users(:family_admin)@account = accounts(:investment)end++ test "changing the method starts one sync of the account" do+ assert @account.cost_basis_average?+ Account.any_instance.expects(:sync_later).once++ patch investment_path(@account), params: { account: { cost_basis_method: "fifo" } }++ assert_redirected_to account_path(@account)+ assert @account.reload.cost_basis_fifo?+ end++ test "resubmitting the same method starts no sync" do+ Account.any_instance.expects(:sync_later).never++ patch investment_path(@account), params: { account: { name: "Renamed", cost_basis_method: "average" } }++ assert_redirected_to account_path(@account)+ assert_equal "Renamed", @account.reload.name+ end++ test "an unknown method is rejected" do+ Account.any_instance.expects(:sync_later).never++ patch investment_path(@account), params: { account: { cost_basis_method: "lifo" } }++ assert_response :unprocessable_entity+ assert @account.reload.cost_basis_average?+ end++ test "the method select is on the form of an account that supports trades, and only there" do+ get edit_investment_path(@account)+ assert_select "select[name='account[cost_basis_method]'] option", count: 2++ get edit_depository_path(accounts(:depository))+ assert_response :success+ assert_select "select[name='account[cost_basis_method]']", count: 0+ end++ test "a new account starts on average whatever the form submits" do+ assert_difference "Account.count", 1 do+ post investments_path, params: {+ account: { name: "New brokerage", currency: "USD", balance: 1000, accountable_type: "Investment", cost_basis_method: "fifo" }+ }+ end++ assert Account.order(:created_at).last.cost_basis_average?+ end++ test "an account that does not support trades ignores a submitted method" do+ depository = accounts(:depository)+ Account.any_instance.expects(:sync_later).never++ patch depository_path(depository), params: { account: { cost_basis_method: "fifo" } }++ assert depository.reload.cost_basis_average?+ end++ # A linked account's provider sync overwrites any attribute not locked, so+ # a field edited on the form is locked whether or not the method changes.+ test "renaming a linked account locks its name, the method unchanged" do+ AccountProvider.create!(account: @account, provider: plaid_accounts(:one))+ assert_not @account.locked?(:name)++ patch investment_path(@account), params: { account: { name: "Renamed", cost_basis_method: "average" } }++ assert_redirected_to account_path(@account)+ assert @account.reload.locked?(:name)+ end++ test "renaming a linked account locks its name, the method changed" do+ AccountProvider.create!(account: @account, provider: plaid_accounts(:one))+ assert_not @account.locked?(:name)++ patch investment_path(@account), params: { account: { name: "Renamed", cost_basis_method: "fifo" } }++ assert_redirected_to account_path(@account)+ @account.reload+ assert @account.locked?(:name)+ assert @account.cost_basis_fifo?+ endenddiff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex ce2e7877d1..52527c6243 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -266,6 +266,28 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestassert_response :okend+ # Under fifo each sale's basis is read from what it took from each lot. The+ # card reads those for every sale in one query, not one per sale.+ test "the card preloads the lot disposals its fifo sales read" do+ date = Date.current.beginning_of_month+ account = @family.accounts.create!(name: "Brokerage FIFO", balance: 10_000, currency: "USD",+ cost_basis_method: "fifo", accountable: Investment.new)+ security = Security.create!(ticker: "FIF#{SecureRandom.hex(3)}", name: "Fifo Listed")+ create_trade(security, account: account, qty: 60, date: date - 20, price: 12)+ create_trade(security, account: account, qty: 40, date: date - 10, price: 20)+ create_trade(security, account: account, qty: -10, date: date, price: 25)+ create_trade(security, account: account, qty: -60, date: date, price: 25)+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings++ queries = capture_sql_queries { get reports_path }++ assert_response :ok+ lines = css_select("[data-testid='realized-gain-line']").map(&:text).select { |text| text.include?(security.ticker) }+ assert_equal 2, lines.size, "both sales must be listed, or this proves nothing"+ assert lines.any? { |text| text.include?("$130.00") }, "10 x (25 - 12), the oldest lot"+ assert_equal 1, queries.count { |sql| sql.include?(%("holding_lot_disposals")) }, "one preload, not one per sale"+ end+test "index renders successfully" doget reports_pathassert_response :okdiff --git a/test/models/account/syncer_test.rb b/test/models/account/syncer_test.rbindex 30171b186c..44885f3e84 100644--- a/test/models/account/syncer_test.rb+++ b/test/models/account/syncer_test.rb@@ -1,5 +1,4 @@require "test_helper"-require "ostruct"class Account::SyncerTest < ActiveSupport::TestCasetest "post-sync auto matches only transfers touching the synced account" do@@ -10,6 +9,55 @@ class Account::SyncerTest < ActiveSupport::TestCaseAccount::Syncer.new(account).perform_post_syncend+ test "a cost basis method changed while the sync ran starts another sync once it completes" do+ account = accounts(:investment)+ sync = account.syncs.create!+ Account::MarketDataImporter.any_instance.stubs(:import_all)+ Balance::Materializer.any_instance.stubs(:materialize_balances).with do+ # The form saves the new method while this run is calculating.+ Account.where(id: account.id).update_all(cost_basis_method: "fifo")+ true+ end++ assert_difference -> { account.syncs.count }, 1 do+ sync.perform+ end++ assert sync.reload.completed?+ assert account.syncs.where.not(id: sync.id).sole.pending?+ end++ # Post-sync runs after a failed sync too. The method change is restated by+ # the next sync that completes, so a failure must not queue one: each+ # failure would otherwise queue another.+ test "a failed sync after a cost basis method change starts no further sync" do+ account = accounts(:investment)+ account.syncs.create!(status: "completed", completed_at: 1.hour.ago, data: { "cost_basis_method" => "average" })+ Account.where(id: account.id).update_all(cost_basis_method: "fifo")+ sync = account.syncs.create!+ Account::MarketDataImporter.any_instance.stubs(:import_all)+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(StandardError, "provider down")++ assert_no_difference -> { account.syncs.count } do+ sync.perform+ end++ assert sync.reload.failed?+ end++ test "an unchanged cost basis method starts no further sync" do+ account = accounts(:investment)+ sync = account.syncs.create!+ Account::MarketDataImporter.any_instance.stubs(:import_all)+ Balance::Materializer.any_instance.stubs(:materialize_balances)++ assert_no_difference -> { account.syncs.count } do+ sync.perform+ end++ assert sync.reload.completed?+ end+test "applies IBKR historical balance overrides after materialization" dofamily = families(:empty)account = family.accounts.create!(@@ -34,7 +82,7 @@ class Account::SyncerTest < ActiveSupport::TestCaseBalance::Materializer.any_instance.expects(:materialize_balances).onceIbkrAccount::HistoricalBalancesSync.any_instance.expects(:sync!).once- Account::Syncer.new(account).perform_sync(OpenStruct.new(window_start_date: nil))+ Account::Syncer.new(account).perform_sync(account.syncs.create!)end# A provider that dates its holdings itself, but anchors the balance on the@@ -162,6 +210,6 @@ class Account::SyncerTest < ActiveSupport::TestCaseAccount::MarketDataImporter.any_instance.stubs(:import_all)Balance::Materializer.any_instance.stubs(:materialize_balances)IbkrAccount::HistoricalBalancesSync.any_instance.stubs(:sync!)- Account::Syncer.new(account).perform_sync(OpenStruct.new(window_start_date: nil))+ Account::Syncer.new(account).perform_sync(account.syncs.create!)endenddiff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex 77e0b11d32..a2071c68a1 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -228,6 +228,44 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert account.reload.logo_automatic?end+ test "restores an account's cost basis method" do+ ndjson = build_ndjson([+ {+ type: "Account",+ data: {+ id: "old-account-1",+ name: "Brokerage",+ balance: "1500.00",+ currency: "USD",+ cost_basis_method: "fifo",+ accountable_type: "Investment",+ accountable: {}+ }+ }+ ])++ account_id = Family::DataImporter.new(@family, ndjson).import![:account_ids].first++ assert Account.find(account_id).cost_basis_fifo?+ end++ test "an export without a known cost basis method imports as average" do+ ndjson = build_ndjson([+ {+ type: "Account",+ data: { id: "old-account-1", name: "Older", balance: "100", currency: "USD", accountable_type: "Investment", accountable: {} }+ },+ {+ type: "Account",+ data: { id: "old-account-2", name: "Newer", balance: "100", currency: "USD", cost_basis_method: "some-future-method", accountable_type: "Investment", accountable: {} }+ }+ ])++ account_ids = Family::DataImporter.new(@family, ndjson).import![:account_ids]++ assert_equal %w[average average], Account.where(id: account_ids).pluck(:cost_basis_method)+ end+test "imports non-destructive account status from ndjson" dondjson = build_ndjson([{diff --git a/test/models/holding/lot_book_test.rb b/test/models/holding/lot_book_test.rbindex 1682090501..3a992f7ab9 100644--- a/test/models/holding/lot_book_test.rb+++ b/test/models/holding/lot_book_test.rb@@ -533,7 +533,7 @@ class Holding::LotBookTest < ActiveSupport::TestCaserun = -> { Holding::Materializer.new(@account.reload, strategy: strategy).materialize_holdings }if reference- Holding::LotBook.stub(:new, -> { ReferenceCalculatorTracker.new }) { run.call }+ Holding::LotBook.stub(:new, ->(**) { ReferenceCalculatorTracker.new }) { run.call }elserun.callenddiff --git a/test/models/holding_lot_disposal_test.rb b/test/models/holding_lot_disposal_test.rbnew file mode 100644index 0000000000..abaed87a21--- /dev/null+++ b/test/models/holding_lot_disposal_test.rb@@ -0,0 +1,416 @@+require "test_helper"++class HoldingLotDisposalTest < ActiveSupport::TestCase+ include EntriesTestHelper+ include SqlQueryCapture++ TODAY = Time.zone.local(2024, 6, 10, 12)++ # --- The book ---------------------------------------------------------------++ test "under fifo the book consumes the oldest lot first and records what each sale took" do+ book = Holding::LotBook.new(method: "fifo")+ book.apply(BigDecimal("12"), 60, source_id: "first")+ book.apply(BigDecimal("20"), 40, source_id: "second")++ book.apply(BigDecimal("25"), -70, source_id: "sale")++ assert_equal [ [ "sale", "first", 60, 12 ], [ "sale", "second", 10, 20 ] ],+ book.disposals.map { |d| [ d.sale_id, d.lot_source_id, d.qty, d.unit_cost ] }+ assert_equal [ [ "second", 30 ] ], book.lots.map { |lot| [ lot.source_id, lot.qty ] }+ assert_equal 20, book.average_cost+ end++ test "under fifo a sale beyond the open lots records the excess at an unknown cost" do+ book = Holding::LotBook.new(method: "fifo")+ book.apply(BigDecimal("12"), 5, source_id: "buy")++ book.apply(nil, -8, source_id: "sale")++ assert_equal [ [ "buy", 5, 12 ], [ nil, 3, nil ] ], book.disposals.map { |d| [ d.lot_source_id, d.qty, d.unit_cost ] }+ assert_equal 0, book.open_qty+ end++ test "under fifo a purchase covers a transfer out's shortfall before a later sale's" do+ book = Holding::LotBook.new(method: "fifo")+ book.apply(nil, -4)+ book.apply(nil, -6, source_id: "sale")++ book.apply(BigDecimal("20"), 5, source_id: "cover")++ assert_equal [ [ nil, 5, nil ], [ "cover", 1, 20 ] ],+ book.disposals.map { |d| [ d.lot_source_id, d.qty, d.unit_cost ] }+ end++ test "under average the book records no disposals" do+ book = Holding::LotBook.new+ book.apply(BigDecimal("12"), 60, source_id: "first")+ book.apply(BigDecimal("20"), 40, source_id: "second")++ book.apply(BigDecimal("25"), -40, source_id: "sale")++ assert_empty book.disposals+ assert_equal BigDecimal("15.2"), book.average_cost+ end++ test "under fifo a consumed transfer-in lot no longer makes the cost unknown" do+ fifo = Holding::LotBook.new(method: "fifo")+ fifo.add_unknown(10, source_id: "transfer")+ fifo.apply(BigDecimal("12"), 10, source_id: "buy")+ assert fifo.unknown_cost?++ fifo.apply(BigDecimal("30"), -10, source_id: "sale")++ assert_not fifo.unknown_cost?+ assert_equal 12, fifo.average_cost+ end++ test "a transfer-in sold under fifo leaves the remaining position's basis known, forward and reverse" do+ travel_to TODAY do+ %i[forward reverse].each do |strategy|+ figures = %w[average fifo].map do |method|+ setup_account(method: method)+ security = priced_security("FIFT#{strategy.to_s[0]}#{method[0]}", 30)+ trade(security, 10, 30, 2).entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)+ trade(security, 10, 12, 3)+ trade(security, -10, 30, 5)+ if strategy == :reverse+ link_account+ @account.holdings.create!(security: security, date: d(10), qty: 10, price: 30, amount: 300, currency: "USD", account_provider: @account_provider)+ end+ materialize(strategy)+ @account.holdings.find_by!(security: security, date: d(9)).cost_basis+ end++ assert_equal [ nil, 12 ], figures, "#{strategy}: average stays unknown until the position closes"+ end+ end+ end++ # --- The Example from the lot cost basis proposal ---------------------------+ # 60 bought at $12, 40 at $20; 40 sold at $25.++ test "fifo consumes the oldest lot first" do+ travel_to TODAY do+ average = example(method: "average")+ fifo = example(method: "fifo")++ assert_equal [ 392, BigDecimal("15.2") ], average+ assert_equal 520, fifo.first, "basis 40 x $12 = $480"+ assert_in_delta BigDecimal("17.3333"), fifo.last, BigDecimal("0.0001")+ end+ end++ test "fifo sale crossing two lots" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFB", 30)+ trade(security, 60, 12, 2)+ trade(security, 40, 20, 3)+ sale = trade(security, -70, 25, 6)+ materialize(:forward)++ assert_equal 1750 - 920, gain(sale), "60 x $12 + 10 x $20 = $920"+ assert_equal 920, HoldingLotDisposal.where(sale_entry: sale).sum("qty * unit_cost")+ end+ end++ # A same-day round trip from a flat position, with the sale entered before+ # the purchase. Entry order stands, so the sale runs short, and the purchase+ # that covers it prices it.+ test "under fifo a sale entered ahead of the day's purchase is priced at that purchase" do+ travel_to TODAY do+ gains = %w[average fifo].map do |method|+ setup_account(method: method)+ security = priced_security("FIFD#{method[0]}", 30)+ sale = trade(security, -10, 250, 5)+ buy = trade(security, 10, 200, 5)+ entered_in_order(sale, buy)+ materialize(:forward)+ gain(sale)+ end++ assert_equal [ 500, 500 ], gains, "the fifo sale is covered by the day's 10 at $200"+ end+ end++ test "under fifo a short sale covered on a later day is measured against that cover" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFL", 30)+ lot = trade(security, 5, 100, 2)+ sale = trade(security, -15, 220, 3)+ cover = trade(security, 10, 250, 7)+ materialize(:forward)++ assert_equal 3300 - (5 * 100 + 10 * 250), gain(sale), "5 from the lot at $100, 10 covered at $250"+ assert_equal [ [ lot.id, 5, 100 ], [ cover.id, 10, 250 ] ].sort_by(&:last),+ HoldingLotDisposal.where(sale_entry: sale).pluck(:lot_source_entry_id, :qty, :unit_cost)+ .map { |id, qty, cost| [ id, qty.to_i, cost.to_i ] }.sort_by(&:last)+ end+ end++ # Under average a sale entered ahead of the same day's purchase, from a flat+ # position, must not leave that purchase in the pool once the position is+ # back to zero, or the next purchase averages against it.+ test "under average a same-day round trip entered sale first leaves no cost behind" do+ travel_to TODAY do+ setup_account+ security = priced_security("AVGD", 30)+ sale = trade(security, -10, 250, 5)+ buy = trade(security, 10, 200, 5)+ entered_in_order(sale, buy)+ trade(security, 10, 300, 6)+ materialize(:forward)++ assert_equal 300, @account.holdings.find_by!(security: security, date: d(6)).avg_cost.amount+ assert_equal 500, gain(sale)+ end+ end++ test "under fifo a day's purchase entered first replays as before" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFE", 30)+ buy = trade(security, 10, 200, 5)+ sale = trade(security, -10, 250, 5)+ entered_in_order(buy, sale)+ materialize(:forward)++ assert_equal 500, gain(sale)+ end+ end++ # Older lots still come first: only what the sale could not take from them is+ # left for a later purchase to cover.+ test "under fifo a sale entered ahead of the day's purchase still takes the oldest lot" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFO", 30)+ trade(security, 10, 100, 2)+ sale = trade(security, -10, 250, 5)+ buy = trade(security, 10, 200, 5)+ entered_in_order(sale, buy)+ materialize(:forward)++ assert_equal 1500, gain(sale), "10 x ($250 - $100)"+ assert_equal [ [ 10, 200 ] ], @account.holding_lots.where(security: security).where("qty > 0").pluck(:qty, :unit_cost).map { |q, c| [ q.to_i, c.to_i ] }+ end+ end++ # Sold short in the morning and covered at a higher price later the same day.+ test "under fifo an intraday short sale is measured against the day's cover" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFS", 30)+ sale = trade(security, -10, 200, 5)+ cover = trade(security, 10, 250, 5)+ entered_in_order(sale, cover)+ materialize(:forward)++ assert_equal(-500, gain(sale))+ end+ end++ test "average account figures unchanged after the method column exists" do+ travel_to TODAY do+ setup_account+ assert_equal "average", @account.cost_basis_method++ assert_no_difference "HoldingLotDisposal.count" do+ assert_equal [ 392, BigDecimal("15.2") ], example_on_account+ end+ end+ end++ test "realized gain reads the persisted consumption, not the post-sale snapshot" do+ travel_to TODAY do+ setup_account(method: "fifo")+ sale = example_trades+ materialize(:forward)+ snapshot_basis = @account.holdings.find_by!(security: @security, date: d(6)).avg_cost.amount * 40++ assert_in_delta 1000 - snapshot_basis, BigDecimal("306.67"), BigDecimal("0.01"), "the snapshot holds what remains"+ assert_equal 520, gain(sale)+ end+ end++ test "foreign-currency lot: basis at acquisition-date rate, proceeds at sale-date rate" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFE", 30)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: d(2), rate: 1.5)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: d(6), rate: 2)+ create_trade(security, account: @account, qty: 10, price: 100, date: d(2), currency: "EUR")+ sale = create_trade(security, account: @account, qty: -10, price: 130, date: d(6), currency: "EUR")+ materialize(:forward)++ assert_equal Money.new(1500, "USD"), HoldingLotDisposal.find_by!(sale_entry: sale).then { |d| Money.new(d.qty * d.unit_cost, d.currency) }+ assert_equal 2600 - 1500, gain(sale), "not 2600 - 2000, the basis at the sale-date rate"+ end+ end++ test "missing sale-date rate still reports :missing_exchange_rate" do+ travel_to TODAY do+ setup_account(method: "fifo")+ security = priced_security("FIFM", 30)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: d(2), rate: 1.5)+ create_trade(security, account: @account, qty: 10, price: 100, date: d(2), currency: "EUR")+ sale = create_trade(security, account: @account, qty: -10, price: 130, date: d(6), currency: "EUR")+ materialize(:forward)+ assert HoldingLotDisposal.exists?(sale_entry: sale), "the lot side is known"++ trade = Trade.find(sale.entryable_id)+ assert_nil trade.realized_gain_loss+ end+ end++ test "a sale that consumes the opening lot has an unknown basis" do+ travel_to TODAY do+ build_reverse_fixture(pre_history: 2)+ materialize(:reverse)++ trade = Trade.find(@sale.entryable_id)+ assert_nil trade.realized_gain_loss+ assert_equal [ [ nil, 2 ], [ @first.id, 2 ] ],+ HoldingLotDisposal.where(sale_entry: @sale).map { |d| [ d.lot_source_entry_id, d.qty ] }.sort_by { |id, _| id.to_s }+ end+ end++ test "a materialization scoped to one security restates only that security's disposals" do+ travel_to TODAY do+ setup_account(method: "fifo")+ kept, restated = priced_security("FIFK", 30), priced_security("FIFS", 30)+ [ kept, restated ].each { |security| trade(security, 10, 12, 2) }+ kept_sale = trade(kept, -4, 25, 5)+ restated_sale = trade(restated, -4, 25, 5)+ materialize(:forward)+ kept_ids = HoldingLotDisposal.where(sale_entry: kept_sale).pluck(:id)++ restated_sale.entryable.update!(qty: -6)+ Holding::Materializer.new(@account.reload, strategy: :forward, security_ids: [ restated.id ]).materialize_holdings++ assert_equal kept_ids, HoldingLotDisposal.where(sale_entry: kept_sale).pluck(:id)+ assert_equal [ 6 ], HoldingLotDisposal.where(sale_entry: restated_sale).pluck(:qty)+ end+ end++ # --- The partition guard ----------------------------------------------------++ # The snapshot is the open lots' mean after the sale, not what the sale+ # consumed, so under fifo a sale its lot records do not cover has an unknown+ # gain rather than one priced off the snapshot.+ test "unlink, forward sync, then read: lots out of partition leave a fifo gain unknown" do+ travel_to TODAY do+ # 6 units before the trades: the sale takes 4 of them, and 2 stay open.+ build_reverse_fixture(pre_history: 6)+ materialize(:reverse)+ assert_nil Trade.find(@sale.entryable_id).realized_gain_loss+ @account_provider.destroy!+ materialize(:forward)++ assert_equal 16, @account.holdings.find_by!(security: @security, date: d(10)).qty+ assert_equal 18, HoldingLot.where(security: @security).sum(:qty), "the retained opening lot's 2"+ assert_equal 400, HoldingLotDisposal.where(sale_entry: @sale).sum("qty * unit_cost"), "the forward run's record"++ assert_nil gain(@sale), "not the snapshot's $650, which is not what the sale consumed"+ end+ end++ test "lots in partition are read" do+ travel_to TODAY do+ build_reverse_fixture(pre_history: 0)+ materialize(:reverse)++ assert_equal 16, HoldingLot.where(security: @security).sum(:qty)+ assert_equal 650, @account.holdings.find_by!(security: @security, date: d(5)).avg_cost.amount * 4+ assert_equal 4 * 300 - 400, gain(@sale), "the lot record, not the snapshot's $650"+ end+ end++ test "lots short of the holding leave a fifo gain unknown" do+ travel_to TODAY do+ build_reverse_fixture(pre_history: 0)+ materialize(:reverse)+ lot = HoldingLot.where(security: @security).where("qty >= 2").order(:id).first+ lot.update_columns(qty: lot.qty - 2)++ assert_equal 14, HoldingLot.where(security: @security).sum(:qty), "2 short of the holding's 16"+ assert_nil gain(@sale), "neither the lot record's $400 nor the snapshot's $650"+ end+ end++ private+ def d(day)+ Date.new(2024, 6, day)+ end++ def setup_account(method: "average")+ @family = families(:empty)+ @account = @family.accounts.create!(name: "Lots", balance: 20000, cash_balance: 20000, currency: "USD",+ accountable: Investment.new, cost_basis_method: method)+ end++ def link_account+ coinstats_item = @family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")+ @account_provider = AccountProvider.create!(account: @account, provider: coinstats_account)+ end++ def priced_security(ticker, price)+ security = Security.create!(ticker: ticker, name: ticker)+ Security::Price.insert_all((d(1)..d(10)).map { |date| { security_id: security.id, date: date, price: price, currency: "USD" } })+ security+ end++ def trade(security, qty, price, day)+ create_trade(security, account: @account, qty: qty, price: price, date: d(day))+ end++ def example_trades+ @security = priced_security("FIF#{@account.cost_basis_method[0]}", 30)+ trade(@security, 60, 12, 2)+ trade(@security, 40, 20, 4)+ trade(@security, -40, 25, 6)+ end++ # [realized gain of the sale, average cost of what remains]+ def example(method:)+ setup_account(method: method)+ example_on_account+ end++ def example_on_account+ sale = example_trades+ materialize(:forward)+ [ gain(sale), @account.holdings.find_by!(security: @security, date: d(10)).avg_cost.amount ]+ end++ # A linked fifo account holding `pre_history` units from before its first+ # imported trade: 10 bought at $100, 10 at $200, then 4 sold at $300.+ def build_reverse_fixture(pre_history:)+ setup_account(method: "fifo")+ link_account+ @security = priced_security("FIFR", 30)+ @first = trade(@security, 10, 100, 3)+ trade(@security, 10, 200, 4)+ @sale = trade(@security, -4, 300, 5)+ qty = 16 + pre_history+ @account.holdings.create!(security: @security, date: d(10), qty: qty, price: 30, amount: qty * 30, currency: "USD",+ account_provider: @account_provider)+ end++ # Under travel_to every entry shares one created_at; spread them out in the+ # order given.+ def entered_in_order(*entries)+ entries.each_with_index { |entry, index| entry.update_columns(created_at: TODAY - (entries.size - index).minutes) }+ end++ def materialize(strategy)+ Holding::Materializer.new(@account.reload, strategy: strategy).materialize_holdings+ end++ def gain(entry)+ Trade.find(entry.entryable_id).realized_gain_loss&.value&.amount+ end+enddiff --git a/test/models/holding_lot_test.rb b/test/models/holding_lot_test.rbindex 47616b1193..d35b1a17a1 100644--- a/test/models/holding_lot_test.rb+++ b/test/models/holding_lot_test.rb@@ -162,12 +162,52 @@ class HoldingLotTest < ActiveSupport::TestCaselots = HoldingLot.where(account: @account, security: security)assert_equal BigDecimal("10"), lots.sum(:qty)+ assert_includes HoldingLot.in_partition([ @account.id ], [ security.id ]), [ @account.id, security.id ]assert_equal [ BigDecimal("7"), BigDecimal("3") ], [ lots.opening.sole.qty, lots.derived.sole.qty ], "only the opening lot moved"endend+ test "absorbing the residual records no disposal and moves no other lot under the average method" do+ travel_to TODAY do+ setup_account+ link_account+ security = priced_security("SPL4", 30)+ trade(security, 2, 10, 2)+ Security::Split.create!(security: security, ex_date: d(4), numerator: 3, denominator: 2, source: "manual")+ @account.holdings.create!(security: security, date: d(10), qty: 10, price: 30, amount: 300, currency: "USD", account_provider: @account_provider)++ assert_no_difference "HoldingLotDisposal.count" do+ materialize(:reverse)+ end+ lots = HoldingLot.where(account: @account, security: security)+ assert_equal BigDecimal("3"), lots.derived.sole.qty+ assert_equal BigDecimal("10"), lots.sum(:qty)+ assert_includes HoldingLot.in_partition([ @account.id ], [ security.id ]), [ @account.id, security.id ]+ end+ end++ # A FIFO sale takes the opening lot first; the rounding it carried is then+ # in the lots left, and the last of them takes it.+ test "once a fifo sale has taken the opening lot, the last open lot takes the residual" do+ travel_to TODAY do+ setup_account+ link_account+ @account.update!(cost_basis_method: "fifo")+ security = priced_security("SPL5", 30)+ trade(security, 2, 10, 2)+ Security::Split.create!(security: security, ex_date: d(4), numerator: 3, denominator: 2, source: "manual")+ trade(security, -8, 30, 5)+ @account.holdings.create!(security: security, date: d(10), qty: 2, price: 30, amount: 60, currency: "USD", account_provider: @account_provider)++ materialize(:reverse)++ assert_equal BigDecimal("2"), HoldingLot.where(account: @account, security: security).sum(:qty)+ assert_includes HoldingLot.in_partition([ @account.id ], [ security.id ]), [ @account.id, security.id ]+ end+ end+# Fixtures only ever leave 10^-18; a real gap is far wider and is not- # rounding, so it stays a difference the lots show.+ # rounding, so it stays for in_partition to catch.test "the opening lot does not absorb a residual above the bound" dobook = Holding::LotBook.newbook.add_unknown(BigDecimal("10"))@@ -579,20 +619,18 @@ class HoldingLotTest < ActiveSupport::TestCaseendend- # A cost per unit in the account's currency can pass 10^9 where the trade's- # own currency is far stronger: one share at USD 700,000 in a VND account.- test "a position costing 10^9 or more a unit in the account's currency syncs and stores its lots" do+ test "a fifo sale of a position costing 10^9 or more a unit stores its disposal" dotravel_to TODAY do- @account = families(:empty).accounts.create!(name: "VND", balance: 0, cash_balance: 0, currency: "VND", accountable: Investment.new)- security = Security.create!(ticker: "BRKV", name: "BRKV")+ @account = families(:empty).accounts.create!(name: "VND", balance: 0, cash_balance: 0, currency: "VND", cost_basis_method: "fifo", accountable: Investment.new)+ security = Security.create!(ticker: "BRKD", name: "BRKD")Security::Price.insert_all((d(1)..d(10)).map { |date| { security_id: security.id, date: date, price: 700_000, currency: "USD" } })ExchangeRate.insert_all((d(1)..d(10)).map { |date| { from_currency: "USD", to_currency: "VND", date: date, rate: 25_000 } })- create_trade(security, account: @account, qty: 1, price: 700_000, currency: "USD", date: d(2))+ create_trade(security, account: @account, qty: 2, price: 700_000, currency: "USD", date: d(2))+ sale = create_trade(security, account: @account, qty: -1, price: 700_000, currency: "USD", date: d(3))materialize(:forward)- assert_equal BigDecimal("17500000000"), HoldingLot.find_by!(account: @account, security: security).unit_cost- assert_equal BigDecimal("17500000000"), @account.holdings.find_by!(security: security, date: d(10)).cost_basis+ assert_equal BigDecimal("17500000000"), HoldingLotDisposal.find_by!(sale_entry_id: sale.id).unit_costendend