Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(trades): count fees in gains and treat a missing rate as unknown (#4033)

Daniel Garcia Sardina251b7bc2dcc2
diff --git a/app/models/holding.rb b/app/models/holding.rb
index 2f0f8a0cf7..cf81d61a34 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -308,10 +308,38 @@ class Holding < ApplicationRecord
Trade::INTERNAL_MOVEMENT_LABELS
)
- total_cost, total_qty = trades.pick(
- Arel.sql("SUM(trades.price * trades.qty * COALESCE(exchange_rates.rate, 1))"),
- Arel.sql("SUM(trades.qty)")
+ # 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.
+ rate = <<~SQL.squish
+ 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
+ foreign = ActiveRecord::Base.sanitize_sql_array([ "trades.currency <> ?", account.currency ])
+
+ # 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.
+ total_cost, total_qty, rate_missing = trades.pick(
+ Arel.sql("SUM((trades.price * trades.qty + trades.fee) * CASE WHEN #{foreign} THEN #{rate} ELSE 1 END)"),
+ Arel.sql("SUM(trades.qty)"),
+ Arel.sql("BOOL_OR(#{foreign} AND (#{rate} IS NULL OR #{rate} <= 0))")
)
+ return nil if rate_missing
# Return nil when no trades exist - cost basis is genuinely unknown
# Previously this fell back to current market price, which was misleading
diff --git a/app/models/holding/cost_basis_tracker.rb b/app/models/holding/cost_basis_tracker.rb
index 771b7ce14f..43937194c0 100644
--- a/app/models/holding/cost_basis_tracker.rb
+++ b/app/models/holding/cost_basis_tracker.rb
@@ -10,10 +10,14 @@
#
# 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
- @total_cost = BigDecimal("0")
- @total_qty = BigDecimal("0")
+ reset
end
# Applies a trade by its signed quantity: positive is a buy, negative a sell.
@@ -27,11 +31,11 @@ class Holding::CostBasisTracker
end
def buy(price, qty)
- price = price&.to_d
qty = qty&.to_d
- return if price.nil? || qty.nil? || !qty.positive?
+ return if qty.nil? || !qty.positive?
- @total_cost += price * qty
+ @unknown = true if price.nil?
+ @total_cost += price.to_d * qty unless price.nil?
@total_qty += qty
end
@@ -42,7 +46,7 @@ class Holding::CostBasisTracker
# 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_cost -= (@total_cost / @total_qty) * relieved_qty
@total_qty -= relieved_qty
# Coercing to BigDecimal keeps arithmetic exact, so a full liquidation lands
@@ -56,9 +60,10 @@ class Holding::CostBasisTracker
@total_qty = Security::Split.scale(@total_qty, ratio)
end
- # Current weighted-average cost per share, or nil when nothing is held.
+ # 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?
+ return nil if @total_qty.zero? || @unknown
@total_cost / @total_qty
end
@@ -67,5 +72,6 @@ class Holding::CostBasisTracker
def reset
@total_cost = BigDecimal("0")
@total_qty = BigDecimal("0")
+ @unknown = false
end
end
diff --git a/app/models/holding/trade_calculator_helpers.rb b/app/models/holding/trade_calculator_helpers.rb
index 0a387ccbf7..e1d513e8aa 100644
--- a/app/models/holding/trade_calculator_helpers.rb
+++ b/app/models/holding/trade_calculator_helpers.rb
@@ -3,7 +3,7 @@
module Holding::TradeCalculatorHelpers
private
# Converts a trade's price into the account's currency at the rate of the
- # day it was made, falling back to the raw price when no rate is available.
+ # day it was made, or nil when there is no rate for that day.
def converted_trade_price(trade, date:)
convert_to_account_currency(trade.price, trade, date: date)
end
@@ -35,16 +35,24 @@ module Holding::TradeCalculatorHelpers
return price unless trade.qty&.positive?
fee = converted_trade_fee(trade, date: date)
+ return nil if price.nil? || fee.nil?
return price if fee.zero?
price + (fee / trade.qty)
end
# The rate on the trade's own day: a basis is what was paid then, and must
- # not drift with the exchange rate afterwards.
+ # not drift with the exchange rate afterwards. A rate the trade carries
+ # itself (`extra["exchange_rate"]`, e.g. IBKR's fx_rate_to_base) comes
+ # first, as it does for the cash balance in Balance::SyncCache. No rate means
+ # the amount in the account's currency is unknown -- not the raw figure,
+ # which is what a rate of 1.0 would give -- the same answer
+ # Trade#calculate_realized_gain_loss gives.
def convert_to_account_currency(amount, trade, date:)
- Money.new(amount, trade.currency).exchange_to(account.currency, date: date).amount
+ Money.new(amount, trade.currency)
+ .exchange_to(account.currency, date: date, custom_rate: trade.exchange_rate)
+ .amount
rescue Money::ConversionError
- amount
+ nil
end
end
diff --git a/app/models/trade.rb b/app/models/trade.rb
index 825f0fad14..297a6753ad 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -83,7 +83,7 @@ class Trade < ApplicationRecord
return nil if current_price.nil?
current_value = current_price * qty.abs
- cost_basis = price_money * qty.abs
+ cost_basis = price_money * qty.abs + fee_money
Trend.new(current: current_value, previous: cost_basis)
end
@@ -218,7 +218,8 @@ class Trade < ApplicationRecord
return nil unless holding&.avg_cost
cost_basis = holding.avg_cost * qty.abs
- sale_proceeds = converted_to_basis_currency(price_money * qty.abs, cost_basis.currency)
+ # A disposal's fee is what selling cost, so it comes off the proceeds.
+ sale_proceeds = converted_to_basis_currency(price_money * qty.abs - fee_money, cost_basis.currency)
# No rate for that day means the gain is unknown, not zero and not the
# figure a rate of 1.0 would give.
diff --git a/test/models/holding/cost_basis_tracker_test.rb b/test/models/holding/cost_basis_tracker_test.rb
index 5a2657541f..0ba17761af 100644
--- a/test/models/holding/cost_basis_tracker_test.rb
+++ b/test/models/holding/cost_basis_tracker_test.rb
@@ -38,6 +38,21 @@ class Holding::CostBasisTrackerTest < ActiveSupport::TestCase
assert_equal BigDecimal("300"), @tracker.average_cost
end
+ # Skipping a buy whose price is unknown would average the known buys over
+ # fewer units than are held.
+ test "a buy at an unknown price makes the average unknown until the position closes" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("10"))
+ @tracker.apply(nil, BigDecimal("10"))
+ assert_nil @tracker.average_cost
+
+ @tracker.apply(BigDecimal("999"), BigDecimal("-5"))
+ assert_nil @tracker.average_cost, "a partial sell does not make it known"
+
+ @tracker.apply(BigDecimal("999"), BigDecimal("-15"))
+ @tracker.apply(BigDecimal("120"), BigDecimal("4"))
+ assert_equal BigDecimal("120"), @tracker.average_cost, "a repurchase after a full close starts clean"
+ 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
diff --git a/test/models/holding/forward_calculator_test.rb b/test/models/holding/forward_calculator_test.rb
index 4f8c4ad688..cde043015e 100644
--- a/test/models/holding/forward_calculator_test.rb
+++ b/test/models/holding/forward_calculator_test.rb
@@ -239,6 +239,37 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
assert_equal BigDecimal("202"), current.cost_basis
end
+ # No rate for the trade's day means its cost in the account's currency is
+ # unknown. Counting it at 1:1 would report 1,010 for a purchase that cost
+ # 2,020 at the real rate, and nothing would mark the figure as a guess.
+ test "a foreign purchase with no rate for its day leaves the basis unknown" do
+ load_prices
+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)
+
+ create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 100, fee: 10, currency: "EUR", account: @account)
+
+ calculated = Holding::ForwardCalculator.new(@account).calculate
+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ assert_nil current.cost_basis
+ end
+
+ # A rate the trade carries itself (IBKR's fx_rate_to_base) is a rate for its
+ # day, so the basis is known even when the rates table has a gap.
+ test "a foreign purchase converts at the rate it carries when the table has none" do
+ load_prices
+ ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)
+
+ entry = create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 100, fee: 10, currency: "EUR", account: @account)
+ entry.entryable.update!(exchange_rate: 2.0)
+
+ calculated = Holding::ForwardCalculator.new(@account).calculate
+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
+
+ # (10 * 100 + 10) EUR at the trade's own 2.0 = 2,020 USD for 10 units
+ assert_equal BigDecimal("202"), current.cost_basis
+ end
+
# The tracker never reads a disposal's price, so this cannot be observed
# through the basis; it is pinned on the helper directly.
test "a disposal's price is returned without its fee" do
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index 78c9b5037a..43eee1e681 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -57,6 +57,10 @@ class HoldingTest < ActiveSupport::TestCase
end
test "calculates average cost basis from another currency" do
+ [ 1.day.ago.to_date, Date.current ].each do |date|
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: date, rate: 1)
+ end
+
create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
create_trade(@amzn.security, account: @account, qty: 15, price: 216.00, date: Date.current, currency: "CAD")
@@ -79,6 +83,68 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal Money.new(expected_nvda_usd, "CAD").exchange_to("USD"), @nvda.avg_cost
end
+ test "the average cost includes what the purchases cost in fees" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, fee: 10, date: 1.day.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 15, price: 216.00, fee: 5, date: Date.current)
+
+ # (10 * 212 + 10 + 15 * 216 + 5) / 25 = 5,375 / 25
+ assert_equal Money.new(BigDecimal("215")), @amzn.avg_cost
+ end
+
+ # The fallback's COALESCE(rate, 1) counted a foreign purchase at 1:1 when its
+ # day had no rate, stating a cost that looks measured and is not.
+ test "a foreign purchase with no rate for its day makes the average cost unknown" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
+
+ assert_nil @amzn.avg_cost
+ end
+
+ test "a foreign purchase whose stored rate cannot convert makes the average cost unknown" do
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: 1.day.ago.to_date, rate: 0)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")
+
+ assert_nil @amzn.avg_cost
+ end
+
+ test "the fallback converts a purchase at the rate it carries when the table has none" 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.25)
+
+ # 10 * 212 CAD at the trade's own 1.25 = 2,650 USD for 10 units
+ assert_equal Money.new(BigDecimal("265")), @amzn.avg_cost
+ end
+
+ # Trade#exchange_rate= stores a number, but a rate written to `extra` directly
+ # stays a string, and Trade and Money#exchange_to both accept it.
+ test "the fallback converts a purchase at a rate it carries as a string" 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" => "1.25" })
+
+ assert entry.entryable.reload.valid?
+ assert_equal Money.new(BigDecimal("265")), @amzn.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
+ end
+ 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
+ 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 }
+
+ assert_equal 2, queries.count { |sql| sql.include?('FROM "trades"') }
+ end
+
test "calculates total return trend" do
@amzn.stubs(:avg_cost).returns(Money.new(214.00))
@nvda.stubs(:avg_cost).returns(Money.new(126.00))
diff --git a/test/models/trade_test.rb b/test/models/trade_test.rb
index 4b06804c47..3089accd0f 100644
--- a/test/models/trade_test.rb
+++ b/test/models/trade_test.rb
@@ -30,6 +30,26 @@ class TradeTest < ActiveSupport::TestCase
assert_equal BigDecimal(10), sell.realized_gain_loss.value.amount
end
+ # A disposal's fee is what selling cost, so it comes off the proceeds before
+ # they are converted. 2 sold at 150 EUR less a 10 EUR fee is 290 EUR, 435 USD
+ # at 1.5, less 200 USD of basis: a 235 USD gain, where ignoring the fee
+ # reported 250.
+ test "a disposal's fee comes off its proceeds" do
+ sell = cross_currency_disposal(rate: 1.5, fee: 10)
+
+ assert_equal BigDecimal(235), sell.realized_gain_loss.value.amount
+ end
+
+ # A lot cost what was paid for it, fee included: 10 bought at 100 with a 20
+ # fee cost 1,020, so at 120 the lot is up 180, not 200.
+ test "a purchase's unrealized gain is measured against its price plus its fee" do
+ account, security = cross_currency_account
+ buy = create_trade(security, account: account, qty: 10, date: Date.current, price: 100, fee: 20, currency: "USD").entryable
+ buy.security.stubs(:current_price).returns(Money.new(120, "USD"))
+
+ assert_equal BigDecimal(180), buy.unrealized_gain_loss.value.amount
+ end
+
# No rate for that date means the gain is unknown, not zero and not the
# figure a rate of 1.0 would produce.
test "a cross-currency disposal with no rate for its date has no figure" do
@@ -289,7 +309,7 @@ class TradeTest < ActiveSupport::TestCase
private
# A USD account holding a EUR-listed security, with one disposal in it.
- def cross_currency_disposal(rate:, rate_date: Date.new(2026, 3, 10))
+ def cross_currency_disposal(rate:, rate_date: Date.new(2026, 3, 10), fee: 0)
account, security = cross_currency_account
date = Date.new(2026, 3, 10)
@@ -297,7 +317,7 @@ class TradeTest < ActiveSupport::TestCase
account.holdings.create!(security: security, date: date, qty: 5, price: 150,
amount: BigDecimal(750), currency: "USD", cost_basis: 100)
- create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR").entryable
+ create_trade(security, account: account, qty: -2, date: date, price: 150, fee: fee, currency: "EUR").entryable
end
def cross_currency_account