Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Replace the cost-basis tracker with an in-memory lot book (#4495)

jaysbeekay562fe096d149
diff --git a/app/models/holding/cost_basis_tracker.rb b/app/models/holding/cost_basis_tracker.rb
index 43937194c0..f15b17bdf6 100644
--- a/app/models/holding/cost_basis_tracker.rb
+++ b/app/models/holding/cost_basis_tracker.rb
@@ -1,77 +1,5 @@
-# Tracks weighted-average cost basis for a single security as trades are
-# applied in chronological order.
-#
-# 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
-# position is fully closed the tracker resets so a later repurchase starts from
-# a clean basis. Without this relief, cost basis would be averaged over every
-# buy the account ever made for the security — corrupting the figure after a
-# position is sold off and bought again.
-#
-# Prices are expected in the account's currency (callers convert before
-# applying), so the tracker itself is currency-agnostic.
-#
-# A buy whose price is unknown (nil, e.g. no exchange rate for its day) makes
-# the average unknown until the position is fully closed. Skipping it instead
-# would average the known buys over fewer units than are held -- a figure that
-# looks measured and is not.
-class Holding::CostBasisTracker
- def initialize
- reset
- end
-
- # Applies a trade by its signed quantity: positive is a buy, negative a sell.
- def apply(price, qty)
- return if qty.nil?
-
- qty = qty.to_d
- return if qty.zero?
-
- qty.positive? ? buy(price, qty) : sell(qty)
- end
-
- def buy(price, qty)
- qty = qty&.to_d
- return if qty.nil? || !qty.positive?
-
- @unknown = true if price.nil?
- @total_cost += price.to_d * qty unless price.nil?
- @total_qty += qty
- end
-
- def sell(qty)
- qty = qty&.to_d
- return if qty.nil? || qty.zero? || @total_qty.zero?
-
- # Relieve at the current average cost so the per-share average is unchanged.
- # Guard against over-selling more than is currently held.
- relieved_qty = [ qty.abs, @total_qty ].min
- @total_cost -= (@total_cost / @total_qty) * relieved_qty
- @total_qty -= relieved_qty
-
- # Coercing to BigDecimal keeps arithmetic exact, so a full liquidation lands
- # on exactly zero and the reset fires (Float math could leave a tiny remainder).
- reset if @total_qty <= 0
- end
-
- # A split changes the share count and not the money invested, so total cost
- # stays and the per-share average moves by the inverse of the ratio.
- def split(ratio)
- @total_qty = Security::Split.scale(@total_qty, ratio)
- end
-
- # 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 nil if @total_qty.zero? || @unknown
-
- @total_cost / @total_qty
- end
-
- private
- def reset
- @total_cost = BigDecimal("0")
- @total_qty = BigDecimal("0")
- @unknown = false
- end
+# 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.
+class Holding::CostBasisTracker < Holding::LotBook
end
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index 2ba5ee814c..33b7941d4b 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -6,9 +6,10 @@ class Holding::ForwardCalculator
def initialize(account, security_ids: nil)
@account = account
@security_ids = security_ids
- # Track weighted-average cost basis per security, relieving sells so the
- # figure stays correct after a position is fully sold and repurchased.
- @cost_basis_trackers = Hash.new { |h, k| h[k] = Holding::CostBasisTracker.new }
+ # 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 }
# 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.
@@ -73,13 +74,13 @@ class Holding::ForwardCalculator
# A split takes effect at the open of its ex-date, before that day's trades,
# which are already in post-split shares (#249). It scales the position and
- # its cost-basis tracker together, so total cost carries across unchanged.
+ # its lot book together, so total cost carries across unchanged.
def apply_splits(opening_portfolio, date)
opening_portfolio.to_h do |security_id, qty|
ratio = portfolio_cache.get_split_ratio(security_id, date)
next [ security_id, qty ] unless ratio
- @cost_basis_trackers[security_id].split(ratio)
+ @lot_books[security_id].split(ratio)
[ security_id, Security::Split.scale(qty, ratio) ]
end
end
@@ -107,11 +108,12 @@ class Holding::ForwardCalculator
# (like a sell) rather than leaving them to contaminate a later buy.
if trade.qty.positive?
@transferred_security_ids << security_id
+ @lot_books[security_id].add_unknown(trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)
else
- @cost_basis_trackers[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)
+ @lot_books[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)
end
else
- @cost_basis_trackers[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)
+ @lot_books[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)
end
portfolio[security_id] = previous_quantity + trade.qty
@@ -130,6 +132,6 @@ class Holding::ForwardCalculator
def cost_basis_for(security_id, currency)
return nil if @transferred_security_ids.include?(security_id)
- @cost_basis_trackers[security_id].average_cost
+ @lot_books[security_id].average_cost
end
end
diff --git a/app/models/holding/lot_book.rb b/app/models/holding/lot_book.rb
new file mode 100644
index 0000000000..36d825be0b
--- /dev/null
+++ b/app/models/holding/lot_book.rb
@@ -0,0 +1,150 @@
+# The lots of a single security in one account, built as its trades are applied
+# in chronological order.
+#
+# Every acquisition is one lot, keyed by its source entry, with its own
+# 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.
+#
+# 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
+# lot quantities carry BigDecimal rounding the pool does not; relief now rounds
+# at the trade quantity scale and #rescale_lots puts the difference back, so
+# the open sum stays exact to the last digit and every stored figure is
+# computed from the pool. A transfer-in stays outside the pool; the calculators
+# report a position holding one as unknown.
+#
+# 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
+# position is fully closed the pool resets so a later repurchase starts from a
+# clean basis. A buy whose price is unknown makes the average unknown until the
+# position is fully closed.
+#
+# Prices are expected in the account's currency (callers convert before
+# applying), so the book itself is currency-agnostic.
+class Holding::LotBook
+ Lot = Data.define(:source_id, :acquired_on, :qty, :unit_cost)
+
+ attr_reader :lots
+
+ def initialize
+ @lots = []
+ reset
+ 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?
+
+ qty = qty.to_d
+ return if qty.zero?
+
+ qty.positive? ? buy(price, qty, source_id: source_id, acquired_on: acquired_on) : sell(qty)
+ end
+
+ def buy(price, qty, source_id: nil, acquired_on: nil)
+ qty = qty&.to_d
+ return if qty.nil? || !qty.positive?
+
+ add_lot(source_id, acquired_on, qty, price&.to_d)
+ @unknown = true if price.nil?
+ @total_cost += price.to_d * qty unless price.nil?
+ @total_qty += qty
+ end
+
+ # Units that arrived by internal movement, at a cost nothing here knows.
+ def add_unknown(qty, source_id: nil, acquired_on: nil)
+ qty = qty&.to_d
+ return if qty.nil? || !qty.positive?
+
+ add_lot(source_id, acquired_on, qty, nil)
+ end
+
+ def sell(qty)
+ qty = qty&.to_d
+ return if qty.nil? || qty.zero?
+
+ relieve_lots(qty.abs)
+ return if @total_qty.zero?
+
+ # Relieve at the current average cost so the per-share average is unchanged.
+ # Guard against over-selling more than is currently held.
+ relieved_qty = [ qty.abs, @total_qty ].min
+ @total_cost -= (@total_cost / @total_qty) * relieved_qty
+ @total_qty -= relieved_qty
+
+ # Coercing to BigDecimal keeps arithmetic exact, so a full liquidation lands
+ # on exactly zero and the reset fires (Float math could leave a tiny remainder).
+ reset if @total_qty <= 0
+ end
+
+ # A split changes the share count and not the money invested, so total cost
+ # stays and the per-share average moves by the inverse of the ratio. Each lot
+ # is restated the same way.
+ def split(ratio)
+ @total_qty = Security::Split.scale(@total_qty, ratio)
+ rescale_lots(Security::Split.scale(open_qty, ratio)) do |lot|
+ lot.with(
+ qty: Security::Split.scale(lot.qty, ratio),
+ unit_cost: lot.unit_cost && lot.unit_cost * ratio.denominator / ratio.numerator
+ )
+ end
+ end
+
+ # 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 nil if @total_qty.zero? || @unknown
+
+ @total_cost / @total_qty
+ end
+
+ def open_qty
+ @lots.sum(BigDecimal("0"), &:qty)
+ end
+
+ private
+ def reset
+ @total_cost = BigDecimal("0")
+ @total_qty = BigDecimal("0")
+ @unknown = false
+ end
+
+ def add_lot(source_id, acquired_on, qty, unit_cost)
+ @lots << Lot.new(source_id: source_id, acquired_on: acquired_on, qty: qty, unit_cost: unit_cost)
+ end
+
+ # Pro-rata relief across every open lot; an oversell closes them all.
+ # Rounding at the split scale, with #rescale_lots' drift correction, keeps
+ # each quantity bounded and the open sum exact — without
+ # it, repeated partial relief at non-terminating ratios grows each
+ # quantity one decimal place per step.
+ def relieve_lots(qty)
+ open = open_qty
+ return if open.zero?
+
+ remaining = open - [ qty, open ].min
+ rescale_lots(remaining) { |lot| lot.with(qty: (lot.qty * remaining / open).round(Security::Split::QTY_SCALE)) }
+ end
+
+ # Restates each lot, then settles whatever rounding is left from the last
+ # lot back, so the lots always sum to exactly `target`.
+ def rescale_lots(target)
+ scaled = target.zero? ? [] : @lots.map { |lot| yield lot }
+ settle_drift(scaled, target - scaled.sum(BigDecimal("0"), &:qty))
+ @lots = scaled.select { |lot| lot.qty.positive? }
+ end
+
+ # A negative drift can exceed the last lot, which may have rounded to zero,
+ # so no lot gives up more than it holds.
+ def settle_drift(lots, drift)
+ lots.each_index.reverse_each do |index|
+ break if drift.zero?
+
+ correction = drift.positive? ? drift : -[ lots[index].qty, -drift ].min
+ lots[index] = lots[index].with(qty: lots[index].qty + correction)
+ drift -= correction
+ end
+ end
+end
diff --git a/app/models/holding/portfolio_cache.rb b/app/models/holding/portfolio_cache.rb
index acbd632521..692bc3814e 100644
--- a/app/models/holding/portfolio_cache.rb
+++ b/app/models/holding/portfolio_cache.rb
@@ -112,8 +112,17 @@ class Holding::PortfolioCache
@split_ratios ||= splits.to_h { |split| [ [ split.security_id, split.ex_date ], split.ratio ] }
end
+ # Entry.chronological, except that trades sharing a date and created_at, as
+ # a batch import stamps them, replay acquisitions before disposals: their
+ # ids say nothing about which came first, and a sale cannot precede the
+ # purchase it sells from. Rows with different created_at keep their order.
def trades
- @trades ||= account.entries.includes(entryable: :security).trades.chronological.to_a
+ @trades ||= chronological_trades
+ .sort_by.with_index { |entry, index| [ entry.date, entry.created_at, entry.entryable.qty.negative? ? 1 : 0, index ] }
+ end
+
+ def chronological_trades
+ @chronological_trades ||= account.entries.includes(entryable: :security).trades.chronological.to_a
end
def trades_by_date
@@ -121,7 +130,8 @@ class Holding::PortfolioCache
end
def trades_by_security_id
- @trades_by_security_id ||= trades.group_by { |t| t.entryable.security_id }
+ # Which trade's price stands for a day must not depend on the replay order.
+ @trades_by_security_id ||= chronological_trades.group_by { |t| t.entryable.security_id }
end
def holdings
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index e29e795182..9421994904 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -127,12 +127,13 @@ 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] = [] }
- trackers = Hash.new { |h, k| h[k] = Holding::CostBasisTracker.new }
+ @lot_books = Hash.new { |h, k| h[k] = Holding::LotBook.new }
open_unknown_start = {}
- # get_trades is already chronological (date, then created_at, then id).
+ # get_trades is already in replay order (date, created_at, acquisitions
+ # before disposals, then id).
# Re-sorting by date alone is unstable and could reorder same-day trades,
- # which matters because the tracker is order-sensitive once sells relieve.
+ # which matters because the lot book is order-sensitive once sells relieve.
trades = portfolio_cache.get_trades
events = replay_events(trades)
@@ -163,8 +164,8 @@ class Holding::ReverseCalculator
next unless positions.key?(security_id)
positions[security_id] = Security::Split.scale(positions[security_id], event.ratio)
- trackers[security_id].split(event.ratio)
- @cost_basis_snapshots[security_id] << [ event.ex_date, trackers[security_id].average_cost ]
+ @lot_books[security_id].split(event.ratio)
+ @cost_basis_snapshots[security_id] << [ event.ex_date, @lot_books[security_id].average_cost ]
next
end
@@ -179,20 +180,21 @@ class Holding::ReverseCalculator
# transfers only remove units, so relieve them at the running average.
if trade.qty.positive?
open_unknown_start[security_id] ||= trade_entry.date
+ @lot_books[security_id].add_unknown(trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)
else
- trackers[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)
- @cost_basis_snapshots[security_id] << [ trade_entry.date, trackers[security_id].average_cost ]
+ @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
else
- tracker = trackers[security_id]
+ book = @lot_books[security_id]
# Buys raise the basis; sells relieve quantity at the running average, and a
# full liquidation resets it so a later repurchase starts from a clean basis.
- tracker.apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)
+ book.apply(effective_trade_price(trade, date: trade_entry.date), trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)
# 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, tracker.average_cost ]
+ @cost_basis_snapshots[security_id] << [ trade_entry.date, book.average_cost ]
end
# Close an open unknown span only on a genuine downward crossing through
diff --git a/test/models/holding/forward_calculator_test.rb b/test/models/holding/forward_calculator_test.rb
index cde043015e..57533cef4b 100644
--- a/test/models/holding/forward_calculator_test.rb
+++ b/test/models/holding/forward_calculator_test.rb
@@ -208,6 +208,41 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
assert_equal BigDecimal("480"), current.cost_basis
end
+ # A batch import stamps every row with one created_at, so only the ids, which
+ # mean nothing, would order a day's trades: a sale could replay before the
+ # purchase it sells from. With nothing else to go on, the purchase goes first.
+ test "a same-day sale and purchase stamped together replay the purchase first" do
+ load_prices
+
+ create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ sale = create_trade(@voo, qty: -10, date: 2.days.ago.to_date, price: 480, account: @account)
+ purchase = create_trade(@voo, qty: 10, date: 2.days.ago.to_date, price: 200, account: @account)
+ stamp_together(sale, purchase)
+
+ current = Holding::ForwardCalculator.new(@account).calculate
+ .find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ # 10 at 100 and 10 at 200 average to 150; selling 10 leaves 10 at 150. Had
+ # the sale replayed first it would have sold the 100s and left 10 at 200.
+ assert_equal BigDecimal("150"), current.cost_basis
+ end
+
+ test "a same-day sale entered before a purchase replays first when their created_at differ" do
+ load_prices
+
+ create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ sale = create_trade(@voo, qty: -10, date: 2.days.ago.to_date, price: 480, account: @account)
+ purchase = create_trade(@voo, qty: 10, date: 2.days.ago.to_date, price: 200, account: @account)
+ Entry.where(id: sale.id).update_all(created_at: 2.hours.ago)
+ Entry.where(id: purchase.id).update_all(created_at: 1.hour.ago)
+
+ current = Holding::ForwardCalculator.new(@account).calculate
+ .find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ # The order the user entered them in is theirs to set.
+ assert_equal BigDecimal("200"), current.cost_basis
+ end
+
# An acquisition fee is part of what the units cost, so it belongs in the
# basis. Providers already record it on the trade; nothing used to read it.
test "an acquisition fee is part of the cost basis" do
@@ -453,6 +488,14 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
end
end
+ # Gives the two entries one created_at and ids that sort sale-first, as a
+ # batch import with unlucky UUIDs would.
+ def stamp_together(sale, purchase)
+ Entry.where(id: [ sale.id, purchase.id ]).update_all(created_at: Time.zone.parse("2026-01-01 10:00:00"))
+ Entry.where(id: sale.id).update_all(id: "00000000-0000-0000-0000-000000000001")
+ Entry.where(id: purchase.id).update_all(id: "ffffffff-ffff-ffff-ffff-ffffffffffff")
+ end
+
def load_prices
@voo = Security.create!(ticker: "VOO", name: "Vanguard S&P 500 ETF")
Security::Price.create!(security: @voo, date: 4.days.ago.to_date, price: 460)
diff --git a/test/models/holding/lot_book_test.rb b/test/models/holding/lot_book_test.rb
new file mode 100644
index 0000000000..6d62c22ea4
--- /dev/null
+++ b/test/models/holding/lot_book_test.rb
@@ -0,0 +1,521 @@
+require "test_helper"
+require "minitest/mock"
+
+class Holding::LotBookTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ # Holding::CostBasisTracker exactly as it stood before the lot book, kept here
+ # as the oracle: under the average method the lot book must give the same
+ # figure at every step, to the last digit.
+ class ReferenceTracker
+ def initialize
+ reset
+ end
+
+ def apply(price, qty)
+ return if qty.nil?
+
+ qty = qty.to_d
+ return if qty.zero?
+
+ qty.positive? ? buy(price, qty) : sell(qty)
+ end
+
+ def buy(price, qty)
+ qty = qty&.to_d
+ return if qty.nil? || !qty.positive?
+
+ @unknown = true if price.nil?
+ @total_cost += price.to_d * qty unless price.nil?
+ @total_qty += qty
+ end
+
+ def sell(qty)
+ qty = qty&.to_d
+ return if qty.nil? || qty.zero? || @total_qty.zero?
+
+ relieved_qty = [ qty.abs, @total_qty ].min
+ @total_cost -= (@total_cost / @total_qty) * relieved_qty
+ @total_qty -= relieved_qty
+
+ reset if @total_qty <= 0
+ end
+
+ def split(ratio)
+ @total_qty = Security::Split.scale(@total_qty, ratio)
+ end
+
+ def average_cost
+ return nil if @total_qty.zero? || @unknown
+
+ @total_cost / @total_qty
+ end
+
+ private
+ def reset
+ @total_cost = BigDecimal("0")
+ @total_qty = BigDecimal("0")
+ @unknown = false
+ end
+ end
+
+ # The oracle behind the calculators' calls: the lot arguments are ignored and
+ # a transfer-in is a no-op, which is what the calculators did before lots.
+ class ReferenceCalculatorTracker < ReferenceTracker
+ def apply(price, qty, **)
+ super(price, qty)
+ end
+
+ def add_unknown(*, **); end
+ end
+
+ THIRD = BigDecimal("10") / 3
+
+ SEQUENCES = {
+ "buys, partial sells, full liquidation and a repurchase" => [
+ [ :buy, 100, 10 ], [ :buy, 200, 10 ], [ :sell, 5 ], [ :buy, 150, 3 ], [ :sell, 18 ], [ :buy, 50, 2 ]
+ ],
+ "the two-parcel example" => [
+ [ :buy, 12, 60 ], [ :buy, 20, 40 ], [ :sell, 40 ]
+ ],
+ "non-terminating relief and splits" => [
+ [ :buy, 10, 10 ], [ :buy, BigDecimal("13.37"), 20 ], [ :sell, THIRD ], [ :split, Rational(3, 1) ],
+ [ :sell, THIRD ], [ :buy, BigDecimal("7.77"), 1 ], [ :split, Rational(1, 7) ], [ :sell, BigDecimal("0.123") ]
+ ],
+ "an unknown price, an oversell and a transfer lot" => [
+ [ :buy, 10, 5 ], [ :unknown, 4 ], [ :buy, nil, 2 ], [ :sell, 3 ], [ :sell, 100 ], [ :buy, 9, 3 ],
+ [ :unknown, 2 ], [ :sell, 1 ]
+ ]
+ }.freeze
+
+ SEQUENCES.each do |name, steps|
+ test "lot book under average reproduces the tracker: #{name}" do
+ book = Holding::LotBook.new
+ reference = ReferenceTracker.new
+
+ steps.each_with_index do |(op, *args), index|
+ case op
+ when :buy
+ book.apply(args[0]&.to_d, args[1], source_id: index, acquired_on: Date.new(2024, 1, 1) + index)
+ reference.apply(args[0]&.to_d, args[1])
+ when :sell
+ book.apply(nil, -args[0])
+ reference.apply(nil, -args[0])
+ when :split
+ book.split(args[0])
+ reference.split(args[0])
+ when :unknown
+ # A transfer-in never reached the tracker.
+ book.add_unknown(args[0], source_id: index, acquired_on: Date.new(2024, 1, 1) + index)
+ end
+
+ if reference.average_cost.nil?
+ assert_nil book.average_cost, "step #{index} (#{op})"
+ else
+ assert_equal reference.average_cost, book.average_cost, "step #{index} (#{op})"
+ end
+ end
+ end
+ end
+
+ test "each acquisition is one lot, keyed by its source entry, and a later buy leaves earlier lots alone" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("12"), 60, source_id: "buy-1", acquired_on: Date.new(2024, 1, 10))
+ first = book.lots.first
+
+ book.apply(BigDecimal("20"), 40, source_id: "buy-2", acquired_on: Date.new(2024, 3, 5))
+
+ assert_equal %w[buy-1 buy-2], book.lots.map(&:source_id)
+ assert_equal [ Date.new(2024, 1, 10), Date.new(2024, 3, 5) ], book.lots.map(&:acquired_on)
+ assert_equal first, book.lots.first, "the earlier lot is untouched by the later buy"
+ assert_equal [ 12, 20 ], book.lots.map(&:unit_cost)
+ end
+
+ test "a sale under average relieves every lot pro rata and keeps each lot's own cost" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("12"), 60, source_id: "a")
+ book.apply(BigDecimal("20"), 40, source_id: "b")
+
+ book.apply(nil, -40)
+
+ assert_equal [ 36, 24 ], book.lots.map(&:qty)
+ assert_equal [ 12, 20 ], book.lots.map(&:unit_cost)
+ assert_equal BigDecimal("15.2"), book.average_cost
+ assert_equal book.average_cost, lots_weighted_mean(book)
+ end
+
+ test "a split restates every lot: more units at a lower cost, same money" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("12"), 60, source_id: "a")
+ book.apply(BigDecimal("20"), 40, source_id: "b")
+
+ book.split(Rational(2, 1))
+
+ assert_equal [ 120, 80 ], book.lots.map(&:qty)
+ assert_equal [ 6, 10 ], book.lots.map(&:unit_cost)
+ assert_equal BigDecimal("7.6"), book.average_cost
+ end
+
+ test "a transfer-in is a lot of unknown cost and does not move the average" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("20"), 40, source_id: "buy")
+ book.add_unknown(60, source_id: "transfer", acquired_on: Date.new(2024, 1, 10))
+
+ assert_equal [ nil ], book.lots.select { |lot| lot.source_id == "transfer" }.map(&:unit_cost)
+ assert_equal 100, book.open_qty
+ assert_equal 20, book.average_cost, "the calculators, not the pool, report the position as unknown"
+ end
+
+ test "the lots' weighted mean matches the average to within rounding of a non-terminating relief" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("10"), 10, source_id: "a")
+ book.apply(BigDecimal("13.37"), 20, source_id: "b")
+ book.apply(nil, -THIRD)
+ book.split(Rational(3, 1))
+ book.apply(nil, -THIRD)
+
+ assert_in_delta book.average_cost, lots_weighted_mean(book), BigDecimal("1e-12")
+ end
+
+ test "sum of open lot qty equals the running position after every step" do
+ book = Holding::LotBook.new
+ position = BigDecimal("0")
+ steps = [
+ [ :buy, 10, 10 ], [ :buy, 12, 5 ], [ :unknown, 4 ], [ :sell, 7 ], [ :split, Rational(2, 1) ],
+ [ :sell, THIRD ], [ :split, Rational(1, 3) ], [ :sell, 3 ], [ :buy, 9, 2 ]
+ ]
+
+ steps.each_with_index do |(op, *args), index|
+ case op
+ when :buy
+ book.apply(args[0].to_d, args[1], source_id: index)
+ position += args[1]
+ when :unknown
+ book.add_unknown(args[0], source_id: index)
+ position += args[0]
+ when :sell
+ book.apply(nil, -args[0])
+ position -= args[0]
+ when :split
+ book.split(args[0])
+ position = Security::Split.scale(position, args[0])
+ end
+
+ assert_equal position, book.open_qty, "step #{index} (#{op})"
+ assert_equal position, book.lots.sum(BigDecimal("0"), &:qty), "step #{index} (#{op})"
+ end
+ end
+
+ test "selling out closes every lot, a transfer lot included" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("10"), 10, source_id: "a")
+ book.add_unknown(5, source_id: "t")
+
+ book.apply(nil, -15)
+
+ assert_empty book.lots
+ assert_equal 0, book.open_qty
+ end
+
+ # The pool never held the transferred units, so this sale empties it and it
+ # resets. The position still holds 5 units, and the lots must still say so.
+ test "a sale that empties the priced pool leaves every lot's share of what is still held" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("10"), 10, source_id: "buy")
+ book.add_unknown(5, source_id: "transfer")
+
+ book.apply(nil, -10)
+
+ assert_nil book.average_cost
+ assert_equal 5, book.open_qty
+ assert_equal %w[buy transfer], book.lots.map(&:source_id)
+ end
+
+ test "the tracker keeps its public interface" do
+ tracker = Holding::CostBasisTracker.new
+ tracker.apply(BigDecimal("100"), BigDecimal("10"))
+ tracker.buy(BigDecimal("200"), BigDecimal("10"))
+ tracker.sell(BigDecimal("-5"))
+ tracker.split(Rational(2, 1))
+
+ assert_equal BigDecimal("75"), tracker.average_cost
+ end
+
+ # --- Through the calculators and the materializer -------------------------
+
+ test "materialize writes identical holdings with lots on the forward strategy" do
+ travel_to Time.zone.local(2024, 6, 10, 12) do
+ build_forward_fixture
+
+ reference = dump_after(:forward, reference: true) { seed_locked_row }
+ actual = dump_after(:forward, reference: false) { seed_locked_row }
+
+ assert_equal reference, actual
+ assert_fixture_not_vacuous(actual)
+ end
+ end
+
+ test "materialize writes identical holdings with lots on the reverse strategy" do
+ travel_to Time.zone.local(2024, 6, 10, 12) do
+ build_reverse_fixture
+
+ reference = dump_after(:reverse, reference: true) { seed_provider_rows }
+ actual = dump_after(:reverse, reference: false) { seed_provider_rows }
+
+ assert_equal reference, actual
+ assert_fixture_not_vacuous(actual)
+ assert(actual.any? { |row| row[4] == "provider" }, "a provider-only position is in the dump")
+ end
+ end
+
+ test "locked manual row keeps its value through re-materialization with lots present" do
+ travel_to Time.zone.local(2024, 6, 10, 12) do
+ build_forward_fixture
+ seed_locked_row
+ locked = @account.holdings.find_by!(security: @parcels, date: d(5))
+
+ Holding::Materializer.new(@account, strategy: :forward).materialize_holdings
+
+ locked.reload
+ assert_equal 99, locked.cost_basis
+ assert_equal "manual", locked.cost_basis_source
+ assert locked.cost_basis_locked
+ assert_equal BigDecimal("15.2"), @account.holdings.find_by!(security: @parcels, date: d(4)).cost_basis,
+ "the neighbouring unlocked row still takes the calculated figure"
+ end
+ end
+
+ test "transfer-in leaves the position unknown while its lot is held, and known once sold out" do
+ travel_to Time.zone.local(2024, 6, 10, 12) do
+ build_forward_fixture
+
+ calculator = Holding::ForwardCalculator.new(@account)
+ calculator.calculate
+ transfer_entry = @account.entries.find_by!(name: "Transfer in")
+
+ Holding::Materializer.new(@account, strategy: :forward).materialize_holdings
+
+ assert_nil cost_basis_on(@transferred, d(3)), "the transfer lot is held"
+ assert_nil cost_basis_on(@transferred, d(4))
+ assert_equal 15, cost_basis_on(@transferred, d(7)), "sold out on d5, then bought back at 15"
+ rebuy = @account.entries.find_by!(date: d(7), entryable_type: "Trade", entryable_id: Trade.where(security: @transferred).select(:id))
+ lots = calculator.instance_variable_get(:@lot_books)[@transferred.id].lots
+ assert_equal [ [ rebuy.id, d(7), 8, 15 ] ], lots.map { |lot| [ lot.source_id, lot.acquired_on, lot.qty, lot.unit_cost ] },
+ "the transfer lot and the first buy closed with the sell-out; only the rebuy is open"
+ assert_not_includes lots.map(&:source_id), transfer_entry.id
+ end
+ end
+
+ test "the reverse calculator books a lot per acquisition, a transfer-in included" do
+ travel_to Time.zone.local(2024, 6, 10, 12) do
+ build_reverse_fixture
+ seed_provider_rows
+ transfer, buy = @account.entries.where(entryable_id: Trade.where(security: @gapped).select(:id)).order(:date).to_a
+
+ calculator = Holding::ReverseCalculator.new(@account, portfolio_snapshot: Holding::PortfolioSnapshot.new(@account))
+ calculator.calculate
+
+ lots = calculator.instance_variable_get(:@lot_books)[@gapped.id].lots
+ assert_equal [ [ transfer.id, d(2), 5, nil ], [ buy.id, d(4), 5, 150 ] ],
+ lots.map { |lot| [ lot.source_id, lot.acquired_on, lot.qty, lot.unit_cost ] }
+ end
+ end
+
+ test "sum of open lot qty equals the trade-driven position on every date" do
+ travel_to Time.zone.local(2024, 6, 10, 12) do
+ build_forward_fixture
+ probe = PartitionProbe.new(@account, security_ids: [ @parcels.id, @transferred.id, @split.id ])
+
+ probe.calculate
+
+ assert_equal (d(1)..d(10)).count * 3, probe.checks.size, "every date for each of the three positions"
+ probe.checks.each do |date, security_id, position, open_qty|
+ assert_equal position.to_d, open_qty, "#{Security.find(security_id).ticker} on #{date}"
+ end
+ # Every movement kind is crossed: buy, sell, transfer, split.
+ assert(probe.checks.any? { |_, id, position, _| id == @split.id && position == 81 }, "after the 3-for-1 split and the sales")
+ assert(probe.checks.any? { |_, id, position, _| id == @transferred.id && position == 15 }, "the transfer lot is counted")
+ end
+ end
+
+ test "relief that rounds a lot away keeps the open sum exact" do
+ tiny = BigDecimal("1e-18")
+ book = Holding::LotBook.new
+ [ 3, 3, 3, 3, 3, 3, 2 ].each_with_index do |units, index|
+ book.apply(10, units * tiny, source_id: "buy-#{index}", acquired_on: Date.new(2024, 1, 1))
+ end
+
+ book.apply(10, -16 * tiny)
+
+ assert_equal 4 * tiny, book.open_qty
+ assert(book.lots.all? { |lot| lot.qty.positive? })
+ end
+
+ test "relief that rounds every lot down gives the rest to the last lot" do
+ book = Holding::LotBook.new
+ 3.times { |index| book.apply(10, 1, source_id: "buy-#{index}", acquired_on: Date.new(2024, 1, 1)) }
+
+ book.apply(10, -2)
+
+ assert_equal 1, book.open_qty
+ assert_equal [ BigDecimal("0.333333333333333333"), BigDecimal("0.333333333333333333"), BigDecimal("0.333333333333333334") ],
+ book.lots.map(&:qty)
+ end
+
+ test "repeated partial relief keeps lot quantities at the trade scale and the open sum exact" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("1"), 1, source_id: "a", acquired_on: Date.new(2024, 1, 1))
+ book.apply(BigDecimal("1"), 2, source_id: "b", acquired_on: Date.new(2024, 1, 2))
+
+ # Five halves of the open position: the first relief divides by three, so
+ # every lot quantity is a non-terminating decimal from there on.
+ 5.times { book.apply(nil, -BigDecimal("0.5")) }
+
+ assert_equal BigDecimal("0.5"), book.open_qty, "the last-lot drift correction keeps the open sum exact"
+ book.lots.each do |lot|
+ decimals = lot.qty.to_s("F").split(".").last.to_s.length
+ assert_operator decimals, :<=, Security::Split::QTY_SCALE,
+ "lot #{lot.source_id} has #{decimals} decimal places after five partial sells"
+ end
+ end
+
+ class PartitionProbe < Holding::ForwardCalculator
+ def checks
+ @checks ||= []
+ end
+
+ private
+ def build_holdings(portfolio, date, price_source: nil)
+ portfolio.each do |security_id, qty|
+ next unless @security_ids.include?(security_id)
+
+ checks << [ date, security_id, qty, @lot_books[security_id].open_qty ]
+ end
+ super
+ end
+ end
+
+ private
+ def d(day)
+ Date.new(2024, 6, day)
+ end
+
+ def lots_weighted_mean(book)
+ book.lots.sum { |lot| lot.qty * lot.unit_cost } / book.open_qty
+ end
+
+ def setup_account
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Lots", balance: 20000, cash_balance: 20000, currency: "USD", accountable: Investment.new)
+ 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, label: nil, fee: 0)
+ entry = create_trade(security, account: @account, qty: qty, price: price, date: d(day), fee: fee)
+ entry.entryable.update!(investment_activity_label: label) if label
+ entry
+ end
+
+ # Four positions on one forward account: the two-parcel example, a
+ # transfer-in that is sold out and bought back, a negative position a
+ # transfer brings back to zero, and a 3-for-1 split with non-terminating
+ # sales and a fee.
+ def build_forward_fixture
+ setup_account
+ @parcels = priced_security("LOTA", 30)
+ @transferred = priced_security("LOTB", 30)
+ @negative = priced_security("LOTC", 30)
+ @split = priced_security("LOTD", 30)
+
+ trade(@parcels, 60, 12, 2)
+ trade(@parcels, 40, 20, 4)
+ trade(@parcels, -40, 25, 6)
+
+ trade(@transferred, 5, 30, 2, label: Trade::TRANSFER_LABEL).update!(name: "Transfer in")
+ trade(@transferred, 10, 10, 3)
+ trade(@transferred, -15, 30, 5)
+ trade(@transferred, 8, 15, 7)
+
+ trade(@negative, -5, 30, 2)
+ trade(@negative, 5, 30, 3, label: Trade::TRANSFER_LABEL)
+ trade(@negative, 10, 10, 4)
+ trade(@negative, -10, 30, 6)
+ trade(@negative, 10, 20, 8)
+
+ trade(@split, 10, 10, 2)
+ trade(@split, 20, BigDecimal("13.37"), 3)
+ Security::Split.create!(security: @split, ex_date: d(4), numerator: 3, denominator: 1, source: "manual")
+ trade(@split, -6, 30, 5)
+ trade(@split, -3, 30, 6)
+ trade(@split, 1, BigDecimal("7.77"), 7, fee: BigDecimal("1.5"))
+ end
+
+ def seed_locked_row
+ @account.holdings.create!(
+ security: @parcels, date: d(5), qty: 100, price: 30, amount: 3000, currency: "USD",
+ cost_basis: 99, cost_basis_source: "manual", cost_basis_locked: true
+ )
+ end
+
+ # A linked account: a provider-only position with no trades, a position
+ # with units held before its first imported trade, and a gapped import
+ # whose trades net to more than the provider reports.
+ def build_reverse_fixture
+ setup_account
+ @provider_only = priced_security("LOTE", 30)
+ @opening = priced_security("LOTF", 30)
+ @gapped = priced_security("LOTG", 30)
+
+ trade(@opening, 10, 100, 3)
+ trade(@opening, -4, 30, 5)
+ trade(@opening, 2, 110, 7)
+
+ trade(@gapped, 5, 30, 2, label: Trade::TRANSFER_LABEL)
+ trade(@gapped, 5, 150, 4)
+
+ 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 seed_provider_rows
+ { @provider_only => [ 10, 50 ], @opening => [ 10, nil ], @gapped => [ 3, nil ] }.each do |security, (qty, basis)|
+ @account.holdings.create!(
+ security: security, date: d(10), qty: qty, price: 30, amount: qty * 30, currency: "USD",
+ cost_basis: basis, cost_basis_source: basis && "provider", account_provider: @account_provider
+ )
+ end
+ end
+
+ # Materializes from an empty holdings table, so a figure left by an earlier
+ # run cannot stand in for one this run failed to write.
+ def dump_after(strategy, reference:)
+ @account.holdings.delete_all
+ yield
+
+ run = -> { Holding::Materializer.new(@account.reload, strategy: strategy).materialize_holdings }
+ if reference
+ Holding::LotBook.stub(:new, -> { ReferenceCalculatorTracker.new }) { run.call }
+ else
+ run.call
+ end
+
+ @account.holdings.order(:security_id, :date, :currency)
+ .pluck(:date, :security_id, :qty, :cost_basis, :cost_basis_source, :cost_basis_locked, :currency)
+ end
+
+ def assert_fixture_not_vacuous(rows)
+ assert_operator rows.size, :>, 20
+ assert(rows.any? { |row| row[3].nil? }, "some rows are unknown")
+ assert(rows.any? { |row| row[3].present? && row[4] == "calculated" }, "some rows are calculated")
+ end
+
+ def cost_basis_on(security, date)
+ @account.holdings.find_by!(security: security, date: date).cost_basis
+ end
+end
diff --git a/test/models/holding/portfolio_cache_test.rb b/test/models/holding/portfolio_cache_test.rb
index 5ea3553950..99fa86b9fe 100644
--- a/test/models/holding/portfolio_cache_test.rb
+++ b/test/models/holding/portfolio_cache_test.rb
@@ -19,6 +19,30 @@ class Holding::PortfolioCacheTest < ActiveSupport::TestCase
@trade = create_trade(@security, account: @account, qty: 1, date: 2.days.ago.to_date, price: 210.23).trade
end
+ test "a day's trades stamped together come back purchases first, whatever their ids" do
+ sale = create_trade(@security, account: @account, qty: -1, date: 1.day.ago.to_date, price: 220)
+ purchase = create_trade(@security, account: @account, qty: 1, date: 1.day.ago.to_date, price: 215)
+ Entry.where(id: [ sale.id, purchase.id ]).update_all(created_at: Time.zone.parse("2026-01-01 10:00:00"))
+ Entry.where(id: sale.id).update_all(id: "00000000-0000-0000-0000-000000000001")
+ Entry.where(id: purchase.id).update_all(id: "ffffffff-ffff-ffff-ffff-ffffffffffff")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal [ "ffffffff-ffff-ffff-ffff-ffffffffffff", "00000000-0000-0000-0000-000000000001" ],
+ cache.get_trades(date: 1.day.ago.to_date).map(&:id)
+ end
+
+ test "a day's trades with different created_at keep the order they were entered in" do
+ sale = create_trade(@security, account: @account, qty: -1, date: 1.day.ago.to_date, price: 220)
+ purchase = create_trade(@security, account: @account, qty: 1, date: 1.day.ago.to_date, price: 215)
+ Entry.where(id: sale.id).update_all(created_at: 2.hours.ago)
+ Entry.where(id: purchase.id).update_all(created_at: 1.hour.ago)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal [ sale.id, purchase.id ], cache.get_trades(date: 1.day.ago.to_date).map(&:id)
+ end
+
test "gets price from DB if available" do
db_price = 210
@@ -39,6 +63,20 @@ class Holding::PortfolioCacheTest < ActiveSupport::TestCase
assert_equal @trade.price, cache.get_price(@security.id, @trade.entry.date).price
end
+ test "a day's price from trades ignores the replay order" do
+ Security::Price.destroy_all
+ sale = create_trade(@security, account: @account, qty: -1, date: 1.day.ago.to_date, price: 220)
+ purchase = create_trade(@security, account: @account, qty: 1, date: 1.day.ago.to_date, price: 215)
+ Entry.where(id: [ sale.id, purchase.id ]).update_all(created_at: Time.zone.parse("2026-01-01 10:00:00"))
+ Entry.where(id: sale.id).update_all(id: "00000000-0000-0000-0000-000000000001")
+ Entry.where(id: purchase.id).update_all(id: "ffffffff-ffff-ffff-ffff-ffffffffffff")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal "ffffffff-ffff-ffff-ffff-ffffffffffff", cache.get_trades(date: 1.day.ago.to_date).first.id
+ assert_equal 220, cache.get_price(@security.id, 1.day.ago.to_date).price
+ end
+
test "if no price from db or trades, search holdings" do
Security::Price.delete_all
Entry.delete_all
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index 1c08f9468a..e0ce2b1b9a 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -582,6 +582,56 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal 0, @account.holdings.where(security: amzn_security).count
end
+ # cost_basis is per share and the merged row carries both sides' units, so
+ # the merge takes the quantity-weighted mean: (5 x 100 + 10 x 40) / 15 = 60.
+ # Neither side's figure, and not their plain mean (70).
+ test "remap_security! merge pins the weighted cost basis" do
+ new_security = create_security("GOOGW", prices: [ { date: Date.current, price: 100.00 } ])
+ existing = @account.holdings.create!(
+ date: @amzn.date, security: new_security, qty: 5, price: 100, amount: 500,
+ currency: "USD", cost_basis: 100
+ )
+ @amzn.update_columns(qty: 10, amount: 2160, cost_basis: 40)
+
+ assert_equal 100, existing.reload.cost_basis
+
+ @amzn.remap_security!(new_security)
+
+ existing.reload
+ assert_equal 15, existing.qty
+ assert_equal 60, existing.cost_basis
+ end
+
+ # When either side has no basis the merge keeps the row merged into as it
+ # was: a known figure is applied to every merged unit, and an unknown one
+ # stays unknown even though the moved side had a figure.
+ test "remap_security! merge with an unknown side keeps the existing basis" do
+ moved_unknown_target = create_security("GOOGU", prices: [ { date: Date.current, price: 100.00 } ])
+ known_existing = @account.holdings.create!(
+ date: @amzn.date, security: moved_unknown_target, qty: 5, price: 100, amount: 500,
+ currency: "USD", cost_basis: 100
+ )
+ @amzn.update_columns(qty: 10, amount: 2160, cost_basis: nil)
+
+ existing_unknown_target = create_security("MSFTU", prices: [ { date: Date.current, price: 100.00 } ])
+ unknown_existing = @account.holdings.create!(
+ date: @nvda.date, security: existing_unknown_target, qty: 5, price: 100, amount: 500,
+ currency: "USD", cost_basis: nil
+ )
+ @nvda.update_columns(qty: 10, amount: 1240, cost_basis: 40)
+
+ @amzn.remap_security!(moved_unknown_target)
+ @nvda.remap_security!(existing_unknown_target)
+
+ known_existing.reload
+ assert_equal 15, known_existing.qty
+ assert_equal 100, known_existing.cost_basis, "the existing figure now covers the moved units too"
+
+ unknown_existing.reload
+ assert_equal 15, unknown_existing.qty
+ assert_nil unknown_existing.cost_basis, "the moved side's 40 is dropped"
+ end
+
test "reset_security_to_provider! restores original security" do
old_security = @amzn.security
new_security = create_security("GOOG", prices: [ { date: Date.current, price: 100.00 } ])
diff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rb
index 4917f866dc..7bfa6b49b8 100644
--- a/test/models/investment_statement_test.rb
+++ b/test/models/investment_statement_test.rb
@@ -738,6 +738,57 @@ class InvestmentStatementTest < ActiveSupport::TestCase
InvestmentStatement.new(@family.reload).totals(period: period)
end
+ # Two parcels of one security, materialised the way a sync does: 60 bought on
+ # 2024-01-10 at $12 and 40 on 2024-03-05 at $20 (blended $15.20), then 40 sold
+ # on 2024-06-01 at $25 and priced at $30 the day after. Average cost relieves
+ # the sale at the blend, so every figure below follows from $15.20, not from
+ # either parcel's own price.
+ test "investment statement figures on the two-parcel fixture" do
+ travel_to Time.zone.local(2024, 6, 2, 12) do
+ account, security, sale = materialize_two_parcel_example(first_parcel_label: "Buy")
+
+ assert_equal 12, cost_basis_on(account, security, Date.new(2024, 3, 4)), "the first parcel alone"
+ assert_equal BigDecimal("15.2"), cost_basis_on(account, security, Date.new(2024, 5, 31)), "both parcels, before the sale"
+ assert_equal BigDecimal("15.2"), cost_basis_on(account, security, Date.new(2024, 6, 1)), "the sale relieves at the blend"
+
+ holding = @statement.current_holdings.first
+ assert_equal 60, holding.qty
+ assert_equal Money.new(BigDecimal("15.2"), "USD"), holding.avg_cost
+ # 60 x $30 = $1,800 against 60 x $15.20 = $912.
+ assert_equal Money.new(1800, "USD"), holding.trend.current
+ assert_equal Money.new(912, "USD"), holding.trend.previous
+ assert_equal 888, @statement.unrealized_gains
+
+ # 40 x $25 = $1,000 against 40 x $15.20 = $608.
+ gain = sale.realized_gain_loss
+ assert_equal Money.new(1000, "USD"), gain.current
+ assert_equal Money.new(608, "USD"), gain.previous
+ assert_equal Money.new(392, "USD"), gain.value
+ end
+ end
+
+ # The same fixture with the first parcel transferred in rather than bought.
+ # Its cost is unknown, and today that makes the whole position unknown on
+ # every date it is held: the $20 parcel's own price is not applied to the
+ # transferred units, and the sale has no realized gain.
+ test "investment statement figures on the two-parcel fixture with the first parcel transferred in" do
+ travel_to Time.zone.local(2024, 6, 2, 12) do
+ account, security, sale = materialize_two_parcel_example(first_parcel_label: Trade::TRANSFER_LABEL)
+
+ assert_nil cost_basis_on(account, security, Date.new(2024, 3, 4))
+ assert_nil cost_basis_on(account, security, Date.new(2024, 5, 31)), "not the $20 parcel's price"
+ assert_nil cost_basis_on(account, security, Date.new(2024, 6, 2))
+
+ holding = @statement.current_holdings.first
+ assert_equal 60, holding.qty
+ assert_nil holding.avg_cost
+ assert_nil holding.trend
+ assert_equal 0, @statement.unrealized_gains
+
+ assert_nil sale.realized_gain_loss
+ end
+ end
+
# ---------------------------------------------- allocation by classification
test "allocation groups by asset class, and cash counts as liquidity" do
@@ -1200,6 +1251,24 @@ class InvestmentStatementTest < ActiveSupport::TestCase
end
private
+ def materialize_two_parcel_example(first_parcel_label:)
+ account = create_investment_account(balance: 1800)
+ security = create_portfolio_security
+ Security::Price.create!(security: security, date: Date.new(2024, 6, 2), price: 30, currency: "USD")
+
+ create_portfolio_trade(account: account, security: security, qty: 60, price: 12, date: Date.new(2024, 1, 10), label: first_parcel_label)
+ create_portfolio_trade(account: account, security: security, qty: 40, price: 20, date: Date.new(2024, 3, 5), label: "Buy")
+ sale = create_portfolio_trade(account: account, security: security, qty: -40, price: 25, date: Date.new(2024, 6, 1), label: "Sell")
+
+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings
+
+ [ account, security, sale.entryable ]
+ end
+
+ def cost_basis_on(account, security, date)
+ account.holdings.find_by!(security: security, date: date).cost_basis
+ end
+
def create_classified_security(**attrs)
Security.create!(
{ ticker: "T#{SecureRandom.hex(6)}", exchange_operating_mic: "XNAS", offline: true }.merge(attrs)