Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix holding cost basis to relieve sells under weighted-average method (#3560)

markschoof1f98e2a6d7bc
diff --git a/app/models/holding/cost_basis_tracker.rb b/app/models/holding/cost_basis_tracker.rb
new file mode 100644
index 0000000000..ceaed8f884
--- /dev/null
+++ b/app/models/holding/cost_basis_tracker.rb
@@ -0,0 +1,65 @@
+# 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.
+class Holding::CostBasisTracker
+ def initialize
+ @total_cost = BigDecimal("0")
+ @total_qty = BigDecimal("0")
+ 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)
+ price = price&.to_d
+ qty = qty&.to_d
+ return if price.nil? || qty.nil? || !qty.positive?
+
+ @total_cost += price * qty
+ @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 -= average_cost * 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
+
+ # Current weighted-average cost per share, or nil when nothing is held.
+ def average_cost
+ return nil if @total_qty.zero?
+
+ @total_cost / @total_qty
+ end
+
+ private
+ def reset
+ @total_cost = BigDecimal("0")
+ @total_qty = BigDecimal("0")
+ end
+end
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index 87b368db61..e44a165e20 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -1,11 +1,14 @@
class Holding::ForwardCalculator
+ include Holding::TradeCalculatorHelpers
+
attr_reader :account
def initialize(account, security_ids: nil)
@account = account
@security_ids = security_ids
- # Track cost basis per security: { security_id => { total_cost: BigDecimal, total_qty: BigDecimal } }
- @cost_basis_tracker = Hash.new { |h, k| h[k] = { total_cost: BigDecimal("0"), total_qty: BigDecimal("0") } }
+ # 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 }
# 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.
@@ -82,44 +85,36 @@ class Holding::ForwardCalculator
end.compact
end
- # Updates cost basis tracker with buy trades (qty > 0)
- # Uses weighted average cost method
+ # Applies each trade to its security's weighted-average cost-basis tracker.
+ # 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.
def update_cost_basis_tracker(trade_entries)
trade_entries.each do |trade_entry|
trade = trade_entry.entryable
- next unless trade.qty > 0 # Only track buys
-
security_id = trade.security_id
- # An internal movement is not a purchase: it contributes no cost and it
- # makes the whole position unknowable, not just its own units.
if trade.internal_movement?
- @transferred_security_ids << security_id
+ # An inbound transfer brings in units at a price nothing here knows, so
+ # it makes the whole position's cost basis unknowable. An outbound
+ # transfer only removes units, so relieve them at the running average
+ # (like a sell) rather than leaving them to contaminate a later buy.
+ if trade.qty.positive?
+ @transferred_security_ids << security_id
+ else
+ @cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)
+ end
next
end
- tracker = @cost_basis_tracker[security_id]
-
- # Convert trade price to account currency if needed
- trade_price = Money.new(trade.price, trade.currency)
- begin
- converted_price = trade_price.exchange_to(account.currency).amount
- rescue Money::ConversionError
- converted_price = trade.price
- end
-
- tracker[:total_cost] += converted_price * trade.qty
- tracker[:total_qty] += trade.qty
+ @cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)
end
end
- # Returns the current cost basis for a security, or nil if no buys recorded
+ # Returns the current cost basis for a security, or nil if nothing is held
+ # or the position contains transferred-in units of unknown cost.
def cost_basis_for(security_id, currency)
return nil if @transferred_security_ids.include?(security_id)
- tracker = @cost_basis_tracker[security_id]
- return nil if tracker[:total_qty].zero?
-
- tracker[:total_cost] / tracker[:total_qty]
+ @cost_basis_trackers[security_id].average_cost
end
end
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index 9289d6d27f..2e0ed89068 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -1,4 +1,6 @@
class Holding::ReverseCalculator
+ include Holding::TradeCalculatorHelpers
+
attr_reader :account, :portfolio_snapshot
def initialize(account, portfolio_snapshot:, security_ids: nil)
@@ -86,33 +88,36 @@ class Holding::ReverseCalculator
# position contains units acquired at a price nothing here knows, so it
# has no cost basis — before it, the purchases still stand on their own.
@first_transfer_dates = {}
- tracker = Hash.new { |h, k| h[k] = { total_cost: BigDecimal("0"), total_qty: BigDecimal("0") } }
+ trackers = Hash.new { |h, k| h[k] = Holding::CostBasisTracker.new }
- portfolio_cache.get_trades.sort_by(&:date).each do |trade_entry|
+ # get_trades is already chronological (date, then created_at, then id).
+ # Re-sorting by date alone is unstable and could reorder same-day trades,
+ # which now matters because the tracker is order-sensitive once sells relieve.
+ portfolio_cache.get_trades.each do |trade_entry|
trade = trade_entry.entryable
- next unless trade.qty > 0
-
security_id = trade.security_id
if trade.internal_movement?
- @first_transfer_dates[security_id] ||= trade_entry.date
+ # Inbound transfers make the basis unknown from that date on; outbound
+ # transfers only remove units, so relieve them at the running average.
+ if trade.qty.positive?
+ @first_transfer_dates[security_id] ||= trade_entry.date
+ else
+ trackers[security_id].apply(converted_trade_price(trade), trade.qty)
+ @cost_basis_snapshots[security_id] << [ trade_entry.date, trackers[security_id].average_cost ]
+ end
next
end
- trade_price = Money.new(trade.price, trade.currency)
- begin
- converted_price = trade_price.exchange_to(account.currency).amount
- rescue Money::ConversionError
- converted_price = trade.price
- end
-
- tracker[security_id][:total_cost] += converted_price * trade.qty
- tracker[security_id][:total_qty] += trade.qty
+ tracker = trackers[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(converted_trade_price(trade), trade.qty)
- @cost_basis_snapshots[security_id] << [
- trade_entry.date,
- tracker[security_id][:total_cost] / tracker[security_id][:total_qty]
- ]
+ # 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 ]
end
end
diff --git a/app/models/holding/trade_calculator_helpers.rb b/app/models/holding/trade_calculator_helpers.rb
new file mode 100644
index 0000000000..db69416792
--- /dev/null
+++ b/app/models/holding/trade_calculator_helpers.rb
@@ -0,0 +1,12 @@
+# Shared helpers for holding calculators (ForwardCalculator / ReverseCalculator).
+# Expects the including class to expose an `account` reader.
+module Holding::TradeCalculatorHelpers
+ private
+ # Converts a trade's price into the account's currency, falling back to the
+ # raw price when no exchange rate is available.
+ def converted_trade_price(trade)
+ Money.new(trade.price, trade.currency).exchange_to(account.currency).amount
+ rescue Money::ConversionError
+ trade.price
+ end
+end
diff --git a/test/models/holding/cost_basis_tracker_test.rb b/test/models/holding/cost_basis_tracker_test.rb
new file mode 100644
index 0000000000..bdf8117c61
--- /dev/null
+++ b/test/models/holding/cost_basis_tracker_test.rb
@@ -0,0 +1,66 @@
+require "test_helper"
+
+class Holding::CostBasisTrackerTest < ActiveSupport::TestCase
+ setup do
+ @tracker = Holding::CostBasisTracker.new
+ end
+
+ test "average cost is nil with no trades" do
+ assert_nil @tracker.average_cost
+ end
+
+ test "weighted average across multiple buys" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("10"))
+ @tracker.apply(BigDecimal("200"), BigDecimal("10"))
+
+ assert_equal BigDecimal("150"), @tracker.average_cost
+ end
+
+ test "a partial sell leaves the per-share average unchanged" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("10"))
+ @tracker.apply(BigDecimal("200"), BigDecimal("10")) # avg 150
+
+ # Sell price is irrelevant to cost basis; shares are relieved at the average.
+ @tracker.apply(BigDecimal("999"), BigDecimal("-5"))
+
+ assert_equal BigDecimal("150"), @tracker.average_cost
+ end
+
+ test "cost basis resets after a full liquidation and repurchase" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("10"))
+ @tracker.apply(BigDecimal("300"), BigDecimal("-10")) # fully sold
+
+ assert_nil @tracker.average_cost
+
+ @tracker.apply(BigDecimal("300"), BigDecimal("10")) # repurchased
+
+ # Only the repurchased lot is held — not (100 + 300) / 2 = 200.
+ assert_equal BigDecimal("300"), @tracker.average_cost
+ end
+
+ test "over-selling cannot drive quantity or basis negative" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("5"))
+ @tracker.apply(BigDecimal("100"), BigDecimal("-10")) # sell more than held
+
+ assert_nil @tracker.average_cost
+ end
+
+ test "selling with no position is a no-op" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("-5"))
+
+ assert_nil @tracker.average_cost
+ end
+
+ test "coerces float quantities so a full liquidation still resets" do
+ # Float inputs must not accumulate rounding error that leaves a tiny
+ # residual quantity and bypasses the reset-on-full-liquidation.
+ @tracker.apply(100.0, 10.0)
+ @tracker.apply(300.0, -10.0)
+
+ assert_nil @tracker.average_cost
+
+ @tracker.apply(300.0, 10.0)
+
+ assert_equal BigDecimal("300"), @tracker.average_cost
+ end
+end
diff --git a/test/models/holding/forward_calculator_test.rb b/test/models/holding/forward_calculator_test.rb
index d8ad7b0165..47b5f00326 100644
--- a/test/models/holding/forward_calculator_test.rb
+++ b/test/models/holding/forward_calculator_test.rb
@@ -129,6 +129,41 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
end
end
+ # Regression: selling a position to zero must relieve the cost-basis tracker so
+ # that a later repurchase is not averaged against the already-sold lots.
+ test "cost basis resets after a position is fully sold and repurchased" do
+ load_prices
+
+ create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
+ create_trade(@voo, qty: -10, date: 3.days.ago.to_date, price: 480, account: @account) # fully sold
+ create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 490, account: @account) # repurchased
+
+ calculated = Holding::ForwardCalculator.new(@account).calculate
+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ # Only the repurchased lot is held, so cost basis is $490 — not the
+ # buggy (460 + 490) / 2 = $475 averaged over the sold-off shares.
+ assert_equal BigDecimal("490"), current.cost_basis
+ end
+
+ # An outbound transfer removes units without a cost; it must relieve the tracker
+ # (not stay in the average) while leaving the basis known, unlike an inbound one.
+ test "an outbound transfer relieves the tracker instead of contaminating a later buy" do
+ load_prices
+
+ create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
+ transfer_out = create_trade(@voo, qty: -10, date: 3.days.ago.to_date, price: 470, account: @account)
+ transfer_out.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # transferred out, not sold
+ create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 490, account: @account)
+
+ calculated = Holding::ForwardCalculator.new(@account).calculate
+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ # Repurchased lot stands alone at $490, not (460 + 490) / 2 = $475.
+ assert_equal BigDecimal("490"), current.cost_basis
+ assert_not current.cost_basis_unknown, "an outbound-only transfer should not mark the basis unknown"
+ end
+
test "offline tickers sync holdings based on most recent trade price" do
offline_security = Security.create!(ticker: "OFFLINE", name: "Offline Ticker")
diff --git a/test/models/holding/reverse_calculator_test.rb b/test/models/holding/reverse_calculator_test.rb
index 978c64ba39..859648e3b9 100644
--- a/test/models/holding/reverse_calculator_test.rb
+++ b/test/models/holding/reverse_calculator_test.rb
@@ -238,6 +238,45 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCase
assert_in_delta 100.0, cost_basis_for(calc, security, Date.current).to_f, 1e-6
end
+ test "cost_basis_for is nil while fully sold and resets after repurchase" do
+ security = Security.create!(ticker: "TST", name: "Test")
+ buy_date = 10.days.ago.to_date
+ sell_all_date = 6.days.ago.to_date
+ rebuy_date = 3.days.ago.to_date
+
+ calc = calculator_with_trades(security) do
+ create_trade(security, account: @account, qty: 10, price: 100, date: buy_date)
+ create_trade(security, account: @account, qty: -10, price: 130, date: sell_all_date) # fully sold
+ create_trade(security, account: @account, qty: 10, price: 150, date: rebuy_date) # repurchased
+ end
+
+ assert_in_delta 100.0, cost_basis_for(calc, security, buy_date).to_f, 1e-6
+ # Fully sold: no basis, not the stale $100 carried forward from the first buy
+ assert_nil cost_basis_for(calc, security, sell_all_date)
+ assert_nil cost_basis_for(calc, security, rebuy_date - 1)
+ # Repurchased lot stands alone at $150, not (100 + 150) / 2 = $125
+ assert_in_delta 150.0, cost_basis_for(calc, security, rebuy_date).to_f, 1e-6
+ assert_in_delta 150.0, cost_basis_for(calc, security, Date.current).to_f, 1e-6
+ end
+
+ test "cost_basis_for relieves an outbound transfer instead of contaminating a later buy" do
+ security = Security.create!(ticker: "TST", name: "Test")
+ buy_date = 10.days.ago.to_date
+ transfer_date = 6.days.ago.to_date
+ rebuy_date = 3.days.ago.to_date
+
+ calc = calculator_with_trades(security) do
+ create_trade(security, account: @account, qty: 10, price: 100, date: buy_date)
+ transfer_out = create_trade(security, account: @account, qty: -10, price: 120, date: transfer_date)
+ transfer_out.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # transferred out, not sold
+ create_trade(security, account: @account, qty: 10, price: 150, date: rebuy_date)
+ end
+
+ # Transferred-out lot is relieved, so the repurchase stands alone at $150.
+ assert_in_delta 150.0, cost_basis_for(calc, security, rebuy_date).to_f, 1e-6
+ assert_in_delta 150.0, cost_basis_for(calc, security, Date.current).to_f, 1e-6
+ end
+
private
def assert_holdings(expected, calculated)
expected.each do |expected_entry|