Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add Holding.preload_avg_costs to batch the cost fallback (#4753)

jaysbeekay44aad3a14b88
diff --git a/app/models/holding.rb b/app/models/holding.rb
index ad9620e8e2..51d0fd9688 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -57,10 +57,128 @@ class Holding < ApplicationRecord
# Use stored cost_basis if available (eliminates N+1 queries)
return Money.new(known_cost_basis, currency) if known_cost_basis
+ # A caller that has many holdings can compute the fallback for all of
+ # them in one query and hand each its answer (.preload_avg_costs), so a
+ # page that lists every position does not run calculate_avg_cost's two
+ # queries per holding. nil is a valid preloaded answer: "unknown".
+ return @preloaded_avg_cost if defined?(@preloaded_avg_cost)
+
# Fallback to calculation for holdings without pre-computed cost_basis
calculate_avg_cost
end
+ # 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.
+ AVG_COST_TRADE_RATE_SQL = <<~SQL.squish.freeze
+ 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
+
+ # #calculate_avg_cost for every holding given, in one query: the same
+ # trades, rates, fees and internal-movement rule, 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
+ # fallback for them. So are holdings with unsaved changes, unsaved ones
+ # included: the query reads the stored row, which is not what they hold.
+ def self.preload_avg_costs(holdings)
+ pending = holdings.reject { |holding| holding.known_cost_basis || holding.changed? }
+ return if pending.empty?
+
+ rows = Holding.where(id: pending.map(&:id))
+ .joins(:account)
+ .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)
+ .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
+ )
+ .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
+ holding.preload_avg_cost(value)
+ end
+ end
+
+ # Joins each trade to the table's rate for its day into the account's
+ # currency: `currency`, one holding's account currency, bound as a value; or
+ # :joined for `accounts.currency`, in a query that joins each holding's
+ # account.
+ def self.avg_cost_rates_join(currency = :joined)
+ target = currency != :joined ? sanitize_sql_array([ "exchange_rates.to_currency = ?", currency ]) : "exchange_rates.to_currency = accounts.currency"
+
+ <<~SQL.squish
+ LEFT JOIN exchange_rates ON (
+ exchange_rates.date = entries.date AND
+ exchange_rates.from_currency = trades.currency AND
+ #{target}
+ )
+ SQL
+ end
+
+ # Total cost with fees in the account's currency, total quantity, and
+ # whether any foreign purchase lacks a usable rate. `currency` as in
+ # .avg_cost_rates_join.
+ #
+ # 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.
+ def self.avg_cost_totals_sql(currency = :joined)
+ foreign = currency != :joined ? sanitize_sql_array([ "trades.currency <> ?", currency ]) : "trades.currency <> accounts.currency"
+ rate = AVG_COST_TRADE_RATE_SQL
+
+ [
+ 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))")
+ ]
+ end
+
+ # nil when there are no purchases -- cost basis is genuinely unknown, not
+ # the market price -- or when a rate is missing.
+ def self.avg_cost_from_totals(total_cost, total_qty, rate_missing, currency)
+ return nil if rate_missing
+ return nil unless total_qty && total_qty > 0
+
+ Money.new(total_cost / total_qty, currency)
+ end
+
+ # Replacing the cost replaces the #trend derived from it.
+ def preload_avg_cost(value)
+ @preloaded_avg_cost = value
+ remove_instance_variable(:@trend) if defined?(@trend)
+ end
+
+ # A reload replaces the attributes, so an answer computed from the old ones
+ # must go with them -- including #trend, which is derived from avg_cost,
+ # and #day_change, which is derived from amount and date.
+ def reload(*)
+ remove_instance_variable(:@preloaded_avg_cost) if defined?(@preloaded_avg_cost)
+ remove_instance_variable(:@trend) if defined?(@trend)
+ remove_instance_variable(:@day_change) if defined?(@day_change)
+ super
+ end
+
def trend
@trend ||= calculate_trend
end
@@ -281,13 +399,7 @@ class Holding < ApplicationRecord
def calculate_avg_cost
trades = account.trades
.with_entry
- .joins(ActiveRecord::Base.sanitize_sql_array([
- "LEFT JOIN exchange_rates ON (
- exchange_rates.date = entries.date AND
- exchange_rates.from_currency = trades.currency AND
- exchange_rates.to_currency = ?
- )", account.currency
- ]))
+ .joins(self.class.avg_cost_rates_join(account.currency))
.where(security_id: security.id)
.where("trades.qty > 0 AND entries.date <= ?", date)
@@ -309,43 +421,8 @@ class Holding < ApplicationRecord
Trade::INTERNAL_MOVEMENT_LABELS
)
- # 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
- return nil unless total_qty && total_qty > 0
+ total_cost, total_qty, rate_missing = trades.pick(*self.class.avg_cost_totals_sql(account.currency))
- Money.new(total_cost / total_qty, currency)
+ self.class.avg_cost_from_totals(total_cost, total_qty, rate_missing, currency)
end
end
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index f4260fc226..1c08f9468a 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -147,6 +147,136 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal 2, queries.count { |sql| sql.include?('FROM "trades"') }
end
+ # Each case pins the figure #avg_cost gives on its own, then checks the batch
+ # hands the holding that same figure and that reading it afterwards runs no
+ # query, so the answer is the preload's and not the per-holding fallback's.
+ test "the batched average cost matches the per-holding one" do
+ sweep = create_security("SWP", prices: [ { date: Date.current, price: 10 } ])
+ plain = create_security("PLN", prices: [ { date: Date.current, price: 10 } ])
+ unrated = create_security("CADX", prices: [ { date: Date.current, price: 10 } ])
+ sweep_holding = create_holding(sweep, Date.current, 5)
+ plain_holding = create_holding(plain, Date.current, 5)
+ unrated_holding = create_holding(unrated, Date.current, 5)
+
+ # fee: (10 * 212 + 10 + 15 * 216 + 5) / 25
+ 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)
+ # a foreign purchase converted at the rate it carries: 10 * 128 CAD at 1.25
+ create_trade(@nvda.security, account: @account, qty: 10, price: 128.00, date: 1.day.ago.to_date, currency: "CAD")
+ .entryable.update!(exchange_rate: 1.25)
+ # a foreign purchase with no rate anywhere
+ create_trade(unrated, account: @account, qty: 5, price: 10, date: Date.current, currency: "CAD")
+ # a sweep is an internal movement, so the position has no knowable cost
+ create_trade(sweep, account: @account, qty: 5, price: 10, date: Date.current)
+ .entryable.update!(investment_activity_label: "Sweep In")
+ create_trade(plain, account: @account, qty: 5, price: 8, date: Date.current)
+ # neither a sale nor a trade dated after the holding enters the average
+ create_trade(@amzn.security, account: @account, qty: -5, price: 300.00, date: Date.current)
+ create_trade(plain, account: @account, qty: 5, price: 999, date: 1.day.from_now.to_date)
+
+ # a second account in another currency: its USD purchase converts into EUR
+ # at the exchange-rate table's rate, 4 * 10 USD at 0.9
+ euro_account = families(:empty).accounts.create!(name: "Euro Brokerage", balance: 0, cash_balance: 0, currency: "EUR", accountable: Investment.new)
+ euro_security = create_security("EURB", prices: [ { date: Date.current, price: 10 } ])
+ euro_holding = euro_account.holdings.create!(date: Date.current, security: euro_security, qty: 4, price: 9, amount: 36, currency: "EUR")
+ ExchangeRate.create!(from_currency: "USD", to_currency: "EUR", date: Date.current, rate: 0.9)
+ create_trade(euro_security, account: euro_account, qty: 4, price: 10, date: Date.current, currency: "USD")
+
+ expected = {
+ @amzn => Money.new(BigDecimal("215")),
+ @nvda => Money.new(BigDecimal("160")),
+ unrated_holding => nil,
+ sweep_holding => nil,
+ plain_holding => Money.new(BigDecimal("8")),
+ euro_holding => Money.new(BigDecimal("9"), "EUR")
+ }
+ expected.each { |holding, value| assert_cost value, Holding.find(holding.id).avg_cost, holding.ticker }
+
+ batch = Holding.where(id: expected.keys.map(&:id)).includes(:security).to_a
+ Holding.preload_avg_costs(batch)
+
+ batch.each do |holding|
+ original = expected.keys.find { |h| h.id == holding.id }
+ # uncached: the per-holding reads above put the fallback's SQL in the
+ # query cache, which capture_sql_queries does not count.
+ queries = Holding.uncached { capture_sql_queries { assert_cost expected[original], holding.avg_cost, holding.ticker } }
+ assert_empty queries, "#{holding.ticker} read its cost after the preload"
+ end
+ end
+
+ test "the batched average cost reads every holding's trades in one query" do
+ batch_sizes = [ 2, 4 ].map do |count|
+ holdings = Array.new(count) do |i|
+ security = create_security("B#{count}#{i}", prices: [ { date: Date.current, price: 10 } ])
+ create_trade(security, account: @account, qty: 1, price: 10, date: Date.current)
+ create_holding(security, Date.current, 1)
+ end
+
+ capture_sql_queries { Holding.preload_avg_costs(holdings) }.size
+ end
+
+ assert_equal [ 1, 1 ], batch_sizes
+ 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)
+
+ queries = capture_sql_queries { Holding.preload_avg_costs([ @amzn ]) }
+
+ assert_empty queries
+ assert_equal Money.new(100), @amzn.avg_cost
+ end
+
+ test "a reload drops the preloaded average cost and the trend built on it" do
+ create_trade(@amzn.security, account: @account, qty: 15, price: 200.00, date: Date.current)
+ Holding.preload_avg_costs([ @amzn ])
+ assert_equal Money.new(200), @amzn.avg_cost
+ trend_before = @amzn.trend
+ assert_not_nil trend_before, "the trend must be built before the reload, or keeping it would go unseen"
+
+ create_trade(@amzn.security, account: @account, qty: 15, price: 100.00, date: Date.current)
+ @amzn.reload
+
+ assert_equal Money.new(150), @amzn.avg_cost
+ assert_not_equal trend_before.value, @amzn.trend.value
+ end
+
+ test "a preload drops the trend built on the cost it replaces" do
+ create_trade(@amzn.security, account: @account, qty: 15, price: 200.00, date: Date.current)
+ assert_equal Money.new(15 * 200), @amzn.trend.previous, "the trend must be built from the fallback before the preload"
+
+ create_trade(@amzn.security, account: @account, qty: 15, price: 100.00, date: Date.current)
+ Holding.preload_avg_costs([ @amzn ])
+
+ assert_equal Money.new(150), @amzn.avg_cost
+ assert_equal Money.new(15 * 150), @amzn.trend.previous
+ end
+
+ test "a reload drops the memoized day change" do
+ assert_equal Money.new(15 * 216), @amzn.day_change.current
+ Holding.where(id: @amzn.id).update_all(amount: 4000)
+
+ @amzn.reload
+
+ assert_equal Money.new(4000), @amzn.day_change.current
+ end
+
+ # The batch reads the stored rows, so for a holding that is unsaved or has
+ # unsaved changes it would answer for another holding -- or for none.
+ test "the batch leaves unsaved and changed holdings to their own attributes" do
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200.00, date: 1.day.ago.to_date)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100.00, date: Date.current)
+ @amzn.date = 1.day.ago.to_date # stored as today, where the average is 150
+ create_trade(@nvda.security, account: @account, qty: 10, price: 120.00, date: Date.current)
+ unsaved = @account.holdings.new(date: Date.current, security: @nvda.security, qty: 1, price: 124, amount: 124, currency: "USD")
+
+ Holding.preload_avg_costs([ @amzn, unsaved ])
+
+ assert_equal Money.new(200), @amzn.avg_cost
+ assert_equal BigDecimal("120"), unsaved.avg_cost&.amount
+ 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))
@@ -491,6 +621,10 @@ class HoldingTest < ActiveSupport::TestCase
private
+ def assert_cost(expected, actual, message)
+ expected.nil? ? assert_nil(actual, message) : assert_equal(expected, actual, message)
+ end
+
def load_holdings
security1 = create_security("AMZN", prices: [
{ date: 1.day.ago.to_date, price: 212.00 },