Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add InvestmentStatement#holdings_table_rows for a holdings table (#4761)

jaysbeekay3d66c6278f39
diff --git a/app/models/holding.rb b/app/models/holding.rb
index 51d0fd9688..1a17094e37 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -30,6 +30,10 @@ class Holding < ApplicationRecord
delegate :ticker, to: :security
+ # Answers derived from the attributes go when a change to them is saved,
+ # as on #reload: `changed?` is false again by then and cannot tell.
+ after_save :forget_derived_answers
+
def name
security.name || ticker
end
@@ -60,8 +64,10 @@ class Holding < ApplicationRecord
# 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)
+ # queries per holding. nil is a valid preloaded answer: "unknown". It
+ # answers for the attributes it was computed from, so a holding changed
+ # since then computes its own.
+ return @preloaded_avg_cost if defined?(@preloaded_avg_cost) && !changed?
# Fallback to calculation for holdings without pre-computed cost_basis
calculate_avg_cost
@@ -173,9 +179,7 @@ class Holding < ApplicationRecord
# 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)
+ forget_derived_answers
super
end
@@ -375,6 +379,12 @@ class Holding < ApplicationRecord
end
private
+ def forget_derived_answers
+ 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)
+ end
+
def amount_in_account_currency
return amount if currency == account.currency
diff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rb
index 06aa3ba92e..040be8ac08 100644
--- a/app/models/investment_statement.rb
+++ b/app/models/investment_statement.rb
@@ -75,6 +75,15 @@ class InvestmentStatement
.includes(:security, :account)
end
+ # current_holdings as an Array, with the average-cost fallback for every
+ # holding that has no stored cost basis computed in one query and handed
+ # to the holding (Holding.preload_avg_costs), so the roll-up's trends, the
+ # unrealized gains and the holdings table do not run
+ # Holding#calculate_avg_cost's two queries per holding. Memoized.
+ def holdings_with_avg_costs
+ @holdings_with_avg_costs ||= current_holdings.to_a.tap { |holdings| Holding.preload_avg_costs(holdings) }
+ end
+
# Top investments rolled up by security across accounts, ranked by
# family-currency value. Weight is % of total portfolio (including cash).
# Presence is gated on holdings totals — not Account#balance — so a stale
@@ -89,7 +98,8 @@ class InvestmentStatement
total = weight_denominator(holdings_total)
# Rank/limit on value first; only then compute cost-basis trends for the
- # rows that will be rendered (avoids avg_cost/trade lookups for the rest).
+ # rows that will be rendered. The cost basis behind them is preloaded for
+ # every holding in one query (holdings_with_avg_costs).
rolled_up
.first(limit)
.map do |security, value, holdings|
@@ -169,9 +179,38 @@ class InvestmentStatement
end
end
+ # Every security the family holds as one row, with its positions across
+ # accounts, sorted for a holdings table. Built from the preloaded
+ # current_holdings (holdings_with_avg_costs) and previous_holdings, so the
+ # query count does not grow with the number of holdings.
+ #
+ # Cost basis and unrealised P&L cover the positions whose Holding#avg_cost
+ # is known -- a stored cost basis, or the average of the purchases -- and a
+ # row with any position outside them is flagged missing_cost_basis. Weights
+ # share top_holdings' denominator.
+ #
+ # sort: one of HOLDINGS_SORT_KEYS; dir: "asc" or "desc". Each falls back on
+ # its own -- an unknown sort to "value", an unknown dir to "desc" -- so the
+ # query string cannot raise and a valid half of it is kept.
+ HOLDINGS_SORT_KEYS = %w[value weight return day_change name].freeze
+ HOLDINGS_SORT_DIRECTIONS = %w[asc desc].freeze
+
+ def holdings_table_rows(sort: "value", dir: "desc")
+ rolled_up = holdings_rolled_up_by_security
+ return [] if rolled_up.empty?
+
+ total = weight_denominator(rolled_up.sum { |_, value, _| value })
+
+ rows = rolled_up.map do |security, value, positions|
+ build_holdings_table_row(security, value, positions, total)
+ end
+
+ sort_holdings_table_rows(rows, sort: sort, dir: dir)
+ end
+
# Unrealized gains across all holdings, summed in family currency
def unrealized_gains
- current_holdings.sum do |holding|
+ holdings_with_avg_costs.sum do |holding|
trend = holding.trend
trend ? convert_to_family_currency(trend.value, holding.currency) : 0
end
@@ -193,7 +232,7 @@ class InvestmentStatement
end
def unrealized_gains_trend
- holdings = current_holdings.to_a
+ holdings = holdings_with_avg_costs
return nil if holdings.empty?
# Only include holdings with known cost basis in the calculation
@@ -284,16 +323,61 @@ class InvestmentStatement
)
end
+ # The snapshot before each current holding, keyed by the current holding's
+ # id: the latest row for the same account, security and currency dated
+ # before the current row, which is what Holding#day_change compares
+ # against. One query for every holding rather than one per holding, so a
+ # page that lists every position does not issue a query per row. Memoized
+ # like current_holdings.
+ def previous_holdings
+ @previous_holdings ||= begin
+ current_ids = current_holdings.map(&:id)
+
+ if current_ids.any?
+ # Keyed by the current holding, not by account and security: a provider
+ # can report one security in two currencies, and each current row has
+ # its own previous snapshot in its own currency.
+ Holding.find_by_sql([ <<~SQL.squish, { current_ids: current_ids } ]).index_by(&:current_holding_id)
+ SELECT prior.*, current_holdings.id AS current_holding_id
+ FROM holdings current_holdings
+ JOIN LATERAL (
+ SELECT holdings.*
+ FROM holdings
+ WHERE holdings.account_id = current_holdings.account_id
+ AND holdings.security_id = current_holdings.security_id
+ AND holdings.currency = current_holdings.currency
+ AND holdings.date < current_holdings.date
+ ORDER BY holdings.date DESC
+ LIMIT 1
+ ) prior ON TRUE
+ WHERE current_holdings.id IN (:current_ids)
+ SQL
+ else
+ {}
+ end
+ end
+ end
+
+ # Day change for one current holding against its previous snapshot, in the
+ # holding's currency, or nil without a prior snapshot. Same result as
+ # Holding#day_change, without its per-holding query.
+ def holding_day_change(holding)
+ return nil unless holding.amount_money
+
+ previous = previous_holdings[holding.id]
+ return nil unless previous&.amount_money
+
+ Trend.new(current: holding.amount_money, previous: previous.amount_money)
+ end
+
# Day change across portfolio, summed in family currency
def day_change
changes = current_holdings.to_a.filter_map do |h|
- t = h.day_change
+ t = holding_day_change(h)
next nil unless t
- curr = t.current.is_a?(Money) ? t.current.amount : t.current
- prev = t.previous.is_a?(Money) ? t.previous.amount : t.previous
[
- convert_to_family_currency(curr, h.currency),
- convert_to_family_currency(prev, h.currency)
+ convert_to_family_currency(t.current.amount, h.currency),
+ convert_to_family_currency(t.previous.amount, h.currency)
]
end
@@ -516,6 +600,106 @@ class InvestmentStatement
end
end
+ # One row of #holdings_table_rows: a security rolled up across the
+ # accounts that hold it, in family currency.
+ HoldingsTableRow = Data.define(
+ :security, :positions, :accounts_count, :qty, :avg_cost, :amount, :weight,
+ :unrealized, :day_change, :missing_cost_basis
+ ) do
+ def ticker = security.ticker
+ def name = security.name.presence || ticker
+ def amount_money = amount
+ end
+
+ # Builds one rolled-up row of the holdings table for `security`: the summed
+ # quantity across `positions`, its average cost and unrealised return over
+ # the positions whose basis is known, and its weight against the caller's
+ # `total` -- which is chosen by #weight_denominator, not here.
+ def build_holdings_table_row(security, value, positions, total)
+ qty = positions.sum(&:qty)
+
+ # Same rule as combined_holding_trend: the return covers the positions
+ # whose cost basis is known, and a position is known when
+ # Holding#avg_cost answers -- which includes the trade-history fallback,
+ # preloaded for every holding by holdings_with_avg_costs. Reading
+ # `cost_basis` directly instead would hide a return on this table that
+ # top_holdings counts for the same security.
+ known = positions.select(&:avg_cost)
+ missing_cost_basis = known.size < positions.size
+
+ cost = nil
+ unrealized = nil
+ known_qty = known.sum(&:qty)
+ if known.any?
+ cost = known.sum { |holding| convert_to_family_currency(holding.qty * holding.avg_cost.amount, holding.currency) }
+ known_value = known.sum { |holding| convert_to_family_currency(holding.amount, holding.currency) }
+ unrealized = Trend.new(current: Money.new(known_value, family.currency), previous: Money.new(cost, family.currency))
+ end
+
+ day_changes = positions.filter_map do |holding|
+ trend = holding_day_change(holding)
+ next unless trend
+ [ convert_to_family_currency(trend.current.amount, holding.currency), convert_to_family_currency(trend.previous.amount, holding.currency) ]
+ end
+ day_change = if day_changes.any?
+ Trend.new(
+ current: Money.new(day_changes.sum(&:first), family.currency),
+ previous: Money.new(day_changes.sum(&:last), family.currency)
+ )
+ end
+
+ HoldingsTableRow.new(
+ security: security,
+ positions: positions,
+ accounts_count: positions.map(&:account_id).uniq.size,
+ qty: qty,
+ avg_cost: (cost && known_qty.positive?) ? Money.new(cost / known_qty, family.currency) : nil,
+ amount: Money.new(value, family.currency),
+ weight: total.zero? ? 0 : (value / total * 100).round(2),
+ unrealized: unrealized,
+ day_change: day_change,
+ missing_cost_basis: missing_cost_basis
+ )
+ end
+
+ def sort_holdings_table_rows(rows, sort:, dir:)
+ sort = HOLDINGS_SORT_KEYS.include?(sort.to_s) ? sort.to_s : "value"
+ dir = HOLDINGS_SORT_DIRECTIONS.include?(dir.to_s) ? dir.to_s : "desc"
+
+ # Rows without the sorted figure go last whichever direction is asked.
+ # Ties break by name, then security id, in both directions, so rows with
+ # the same figure keep their order between requests.
+ present, absent = rows.partition { |row| sort_key_present?(row, sort) }
+ present = present.sort do |a, b|
+ order = sort_value(a, sort) <=> sort_value(b, sort)
+ order = -order if dir == "desc"
+ order.nonzero? || (tiebreak(a) <=> tiebreak(b))
+ end
+ present + absent.sort_by { |row| tiebreak(row) }
+ end
+
+ def tiebreak(row)
+ [ row.name.downcase, row.security.id.to_s ]
+ end
+
+ def sort_value(row, sort)
+ case sort
+ when "value" then row.amount.amount
+ when "weight" then row.weight
+ when "return" then row.unrealized.value.amount
+ when "day_change" then row.day_change.value.amount
+ when "name" then row.name.downcase
+ end
+ end
+
+ def sort_key_present?(row, sort)
+ case sort
+ when "return" then row.unrealized.present?
+ when "day_change" then row.day_change.present?
+ else true
+ end
+ end
+
# Groups current holdings by security and sums family-currency value.
# Returns [[security, value, holdings], ...] sorted by value descending.
# Callers that need return trends should call combined_holding_trend only
@@ -532,9 +716,10 @@ class InvestmentStatement
[ portfolio_value, holdings_total ].max
end
+ # Memoized: top_holdings, allocation and holdings_table_rows all start
+ # here, and the grouping and FX conversion need only run once per instance.
def holdings_rolled_up_by_security
- current_holdings
- .to_a
+ @holdings_rolled_up_by_security ||= holdings_with_avg_costs
.group_by(&:security_id)
.filter_map do |_security_id, holdings|
# Filter row by row rather than on the netted total. current_holdings
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index e0ce2b1b9a..1503a3079c 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -277,6 +277,33 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal BigDecimal("120"), unsaved.avg_cost&.amount
end
+ # A preloaded cost answers for the attributes it was computed from. Once the
+ # holding changes, the holding's own attributes decide again.
+ test "a holding changed after the preload reads its own cost, not the preloaded one" 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)
+ Holding.preload_avg_costs([ @amzn ])
+ assert_equal Money.new(150), @amzn.avg_cost, "the preload answers for today's date"
+
+ @amzn.date = 1.day.ago.to_date
+
+ assert_equal Money.new(200), @amzn.avg_cost
+ end
+
+ test "a holding saved after the preload reads its own cost, not the preloaded one" do
+ earlier = 400.days.ago.to_date
+ create_trade(@amzn.security, account: @account, qty: 10, price: 200.00, date: earlier)
+ create_trade(@amzn.security, account: @account, qty: 10, price: 100.00, date: Date.current)
+ Holding.preload_avg_costs([ @amzn ])
+ assert_equal Money.new(150), @amzn.avg_cost, "the preload answers for today's date"
+ assert_equal Money.new(150 * @amzn.qty), @amzn.trend.previous, "the trend is built on the preloaded cost"
+
+ @amzn.update!(date: earlier)
+
+ assert_equal Money.new(200), @amzn.avg_cost
+ assert_equal Money.new(200 * @amzn.qty), @amzn.trend.previous
+ 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/investment_statement_test.rb b/test/models/investment_statement_test.rb
index 7bfa6b49b8..0b2712d7a0 100644
--- a/test/models/investment_statement_test.rb
+++ b/test/models/investment_statement_test.rb
@@ -1250,6 +1250,257 @@ class InvestmentStatementTest < ActiveSupport::TestCase
assert_empty @statement.allocation_by("nonsense")
end
+ test "previous_holdings loads the prior snapshot of every holding in one query" do
+ ira = create_investment_account(balance: 5000)
+ taxable = create_investment_account(balance: 3000)
+ aapl = Security.create!(ticker: "AAPL", name: "Apple")
+ msft = Security.create!(ticker: "MSFT", name: "Microsoft")
+
+ [ [ ira, aapl, 10 ], [ ira, msft, 5 ], [ taxable, aapl, 4 ] ].each do |account, security, qty|
+ Holding.create!(account: account, security: security, date: 2.days.ago.to_date, qty: qty, price: 100, amount: qty * 100, currency: "USD")
+ Holding.create!(account: account, security: security, date: 1.day.ago.to_date, qty: qty, price: 110, amount: qty * 110, currency: "USD")
+ Holding.create!(account: account, security: security, date: Date.current, qty: qty, price: 120, amount: qty * 120, currency: "USD")
+ end
+ # A holding with no prior snapshot has no day change.
+ only_today = Security.create!(ticker: "NEW", name: "New")
+ Holding.create!(account: taxable, security: only_today, date: Date.current, qty: 1, price: 50, amount: 50, currency: "USD")
+
+ @statement.current_holdings.to_a
+ queries = capture_sql_queries { @statement.previous_holdings; @statement.day_change }
+ holdings_queries = queries.grep(/FROM "?holdings"?\b/)
+
+ assert_equal 1, holdings_queries.size, "previous snapshots must come from one query, not one per holding"
+
+ previous = @statement.previous_holdings
+ current = @statement.current_holdings.index_by { |holding| [ holding.account_id, holding.security_id ] }
+ assert_equal 3, previous.size
+ assert_equal 1.day.ago.to_date, previous[current[[ ira.id, aapl.id ]].id].date
+ assert_nil previous[current[[ taxable.id, only_today.id ]].id]
+
+ # Same answer as the per-holding lookup, summed in family currency:
+ # today 19 * 120 = 2280 vs yesterday 19 * 110 = 2090.
+ day_change = @statement.day_change
+ assert_equal Money.new(2280, "USD"), day_change.current
+ assert_equal Money.new(2090, "USD"), day_change.previous
+ per_holding = @statement.current_holdings.filter_map { |h| h.day_change }
+ assert_equal per_holding.sum { |t| t.current.amount }, day_change.current.amount
+ end
+
+ test "holdings_table_rows measures a row's return over the positions whose cost basis is known" do
+ ira = create_investment_account(balance: 5000, cash_balance: 500)
+ taxable = create_investment_account(balance: 3000)
+ aapl = Security.create!(ticker: "AAPL", name: "Apple")
+ msft = Security.create!(ticker: "MSFT", name: "Microsoft")
+
+ Holding.create!(account: ira, security: aapl, date: 1.day.ago.to_date, qty: 10, price: 190, amount: 1900, currency: "USD", cost_basis: 150, cost_basis_locked: true)
+ Holding.create!(account: ira, security: aapl, date: Date.current, qty: 10, price: 200, amount: 2000, currency: "USD", cost_basis: 150, cost_basis_locked: true)
+ # No stored basis and no trades in the second account, so Holding#avg_cost
+ # is nil there and that position is outside the row's return.
+ Holding.create!(account: taxable, security: aapl, date: Date.current, qty: 5, price: 200, amount: 1000, currency: "USD")
+ Holding.create!(account: ira, security: msft, date: Date.current, qty: 4, price: 500, amount: 2000, currency: "USD", cost_basis: 400, cost_basis_locked: true)
+
+ rows = @statement.holdings_table_rows
+
+ assert_equal %w[AAPL MSFT], rows.map(&:ticker)
+ aapl_row, msft_row = rows
+
+ assert_equal 2, aapl_row.accounts_count
+ assert_equal 15, aapl_row.qty
+ assert_equal Money.new(3000, "USD"), aapl_row.amount_money
+ assert aapl_row.missing_cost_basis, "one position has no known basis, so the row still warns"
+ # Partial credit, the rule unrealized_gains and combined_holding_trend
+ # already use: cost and return cover the 10 shares whose basis is known
+ # (2000 now against 1500 cost), not the 5 that have none.
+ assert_equal Money.new(150, "USD"), aapl_row.avg_cost
+ assert_equal Money.new(2000, "USD"), aapl_row.unrealized.current
+ assert_equal Money.new(1500, "USD"), aapl_row.unrealized.previous
+ assert_equal Money.new(500, "USD"), aapl_row.unrealized.value
+ # Day change from the one position with a prior snapshot: 2000 vs 1900.
+ assert_equal Money.new(100, "USD"), aapl_row.day_change.value
+
+ assert_not msft_row.missing_cost_basis
+ assert_equal Money.new(400, "USD"), msft_row.avg_cost
+ assert_equal Money.new(400, "USD"), msft_row.unrealized.value
+ assert_nil msft_row.day_change
+ # Weights use the same denominator as top_holdings: max(8000, 5000).
+ assert_in_delta 37.5, aapl_row.weight, 0.01
+ assert_in_delta 25.0, msft_row.weight, 0.01
+ end
+
+ test "holdings_table_rows sorts by a whitelisted key and puts rows without the figure last" do
+ account = create_investment_account(balance: 6000)
+ with_basis = Security.create!(ticker: "BBB", name: "Beta")
+ without_basis = Security.create!(ticker: "AAA", name: "Alpha")
+ big = Security.create!(ticker: "CCC", name: "Gamma")
+
+ Holding.create!(account: account, security: with_basis, date: Date.current, qty: 1, price: 1000, amount: 1000, currency: "USD", cost_basis: 800, cost_basis_locked: true)
+ Holding.create!(account: account, security: without_basis, date: Date.current, qty: 1, price: 2000, amount: 2000, currency: "USD")
+ Holding.create!(account: account, security: big, date: Date.current, qty: 1, price: 3000, amount: 3000, currency: "USD", cost_basis: 3500, cost_basis_locked: true)
+
+ assert_equal %w[CCC AAA BBB], @statement.holdings_table_rows.map(&:ticker), "default is value desc"
+ assert_equal %w[BBB AAA CCC], @statement.holdings_table_rows(sort: "value", dir: "asc").map(&:ticker)
+ assert_equal %w[AAA BBB CCC], @statement.holdings_table_rows(sort: "name", dir: "asc").map(&:ticker)
+ assert_equal %w[CCC BBB AAA], @statement.holdings_table_rows(sort: "name", dir: "desc").map(&:ticker)
+ # Return: BBB +200, CCC -500, AAA unknown and therefore last both ways.
+ assert_equal %w[BBB CCC AAA], @statement.holdings_table_rows(sort: "return", dir: "desc").map(&:ticker)
+ assert_equal %w[CCC BBB AAA], @statement.holdings_table_rows(sort: "return", dir: "asc").map(&:ticker)
+ assert_equal %w[CCC AAA BBB], @statement.holdings_table_rows(sort: "drop table", dir: "sideways").map(&:ticker), "unknown keys fall back to the default"
+ assert_equal %w[BBB AAA CCC], @statement.holdings_table_rows(sort: "drop table", dir: "asc").map(&:ticker), "an unknown sort keeps a valid dir"
+ assert_equal %w[CCC BBB AAA], @statement.holdings_table_rows(sort: "name", dir: "sideways").map(&:ticker), "an unknown dir keeps a valid sort"
+ end
+
+ test "holdings_table_rows issues no query per holding" do
+ account = create_investment_account(balance: 10_000)
+ 5.times do |i|
+ security = Security.create!(ticker: "S#{i}", name: "Security #{i}")
+ Holding.create!(account: account, security: security, date: 1.day.ago.to_date, qty: 1, price: 90, amount: 90, currency: "USD")
+ Holding.create!(account: account, security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "USD", cost_basis: 80)
+ end
+ @statement.current_holdings.to_a
+
+ queries = capture_sql_queries { @statement.holdings_table_rows(sort: "day_change", dir: "desc") }
+
+ assert_equal 1, queries.grep(/FROM "?holdings"?\b/).size, "only the previous-snapshot query may run"
+ assert_empty queries.grep(/FROM "trades"|FROM "security_prices"/), "no cost-basis fallback or price lookups per row"
+ end
+
+ # Positions with no stored basis take their cost from the trade history,
+ # which the table reads for every holding in one query rather than two per
+ # row (Holding.preload_avg_costs).
+ test "holdings_table_rows reads the trade-history cost of every holding in one query" do
+ account = create_investment_account(balance: 10_000)
+ 3.times do |i|
+ security = Security.create!(ticker: "T#{i}", name: "Traded #{i}")
+ Holding.create!(account: account, security: security, date: Date.current, qty: 10, price: 100, amount: 1000, currency: "USD")
+ create_trade_for(account: account, security: security, qty: 10, price: 60 + i * 10, date: 1.day.ago.to_date)
+ end
+ @statement.current_holdings.to_a
+
+ rows = nil
+ queries = Holding.uncached { capture_sql_queries { rows = @statement.holdings_table_rows } }
+
+ assert_equal 1, queries.grep(/FROM "trades"|JOIN trades/).size, "one batched cost query, not two per holding"
+ assert_equal({ "T0" => 60, "T1" => 70, "T2" => 80 }, rows.to_h { |row| [ row.ticker, row.avg_cost.amount.to_i ] })
+ assert rows.none?(&:missing_cost_basis)
+ end
+
+ # The dashboard and the report read unrealized_gains_trend before
+ # top_holdings on one statement, so the gains read the trade-history cost
+ # the same batched way, and top_holdings reuses it.
+ test "unrealized gains read the trade-history cost of every holding in one query" do
+ account = create_investment_account(balance: 10_000)
+ 3.times do |i|
+ security = Security.create!(ticker: "G#{i}", name: "Gain #{i}")
+ Holding.create!(account: account, security: security, date: Date.current, qty: 10, price: 100, amount: 1000, currency: "USD")
+ create_trade_for(account: account, security: security, qty: 10, price: 60 + i * 10, date: 1.day.ago.to_date)
+ end
+ cost_queries = ->(statement, &read) do
+ statement.current_holdings.to_a
+ Holding.uncached { capture_sql_queries { read.call(statement) } }.grep(/FROM "trades"|JOIN trades/).size
+ end
+
+ counts = %i[unrealized_gains unrealized_gains_trend].to_h do |method|
+ [ method, cost_queries.call(InvestmentStatement.new(@family, user: nil)) { |s| s.public_send(method) } ]
+ end
+ assert_equal({ unrealized_gains: 1, unrealized_gains_trend: 1 }, counts)
+
+ trend = nil
+ statement = InvestmentStatement.new(@family, user: nil)
+ dashboard = cost_queries.call(statement) { |s| trend = s.unrealized_gains_trend; s.top_holdings(limit: 5) }
+ assert_equal 1, dashboard, "top_holdings must reuse the cost the gains read"
+
+ # 3000 held at a cost of 600 + 700 + 800
+ assert_equal Money.new(3000), trend.current
+ assert_equal Money.new(2100), trend.previous
+ assert_in_delta 900, statement.unrealized_gains, 0.001
+ end
+
+ # A provider can report one security in two currencies in the same account on
+ # the same day, and both rows are current. Each compares against its own
+ # currency's previous snapshot, as Holding#day_change does, and the portfolio
+ # day change counts both. Read through the real current_holdings, not a stub,
+ # so a selection that kept one row per account and security would fail here.
+ test "a security held in two currencies in one account keeps a day change per currency" do
+ account = create_investment_account(balance: 10_000)
+ coinstats_item = @family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ provider = AccountProvider.create!(account: account, provider: coinstats_item.coinstats_accounts.create!(name: "Brokerage", currency: "USD"))
+ security = Security.create!(ticker: "DUAL", name: "Dual listed")
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: Date.current, rate: 0.5)
+ # The USD snapshot is older than the CAD one, so a lookup that ignored
+ # currency would hand the USD row the newer CAD snapshot.
+ { "USD" => [ 100, 130, 2 ], "CAD" => [ 200, 210, 1 ] }.each do |currency, (before, now, days_ago)|
+ Holding.create!(account: account, account_provider: provider, security: security, date: days_ago.days.ago.to_date, qty: 1, price: before, amount: before, currency: currency)
+ .update_columns(updated_at: days_ago.days.ago) # imported that day, not today
+ Holding.create!(account: account, account_provider: provider, security: security, date: Date.current, qty: 1, price: now, amount: now, currency: currency)
+ end
+
+ current = @statement.current_holdings.sort_by(&:currency)
+ assert_equal %w[CAD USD], current.map(&:currency), "both currencies' rows are current"
+
+ changes = current.to_h { |holding| [ holding.currency, @statement.holding_day_change(holding) ] }
+
+ assert_equal Money.new(100, "USD"), changes["USD"].previous
+ assert_equal Money.new(30, "USD"), changes["USD"].value
+ assert_equal Money.new(200, "CAD"), changes["CAD"].previous
+ assert_equal Money.new(10, "CAD"), changes["CAD"].value
+ current.each do |holding|
+ assert_equal holding.day_change.value, @statement.holding_day_change(holding).value, "#{holding.currency} must match Holding#day_change"
+ end
+
+ # 130 + 210 CAD at 0.5 against 100 + 200 CAD at 0.5
+ assert_equal Money.new(235), @statement.day_change.current
+ assert_equal Money.new(200), @statement.day_change.previous
+ end
+
+ test "holdings table rows with the same figure keep a fixed order in both directions" do
+ account = create_investment_account(balance: 10_000)
+ %w[Beta Alpha Gamma].each_with_index do |name, i|
+ security = Security.create!(ticker: "TIE#{i}", name: name)
+ Holding.create!(account: account, security: security, date: Date.current, qty: 10, price: 100, amount: 1000, currency: "USD")
+ end
+
+ asc = @statement.holdings_table_rows(sort: "value", dir: "asc").map(&:name)
+ desc = @statement.holdings_table_rows(sort: "value", dir: "desc").map(&:name)
+
+ assert_equal %w[Alpha Beta Gamma], asc
+ assert_equal %w[Alpha Beta Gamma], desc, "ties break by name in both directions"
+ end
+
+ # Pins top_holdings and allocation on a portfolio that exercises every path
+ # the shared roll-up takes: a stored basis, the trade-history fallback, a
+ # position with no basis, an internal movement, a security held in two
+ # accounts and a corrupt negative row.
+ test "top_holdings and allocation keep their figures on a mixed portfolio" do
+ ira = create_investment_account(balance: 6000, cash_balance: 500)
+ taxable = create_investment_account(balance: 3000)
+ stored = Security.create!(ticker: "STO", name: "Stored")
+ traded = Security.create!(ticker: "TRD", name: "Traded")
+ moved = Security.create!(ticker: "MOV", name: "Moved")
+ corrupt = Security.create!(ticker: "BAD", name: "Corrupt")
+
+ Holding.create!(account: ira, security: stored, date: Date.current, qty: 10, price: 100, amount: 1000, currency: "USD", cost_basis: 50, cost_basis_locked: true)
+ Holding.create!(account: taxable, security: stored, date: Date.current, qty: 5, price: 100, amount: 500, currency: "USD")
+ Holding.create!(account: ira, security: traded, date: Date.current, qty: 10, price: 120, amount: 1200, currency: "USD")
+ create_trade_for(account: ira, security: traded, qty: 10, price: 80, date: 1.day.ago.to_date)
+ Holding.create!(account: taxable, security: moved, date: Date.current, qty: 20, price: 100, amount: 2000, currency: "USD")
+ create_trade_for(account: taxable, security: moved, qty: 20, price: 90, date: 1.day.ago.to_date)
+ .entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ Holding.create!(account: taxable, security: corrupt, date: Date.current, qty: 1, price: 300, amount: 300, currency: "USD")
+ .update_columns(amount: -300)
+
+ figures = ->(rows) { rows.map { |r| [ r.ticker, r.amount.amount.to_i, r.weight.to_f, r.trend&.current&.amount&.to_i, r.trend&.previous&.amount&.to_i ] } }
+
+ # Denominator max(9000 portfolio, 4700 holdings) = 9000.
+ expected = [
+ [ "MOV", 2000, 22.22, nil, nil ],
+ [ "STO", 1500, 16.67, 1000, 500 ],
+ [ "TRD", 1200, 13.33, 1200, 800 ]
+ ]
+ assert_equal expected, figures.call(InvestmentStatement.new(@family, user: nil).top_holdings)
+ assert_equal expected.first(2), figures.call(InvestmentStatement.new(@family, user: nil).top_holdings(limit: 2))
+ assert_equal expected, figures.call(InvestmentStatement.new(@family, user: nil).allocation)
+ end
+
private
def materialize_two_parcel_example(first_parcel_label:)
account = create_investment_account(balance: 1800)