The personal finance app for everyone (by everyone)
Ruby
fix(holdings): an acquisition fee is part of what the position cost (#3758)
Daniel Garcia Sardina56140319dd26
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rbindex 307b3c1276..fd7ac425f1 100644--- a/app/models/holding/forward_calculator.rb+++ b/app/models/holding/forward_calculator.rb@@ -95,10 +95,10 @@ class Holding::ForwardCalculatorif trade.qty.positive?@transferred_security_ids << security_idelse- @cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)+ @cost_basis_trackers[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)endelse- @cost_basis_trackers[security_id].apply(converted_trade_price(trade), trade.qty)+ @cost_basis_trackers[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)endportfolio[security_id] = previous_quantity + trade.qtydiff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rbindex 5f2958f18d..6cf08b043a 100644--- a/app/models/holding/reverse_calculator.rb+++ b/app/models/holding/reverse_calculator.rb@@ -118,14 +118,14 @@ class Holding::ReverseCalculatorif trade.qty.positive?open_unknown_start[security_id] ||= trade_entry.dateelse- trackers[security_id].apply(converted_trade_price(trade), trade.qty)+ 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 ]endelsetracker = 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)+ tracker.apply(effective_trade_price(trade, date: trade_entry.date), 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 adiff --git a/app/models/holding/trade_calculator_helpers.rb b/app/models/holding/trade_calculator_helpers.rbindex db69416792..0a387ccbf7 100644--- a/app/models/holding/trade_calculator_helpers.rb+++ b/app/models/holding/trade_calculator_helpers.rb@@ -2,11 +2,49 @@# Expects the including class to expose an `account` reader.module Holding::TradeCalculatorHelpersprivate- # 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+ # 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.+ def converted_trade_price(trade, date:)+ convert_to_account_currency(trade.price, trade, date: date)+ end++ # Same, for the fee the trade was charged.+ def converted_trade_fee(trade, date:)+ fee = trade.fee || 0+ return fee if fee.zero?++ convert_to_account_currency(fee, trade, date: date)+ end++ # What the units actually cost, per unit.+ #+ # An acquisition fee is part of the cost of the position, so it belongs in+ # the basis. Providers record it on the trade -- `trades.fee` -- but nothing+ # reads it, so the basis, and every gain derived from it, understates what+ # the purchase cost. The only way to get a fee-inclusive basis today is to+ # fold the fee into `price` by hand, which loses the fee as a separate fact.+ #+ # Only acquisitions are adjusted. The cost-basis tracker relieves a disposal+ # at the running average and never reads its price, so a disposal's fee has+ # no effect on the basis here. That fee belongs on the proceeds side, in+ # Trade#calculate_realized_gain_loss, which does not deduct it yet. A+ # disposal's price is returned unchanged rather than as a fee-adjusted figure+ # that nothing should use.+ def effective_trade_price(trade, date:)+ price = converted_trade_price(trade, date: date)+ return price unless trade.qty&.positive?++ fee = converted_trade_fee(trade, date: date)+ 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.+ def convert_to_account_currency(amount, trade, date:)+ Money.new(amount, trade.currency).exchange_to(account.currency, date: date).amountrescue Money::ConversionError- trade.price+ amountendenddiff --git a/test/models/holding/forward_calculator_test.rb b/test/models/holding/forward_calculator_test.rbindex 8113835698..36fa1b7d63 100644--- a/test/models/holding/forward_calculator_test.rb+++ b/test/models/holding/forward_calculator_test.rb@@ -208,6 +208,50 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCaseassert_equal BigDecimal("480"), current.cost_basisend+ # 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+ load_prices++ create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 460, fee: 20, account: @account)++ calculated = Holding::ForwardCalculator.new(@account).calculate+ current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }++ # 10 * 460 + 20 = 4,620 for 10 units+ assert_equal BigDecimal("462"), current.cost_basis+ end++ # A basis is what was paid on the day. Converted at today's rate it would+ # drift with every move in the exchange rate since.+ test "a foreign-currency price and fee are converted at the trade's own rate" do+ load_prices+ trade_date = 1.day.ago.to_date+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: trade_date, rate: 2.0)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.0)++ create_trade(@voo, qty: 10, date: trade_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 }++ # (10 * 100 + 10) EUR at 2.0 = 2,020 USD for 10 units, not 1,010 at today's rate+ 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+ load_prices++ sell = create_trade(@voo, qty: -5, date: 1.day.ago.to_date, price: 480, fee: 30, account: @account)++ price = Holding::ForwardCalculator.new(@account)+ .send(:effective_trade_price, sell.entryable, date: sell.date)++ assert_equal BigDecimal("480"), price+ end+test "offline tickers sync holdings based on most recent trade price" dooffline_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.rbindex 29d0f26e95..223541aad2 100644--- a/test/models/holding/reverse_calculator_test.rb+++ b/test/models/holding/reverse_calculator_test.rb@@ -191,6 +191,20 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCaseassert_in_delta 100.0, cost_basis_for(calc, security, buy_date).to_f, 1e-6end+ # 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 "cost_basis_for includes the fee charged on an acquisition" do+ security = Security.create!(ticker: "TST", name: "Test")+ buy_date = 5.days.ago.to_date++ calc = calculator_with_trades(security) do+ create_trade(security, account: @account, qty: 10, price: 100, fee: 25, date: buy_date)+ end++ # 10 * 100 + 25 = 1,025 for 10 units+ assert_in_delta 102.5, cost_basis_for(calc, security, buy_date).to_f, 1e-6+ end+test "cost_basis_for carries forward to dates between buys" dosecurity = Security.create!(ticker: "TST", name: "Test")first_buy = 10.days.ago.to_datediff --git a/test/support/entries_test_helper.rb b/test/support/entries_test_helper.rbindex 4da7ac5db6..18d3284a91 100644--- a/test/support/entries_test_helper.rb+++ b/test/support/entries_test_helper.rb@@ -34,7 +34,7 @@ module EntriesTestHelperEntry.create! entry_defaults.merge(entry_attributes)end- def create_trade(security, account:, qty:, date:, price: nil, currency: "USD")+ def create_trade(security, account:, qty:, date:, price: nil, currency: "USD", fee: 0)trade_price = price || Security::Price.find_by!(security: security, date: date).pricetrade = Trade.new \@@ -42,6 +42,7 @@ module EntriesTestHelpersecurity: security,price: trade_price,currency: currency,+ fee: fee,investment_activity_label: qty > 0 ? "Buy" : "Sell"account.entries.create! \