The personal finance app for everyone (by everyone)
Ruby
Leave a clamped position's basis unknown, and read lot costs back (#4902)
jaysbeekay60169130dd61
diff --git a/app/models/holding.rb b/app/models/holding.rbindex 3742ff969e..eabe32c33f 100644--- a/app/models/holding.rb+++ b/app/models/holding.rb@@ -99,7 +99,8 @@ class Holding < ApplicationRecordSQL# #calculate_avg_cost for every holding given, in one query: the same- # trades, rates, fees and internal-movement rule, read through the same SQL+ # trades, rates, fees, internal-movement and lot rules (a user-costed lot+ # counts at its cost; a clamped position has none), read through the same SQL# (.avg_cost_rates_join, .avg_cost_totals_sql, .avg_cost_from_totals), so# the batch cannot answer differently from the holding on its own. Holdings# with a stored cost basis are skipped, since #avg_cost never reaches the@@ -114,17 +115,36 @@ class Holding < ApplicationRecord.joins("JOIN entries ON entries.account_id = holdings.account_id AND entries.entryable_type = 'Trade' AND entries.date <= holdings.date").joins("JOIN trades ON trades.id = entries.entryable_id AND trades.security_id = holdings.security_id AND trades.qty > 0").joins(avg_cost_rates_join)+ .joins(<<~SQL.squish)+ LEFT JOIN holding_lots lots ON lots.account_id = entries.account_id+ AND lots.source_entry_id = entries.id+ AND lots.manual_total_cost IS NOT NULL+ AND NOT EXISTS (+ SELECT 1 FROM security_splits lot_splits+ WHERE lot_splits.security_id = trades.security_id+ AND lot_splits.ex_date > entries.date+ AND lot_splits.ex_date <= holdings.date+ )+ SQL.group("holdings.id").pluck(Arel.sql("holdings.id"),- Arel.sql(sanitize_sql_array([ "BOOL_OR(trades.investment_activity_label IN (?))", Trade::INTERNAL_MOVEMENT_LABELS ])),- *avg_cost_totals_sql+ Arel.sql(sanitize_sql_array([ "BOOL_OR(trades.investment_activity_label IN (?) AND lots.id IS NULL)", Trade::INTERNAL_MOVEMENT_LABELS ])),+ Arel.sql(<<~SQL.squish),+ BOOL_OR(EXISTS (+ SELECT 1 FROM holding_lots clamped_lots+ WHERE clamped_lots.account_id = holdings.account_id+ AND clamped_lots.security_id = holdings.security_id+ AND clamped_lots.clamped+ ))+ SQL+ *avg_cost_totals_sql(lots: true)).index_by(&:first)pending.each do |holding|- _id, internal_movement, total_cost, total_qty, rate_missing = rows[holding.id]- value = avg_cost_from_totals(total_cost, total_qty, rate_missing, holding.currency) unless internal_movement+ _id, internal_movement, clamped, total_cost, total_qty, rate_missing = rows[holding.id]+ value = avg_cost_from_totals(total_cost, total_qty, rate_missing, holding.currency) unless internal_movement || clampedholding.preload_avg_cost(value)endend@@ -155,14 +175,25 @@ class Holding < ApplicationRecord# 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.- def self.avg_cost_totals_sql(currency = :joined)+ #+ # `lots: true` is for a query that LEFT JOINs the costed holding_lots as+ # `lots`: a trade whose lot the user has costed counts at that cost, which+ # is already in the account's currency, so it needs no rate.+ def self.avg_cost_totals_sql(currency = :joined, lots: false)foreign = currency != :joined ? sanitize_sql_array([ "trades.currency <> ?", currency ]) : "trades.currency <> accounts.currency"rate = AVG_COST_TRADE_RATE_SQL+ cost = "(trades.price * trades.qty + trades.fee) * CASE WHEN #{foreign} THEN #{rate} ELSE 1 END"+ missing = "#{foreign} AND (#{rate} IS NULL OR #{rate} <= 0)"++ if lots+ cost = "CASE WHEN lots.id IS NOT NULL THEN lots.manual_total_cost ELSE #{cost} END"+ missing = "lots.id IS NULL AND #{missing}"+ end[- Arel.sql("SUM((trades.price * trades.qty + trades.fee) * CASE WHEN #{foreign} THEN #{rate} ELSE 1 END)"),+ Arel.sql("SUM(#{cost})"),Arel.sql("SUM(trades.qty)"),- Arel.sql("BOOL_OR(#{foreign} AND (#{rate} IS NULL OR #{rate} <= 0))")+ Arel.sql("BOOL_OR(#{missing})")]end@@ -438,12 +469,32 @@ class Holding < ApplicationRecord# Calculates weighted average cost from buy trades.# Returns nil if no trades exist (cost basis is unknown).def calculate_avg_cost+ # Fewer units than the trades bought (see Holding::ReverseCalculator), so+ # no figure drawn from those trades is the position's.+ return nil if HoldingLot.where(account_id: account_id, security_id: security_id, clamped: true).exists?+trades = account.trades.with_entry.joins(self.class.avg_cost_rates_join(account.currency)).where(security_id: security.id).where("trades.qty > 0 AND entries.date <= ?", date)+ # A trade whose lot the user has costed counts at that cost, a+ # transfer-in included. The cost is already in the account's currency.+ # This fallback divides by the trades' own quantities, which a later split+ # does not restate, so a cost set on a lot split since is not used here.+ trades = trades.joins(self.class.sanitize_sql_array([ <<~SQL.squish, date ]))+ LEFT JOIN holding_lots lots ON lots.account_id = entries.account_id+ AND lots.source_entry_id = entries.id+ AND lots.manual_total_cost IS NOT NULL+ AND NOT EXISTS (+ SELECT 1 FROM security_splits lot_splits+ WHERE lot_splits.security_id = trades.security_id+ AND lot_splits.ex_date > entries.date+ AND lot_splits.ex_date <= ?+ )+ SQL+# An internal movement is not a purchase: securities moved in from elsewhere were# acquired at a price nothing here knows, so treating the day they# arrived as their cost states a number that looks authoritative and is@@ -453,16 +504,16 @@ class Holding < ApplicationRecord# row. Averaging the purchases alone and applying that to every unit is# the same fabrication in a quieter form: buy one at 30k, receive one, and# the position would report 30k a unit for two units it did not cost that.- return nil if trades.where(investment_activity_label: Trade::INTERNAL_MOVEMENT_LABELS).exists?+ return nil if trades.where(investment_activity_label: Trade::INTERNAL_MOVEMENT_LABELS, lots: { id: nil }).exists?# IS DISTINCT FROM, because `!=` is NULL for an unlabelled row and would# drop the ordinary purchases that carry no label at all.trades = trades.where(- "trades.investment_activity_label NOT IN (?) OR trades.investment_activity_label IS NULL",+ "trades.investment_activity_label NOT IN (?) OR trades.investment_activity_label IS NULL OR lots.id IS NOT NULL",Trade::INTERNAL_MOVEMENT_LABELS)- total_cost, total_qty, rate_missing = trades.pick(*self.class.avg_cost_totals_sql(account.currency))+ total_cost, total_qty, rate_missing = trades.pick(*self.class.avg_cost_totals_sql(account.currency, lots: true))self.class.avg_cost_from_totals(total_cost, total_qty, rate_missing, currency)enddiff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rbindex 3130c0ee65..ed76272c00 100644--- a/app/models/holding/reverse_calculator.rb+++ b/app/models/holding/reverse_calculator.rb@@ -130,7 +130,7 @@ class Holding::ReverseCalculatorcurrency: price.currency,amount: qty * price.price,cost_basis: cost_basis_for(security_id, date),- cost_basis_unknown: transferred_by?(security_id, date)+ cost_basis_unknown: transferred_by?(security_id, date) || @clamped_security_ids.include?(security_id))end.compactend@@ -293,8 +293,10 @@ class Holding::ReverseCalculatorrecorded || @unknown_spans[security_id].any? { |start, stop| start <= date && (stop.nil? || date < stop) }end+ # A clamped position holds fewer units than its trades bought, so no+ # figure drawn from those trades is the position's.def cost_basis_for(security_id, date)- return nil if transferred_by?(security_id, date)+ return nil if transferred_by?(security_id, date) || @clamped_security_ids.include?(security_id)cost_basis_snapshot(security_id, date)&.secondenddiff --git a/test/models/holding/reverse_calculator_test.rb b/test/models/holding/reverse_calculator_test.rbindex 76bcdc8296..e63e440a3f 100644--- a/test/models/holding/reverse_calculator_test.rb+++ b/test/models/holding/reverse_calculator_test.rb@@ -210,7 +210,7 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCasefirst_buy = 10.days.ago.to_datesecond_buy = 3.days.ago.to_date- calc = calculator_with_trades(security) do+ calc = calculator_with_trades(security, held: 15) docreate_trade(security, account: @account, qty: 10, price: 100, date: first_buy)create_trade(security, account: @account, qty: 5, price: 130, date: second_buy)end@@ -228,7 +228,7 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCasesecurity = Security.create!(ticker: "TST", name: "Test")buy_date = 5.days.ago.to_date- calc = calculator_with_trades(security) do+ calc = calculator_with_trades(security, held: 15) docreate_trade(security, account: @account, qty: 10, price: 100, date: buy_date)create_trade(security, account: @account, qty: 5, price: 130, date: buy_date)end@@ -656,9 +656,11 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCase# Brokerage Cash: $5,000# Holdings Value: $15,000# Total Balance: $20,000- def calculator_with_trades(security)+ # `held` is what the provider reports; a position whose trades buy more+ # than that is clamped, and has no cost basis.+ def calculator_with_trades(security, held: 10)yield if block_given?- snapshot = OpenStruct.new(to_h: { security.id => 10 })+ snapshot = OpenStruct.new(to_h: { security.id => held })calc = Holding::ReverseCalculator.new(@account, portfolio_snapshot: snapshot)calc.send(:precompute_cost_basis)calcdiff --git a/test/models/holding_lot_test.rb b/test/models/holding_lot_test.rbindex 4fa8ba5f9d..426ee59b64 100644--- a/test/models/holding_lot_test.rb+++ b/test/models/holding_lot_test.rb@@ -310,7 +310,6 @@ class HoldingLotTest < ActiveSupport::TestCaseclamped = HoldingLot.opening.find_by!(security: @gapped)assert_equal [ 0, true ], [ clamped.qty, clamped.clamped ]- assert_equal 125, @account.holdings.find_by!(security: @gapped, date: d(8)).cost_basis, "the figure is today's"assert_equal [ @gapped.id ], HoldingLot.where(clamped: true).pluck(:security_id), "nothing flagged on the controls"endend@@ -354,12 +353,14 @@ class HoldingLotTest < ActiveSupport::TestCasematerialize(:reverse)lot = HoldingLot.opening.find_by!(security: @opening)assert_equal [ BigDecimal("1.333333333333333333"), false ], [ lot.qty, lot.clamped ]+ assert_equal BigDecimal("102.5"), @account.holdings.find_by!(security: @opening, date: d(9)).cost_basis@account.holdings.find_by!(security: @opening, date: d(10)).update!(qty: 5, amount: 150)materialize(:reverse)lot.reloadassert_equal [ 0, true ], [ lot.qty, lot.clamped ], "5 reported against 8 traded"+ assert_nil @account.holdings.find_by!(security: @opening, date: d(9)).cost_basis, "the stored figure is cleared"endend@@ -802,6 +803,74 @@ class HoldingLotTest < ActiveSupport::TestCaseendend+ # --- Clamped positions ---------------------------------------------------------++ test "provider quantity below trade-derived quantity makes the position unknown" do+ travel_to TODAY do+ build_reverse_fixture+ materialize(:reverse)++ assert_nil @account.holdings.find_by!(security: @gapped, date: d(9)).cost_basis, "trades alone give 125"+ assert_equal BigDecimal("102.5"), @account.holdings.find_by!(security: @opening, date: d(9)).cost_basis, "the control keeps its figure"+ end+ end++ test "the avg-cost fallback answers nil for a clamped position" do+ travel_to TODAY do+ build_reverse_fixture+ materialize(:reverse)+ gapped = @account.holdings.find_by!(security: @gapped, date: d(10))+ control = @account.holdings.find_by!(security: @opening, date: d(10))++ assert_nil Holding.find(gapped.id).avg_cost, "trades alone give 125"+ assert_not_nil Holding.find(control.id).avg_cost+ end+ end++ # --- The fallback reads user-set lot costs ------------------------------------++ # The fallback divides by the trades' own quantities, which a later split+ # does not restate, so a user-set cost spread over them would read high.+ # Across a split the transferred units stay unknown, as before the cost was+ # set, in both the single and the batched path.+ test "the avg-cost fallback leaves a costed transfer unknown across a later split" do+ travel_to TODAY do+ setup_account+ link_account+ security = priced_security("LOTS2", 30)+ transfer = trade(security, 10, 30, 2, label: Trade::TRANSFER_LABEL)+ security.splits.create!(ex_date: d(5), numerator: 2, denominator: 1, source: "manual")+ provider_row = provider_holding(security, 20, nil)+ materialize(:reverse)++ HoldingLot.find_by!(source_entry: transfer).set_manual_total_cost!(1500)++ assert_nil Holding.find(provider_row.id).avg_cost, "not 1500 / 10, the unsplit units"+ batch = [ Holding.find(provider_row.id) ]+ Holding.preload_avg_costs(batch)+ assert_nil batch.first.avg_cost+ end+ end++ test "the avg-cost fallback counts a user-set lot cost, so a linked position resolves" do+ travel_to TODAY do+ setup_account+ link_account+ security = priced_security("LOTR", 30)+ transfer = trade(security, 60, 30, 2, label: Trade::TRANSFER_LABEL)+ buy = trade(security, 40, 20, 3)+ provider_row = provider_holding(security, 100, nil)+ materialize(:reverse)+ assert_nil Holding.find(provider_row.id).avg_cost, "unknown before"++ HoldingLot.find_by!(source_entry: transfer).set_manual_total_cost!(720)+ assert_equal BigDecimal("15.2"), Holding.find(provider_row.id).avg_cost.amount++ HoldingLot.find_by!(source_entry: buy).set_manual_total_cost!(600)+ assert_equal BigDecimal("13.2"), Holding.find(provider_row.id).avg_cost.amount, "(720 + 600) / 100"+ end+ end+test "a user-set lot cost of zero is the holding's cost, alone and in a batch" dotravel_to TODAY dosetup_accountdiff --git a/test/models/holding_test.rb b/test/models/holding_test.rbindex c4828268e4..f2791b7cfa 100644--- a/test/models/holding_test.rb+++ b/test/models/holding_test.rb@@ -262,6 +262,39 @@ class HoldingTest < ActiveSupport::TestCaseassert_equal [ 1, 1 ], batch_sizesend+ # The lot rules #calculate_avg_cost applies, which the batch must apply too:+ # a lot the user has costed counts at that cost (an internal movement+ # included), and a clamped position has no cost at all. The expected+ # column pins #avg_cost itself, so a rule dropped from both paths at once+ # still fails.+ test "the batch follows the holding's own lot rules" do+ day = 1.day.ago.to_date+ costed = create_security("LOTC", prices: [ { date: Date.current, price: 100 } ])+ create_trade(costed, account: @account, qty: 5, price: 100, date: day)+ moved_in = create_trade(costed, account: @account, qty: 5, price: 100, date: day)+ moved_in.entryable.update!(investment_activity_label: "Sweep In")+ HoldingLot.create!(account: @account, security: costed, source_entry: moved_in, qty: 5,+ currency: "USD", acquired_on: day, manual_total_cost: 400)++ clamped = create_security("LOTK", prices: [ { date: Date.current, price: 100 } ])+ create_trade(clamped, account: @account, qty: 10, price: 100, date: day)+ HoldingLot.create!(account: @account, security: clamped, origin_security: clamped, qty: 0, currency: "USD", clamped: true)++ cases = { costed: create_holding(costed, Date.current, 10), clamped: create_holding(clamped, Date.current, 10) }+ expected = {+ costed: BigDecimal("90"), # (5 * 100 + the lot's 400) / 10+ clamped: nil+ }++ batch = Holding.where(id: cases.values.map(&:id)).to_a+ Holding.preload_avg_costs(batch)+ batched = cases.transform_values { |holding| batch.find { |h| h.id == holding.id }.avg_cost&.amount }+ own = cases.transform_values { |holding| holding.reload.avg_cost&.amount }++ assert_equal expected, own, "#avg_cost moved"+ assert_equal own, batched, "the batch disagrees with #avg_cost"+ end+test "the batch leaves a stored cost basis alone and does not query for it" do@amzn.update!(cost_basis: 100)create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: Date.current)