Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Replay the cost-basis tracker in Holding's fallback (#4151)

jaysbeekayb35d6d6cac49
diff --git a/app/models/holding.rb b/app/models/holding.rb
index fcdb1386a0..7a11f879fb 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -65,7 +65,7 @@ class Holding < ApplicationRecord
# basis cannot be determined (no trades and no provider cost_basis).
def avg_cost
# Use stored cost_basis if available (eliminates N+1 queries)
- return Money.new(known_cost_basis, currency) if known_cost_basis
+ return stored_avg_cost if known_cost_basis
# A caller that has many holdings can compute the fallback for all of
# them in one query and hand each its answer (.preload_avg_costs), so a
@@ -76,7 +76,30 @@ class Holding < ApplicationRecord
return @preloaded_avg_cost if defined?(@preloaded_avg_cost) && !changed?
# Fallback to calculation for holdings without pre-computed cost_basis
- calculate_avg_cost
+ replayed_avg_cost
+ end
+
+ # known_cost_basis as average cost per share, or nil when there is none to
+ # trust. Never queries, so a caller with a better fallback than replaying
+ # through this holding's date (Trade#realized_gain_loss) can skip that replay.
+ def stored_avg_cost
+ Money.new(known_cost_basis, currency) if known_cost_basis
+ end
+
+ # The weighted-average cost of the position immediately before `entry`,
+ # replayed from this security's trades as calculate_avg_cost does, or nil
+ # when it is unknown. Realized gain prices a sale at this figure: average
+ # cost does not move on a sale, but a sale that closes the position leaves
+ # a row with nothing held and no basis, so `avg_cost` has no figure to give.
+ #
+ # Trades count when they sort strictly before `entry` in Entry.chronological
+ # order, so a buy earlier the same day counts and the sale itself does not.
+ # A split with an ex-date on or before the sale's date counts, since a split
+ # applies at the open of its ex-date. Units a sale sells beyond the position
+ # are priced at the acquisitions that cover them (.shortfall_cover_cost),
+ # and the figure is the cost per unit across the whole sale.
+ def avg_cost_before(entry)
+ calculate_avg_cost(through: entry.date, before: entry)
end
# The avg-cost fallback for holdings in accounts that sell by fifo, by
@@ -123,147 +146,149 @@ class Holding < ApplicationRecord
end
end
- # The rate a trade carries itself (extra["exchange_rate"], e.g. IBKR's
- # fx_rate_to_base) comes before the table's, as in the calculators and
- # Balance::SyncCache; a trade in the account's own currency converts at 1.
- # Trade#exchange_rate= stores a number, but a row written to `extra`
- # directly can hold the same rate as a string, which Trade's validation
- # and Money#exchange_to both accept -- so a plain decimal string counts
- # too. Anything else, an exponent or an absurd length included, is not
- # cast, so it cannot overflow numeric and fail the query.
- AVG_COST_TRADE_RATE_SQL = <<~SQL.squish.freeze
- COALESCE(
- CASE jsonb_typeof(trades.extra->'exchange_rate')
- WHEN 'number' THEN (trades.extra->>'exchange_rate')::numeric
- WHEN 'string' THEN CASE WHEN trades.extra->>'exchange_rate' ~ '^[[:space:]]*[+-]?([0-9]{1,20}([.][0-9]{0,20})?|[.][0-9]{1,20})[[:space:]]*$'
- THEN (trades.extra->>'exchange_rate')::numeric END
- END,
- exchange_rates.rate
- )
- SQL
-
- # #calculate_avg_cost for every holding given, in one query: the same
- # trades, rates, fees, internal-movement and lot rules (a user-costed lot
- # counts at its cost; a clamped position has none), read through the same
- # SQL (.avg_cost_rates_join, .avg_cost_totals_sql, .avg_cost_from_totals),
- # so the batch cannot answer differently from the holding on its own.
- # Holdings in accounts that sell by fifo read their open lots instead, all
- # of them together through .fifo_avg_costs, in a few more queries. Holdings
- # with a stored cost basis are skipped, since #avg_cost never reaches the
- # fallback for them. So are holdings with unsaved changes, unsaved ones
- # included: the query reads the stored row, which is not what they hold.
+ # #calculate_avg_cost for every holding given: the same trades, read through
+ # the same SQL (.avg_cost_row_sql), replayed by the same code
+ # (.replay_avg_cost), with the same lot rules (a clamped position has no
+ # cost; a fifo one reads its open lots, all of them together through
+ # .fifo_avg_costs), so the batch cannot answer differently from the
+ # holding on its own. The trades of every holding come back in one query and
+ # the splits in another, however many holdings there are. Holdings with a
+ # stored cost basis are skipped, since #avg_cost never reaches the fallback
+ # for them. So are holdings with unsaved changes, unsaved ones included: the
+ # query reads the stored row, which is not what they hold.
def self.preload_avg_costs(holdings)
pending = holdings.reject { |holding| holding.known_cost_basis || holding.changed? }
return if pending.empty?
- rows = Holding.where(id: pending.map(&:id))
- .joins(:account)
- .joins("JOIN entries ON entries.account_id = holdings.account_id AND entries.entryable_type = 'Trade' AND entries.date <= holdings.date")
- .joins("JOIN trades ON trades.id = entries.entryable_id AND trades.security_id = holdings.security_id AND trades.qty > 0")
- .joins(avg_cost_rates_join)
+ unit_cost, internal_movement = avg_cost_row_sql(holding_currency: "cur.currency", account_currency: "accounts.currency")
+ lot_joins = avg_cost_lot_joins_sql(holding_currency: "cur.currency", account_currency: "accounts.currency", holding_date: "cur.date")
+ rows = Holding.from("holdings cur")
.joins(<<~SQL.squish)
- LEFT JOIN holding_lots lots ON lots.account_id = entries.account_id
- AND lots.source_entry_id = entries.id
- AND lots.manual_total_cost IS NOT NULL
- AND NOT EXISTS (
- SELECT 1 FROM security_splits lot_splits
- WHERE lot_splits.security_id = trades.security_id
- AND lot_splits.ex_date > entries.date
- AND lot_splits.ex_date <= holdings.date
- )
+ JOIN accounts ON accounts.id = cur.account_id
+ JOIN entries ON entries.account_id = cur.account_id
+ AND entries.entryable_type = 'Trade'
+ AND entries.date <= cur.date
+ JOIN trades ON trades.id = entries.entryable_id AND trades.security_id = cur.security_id
+ LEFT JOIN exchange_rates ON (
+ exchange_rates.date = entries.date AND
+ exchange_rates.from_currency = trades.currency AND
+ exchange_rates.to_currency = cur.currency
+ )
SQL
- .group("holdings.id")
- .pluck(
- Arel.sql("holdings.id"),
- Arel.sql(sanitize_sql_array([ "BOOL_OR(trades.investment_activity_label IN (?) AND lots.id IS NULL)", Trade::INTERNAL_MOVEMENT_LABELS ])),
- Arel.sql(<<~SQL.squish),
- BOOL_OR(EXISTS (
- SELECT 1 FROM holding_lots clamped_lots
- WHERE clamped_lots.account_id = holdings.account_id
- AND clamped_lots.security_id = holdings.security_id
- AND clamped_lots.clamped
- ))
- SQL
- Arel.sql("BOOL_OR(accounts.cost_basis_method = 'fifo')"),
- *avg_cost_totals_sql(lots: true)
- )
- .index_by(&:first)
+ .joins(lot_joins)
+ .where("cur.id IN (?)", pending.map(&:id))
+ .reorder(Arel.sql("cur.id, #{AVG_COST_REPLAY_ORDER}"))
+ .pluck(Arel.sql("cur.id"), Arel.sql("entries.date"), Arel.sql("trades.qty"), Arel.sql(unit_cost), Arel.sql(internal_movement),
+ Arel.sql("accounts.cost_basis_method = 'fifo'"), Arel.sql(<<~SQL.squish))
+ EXISTS (
+ SELECT 1 FROM holding_lots clamped_lots
+ WHERE clamped_lots.account_id = cur.account_id
+ AND clamped_lots.security_id = cur.security_id
+ AND clamped_lots.clamped
+ )
+ SQL
+ .group_by(&:first)
+
+ # A holding with no trades has nothing to replay, so its splits are not read.
+ traded = pending.select { |holding| rows.key?(holding.id) }
+ splits = traded.empty? ? {} : Security::Split.where(security_id: traded.map(&:security_id).uniq, ex_date: ..traded.map(&:date).max)
+ .order(:ex_date).to_a.group_by(&:security_id)
# The account decides fifo. A holding with no row (no buy dated on or
# before it, as with a provider row that predates its trade) still reads
# its lots, so its account is looked up; nothing extra runs otherwise.
unrowed = pending.reject { |holding| rows.key?(holding.id) }
fifo_account_ids = unrowed.any? ? Account.where(id: unrowed.map(&:account_id).uniq, cost_basis_method: "fifo").pluck(:id).to_set : Set.new
- lot_costs = fifo_avg_costs(pending.select { |holding| rows.key?(holding.id) ? rows[holding.id][3] : fifo_account_ids.include?(holding.account_id) })
+ lot_costs = fifo_avg_costs(pending.select { |holding| rows.key?(holding.id) ? rows[holding.id].first[5] : fifo_account_ids.include?(holding.account_id) })
pending.each do |holding|
- _id, internal_movement, clamped, _fifo, total_cost, total_qty, rate_missing = rows[holding.id]
- value = if clamped
+ holding_rows = rows.fetch(holding.id, [])
+ value = if holding_rows.first&.last
nil
elsif lot_costs.key?(holding.id)
lot_costs[holding.id]
- elsif !internal_movement
- avg_cost_from_totals(total_cost, total_qty, rate_missing, holding.currency)
+ else
+ trade_rows = holding_rows.map { |row| row[1..4] + [ true ] }
+ replay_avg_cost(trade_rows, splits.fetch(holding.security_id, []).select { |split| split.ex_date <= holding.date },
+ qty: holding.qty, date: holding.date, through: holding.date, currency: holding.currency)
end
holding.preload_avg_cost(value)
end
end
- # Joins each trade to the table's rate for its day into the account's
- # currency: `currency`, one holding's account currency, bound as a value; or
- # :joined for `accounts.currency`, in a query that joins each holding's
- # account.
- def self.avg_cost_rates_join(currency = :joined)
- target = currency != :joined ? sanitize_sql_array([ "exchange_rates.to_currency = ?", currency ]) : "exchange_rates.to_currency = accounts.currency"
-
- <<~SQL.squish
- LEFT JOIN exchange_rates ON (
- exchange_rates.date = entries.date AND
- exchange_rates.from_currency = trades.currency AND
- #{target}
- )
- SQL
- end
-
- # Total cost with fees in the account's currency, total quantity, and
- # whether any foreign purchase lacks a usable rate. `currency` as in
- # .avg_cost_rates_join.
+ # The order the calculators replay trades in (Holding::PortfolioCache#trades):
+ # by date, then as entered, and a buy before a sale entered with it, as an
+ # import stamps a day's trades with one created_at; then by id.
+ AVG_COST_REPLAY_ORDER = "entries.date ASC, entries.created_at ASC, (trades.qty < 0) ASC, entries.id ASC".freeze
+
+ # The per-trade columns the replay reads, as SQL over `trades`, `entries` and
+ # an `exchange_rates` row joined for the trade's day into the holding's
+ # currency: the unit cost in the holding's currency, fee included on a
+ # purchase (Holding::TradeCalculatorHelpers#effective_trade_price), or NULL
+ # when a foreign trade has no usable rate; and whether it is an internal
+ # movement. `holding_currency` and `account_currency` are SQL expressions.
+ # The query also joins .avg_cost_lot_joins_sql: a trade whose lot the user
+ # has costed counts at that cost, a transfer in included, so it is no
+ # internal movement here.
#
- # A foreign purchase with no usable rate for its day has a cost nothing
- # here knows, so the position's is unknown too, as with an internal
- # movement -- counting it at 1:1 would state a figure that looks measured
- # and is not. A rate of zero or less converts nothing, so it counts as
- # missing, as it does in Money#exchange_to. Checked in the same query as
- # the totals rather than in another round trip.
- #
- # `lots: true` is for a query that LEFT JOINs the costed holding_lots as
- # `lots`: a trade whose lot the user has costed counts at that cost, which
- # is already in the account's currency, so it needs no rate.
- def self.avg_cost_totals_sql(currency = :joined, lots: false)
- foreign = currency != :joined ? sanitize_sql_array([ "trades.currency <> ?", currency ]) : "trades.currency <> accounts.currency"
- rate = AVG_COST_TRADE_RATE_SQL
- cost = "(trades.price * trades.qty + trades.fee) * CASE WHEN #{foreign} THEN #{rate} ELSE 1 END"
- missing = "#{foreign} AND (#{rate} IS NULL OR #{rate} <= 0)"
-
- if lots
- cost = "CASE WHEN lots.id IS NOT NULL THEN lots.manual_total_cost ELSE #{cost} END"
- missing = "lots.id IS NULL AND #{missing}"
- end
+ # The rate a trade carries itself (extra["exchange_rate"], e.g. IBKR's
+ # fx_rate_to_base) comes before the table's, as in the calculators and
+ # Balance::SyncCache, but it is into the account's currency, so it only
+ # applies to a holding in that currency; one a provider holds in another
+ # currency converts at the table's rate alone. A rate written to `extra`
+ # directly can be a plain decimal string, which Trade's validation and
+ # Money#exchange_to both accept, so that counts too; anything else, an
+ # exponent or an absurd length included, is not cast. A number is held to 20
+ # integer digits by size, so multiplying it by the price cannot overflow the
+ # query. A rate of zero or less converts nothing, so it counts as missing.
+ def self.avg_cost_row_sql(holding_currency:, account_currency:)
+ own_rate = <<~SQL.squish
+ CASE jsonb_typeof(trades.extra->'exchange_rate')
+ WHEN 'number' THEN CASE WHEN abs((trades.extra->>'exchange_rate')::numeric) < 1e20
+ THEN (trades.extra->>'exchange_rate')::numeric END
+ WHEN 'string' THEN CASE WHEN trades.extra->>'exchange_rate' ~ '^[[:space:]]*[+-]?([0-9]{1,20}([.][0-9]{0,20})?|[.][0-9]{1,20})[[:space:]]*$'
+ THEN (trades.extra->>'exchange_rate')::numeric END
+ END
+ SQL
+ rate = "CASE WHEN #{holding_currency} = #{account_currency} THEN COALESCE(#{own_rate}, exchange_rates.rate) ELSE exchange_rates.rate END"
+ factor = "CASE WHEN trades.currency <> #{holding_currency} THEN CASE WHEN #{rate} > 0 THEN #{rate} END ELSE 1 END"
+ lot_factor = "CASE WHEN #{holding_currency} = #{account_currency} THEN 1 WHEN lot_rates.rate > 0 THEN lot_rates.rate END"
+ unit_cost = <<~SQL.squish
+ CASE
+ WHEN lots.id IS NOT NULL THEN lots.manual_total_cost / trades.qty * #{lot_factor}
+ WHEN trades.qty > 0 THEN (trades.price + COALESCE(trades.fee, 0) / trades.qty) * #{factor}
+ END
+ SQL
+ internal_movement = sanitize_sql_array([ "COALESCE(trades.investment_activity_label IN (?), FALSE) AND lots.id IS NULL", Trade::INTERNAL_MOVEMENT_LABELS ])
- [
- Arel.sql("SUM(#{cost})"),
- Arel.sql("SUM(trades.qty)"),
- Arel.sql("BOOL_OR(#{missing})")
- ]
+ [ unit_cost, internal_movement ]
end
- # nil when there are no purchases -- cost basis is genuinely unknown, not
- # the market price -- or when a rate is missing.
- def self.avg_cost_from_totals(total_cost, total_qty, rate_missing, currency)
- return nil if rate_missing
- return nil unless total_qty && total_qty > 0
-
- Money.new(total_cost / total_qty, currency)
+ # The joins .avg_cost_row_sql reads a costed lot through: `lots`, the lot an
+ # acquisition opened when the user has set what it cost, and `lot_rates`,
+ # the rate on the acquisition's day from the account's currency, which the
+ # cost is in, into the holding's. A cost basis is what was paid then, so a
+ # lot in a holding of another currency converts at that day's rate, and is
+ # unknown without one. A cost set on a lot that a split has restated since
+ # its acquisition is not used. All three arguments are SQL expressions.
+ def self.avg_cost_lot_joins_sql(holding_currency:, account_currency:, holding_date:)
+ <<~SQL.squish
+ LEFT JOIN holding_lots lots ON lots.account_id = entries.account_id
+ AND lots.source_entry_id = entries.id
+ AND lots.manual_total_cost IS NOT NULL
+ AND trades.qty > 0
+ AND NOT EXISTS (
+ SELECT 1 FROM security_splits lot_splits
+ WHERE lot_splits.security_id = trades.security_id
+ AND lot_splits.ex_date > entries.date
+ AND lot_splits.ex_date <= #{holding_date}
+ )
+ LEFT JOIN exchange_rates lot_rates ON (
+ lot_rates.date = entries.date AND
+ lot_rates.from_currency = #{account_currency} AND
+ lot_rates.to_currency = #{holding_currency}
+ )
+ SQL
end
# Replacing the cost replaces the #trend derived from it.
@@ -499,8 +524,125 @@ class Holding < ApplicationRecord
I18n.t("holdings.cost_basis_sources.#{cost_basis_source}")
end
+ # The replay #calculate_avg_cost and .preload_avg_costs share: walks `rows`
+ # ([date, qty, unit cost, internal movement?, replayed?], oldest first in
+ # AVG_COST_REPLAY_ORDER) and `splits` (ex-date order) as the calculators do,
+ # starting from the position the rows do not explain, and returns the
+ # average cost in `currency`, or nil when it is unknown. With `sale_qty`,
+ # the units sold by the first row not replayed, the figure is that sale's
+ # cost per unit: the average for the units held and the covering
+ # acquisitions' cost for the rest.
+ def self.replay_avg_cost(rows, all_splits, qty:, date:, through:, currency:, sale_qty: nil)
+ book = Holding::LotBook.new
+ transferred = false
+ position = opening_position(rows, all_splits, qty: qty, date: date)
+ # The opening position and each transfer in are lots of unknown cost, as
+ # the calculators book them, so a sale from them relieves units the book
+ # holds rather than leaving a shortfall the next buy would fill.
+ book.add_unknown(position)
+ splits, later_splits = all_splits.partition { |split| split.ex_date <= through }
+
+ apply_splits = lambda do |up_to|
+ while splits.any? && splits.first.ex_date <= up_to
+ ratio = splits.shift.ratio
+ book.split(ratio)
+ position = Security::Split.scale(position, ratio)
+ end
+ end
+
+ rows.each do |trade_date, trade_qty, unit_cost, internal_movement, replayed|
+ break unless replayed
+
+ apply_splits.call(trade_date)
+ previous_position = position
+
+ # Units moved in were acquired at a price nothing here knows -- a coin
+ # bought at 30k and moved in at 60k would report no gain -- so they
+ # make the whole position's cost unknown. Units moved out are relieved
+ # at the running average, like a sell.
+ if internal_movement && trade_qty.positive?
+ transferred = true
+ book.add_unknown(trade_qty)
+ else
+ book.apply(unit_cost, trade_qty)
+ end
+
+ position += trade_qty
+ # Only a genuine downward crossing through zero clears the mark, as in
+ # the calculators: a position that was never positive held no units.
+ transferred = false if previous_position.positive? && position <= 0
+ end
+ apply_splits.call(through)
+
+ average = book.average_cost unless transferred
+ held = [ sale_qty, book.open_qty ].min if sale_qty
+ if held && held < sale_qty
+ return nil if held.positive? && average.nil?
+
+ cover = shortfall_cover_cost(rows.drop_while { |row| row[4] }.drop(1), later_splits,
+ ahead: book.shortfall, short: sale_qty - held)
+ return nil unless cover
+
+ average = ((average || 0) * held + cover) / sale_qty
+ end
+ return nil unless average
+
+ # Rounded to the scale `cost_basis` is stored at, so the figure is the one
+ # the next materialization writes, not one a per-unit fee leaves at
+ # 214.99999... when the stored basis reads 215. A cost too small for that
+ # scale keeps its precision rather than rounding to a free position.
+ rounded = average.round(columns_hash["cost_basis"].scale)
+ Money.new(rounded.zero? && !average.zero? ? average : rounded, currency)
+ end
+
+ # What `short` units sold beyond the position cost, priced as
+ # Holding::LotBook prices a fifo sale's shortfall (#add_lot and #cover): the
+ # acquisitions in `rows`, those after the sale, fill the oldest shortfall
+ # first, `ahead` being what earlier sales left uncovered, each at its own
+ # cost. nil when an acquisition that covers it has no known cost (a transfer
+ # in, a buy with no rate), when a split comes first (#split: a cover after
+ # it is in other shares), or when the rows never cover it all.
+ def self.shortfall_cover_cost(rows, splits, ahead:, short:)
+ cost = BigDecimal("0")
+ rows.each do |trade_date, trade_qty, unit_cost, internal_movement|
+ return nil if splits.any? { |split| split.ex_date <= trade_date }
+ next unless trade_qty.positive?
+
+ ahead_filled = [ trade_qty, ahead ].min
+ ahead -= ahead_filled
+ filled = [ trade_qty - ahead_filled, short ].min
+ next unless filled.positive?
+ return nil if internal_movement || unit_cost.nil?
+
+ cost += filled * unit_cost
+ short -= filled
+ return cost if short.zero?
+ end
+ nil
+ end
+
+ # The position held before the first of `rows`: this holding's quantity
+ # with every trade and split up to its date undone, latest first. A split
+ # applies at the open of its ex-date, so it is undone after that day's
+ # trades.
+ def self.opening_position(rows, splits, qty:, date:)
+ position = qty.to_d
+ pending = splits.select { |split| split.ex_date <= date }
+
+ rows.reverse_each do |trade_date, trade_qty|
+ next if trade_date > date
+
+ position = Security::Split.unscale(position, pending.pop.ratio) while pending.any? && pending.last.ex_date > trade_date
+ position -= trade_qty
+ end
+ pending.reverse_each { |split| position = Security::Split.unscale(position, split.ratio) }
+
+ position
+ end
+
private
def forget_derived_answers
+ remove_instance_variable(:@replayed_avg_cost) if defined?(@replayed_avg_cost)
remove_instance_variable(:@preloaded_avg_cost) if defined?(@preloaded_avg_cost)
remove_instance_variable(:@trend) if defined?(@trend)
remove_instance_variable(:@day_change) if defined?(@day_change)
@@ -526,56 +668,90 @@ class Holding < ApplicationRecord
previous: start_amount
end
- # Calculates weighted average cost from buy trades.
- # Returns nil if no trades exist (cost basis is unknown).
- def calculate_avg_cost
- # Fewer units than the trades bought (see Holding::ReverseCalculator), so
- # no figure drawn from those trades is the position's.
+ # calculate_avg_cost through this holding's date, once per instance, nil
+ # included: a page asks a holding for its average cost several times, and
+ # each answer would replay the whole history. Only this default cut-off is
+ # kept; avg_cost_before replays to its own.
+ def replayed_avg_cost
+ return @replayed_avg_cost if defined?(@replayed_avg_cost)
+
+ @replayed_avg_cost = calculate_avg_cost
+ end
+
+ # The weighted-average cost of the position on this holding's date, worked
+ # out from the trades the way the holding calculators work it out
+ # (Holding::ForwardCalculator#apply_trades), so a holding with no stored
+ # basis shows the figure the next materialization would store: sells are
+ # relieved at the running average, a split rescales the position at the
+ # open of its ex-date, and a transfer in makes the cost unknown until the
+ # position is closed. Returns nil when the cost is unknown.
+ #
+ # `through` is the last day replayed, the holding's own date by default.
+ # `before`, an entry on that day, stops the replay just short of it
+ # (avg_cost_before).
+ #
+ # The replay starts from the position the trades do not explain, as
+ # Holding::ReverseCalculator#precompute_cost_basis seeds it from the
+ # provider's snapshot: a reverse-synced account can hold shares from
+ # before its first imported trade, and a sale that empties the imported
+ # trades then leaves those still held, so a transfer among them stays
+ # unknown. This holding's quantity, walked back through the trades and
+ # splits up to its date, is that opening position; for a forward-synced
+ # or manual account it is zero.
+ #
+ # Two lot rules come first. A clamped position holds fewer units than the
+ # trades bought (see Holding::ReverseCalculator), so no figure drawn from
+ # those trades is its cost. A fifo position holds its open lots
+ # (.fifo_avg_costs), which are the position as it stands, so they say
+ # nothing about the cost just before an earlier sale, and the trades'
+ # pooled average is the average method's figure, not fifo's.
+ def calculate_avg_cost(through: date, before: nil)
return nil if HoldingLot.where(account_id: account_id, security_id: security_id, clamped: true).exists?
- return self.class.fifo_avg_costs([ self ])[id] if account.cost_basis_fifo?
+ return before ? nil : self.class.fifo_avg_costs([ self ])[id] if account.cost_basis_fifo?
- trades = account.trades
- .with_entry
- .joins(self.class.avg_cost_rates_join(account.currency))
- .where(security_id: security.id)
- .where("trades.qty > 0 AND entries.date <= ?", date)
-
- # A trade whose lot the user has costed counts at that cost, a
- # transfer-in included. The cost is already in the account's currency.
- # This fallback divides by the trades' own quantities, which a later split
- # does not restate, so a cost set on a lot split since is not used here.
- trades = trades.joins(self.class.sanitize_sql_array([ <<~SQL.squish, date ]))
- LEFT JOIN holding_lots lots ON lots.account_id = entries.account_id
- AND lots.source_entry_id = entries.id
- AND lots.manual_total_cost IS NOT NULL
- AND NOT EXISTS (
- SELECT 1 FROM security_splits lot_splits
- WHERE lot_splits.security_id = trades.security_id
- AND lot_splits.ex_date > entries.date
- AND lot_splits.ex_date <= ?
- )
- SQL
+ splits = Security::Split.where(security_id: security_id).order(:ex_date)
+ splits = splits.where(ex_date: ..[ through, date ].max) unless before
+ sale_qty = -before.entryable.qty if before && before.entryable.try(:qty).to_d.negative?
+ self.class.replay_avg_cost(avg_cost_trade_rows(through: through, before: before), splits.to_a,
+ qty: qty, date: date, through: through, currency: currency, sale_qty: sale_qty)
+ end
- # An internal movement is not a purchase: securities moved in from elsewhere were
- # acquired at a price nothing here knows, so treating the day they
- # arrived as their cost states a number that looks authoritative and is
- # wrong — a coin bought at 30k and moved in at 60k would report no gain.
- #
- # One internal movement makes the whole position unknown, rather than just its own
- # row. Averaging the purchases alone and applying that to every unit is
- # the same fabrication in a quieter form: buy one at 30k, receive one, and
- # the position would report 30k a unit for two units it did not cost that.
- return nil if trades.where(investment_activity_label: Trade::INTERNAL_MOVEMENT_LABELS, lots: { id: nil }).exists?
-
- # IS DISTINCT FROM, because `!=` is NULL for an unlabelled row and would
- # drop the ordinary purchases that carry no label at all.
- trades = trades.where(
- "trades.investment_activity_label NOT IN (?) OR trades.investment_activity_label IS NULL OR lots.id IS NOT NULL",
- Trade::INTERNAL_MOVEMENT_LABELS
+ # This security's trades up to this holding's date and up to the replay's
+ # cutoff -- `through`, or strictly before the entry `before` in the same
+ # order -- oldest first in AVG_COST_REPLAY_ORDER, as
+ # [date, qty, unit cost, internal movement?, replayed?] (see
+ # .avg_cost_row_sql). Both sets are a prefix of that order, so the replayed
+ # rows lead and one query serves the walk back to the opening position and
+ # the replay. With `before`, the trades after it come too, since what
+ # covers a sale beyond the position comes later.
+ def avg_cost_trade_rows(through:, before:)
+ quoted = { holding_currency: self.class.connection.quote(currency), account_currency: self.class.connection.quote(account.currency) }
+ unit_cost, internal_movement = self.class.avg_cost_row_sql(**quoted)
+ lot_joins = self.class.avg_cost_lot_joins_sql(**quoted, holding_date: self.class.connection.quote(date))
+
+ cutoff = ActiveRecord::Base.sanitize_sql_array(
+ if before
+ # A row comparison, so it sorts exactly as AVG_COST_REPLAY_ORDER does.
+ [ "(entries.date, entries.created_at, (trades.qty < 0), entries.id) < (?, ?, ?, ?)",
+ before.date, before.created_at, before.entryable.try(:qty).to_d.negative?, before.id ]
+ else
+ [ "entries.date <= ?", through ]
+ end
)
- total_cost, total_qty, rate_missing = trades.pick(*self.class.avg_cost_totals_sql(account.currency, lots: true))
-
- self.class.avg_cost_from_totals(total_cost, total_qty, rate_missing, currency)
+ account.trades
+ .with_entry
+ .joins(ActiveRecord::Base.sanitize_sql_array([
+ "LEFT JOIN exchange_rates ON (
+ exchange_rates.date = entries.date AND
+ exchange_rates.from_currency = trades.currency AND
+ exchange_rates.to_currency = ?
+ )", currency
+ ]))
+ .joins(lot_joins)
+ .where(security_id: security_id)
+ .then { |trades| before ? trades : trades.where("(#{cutoff}) OR entries.date <= ?", date) }
+ .reorder(Arel.sql(AVG_COST_REPLAY_ORDER))
+ .pluck(Arel.sql("entries.date"), Arel.sql("trades.qty"), Arel.sql(unit_cost), Arel.sql(internal_movement), Arel.sql("COALESCE(#{cutoff}, FALSE)"))
end
end
diff --git a/app/models/holding/lot_book.rb b/app/models/holding/lot_book.rb
index a99a4365dc..2506f8b17e 100644
--- a/app/models/holding/lot_book.rb
+++ b/app/models/holding/lot_book.rb
@@ -46,7 +46,7 @@ class Holding::LotBook
# divide evenly; anything wider is a real difference.
OPENING_RESIDUAL_BOUND = BigDecimal("1e-12")
- attr_reader :lots
+ attr_reader :lots, :shortfall
def initialize(method: "average")
@fifo = method.to_s == "fifo"
diff --git a/app/models/trade.rb b/app/models/trade.rb
index 9edb5f867a..bb6608c724 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -407,10 +407,20 @@ class Trade < ApplicationRecord
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.
+ # The position's average cost just before the sale, applied to the units
+ # sold. A sale that closes the position leaves a snapshot with nothing held
+ # and no basis, so the cost has to come from the trades before the sale.
+ # Average cost does not move on a sale, so where the snapshot has a figure
+ # it is the same one. Where it has none, the replay up to the sale is the
+ # figure, and also the right one when trades fall between the snapshot's
+ # date and the sale, so the history is replayed once rather than through
+ # the snapshot's date first.
def snapshot_cost
holding = basis_holding
- holding.avg_cost * qty.abs if holding&.avg_cost
+ return unless holding
+
+ avg_cost = holding.stored_avg_cost || holding.avg_cost_before(entry)
+ avg_cost * qty.abs if avg_cost
end
def calculate_realized_gain_loss
diff --git a/test/migrations/clear_transferred_position_cost_bases_migration_test.rb b/test/migrations/clear_transferred_position_cost_bases_migration_test.rb
index a4be20d09e..076e1ab435 100644
--- a/test/migrations/clear_transferred_position_cost_bases_migration_test.rb
+++ b/test/migrations/clear_transferred_position_cost_bases_migration_test.rb
@@ -32,7 +32,7 @@ class ClearTransferredPositionCostBasesMigrationTest < ActiveSupport::TestCase
end
# The runtime only invalidates on a transfer IN: both `calculate_avg_cost` and
- # the calculators drop `qty <= 0` rows before they ever look at the label.
+ # the calculators relieve a transfer out at the running average, like a sell.
# Shares sent elsewhere leave the remaining ones with the cost they were
# actually bought at, and that figure is correct.
test "a position transferred out keeps it" do
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index da7d8dd41a..ca570ca2df 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -96,8 +96,9 @@ class HoldingTest < ActiveSupport::TestCase
nvda_qty = BigDecimal("5") + BigDecimal("30")
expected_nvda = nvda_total / nvda_qty
- assert_equal Money.new(expected_amzn), @amzn.avg_cost
- assert_equal Money.new(expected_nvda), @nvda.avg_cost
+ # At the four places `cost_basis` is stored at, as the calculators store it
+ assert_equal Money.new(expected_amzn.round(4)), @amzn.avg_cost
+ assert_equal Money.new(expected_nvda.round(4)), @nvda.avg_cost
end
test "calculates average cost basis from another currency" do
@@ -123,8 +124,8 @@ class HoldingTest < ActiveSupport::TestCase
expected_nvda_usd = nvda_total_usd / nvda_qty
ExchangeRate.stubs(:find_or_fetch_rate).returns(OpenStruct.new(rate: 1))
- assert_equal Money.new(expected_amzn_usd, "CAD").exchange_to("USD"), @amzn.avg_cost
- assert_equal Money.new(expected_nvda_usd, "CAD").exchange_to("USD"), @nvda.avg_cost
+ assert_equal Money.new(expected_amzn_usd.round(4), "CAD").exchange_to("USD"), @amzn.avg_cost
+ assert_equal Money.new(expected_nvda_usd.round(4), "CAD").exchange_to("USD"), @nvda.avg_cost
end
test "the average cost includes what the purchases cost in fees" do
@@ -170,25 +171,337 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal Money.new(BigDecimal("265")), @amzn.avg_cost
end
+ # Holding#avg_cost is Money in the holding's own currency, which a provider
+ # can set to something other than the account's, so the replay converts the
+ # trades into that currency rather than the account's.
+ test "the fallback carries a foreign-currency holding's cost in its own currency" do
+ security = create_security("ASML", prices: [ { date: Date.current, price: 120 } ])
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: 1.day.ago.to_date, rate: 1.5)
+ create_trade(security, account: @account, qty: 10, price: 100, date: 1.day.ago.to_date, currency: "EUR")
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 10, price: 120,
+ amount: 1200, currency: "EUR", cost_basis: nil)
+
+ assert_equal Money.new(BigDecimal("100"), "EUR"), holding.avg_cost
+ end
+
+ test "the fallback converts a trade in the account's currency into the holding's" do
+ security = create_security("ASML", prices: [ { date: Date.current, price: 120 } ])
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: 1.day.ago.to_date, rate: 0.5)
+ create_trade(security, account: @account, qty: 10, price: 150, date: 1.day.ago.to_date, currency: "USD")
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 10, price: 120,
+ amount: 1200, currency: "EUR", cost_basis: nil)
+
+ assert_equal Money.new(BigDecimal("75"), "EUR"), holding.avg_cost
+ end
+
+ # A rate a trade carries converts into the account's currency (IBKR's
+ # fx_rate_to_base), so it says nothing about a holding in another one.
+ test "the fallback does not apply a trade's own rate to a holding in another currency" do
+ security = create_security("ASML", prices: [ { date: Date.current, price: 120 } ])
+ entry = create_trade(security, account: @account, qty: 10, price: 100, date: 1.day.ago.to_date, currency: "GBP")
+ entry.entryable.update!(exchange_rate: 1.25)
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 10, price: 120,
+ amount: 1200, currency: "EUR", cost_basis: nil)
+
+ assert_nil holding.avg_cost
+ end
+
test "the fallback ignores a rate string that is not a plain decimal" do
entry = create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
[ "n/a", "1e999999" ].each do |rate|
entry.entryable.update_column(:extra, { "exchange_rate" => rate })
- assert_nil @amzn.avg_cost, rate
+ # A fresh instance each time: the holding remembers its replayed cost.
+ assert_nil @amzn.reload.avg_cost, rate
end
end
+ # Trade#exchange_rate= only stores a finite Float, but a number written to
+ # `extra` directly can be as long as numeric allows, and multiplying it by the
+ # price would overflow numeric and fail the query. Past the 20 integer digits
+ # a rate string may have, it is not used either.
+ test "the fallback ignores a numeric rate too large to convert" do
+ entry = create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
+
+ [ 10**131071, 10**20 ].each do |rate|
+ entry.entryable.update_column(:extra, { "exchange_rate" => rate })
+
+ assert_nil @amzn.reload.avg_cost, rate.to_s.length
+ end
+ end
+
+ # The bound is on size, not on the string format: a small Float rate is stored
+ # with more than the 20 decimal places a rate string may have, and still counts.
+ test "the fallback converts at a small numeric rate with many decimal places" do
+ entry = create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
+ entry.entryable.update!(exchange_rate: 1.2345678901234567e-05)
+
+ # 212 CAD at 0.000012345678901234567 is 0.00261728..., 0.0026 at cost_basis's scale
+ assert_equal Money.new(BigDecimal("0.0026")), @amzn.avg_cost
+ end
+
# The missing-rate check rides on the totals query instead of adding a round
# trip to a path that exists to avoid N+1 queries.
- test "the fallback reads the trades in two queries" do
+ test "the fallback reads the trades and the splits in one query each" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date)
+ @amzn.account
+
+ queries = ActiveRecord::Base.uncached { capture_sql_queries { @amzn.avg_cost } }
+
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "trades"') }
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "security_splits"') }
+ end
+
+ # A page asks a holding for its average cost several times (the cell, the
+ # trend, the statement's totals); each answer would replay the history.
+ test "the fallback replays the trades once per holding instance" do
create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date)
@amzn.account
- queries = capture_sql_queries { @amzn.avg_cost }
+ queries = ActiveRecord::Base.uncached do
+ capture_sql_queries { 4.times { @amzn.avg_cost } }
+ end
+
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "trades"') }
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "security_splits"') }
+ end
+
+ test "the fallback remembers an unknown cost too" do
+ transfer_in = create_trade(@amzn.security, account: @account, qty: 15, price: 212.00, date: 1.day.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ @amzn.account
+
+ queries = ActiveRecord::Base.uncached do
+ capture_sql_queries { 3.times { assert_nil @amzn.avg_cost } }
+ end
- assert_equal 2, queries.count { |sql| sql.include?('FROM "trades"') }
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "trades"') }
+ end
+
+ test "reload forgets the remembered fallback, so a later trade counts" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 3.days.ago.to_date)
+ assert_equal Money.new(BigDecimal("100")), @amzn.avg_cost
+
+ create_trade(@amzn.security, account: @account, qty: 5, price: 250, date: 2.days.ago.to_date)
+
+ # 10 at 100 plus 5 at 250: 2,250 for 15 units
+ assert_equal Money.new(BigDecimal("150")), @amzn.reload.avg_cost
+ end
+
+ test "the remembered fallback never answers for a sale's earlier cut-off" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 3.days.ago.to_date)
+ second_buy = create_trade(@amzn.security, account: @account, qty: 5, price: 250, date: 2.days.ago.to_date)
+
+ assert_equal Money.new(BigDecimal("150")), @amzn.avg_cost
+ assert_equal Money.new(BigDecimal("100")), @amzn.avg_cost_before(second_buy)
+
+ fresh = Holding.find(@amzn.id)
+ assert_equal Money.new(BigDecimal("100")), fresh.avg_cost_before(second_buy)
+ assert_equal Money.new(BigDecimal("150")), fresh.avg_cost
+ end
+
+ # The fallback answers for a holding with no stored basis, so it has to give
+ # the figure the holding calculators would store (#3566): the same tracker,
+ # relieving sells, splitting, and releasing a transfer once the position closes.
+ test "the fallback relieves a full sell, so a rebuy starts a clean basis" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: -10, price: 150, date: 5.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200, date: 1.day.ago.to_date)
+
+ assert_equal Money.new(BigDecimal("200")), @amzn.avg_cost
+ end
+
+ test "the fallback relieves a partial sell at the running average" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: -5, price: 150, date: 5.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 5, price: 200, date: 1.day.ago.to_date)
+
+ # 5 left at 100, plus 5 at 200: 1,500 for 10 units
+ assert_equal Money.new(BigDecimal("150")), @amzn.avg_cost
+ end
+
+ test "a transfer in stops making the fallback unknown once the position is closed" do
+ transfer_in = create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: "Transfer")
+ create_trade(@amzn.security, account: @account, qty: -10, price: 150, date: 5.days.ago.to_date)
+
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200, date: 1.day.ago.to_date)
+ # The 10 these trades hold, so no opening shares keep the transferred
+ # units in the position (see the opening-shares tests below)
+ @amzn.update!(qty: 10, amount: 2160)
+
+ assert_equal Money.new(BigDecimal("200")), @amzn.avg_cost
+ end
+
+ test "the fallback stays unknown while transferred-in units are held" do
+ transfer_in = create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: "Transfer")
+ create_trade(@amzn.security, account: @account, qty: -5, price: 150, date: 5.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200, date: 1.day.ago.to_date)
+
+ assert_nil @amzn.avg_cost
+ end
+
+ # A reverse-synced account can hold shares from before its first imported
+ # trade. Holding 10 where the trades net to 8 leaves two opening shares, so
+ # the -15 sale never empties the position and the transferred units may
+ # still be among those held: Holding::ReverseCalculator stores no basis for
+ # this history, and the fallback must not invent the rebuy's 150.
+ test "avg_cost stays unknown while opening shares keep transferred units in the position" do
+ holding = opening_shares_holding(qty: 10)
+
+ assert_nil holding.avg_cost
+ end
+
+ # The same trades with a holding of 8: the history explains the whole
+ # position, so the sale does empty it, the transfer is released and the
+ # rebuy is the cost.
+ test "avg_cost is known again after a real close when the history explains the whole position" do
+ holding = opening_shares_holding(qty: 8)
+
+ assert_equal Money.new(BigDecimal("150")), holding.avg_cost
+ end
+
+ # Holding 10 where the trades net to 0 leaves ten opening shares. Selling
+ # five of them relieves units the book holds, as the calculators book the
+ # opening position as a lot, so the rebuy joins the average rather than
+ # covering a shortfall and leaving nothing priced: 200, not unknown.
+ test "a sale from opening shares leaves no shortfall for the next buy" do
+ security = create_security("OPNS", prices: [ { date: Date.current, price: 210 } ])
+ create_trade(security, account: @account, qty: -5, price: 150, date: 5.days.ago.to_date)
+ create_trade(security, account: @account, qty: 5, price: 200, date: 2.days.ago.to_date)
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 10, price: 210,
+ amount: 2100, currency: "USD", cost_basis: nil)
+
+ batch = [ Holding.find(holding.id) ]
+ Holding.preload_avg_costs(batch)
+
+ assert_equal Money.new(BigDecimal("200")), holding.avg_cost
+ assert_equal Money.new(BigDecimal("200")), batch.first.avg_cost
+ end
+
+ # The walk back to the opening position has to undo the split as well as the
+ # trades: 10 bought and 5 moved in become 30 on a 2-for-1 split, and selling
+ # all 30 closes the position. Subtracting the trades from the 8 held without
+ # halving the 30 would leave 15 phantom opening shares that never sell, and
+ # the transfer would keep the rebuy's cost unknown.
+ test "avg_cost walks the opening position back through a split" do
+ security = create_security("SPLT", prices: [ { date: Date.current, price: 160 } ])
+ create_trade(security, account: @account, qty: 10, price: 100, date: 12.days.ago.to_date)
+ transfer_in = create_trade(security, account: @account, qty: 5, price: 120, date: 9.days.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ security.splits.create!(ex_date: 7.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ create_trade(security, account: @account, qty: -30, price: 65, date: 6.days.ago.to_date)
+ create_trade(security, account: @account, qty: 8, price: 150, date: 3.days.ago.to_date)
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 8, price: 160,
+ amount: 1280, currency: "USD", cost_basis: nil)
+
+ assert_equal Money.new(BigDecimal("150")), holding.avg_cost
+ end
+
+ test "an outbound transfer is relieved like a sell in the fallback" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date)
+ transfer_out = create_trade(@amzn.security, account: @account, qty: -10, price: 100, date: 5.days.ago.to_date)
+ transfer_out.entryable.update!(investment_activity_label: "Transfer")
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200, date: 1.day.ago.to_date)
+
+ assert_equal Money.new(BigDecimal("200")), @amzn.avg_cost
+ end
+
+ test "the fallback applies a stock split at the open of its ex-date" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date)
+ @amzn.security.splits.create!(ex_date: 5.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ create_trade(@amzn.security, account: @account, qty: 10, price: 60, date: 5.days.ago.to_date)
+
+ # 1,000 for 20 post-split units, plus 600 for 10: 1,600 for 30, at the
+ # four places `cost_basis` is stored at
+ assert_equal Money.new(BigDecimal("53.3333")), @amzn.avg_cost
+ end
+
+ test "a buy with no rate stops making the fallback unknown once the position is closed" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 10.days.ago.to_date, currency: "CAD")
+ create_trade(@amzn.security, account: @account, qty: -10, price: 150, date: 5.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200, date: 1.day.ago.to_date)
+
+ assert_equal Money.new(BigDecimal("200")), @amzn.avg_cost
+ end
+
+ test "the fallback agrees with the forward calculator" do
+ account = families(:empty).accounts.create!(name: "Parity Brokerage", balance: 0, cash_balance: 0, currency: "USD", accountable: Investment.new)
+ security = create_security("PRTY", prices: (0..12).map { |days| { date: days.days.ago.to_date, price: 120 } })
+
+ create_trade(security, account: account, qty: 10, price: 100, fee: 10, date: 12.days.ago.to_date)
+ create_trade(security, account: account, qty: -4, price: 130, date: 10.days.ago.to_date)
+ transfer_in = create_trade(security, account: account, qty: 3, price: 90, date: 9.days.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: "Transfer")
+ create_trade(security, account: account, qty: -9, price: 140, date: 8.days.ago.to_date)
+ create_trade(security, account: account, qty: 8, price: 110, fee: 4, date: 7.days.ago.to_date)
+ security.splits.create!(ex_date: 6.days.ago.to_date, numerator: 3, denominator: 2, source: "manual")
+ transfer_out = create_trade(security, account: account, qty: -3, price: 75, date: 5.days.ago.to_date)
+ transfer_out.entryable.update!(investment_activity_label: "Transfer")
+ create_trade(security, account: account, qty: 6, price: 80, date: 3.days.ago.to_date)
+
+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings
+ holdings = account.holdings.where(security: security).where("date >= ?", 7.days.ago.to_date).order(:date).to_a
+
+ assert holdings.all? { |holding| holding.cost_basis.present? }, "every compared day needs a calculated basis"
+ holdings.each do |holding|
+ assert_equal holding.cost_basis, holding.send(:calculate_avg_cost)&.amount, holding.date.to_s
+ end
+ end
+
+ # The two paths convert differently: the fallback joins the rate stored for
+ # the trade's exact date, the calculators go through Money#exchange_to. With
+ # a rate on every trade date those must give the same figure.
+ test "the fallback agrees with the forward calculator for trades in another currency" do
+ account = families(:empty).accounts.create!(name: "FX Parity Brokerage", balance: 0, cash_balance: 0, currency: "USD", accountable: Investment.new)
+ security = create_security("FXPT", prices: (0..12).map { |days| { date: days.days.ago.to_date, price: 120 } })
+
+ { 12 => 0.70, 10 => 0.72, 8 => 0.75, 5 => 0.74, 3 => 0.73, 2 => 0.71 }.each do |days, rate|
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: days.days.ago.to_date, rate: rate)
+ end
+
+ create_trade(security, account: account, qty: 10, price: 100, fee: 10, currency: "CAD", date: 12.days.ago.to_date)
+ create_trade(security, account: account, qty: -4, price: 130, currency: "CAD", date: 10.days.ago.to_date)
+ create_trade(security, account: account, qty: 6, price: 110, fee: 4, currency: "CAD", date: 8.days.ago.to_date)
+ security.splits.create!(ex_date: 6.days.ago.to_date, numerator: 3, denominator: 2, source: "manual")
+ # A rate the trade carries itself comes before the table's 0.74
+ own_rate = create_trade(security, account: account, qty: 4, price: 90, currency: "CAD", date: 5.days.ago.to_date)
+ own_rate.entryable.update!(exchange_rate: 0.8)
+ create_trade(security, account: account, qty: 3, price: 85, date: 4.days.ago.to_date)
+ create_trade(security, account: account, qty: -10, price: 140, currency: "CAD", date: 3.days.ago.to_date)
+ create_trade(security, account: account, qty: 5, price: 100, fee: 5, currency: "CAD", date: 2.days.ago.to_date)
+
+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings
+ holdings = account.holdings.where(security: security).order(:date).to_a
+
+ assert_equal 13, holdings.size
+ # (100 + 10 / 10) CAD at 0.70: the first day's basis is converted in USD
+ assert_equal BigDecimal("70.7"), holdings.first.cost_basis
+ assert holdings.all? { |holding| holding.cost_basis.present? }, "every compared day needs a calculated basis"
+ holdings.each do |holding|
+ assert_equal holding.cost_basis, holding.send(:calculate_avg_cost)&.amount, holding.date.to_s
+ end
+ end
+
+ # Known divergence, out of scope here (we-promise/sure#2012): with no rate
+ # stored for a foreign trade's own date, Money#exchange_to falls back to the
+ # nearest earlier rate, so the calculator stores a basis, while the fallback's
+ # exact-date join finds no rate and reports the cost as unknown. This pins
+ # both answers so a change to either path shows up here.
+ test "the fallback reports unknown where the calculator uses an earlier rate (#2012)" do
+ account = families(:empty).accounts.create!(name: "FX Gap Brokerage", balance: 0, cash_balance: 0, currency: "USD", accountable: Investment.new)
+ security = create_security("FXGP", prices: (0..5).map { |days| { date: days.days.ago.to_date, price: 120 } })
+
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: 5.days.ago.to_date, rate: 0.70)
+ create_trade(security, account: account, qty: 10, price: 100, currency: "CAD", date: 3.days.ago.to_date)
+
+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings
+ holding = account.holdings.find_by!(security: security, date: 3.days.ago.to_date)
+
+ assert_equal BigDecimal("70"), holding.cost_basis
+ assert_nil holding.send(:calculate_avg_cost)
end
# Each case pins the figure #avg_cost gives on its own, then checks the batch
@@ -248,6 +561,52 @@ class HoldingTest < ActiveSupport::TestCase
end
end
+ # The batch replays the trades as #avg_cost does, so a position that was
+ # closed and reopened starts its basis again, a split rescales it, and a
+ # tiny unit cost survives rounding. The expected column pins #avg_cost
+ # itself, so a rule dropped from both paths still fails.
+ test "the batch replays each holding's trades as its own fallback does" do
+ reopened = create_security("REOP", prices: [ { date: Date.current, price: 250 } ])
+ create_trade(reopened, account: @account, qty: 10, price: 100, date: 6.days.ago.to_date)
+ create_trade(reopened, account: @account, qty: -10, price: 150, date: 4.days.ago.to_date)
+ create_trade(reopened, account: @account, qty: 10, price: 200, date: 2.days.ago.to_date)
+
+ split = create_security("SPLT", prices: [ { date: Date.current, price: 60 } ])
+ create_trade(split, account: @account, qty: 10, price: 100, date: 6.days.ago.to_date)
+ split.splits.create!(ex_date: 3.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+
+ tiny = create_security("TINY", prices: [ { date: Date.current, price: 0.00002 } ])
+ create_trade(tiny, account: @account, qty: 10_000_000, price: 0.00001, date: 2.days.ago.to_date)
+
+ cases = {
+ reopened: [ create_holding(reopened, Date.current, 10), BigDecimal("200") ],
+ split: [ create_holding(split, Date.current, 20), BigDecimal("50") ],
+ tiny: [ create_holding(tiny, Date.current, 10_000_000), BigDecimal("0.00001") ]
+ }
+
+ own = cases.transform_values { |(holding, _)| Holding.find(holding.id).avg_cost&.amount }
+ batch = Holding.where(id: cases.values.map { |(holding, _)| holding.id }).to_a
+ Holding.preload_avg_costs(batch)
+ batched = cases.transform_values { |(holding, _)| batch.find { |h| h.id == holding.id }.avg_cost&.amount }
+
+ assert_equal cases.transform_values(&:last), own, "#avg_cost moved"
+ assert_equal own, batched, "the batch disagrees with #avg_cost"
+ end
+
+ # Like the per-holding fallback, a foreign trade's own rate is used only up
+ # to 20 integer digits; past that the batch must not overflow the query.
+ test "the batch ignores a numeric rate too large to convert" do
+ entry = create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
+ entry.entryable.update_column(:extra, { "exchange_rate" => 10**131071 })
+
+ batch = [ Holding.find(@amzn.id) ]
+ Holding.preload_avg_costs(batch)
+
+ assert_nil batch.first.avg_cost
+ end
+
+ # The trades and the splits each come back in one query, however many
+ # holdings the batch answers for.
test "the batched average cost reads every holding's trades in one query" do
batch_sizes = [ 2, 4 ].map do |count|
holdings = Array.new(count) do |i|
@@ -256,10 +615,25 @@ class HoldingTest < ActiveSupport::TestCase
create_holding(security, Date.current, 1)
end
- capture_sql_queries { Holding.preload_avg_costs(holdings) }.size
+ queries = capture_sql_queries { Holding.preload_avg_costs(holdings) }
+ [ queries.count { |sql| sql.include?('FROM "trades"') || sql.include?("JOIN trades") }, queries.count { |sql| sql.include?('"security_splits"') }, queries.size ]
end
- assert_equal [ 1, 1 ], batch_sizes
+ assert_equal batch_sizes.first, batch_sizes.last
+ assert_equal [ 1, 1, 2 ], batch_sizes.first
+ end
+
+ # A save replaces the attributes the replayed cost was worked out from.
+ test "a saved holding replays its cost again" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100, date: 3.days.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 300, date: 1.day.ago.to_date)
+ holding = Holding.find(@amzn.id)
+ assert_equal Money.new(200), holding.avg_cost
+
+ holding.update!(date: 2.days.ago.to_date)
+
+ assert_equal Holding.find(holding.id).avg_cost, holding.avg_cost
+ assert_equal Money.new(100), holding.avg_cost
end
# The lot rules #calculate_avg_cost applies, which the batch must apply too:
@@ -295,6 +669,48 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal own, batched, "the batch disagrees with #avg_cost"
end
+ # A lot's cost is in the account's currency; a holding in another currency
+ # carries its cost in its own, converted at the rate on the day the lot was
+ # acquired, not today's: a basis is what was paid then. 400 USD for 5 units
+ # at 0.9 is 72 EUR a unit; today's 0.5 would say 40, and no conversion 80.
+ test "a costed lot in a holding of another currency converts at its acquisition-date rate" do
+ day = 2.days.ago.to_date
+ security = create_security("LOTF", prices: [ { date: Date.current, price: 100 } ])
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: day, rate: 0.9)
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.5)
+ buy = create_trade(security, account: @account, qty: 5, price: 100, date: day)
+ HoldingLot.create!(account: @account, security: security, source_entry: buy, qty: 5,
+ currency: "USD", acquired_on: day, manual_total_cost: 400)
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 5, price: 100,
+ amount: 500, currency: "EUR", cost_basis: nil)
+
+ batch = [ Holding.find(holding.id) ]
+ Holding.preload_avg_costs(batch)
+
+ assert_equal Money.new(BigDecimal("72"), "EUR"), Holding.find(holding.id).avg_cost
+ assert_equal Money.new(BigDecimal("72"), "EUR"), batch.first.avg_cost
+ end
+
+ # With no rate for the lot's day, its cost in the holding's currency is
+ # unknown, so the position's is too, as for a foreign buy with no rate.
+ test "a costed lot in a holding of another currency with no rate for its day is unknown" do
+ day = 2.days.ago.to_date
+ security = create_security("LOTN", prices: [ { date: Date.current, price: 100 } ])
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.5)
+ moved_in = create_trade(security, account: @account, qty: 5, price: 100, date: day)
+ moved_in.entryable.update!(investment_activity_label: "Sweep In")
+ HoldingLot.create!(account: @account, security: security, source_entry: moved_in, qty: 5,
+ currency: "USD", acquired_on: day, manual_total_cost: 400)
+ holding = @account.holdings.create!(security: security, date: Date.current, qty: 5, price: 100,
+ amount: 500, currency: "EUR", cost_basis: nil)
+
+ batch = [ Holding.find(holding.id) ]
+ Holding.preload_avg_costs(batch)
+
+ assert_nil Holding.find(holding.id).avg_cost
+ assert_nil batch.first.avg_cost
+ end
+
# A fifo position holds its open lots, so with no stored cost its fallback
# is their mean, as #calculate_avg_cost gives it: 20 here, where the
# average method would say 15. The batch reads every fifo holding's lots together, so a page of them
@@ -344,6 +760,23 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal BigDecimal("20"), batch.first.avg_cost&.amount, "the batch's figure"
end
+ # The open lots are the position as it stands, so under fifo they say
+ # nothing about the cost just before an earlier sale, and the trades'
+ # pooled average (15 here) is the average method's figure.
+ test "a fifo holding gives no cost just before a sale" do
+ @account.update!(cost_basis_method: "fifo")
+ security = create_security("FIFOB", prices: [ { date: Date.current, price: 30 } ])
+ create_trade(security, account: @account, qty: 10, price: 10, date: 3.days.ago.to_date)
+ create_trade(security, account: @account, qty: 10, price: 20, date: 2.days.ago.to_date)
+ sale = create_trade(security, account: @account, qty: -10, price: 30, date: 1.day.ago.to_date)
+ Holding::Materializer.new(@account.reload, strategy: :forward).materialize_holdings
+ holding = @account.holdings.where(security: security).order(:date).last
+ holding.update!(cost_basis: nil)
+
+ assert_equal BigDecimal("20"), holding.avg_cost&.amount, "the open lots answer for the position as it stands"
+ assert_nil holding.avg_cost_before(sale)
+ end
+
test "the batch leaves a stored cost basis alone and does not query for it" do
@amzn.update!(cost_basis: 100)
create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: Date.current)
@@ -848,6 +1281,20 @@ class HoldingTest < ActiveSupport::TestCase
[ amzn, nvda ]
end
+ # Holding::ReverseCalculatorTest's opening-shares history: buy 10, move 5
+ # in, sell 15, rebuy 8 at 150. A holding of `qty` today, with no basis.
+ def opening_shares_holding(qty:)
+ security = create_security("OPEN", prices: [ { date: Date.current, price: 160 } ])
+ create_trade(security, account: @account, qty: 10, price: 100, date: 12.days.ago.to_date)
+ transfer_in = create_trade(security, account: @account, qty: 5, price: 120, date: 9.days.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ create_trade(security, account: @account, qty: -15, price: 130, date: 6.days.ago.to_date)
+ create_trade(security, account: @account, qty: 8, price: 150, date: 3.days.ago.to_date)
+
+ @account.holdings.create!(security: security, date: Date.current, qty: qty, price: 160,
+ amount: qty * 160, currency: "USD", cost_basis: nil)
+ end
+
def create_holding(security, date, qty)
price = Security::Price.find_by(date: date, security: security).price
diff --git a/test/models/trade_test.rb b/test/models/trade_test.rb
index cb92ccff02..831e13a7c2 100644
--- a/test/models/trade_test.rb
+++ b/test/models/trade_test.rb
@@ -182,6 +182,244 @@ class TradeTest < ActiveSupport::TestCase
assert_equal [ BigDecimal(40) ] * 4, trades.map { |t| t.realized_gain_loss.value.amount }
end
+ # A sale that closes the position leaves a snapshot holding nothing, with no
+ # stored basis, so the snapshot cannot say what the units cost. Average cost
+ # does not move on a sale, so the sale is priced at the average before it:
+ # 10 at 100 and 10 at 200 is 3,000 for 20, sold at 180 for 3,600, a 600
+ # gain. Replaying through the sale itself closes the position and leaves no
+ # figure at all.
+ test "a sale that closes the position realises its gain against the cost before the sale" do
+ account, security = cross_currency_account
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100)
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 3), price: 200)
+ sell = create_trade(security, account: account, qty: -20, date: Date.new(2026, 3, 4), price: 180).entryable
+ closed_snapshot(account, security, Date.new(2026, 3, 4))
+
+ gain = sell.realized_gain_loss
+
+ assert_not_nil gain, "a closing sale still realises a gain"
+ assert_equal BigDecimal(3000), gain.previous.amount
+ assert_equal BigDecimal(600), gain.value.amount
+ end
+
+ # Bought and sold on one day, the only snapshot is the closed one and there
+ # is no earlier day to read a cost from. The buy sorts before the sale in
+ # Entry.chronological order, so it is the cost: 10 at 100 sold at 130 is a
+ # 300 gain.
+ test "a position bought and sold on the same day realises its gain" do
+ account, security = cross_currency_account
+ date = Date.new(2026, 3, 4)
+ create_trade(security, account: account, qty: 10, date: date, price: 100)
+ sell = create_trade(security, account: account, qty: -10, date: date, price: 130).entryable
+ closed_snapshot(account, security, date)
+
+ gain = sell.realized_gain_loss
+
+ assert_not_nil gain, "the same day's buy is the cost"
+ assert_equal BigDecimal(300), gain.value.amount
+ end
+
+ # An import stamps a day's trades with one created_at, and the calculators
+ # then replay a buy before a sale whatever their ids
+ # (Holding::PortfolioCache#trades). The sale's cost must too, even when the
+ # sale's id sorts first.
+ test "a same-day sale imported with its buy realises its gain whatever the ids" do
+ account, security = cross_currency_account
+ date = Date.new(2026, 3, 4)
+ buy = create_trade(security, account: account, qty: 10, date: date, price: 100)
+ sell_entry = create_trade(security, account: account, qty: -10, date: date, price: 130)
+ stamp = Time.zone.local(2026, 3, 4, 9)
+ Entry.where(id: [ buy.id, sell_entry.id ]).update_all(created_at: stamp)
+ sell_entry.update_columns(id: "00000000-0000-0000-0000-000000000001")
+ closed_snapshot(account, security, date)
+
+ gain = Trade.find(sell_entry.entryable_id).realized_gain_loss
+
+ assert_not_nil gain, "the same day's buy is the cost"
+ assert_equal BigDecimal(300), gain.value.amount
+ end
+
+ # A provider can hold a position in the security's currency rather than the
+ # account's, and the replayed cost is then in that currency too. 10 bought
+ # at 100 EUR and sold at 130 EUR is a 300 EUR gain; costing the units in
+ # USD (150 each at 1.5) but labelling them EUR reported a 200 EUR loss.
+ test "a closing sale of a position held in another currency realises its gain in that currency" do
+ account, security = cross_currency_account
+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.new(2026, 3, 2), rate: 1.5)
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100, currency: "EUR")
+ sell = create_trade(security, account: account, qty: -10, date: Date.new(2026, 3, 4), price: 130, currency: "EUR").entryable
+ account.holdings.create!(security: security, date: Date.new(2026, 3, 4), qty: 0, price: 0,
+ amount: 0, currency: "EUR", cost_basis: nil)
+
+ gain = sell.realized_gain_loss
+
+ assert_equal Money.new(BigDecimal(1000), "EUR"), gain.previous
+ assert_equal Money.new(BigDecimal(300), "EUR"), gain.value
+ end
+
+ # A split applies at the open of its ex-date, before that day's trades. 10
+ # bought at 100 become 20 at 50 on a 2-for-1 split; all 20 sold that day at
+ # 70 is 1,400 against 1,000, a 400 gain. Pricing the 20 units at the
+ # pre-split 100 would report a 600 loss.
+ test "a closing sale after a split uses the split-adjusted cost" do
+ account, security = cross_currency_account
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100)
+ security.splits.create!(ex_date: Date.new(2026, 3, 4), numerator: 2, denominator: 1, source: "manual")
+ sell = create_trade(security, account: account, qty: -20, date: Date.new(2026, 3, 4), price: 70).entryable
+ closed_snapshot(account, security, Date.new(2026, 3, 4))
+
+ gain = sell.realized_gain_loss
+
+ assert_not_nil gain
+ assert_equal BigDecimal(1000), gain.previous.amount
+ assert_equal BigDecimal(400), gain.value.amount
+ end
+
+ # A sale that leaves units held keeps reading the snapshot's own figure. The
+ # stored 160 is deliberately not what the trades replay to (150), so this
+ # fails if the replay ever displaces a basis the snapshot has: 5 sold at 180
+ # is 900 against 800, a 100 gain.
+ test "a partial sale's realized gain is unchanged" do
+ account, security = cross_currency_account
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100)
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 3), price: 200)
+ sell = create_trade(security, account: account, qty: -5, date: Date.new(2026, 3, 4), price: 180).entryable
+ account.holdings.create!(security: security, date: Date.new(2026, 3, 4), qty: 15, price: 180,
+ amount: BigDecimal(2700), currency: "USD", cost_basis: 160)
+
+ gain = sell.realized_gain_loss
+
+ assert_equal BigDecimal(800), gain.previous.amount
+ assert_equal BigDecimal(100), gain.value.amount
+ end
+
+ # With no stored basis, the snapshot's own figure is unknown, and the cost
+ # before the sale is all the gain needs. Replaying the history for the
+ # snapshot first, only to find a closed position, then replaying it again up
+ # to the sale, reads every trade and split twice on each sale Reports prices.
+ test "realized gain on a closing sale with no stored basis replays the history once" do
+ account, security = cross_currency_account
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100)
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 3), price: 200)
+ sell = create_trade(security, account: account, qty: -20, date: Date.new(2026, 3, 4), price: 180).entryable
+ closed_snapshot(account, security, Date.new(2026, 3, 4))
+ sell.entry.account
+
+ gain = nil
+ # Uncached, so a second replay counts rather than hitting the query cache.
+ queries = ActiveRecord::Base.uncached { capture_sql_queries { gain = sell.realized_gain_loss } }
+
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "trades"') }
+ assert_equal 1, queries.count { |sql| sql.include?('FROM "security_splits"') }
+ assert_equal BigDecimal(600), gain.value.amount
+ end
+
+ # Units sold beyond the position are priced at the acquisitions that cover
+ # them, as a fifo sale's shortfall is (Holding::LotBook#cover): 5 held at
+ # 100 and 5 covered by the same day's later buy at 200 is 1,500 against
+ # 1,800 of proceeds.
+ test "a sale beyond the position prices the units held at the average and the rest at their cover" do
+ account, security = cross_currency_account
+ closed_snapshot(account, security, Date.new(2026, 3, 1))
+ create_trade(security, account: account, qty: 5, date: Date.new(2026, 3, 2), price: 100)
+ sale = create_trade(security, account: account, qty: -10, date: Date.new(2026, 3, 3), price: 180)
+ cover = create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 3), price: 200)
+ cover.update_columns(created_at: sale.created_at + 1.second)
+
+ assert_equal BigDecimal(300), sale.entryable.realized_gain_loss.value.amount
+ end
+
+ # An earlier sale's shortfall is covered first, so this one takes the 200.
+ test "a sale beyond the position is covered after an earlier sale's shortfall" do
+ account, security = cross_currency_account
+ closed_snapshot(account, security, Date.new(2026, 3, 1))
+ create_trade(security, account: account, qty: -5, date: Date.new(2026, 3, 2), price: 180)
+ sale = create_trade(security, account: account, qty: -5, date: Date.new(2026, 3, 3), price: 180)
+ create_trade(security, account: account, qty: 5, date: Date.new(2026, 3, 4), price: 100)
+ create_trade(security, account: account, qty: 5, date: Date.new(2026, 3, 5), price: 200)
+
+ assert_equal BigDecimal(-100), sale.entryable.realized_gain_loss.value.amount
+ end
+
+ # Nothing covers the shortfall, a transfer in or a foreign buy with no rate
+ # covers it at a cost nothing here knows, a split comes before the cover, or
+ # the units held have no known cost: each leaves the sale's cost unknown.
+ test "a sale beyond the position with no known cover realises no gain" do
+ cases = {
+ uncovered: [ [ 5, 100, 2 ], [ :sale, 3 ] ],
+ transfer_cover: [ [ :sale, 2 ], [ :transfer, 3 ], [ 5, 100, 4 ] ],
+ unpriced_cover: [ [ :sale, 2 ], [ :unpriced, 3 ] ],
+ split_first: [ [ :sale, 2 ], [ :split, 3 ], [ 10, 100, 4 ] ],
+ unknown_held: [ [ :transfer, 2 ], [ :sale, 3 ], [ 10, 200, 4 ] ]
+ }
+
+ gains = cases.transform_values do |steps|
+ account, security = cross_currency_account
+ closed_snapshot(account, security, Date.new(2026, 3, 1))
+ sale = nil
+ steps.each do |kind, *rest|
+ day = Date.new(2026, 3, rest.last)
+ case kind
+ when :sale then sale = create_trade(security, account: account, qty: -10, date: day, price: 180)
+ when :transfer
+ moved_in = create_trade(security, account: account, qty: 5, date: day, price: 100)
+ moved_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ when :split then security.splits.create!(ex_date: day, numerator: 2, denominator: 1, source: "manual")
+ when :unpriced then create_trade(security, account: account, qty: 10, date: day, price: 100, currency: "CAD")
+ else create_trade(security, account: account, qty: kind, date: day, price: rest.first)
+ end
+ end
+ sale.entryable.realized_gain_loss
+ end
+
+ assert_equal cases.keys.index_with(nil), gains
+ end
+
+ # A reverse-synced account with two shares from before its first imported
+ # trade: 10 bought, 5 moved in, 15 sold, 8 bought at 150, then 3 sold. The
+ # -15 sale left two shares, so the transferred units were never cleared out
+ # and the cost of what the later sale disposes of is unknown -- pricing it
+ # at the rebuy's 150 would book a gain the history cannot support.
+ test "a sale after opening shares kept transferred units held realises no gain" do
+ account, security = cross_currency_account
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100)
+ transfer_in = create_trade(security, account: account, qty: 5, date: Date.new(2026, 3, 3), price: 120)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ create_trade(security, account: account, qty: -15, date: Date.new(2026, 3, 4), price: 130)
+ create_trade(security, account: account, qty: 8, date: Date.new(2026, 3, 5), price: 150)
+ sell = create_trade(security, account: account, qty: -3, date: Date.new(2026, 3, 6), price: 170).entryable
+ account.holdings.create!(security: security, date: Date.new(2026, 3, 6), qty: 7, price: 170,
+ amount: BigDecimal(1190), currency: "USD", cost_basis: nil)
+
+ assert_nil sell.realized_gain_loss
+ end
+
+ # The latest snapshot on or before the sale can predate trades the replay
+ # still needs. Its quantity explains the trades up to its own date only:
+ # the 8 held on 3/5 is the whole history (10 in, 5 moved in, 15 sold, 8
+ # bought), so the position did close and the transfer is released. The 3
+ # sold on 3/6 came after the snapshot, and undoing it too would invent 3
+ # opening shares that keep the transfer held. 2 sold at 170 against 150 is
+ # a 40 gain.
+ test "a sale after the snapshot's date walks back only the snapshot's trades" do
+ account, security = cross_currency_account
+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 2), price: 100)
+ transfer_in = create_trade(security, account: account, qty: 5, date: Date.new(2026, 3, 3), price: 120)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ create_trade(security, account: account, qty: -15, date: Date.new(2026, 3, 4), price: 130)
+ create_trade(security, account: account, qty: 8, date: Date.new(2026, 3, 5), price: 150)
+ create_trade(security, account: account, qty: -3, date: Date.new(2026, 3, 6), price: 160)
+ sell = create_trade(security, account: account, qty: -2, date: Date.new(2026, 3, 7), price: 170).entryable
+ account.holdings.create!(security: security, date: Date.new(2026, 3, 5), qty: 8, price: 150,
+ amount: BigDecimal(1200), currency: "USD", cost_basis: nil)
+
+ gain = sell.realized_gain_loss
+
+ assert_not_nil gain, "the history explains the whole position, so the rebuy is the cost"
+ assert_equal BigDecimal(300), gain.previous.amount
+ assert_equal BigDecimal(40), gain.value.amount
+ end
+
# A sale is measured against its security's latest position on or before the
# sale: one row. Preloading used to read every holding of the sale's account
# instead, a row per security per day of its history.
@@ -442,6 +680,13 @@ class TradeTest < ActiveSupport::TestCase
create_trade(security, account: account, qty: -2, date: date, price: 150, fee: fee, currency: "EUR").entryable
end
+ # The snapshot the calculators write on the day a position closes: nothing
+ # held and no basis.
+ def closed_snapshot(account, security, date)
+ account.holdings.create!(security: security, date: date, qty: 0, price: 0,
+ amount: 0, currency: "USD", cost_basis: nil)
+ end
+
def cross_currency_account
account = families(:empty).accounts.create!(
name: "Brokerage", balance: 10_000, currency: "USD", accountable: Investment.new