Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Release the transfer "unknown" cost basis once the position is closed (#3567)

markschoof8ea2026271ac
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index e44a165e20..307b3c1276 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -23,8 +23,7 @@ class Holding::ForwardCalculator
account.start_date.upto(Date.current).each do |date|
trades = portfolio_cache.get_trades(date: date)
- update_cost_basis_tracker(trades)
- next_portfolio = transform_portfolio(current_portfolio, trades, direction: :forward)
+ next_portfolio = apply_trades(current_portfolio, trades)
holdings.concat(build_holdings(next_portfolio, date))
current_portfolio = next_portfolio
end
@@ -47,19 +46,6 @@ class Holding::ForwardCalculator
empty_portfolio
end
- def transform_portfolio(previous_portfolio, trade_entries, direction: :forward)
- new_quantities = previous_portfolio.dup
-
- trade_entries.each do |trade_entry|
- trade = trade_entry.entryable
- security_id = trade.security_id
- qty_change = trade.qty
- qty_change = qty_change * -1 if direction == :reverse
- new_quantities[security_id] = (new_quantities[security_id] || 0) + qty_change
- end
-
- new_quantities
- end
def build_holdings(portfolio, date, price_source: nil)
portfolio.map do |security_id, qty|
@@ -85,13 +71,21 @@ class Holding::ForwardCalculator
end.compact
end
- # 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)
+ # Applies the day's trades in order and returns the resulting portfolio, so the
+ # caller does not walk the same trades again to compute quantities.
+ #
+ # Buys raise a security's weighted-average cost basis; sells relieve quantity at
+ # the running average and a full liquidation resets it, so a later repurchase
+ # starts from a clean basis. Tracking the running position here lets an inbound
+ # transfer's "unknown" mark release the moment the position hits zero — even when
+ # a same-day sell-off and repurchase net back to a positive end-of-day quantity.
+ def apply_trades(opening_portfolio, trade_entries)
+ portfolio = opening_portfolio.dup
+
trade_entries.each do |trade_entry|
trade = trade_entry.entryable
security_id = trade.security_id
+ previous_quantity = portfolio[security_id] || 0
if trade.internal_movement?
# An inbound transfer brings in units at a price nothing here knows, so
@@ -103,11 +97,19 @@ class Holding::ForwardCalculator
else
@cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)
end
- next
+ else
+ @cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)
end
- @cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)
+ portfolio[security_id] = previous_quantity + trade.qty
+
+ # Release the "unknown" mark only on a genuine downward crossing through
+ # zero: a position that was already non-positive never held these units, so
+ # opening and closing must not collapse onto the same trade.
+ @transferred_security_ids.delete(security_id) if previous_quantity.positive? && portfolio[security_id] <= 0
end
+
+ portfolio
end
# Returns the current cost basis for a security, or nil if nothing is held
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index 2e0ed89068..5f2958f18d 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -84,46 +84,71 @@ class Holding::ReverseCalculator
def precompute_cost_basis
@cost_basis_snapshots = Hash.new { |h, k| h[k] = [] }
- # First date a transfer landed on each security. From that day on the
- # 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 = {}
+ # 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 }
+ open_unknown_start = {}
# 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|
+ # which matters because the tracker is order-sensitive once sells relieve.
+ trades = portfolio_cache.get_trades
+
+ # A reverse-synced account can hold shares before its first imported trade,
+ # because the provider gives current holdings rather than full history. Seed
+ # each running position from the snapshot minus the net imported trades, so
+ # "position back at zero" reflects the real position, not just the trades we
+ # happen to have.
+ net_qty = Hash.new(0)
+ trades.each { |te| net_qty[te.entryable.security_id] += te.entryable.qty }
+ snapshot = portfolio_snapshot.to_h
+ positions = Hash.new(0)
+ net_qty.each_key { |security_id| positions[security_id] = (snapshot[security_id] || 0) - net_qty[security_id] }
+
+ trades.each do |trade_entry|
trade = trade_entry.entryable
security_id = trade.security_id
+ previous_position = positions[security_id]
+ positions[security_id] += trade.qty
if trade.internal_movement?
# 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
+ open_unknown_start[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
+ else
+ 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)
+
+ # 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
- 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)
-
- # 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 ]
+ # Close an open unknown span only on a genuine downward crossing through
+ # zero. A position that was already non-positive — e.g. a gapped import
+ # whose reconstructed baseline is negative — never held these units, so
+ # opening and closing must not collapse onto the same trade.
+ if open_unknown_start[security_id] && previous_position.positive? && positions[security_id] <= 0
+ @unknown_spans[security_id] << [ open_unknown_start[security_id], trade_entry.date ]
+ open_unknown_start.delete(security_id)
+ end
end
+
+ # Spans still open at the last trade stay unknown through to the present.
+ open_unknown_start.each { |security_id, start| @unknown_spans[security_id] << [ start, nil ] }
end
def transferred_by?(security_id, date)
- first = @first_transfer_dates[security_id]
- first.present? && first <= date
+ @unknown_spans[security_id].any? { |start, stop| start <= date && (stop.nil? || date < stop) }
end
def cost_basis_for(security_id, date)
diff --git a/test/models/holding/forward_calculator_test.rb b/test/models/holding/forward_calculator_test.rb
index 47b5f00326..8113835698 100644
--- a/test/models/holding/forward_calculator_test.rb
+++ b/test/models/holding/forward_calculator_test.rb
@@ -164,6 +164,50 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
assert_not current.cost_basis_unknown, "an outbound-only transfer should not mark the basis unknown"
end
+ # An inbound transfer marks the basis unknown while those units are held, but once
+ # the position is fully closed and repurchased the new lot must read as known again.
+ test "an inbound transfer stops shadowing the basis once the position is closed and repurchased" do
+ load_prices
+
+ create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
+ transfer_in = create_trade(@voo, qty: 5, date: 3.days.ago.to_date, price: 470, account: @account)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # moved in, unknown cost
+ create_trade(@voo, qty: -15, date: 2.days.ago.to_date, price: 480, account: @account) # fully closed
+ create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 490, account: @account) # repurchased
+
+ calculated = Holding::ForwardCalculator.new(@account).calculate
+
+ # While the transferred-in units are held, the basis is unknown.
+ while_held = calculated.find { |h| h.security_id == @voo.id && h.date == 3.days.ago.to_date }
+ assert while_held.cost_basis_unknown
+ assert_nil while_held.cost_basis
+
+ # After the position is fully closed and bought again, the new lot is known.
+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
+ assert_not current.cost_basis_unknown
+ assert_equal BigDecimal("490"), current.cost_basis
+ end
+
+ # A same-day sell-to-zero and repurchase nets back to a positive end-of-day
+ # quantity, so the release has to run per trade, not just on the day's net.
+ test "an inbound transfer is released even when the position crosses zero within a day" do
+ load_prices
+
+ create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
+ # All on the same day: transfer in, sell the whole position to zero, buy back.
+ transfer_in = create_trade(@voo, qty: 5, date: 2.days.ago.to_date, price: 480, account: @account)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ create_trade(@voo, qty: -15, date: 2.days.ago.to_date, price: 480, account: @account)
+ create_trade(@voo, qty: 10, date: 2.days.ago.to_date, price: 480, account: @account)
+
+ calculated = Holding::ForwardCalculator.new(@account).calculate
+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ # The intra-day liquidation released the mark, so the repurchase is known.
+ assert_not current.cost_basis_unknown
+ assert_equal BigDecimal("480"), current.cost_basis
+ 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 859648e3b9..29d0f26e95 100644
--- a/test/models/holding/reverse_calculator_test.rb
+++ b/test/models/holding/reverse_calculator_test.rb
@@ -277,6 +277,76 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCase
assert_in_delta 150.0, cost_basis_for(calc, security, Date.current).to_f, 1e-6
end
+ test "cost_basis_for clears the unknown state once a transferred-in position is fully closed" do
+ security = Security.create!(ticker: "TST", name: "Test")
+ buy_date = 12.days.ago.to_date
+ transfer_date = 9.days.ago.to_date
+ close_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_in = create_trade(security, account: @account, qty: 5, price: 120, date: transfer_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # moved in, unknown cost
+ create_trade(security, account: @account, qty: -15, price: 130, date: close_date) # fully closed
+ create_trade(security, account: @account, qty: 10, price: 150, date: rebuy_date) # repurchased
+ end
+
+ # Trades net to 10, matching the 10-share snapshot, so the position really does
+ # hit zero at the close before the repurchase.
+ # Unknown while the transferred-in units are held
+ assert_nil cost_basis_for(calc, security, transfer_date)
+ assert_nil cost_basis_for(calc, security, close_date - 1)
+ # Known again once the position is fully closed and bought back
+ 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
+
+ # A reverse-synced account can hold shares before its first imported trade. Here
+ # the snapshot is 10 but the trades net to only 8, so two shares predate the
+ # history and the position never truly reaches zero — the transferred-in units
+ # are still mixed in, so the basis must stay unknown.
+ test "cost_basis_for keeps a transferred position unknown when opening shares prevent liquidation" do
+ security = Security.create!(ticker: "TST", name: "Test")
+ buy_date = 12.days.ago.to_date
+ transfer_date = 9.days.ago.to_date
+ sell_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_in = create_trade(security, account: @account, qty: 5, price: 120, date: transfer_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # moved in, unknown cost
+ create_trade(security, account: @account, qty: -15, price: 130, date: sell_date)
+ create_trade(security, account: @account, qty: 8, price: 150, date: rebuy_date)
+ end
+
+ assert_nil cost_basis_for(calc, security, rebuy_date)
+ assert_nil cost_basis_for(calc, security, Date.current)
+ end
+
+ # A gapped import can record more net buys than the current snapshot, so the
+ # reconstructed baseline is negative. Opening and closing the unknown span must
+ # not collapse onto the transfer's own trade, which would wrongly mark it known.
+ test "cost_basis_for keeps a transferred position unknown when a gapped import gives a negative baseline" do
+ security = Security.create!(ticker: "TST", name: "Test")
+ transfer_date = 9.days.ago.to_date
+ buy_date = 5.days.ago.to_date
+
+ transfer_in = create_trade(security, account: @account, qty: 5, price: 120, date: transfer_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # moved in, unknown cost
+ create_trade(security, account: @account, qty: 5, price: 150, date: buy_date)
+
+ # Snapshot shows no current holding, but the trades net to +10, so the seeded
+ # baseline is -10 and the transfer lands while the running position is negative.
+ snapshot = OpenStruct.new(to_h: { security.id => 0 })
+ calc = Holding::ReverseCalculator.new(@account, portfolio_snapshot: snapshot)
+ calc.send(:precompute_cost_basis)
+
+ assert_nil cost_basis_for(calc, security, transfer_date)
+ assert_nil cost_basis_for(calc, security, Date.current)
+ end
+
private
def assert_holdings(expected, calculated)
expected.each do |expected_entry|