Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop trades at no price from pricing their day (#4504)

Yong Cong Sin8e3d219d4552
diff --git a/app/models/holding/portfolio_cache.rb b/app/models/holding/portfolio_cache.rb
index 692bc3814e..619abc9db6 100644
--- a/app/models/holding/portfolio_cache.rb
+++ b/app/models/holding/portfolio_cache.rb
@@ -1,6 +1,16 @@
class Holding::PortfolioCache
attr_reader :account, :use_holdings
+ # Labels under which a trade at no price adds or moves units that nobody
+ # observed to be worth nothing: an internal movement, a stock dividend, a
+ # reinvestment, shares bought or paid in kind. Any other trade at no price
+ # (Other, which providers book splits as; Exchange, a corporate action;
+ # Sell; or no label) might be a split or a real zero, so its zero stays a
+ # price (see #price_unpriced_trade_days).
+ UNPRICED_SHARE_LABELS = (Trade::INTERNAL_MOVEMENT_LABELS + %w[Buy Dividend Reinvestment Interest Fee Contribution Withdrawal]).freeze
+ # Labels a trade at no price can carry when it is a split booked as a trade.
+ SPLIT_LIKE_LABELS = [ nil, "Other" ].freeze
+
class SecurityNotFound < StandardError
def initialize(security_id, account_id)
super("Security id=#{security_id} not found in portfolio cache for account #{account_id}. This should not happen unless securities were preloaded incorrectly.")
@@ -154,8 +164,16 @@ class Holding::PortfolioCache
# 1 - DB or provider prices
# 2 - Trade prices
# 3 - Holding prices
+ #
+ # A trade booked at no price that moves or adds units (a share journal, a
+ # stock-plan deposit, a stock dividend) says nothing about what they were
+ # worth. Taken as that day's price, its zero would value the whole
+ # position at nothing until the next priced day, which without market data
+ # can be months. Such a day takes the nearest real price instead (see
+ # #price_unpriced_trade_days).
def load_prices
@security_cache = {}
+ unpriced_trades_by_security_id = {}
securities = collect_unique_securities
Rails.logger.info "Preloading #{securities.size} securities for account #{account.id}"
@@ -186,8 +204,22 @@ class Holding::PortfolioCache
# zero-amount holding. Use qty (the same heuristic as
# Balance::BaseCalculator) rather than price to avoid blocking
# non-income zero-price trades such as Questrade journal transfers.
- trade_prices = (trades_by_security_id[security.id] || [])
+ unpriced_trades, priced_trades = (trades_by_security_id[security.id] || [])
.reject { |t| t.entryable.qty == 0 }
+ .partition { |t| unpriced_trade?(t.entryable) }
+ unpriced_trades_by_security_id[security.id] = unpriced_trades if unpriced_trades.any?
+ unpriced_dates = unpriced_trades.map(&:date).to_set
+
+ # A trade at no price that might be a split stays a barrier to the
+ # nearest-price search even on a day another price outranks it (see
+ # #nearest_known_price). Only an unlabelled or "Other" trade might be
+ # one: a sale or an exchange at no price leaves the shares as they
+ # were, so that day's quote is in the same shares.
+ barrier_dates = priced_trades
+ .select { |t| !t.entryable.price&.positive? && SPLIT_LIKE_LABELS.include?(t.entryable.investment_activity_label) }
+ .map(&:date).to_set
+
+ trade_prices = priced_trades
.map do |trade|
PriceWithPriority.new(
price: Security::Price.new(
@@ -200,10 +232,54 @@ class Holding::PortfolioCache
source: "trade"
)
end
-
- # Low priority prices from holdings (if applicable)
+ # On a day that might be a split, the first priced trade, which the
+ # trade at no price can win a tie against (see #price_unpriced_trade_days)
+ priced_trade_on_barrier = trade_prices
+ .select { |p| barrier_dates.include?(p.price.date) && p.price.price.positive? }
+ .group_by { |p| p.price.date }.transform_values(&:first)
+
+ # Provider rows first, so a provider snapshot wins a day it shares with a
+ # calculated row (in another currency, before the calculated one is
+ # cleaned up) where both rank the same
+ # A provider row with no units marks a position closed, not a price
+ # (some providers write one at no price), so it is left out.
+ security_holdings = if use_holdings
+ (holdings_by_security_id[security.id] || [])
+ .reject { |h| h.account_provider_id && h.qty.to_d.zero? }
+ .sort_by { |h| h.account_provider_id ? 0 : 1 }
+ else
+ []
+ end
+ # Days whose holding price is only a calculated row's, which an earlier
+ # sync derived from the prices known then
+ calculated_holding_dates = security_holdings.select { |h| h.account_provider_id.nil? }.map(&:date).to_set -
+ security_holdings.select(&:account_provider_id).map(&:date).to_set
+ # Days from the first trade at no price on: their calculated rows were
+ # filled in from prices as an earlier sync worked them out, the
+ # movement's included, and anything seen since (a quote between two
+ # runs, even today's) may change them. They give way like the movement
+ # day's own, so the prices known now carry forward instead.
+ first_unpriced = unpriced_dates.min
+ carried_dates = if first_unpriced
+ security_holdings.select { |h| h.account_provider_id.nil? && h.date > first_unpriced }.map(&:date).to_set
+ else
+ Set.new
+ end
+ passed_over = ->(h) { h.account_provider_id.nil? && (!h.price.positive? || unpriced_dates.include?(h.date) || carried_dates.include?(h.date)) }
+ # The calculated rows passed over below (see #reprice_holding_source)
+ passed_over_holdings = security_holdings.select(&passed_over)
+
+ # Low priority prices from holdings (if applicable). A calculated row at
+ # no price is skipped: its zero came from such a trade on an earlier
+ # sync, and reading it back would keep the position at zero for good.
+ # So is a calculated row on the day of a trade at no price, or on a day
+ # after it up to the next price seen: its price was filled in on an
+ # earlier sync from the prices known then, and is worked out again from
+ # the prices known now.
holding_prices = if use_holdings
- (holdings_by_security_id[security.id] || []).map do |holding|
+ security_holdings.filter_map do |holding|
+ next if passed_over.call(holding)
+
PriceWithPriority.new(
price: Security::Price.new(
security: security,
@@ -230,8 +306,176 @@ class Holding::PortfolioCache
@security_cache[security.id] = {
security: security,
prices_by_date: prices_by_date,
- prices_by_date_and_source: prices_by_date_and_source
+ prices_by_date_and_source: prices_by_date_and_source,
+ barrier_dates: barrier_dates,
+ priced_trade_on_barrier: priced_trade_on_barrier,
+ calculated_holding_dates: calculated_holding_dates,
+ passed_over_holdings: passed_over_holdings,
+ carried_dates: carried_dates
}
end
+
+ # After the loop: the split lookup reads every security in the cache.
+ earlier = latest_db_prices_before(account.start_date, unpriced_trades_by_security_id.keys)
+ unpriced_trades_by_security_id.each do |security_id, trades|
+ price_unpriced_trade_days(security_id, trades, earlier: earlier[security_id])
+ end
+ @security_cache.each_key { |security_id| reprice_holding_source(security_id) }
+ end
+
+ # A lookup for holding prices alone (the reverse calculator reads today's
+ # that way) still finds a day whose calculated row was passed over: it
+ # finds the day's price as worked out on this sync; on a day after a trade
+ # at no price, the latest one before it, which that trade's day carries
+ # forward; otherwise, where the day has none, the row's own, as before.
+ def reprice_holding_source(security_id)
+ cached = @security_cache[security_id]
+ known_dates = nil
+ cached[:passed_over_holdings].each do |holding|
+ key = [ holding.date, "holding" ]
+ next if cached[:prices_by_date_and_source].key?(key)
+
+ price = cached[:prices_by_date][holding.date]&.price
+ if price.nil? && cached[:carried_dates].include?(holding.date)
+ known_dates ||= cached[:prices_by_date].keys.sort
+ index = known_dates.bsearch_index { |d| d >= holding.date } || known_dates.size
+ if index.positive?
+ carried = cached[:prices_by_date][known_dates[index - 1]].price
+ # Carried across any split in between, as the rows themselves are
+ factor = price_split_factor(security_id, carried.date, holding.date)
+ amount = factor == 1 ? carried.price : Security::Split.unscale(carried.price, factor)
+ price = Security::Price.new(security: cached[:security], price: amount, currency: carried.currency, date: holding.date)
+ end
+ end
+ price ||= Security::Price.new(security: cached[:security], price: holding.price, currency: holding.currency, date: holding.date)
+ cached[:prices_by_date_and_source][key] = PriceWithPriority.new(price: price, priority: 3, source: "holding")
+ end
+ end
+
+ def unpriced_trade?(trade)
+ !trade.price&.positive? && UNPRICED_SHARE_LABELS.include?(trade.investment_activity_label)
+ end
+
+ # A day whose only price would have been an unpriced trade's takes the
+ # nearest price the security has: the latest before it, else the earliest
+ # after it, carried across any recorded split in between. A zero found
+ # there is taken rather than passed over: a position the provider prices
+ # at nothing is worthless, and a split booked as a trade at no price
+ # leaves the prices beyond it in other shares, by a ratio nothing here
+ # knows. The day keeps a price, so the calculators still give it a holding
+ # with the moved quantity. A security with no price at all keeps the
+ # trade's zero.
+ def price_unpriced_trade_days(security_id, trades, earlier: nil)
+ cached = @security_cache[security_id]
+ prices_by_date = cached[:prices_by_date]
+ unpriced_days = trades.group_by(&:date).reject { |date, _| prices_by_date.key?(date) }
+ return if unpriced_days.empty?
+
+ # Observed prices only, zeros included: the unpriced trades' own and
+ # calculated rows' zeros were never loaded, so any zero here was
+ # observed. A calculated row's price is passed over too: an earlier sync
+ # derived it from the prices known then, and a quote that has arrived
+ # since must be able to replace it. So is the zero of a trade that might
+ # be a split on a day a split is recorded: the recorded ratio carries the
+ # prices on either side across it. The latest stored price
+ # before the account's history is the nearest earlier one for a
+ # trade on its first days.
+ # A provider snapshot can be dated before that stored price, so the
+ # list is sorted again; on the same date the stored price ranks first.
+ # A priced trade the passed-over zero tied with on its day, else a
+ # provider snapshot it outranked, takes the day instead.
+ candidates = prices_by_date.each_with_object({}) do |(date, entry), kept|
+ next if entry.source == "holding" && cached[:calculated_holding_dates].include?(date)
+
+ if entry.source == "trade" && !entry.price.price.positive? && cached[:barrier_dates].include?(date) && split_recorded_on?(security_id, date)
+ provider = cached[:prices_by_date_and_source][[ date, "holding" ]]
+ provider = nil if cached[:calculated_holding_dates].include?(date)
+ replacement = cached[:priced_trade_on_barrier][date] || provider
+ kept[date] = replacement if replacement
+ else
+ kept[date] = entry
+ end
+ end
+ if earlier
+ stored = PriceWithPriority.new(price: earlier, priority: 1, source: "db")
+ candidates[earlier.date] = stored if candidates[earlier.date].nil? || candidates[earlier.date].priority > stored.priority
+ end
+ known = candidates.sort_by(&:first)
+
+ unpriced_days.each do |date, day_trades|
+ filled = nearest_known_price(cached[:security], known, date, barrier_dates: cached[:barrier_dates]) ||
+ PriceWithPriority.new(
+ price: Security::Price.new(security: cached[:security], price: 0, currency: day_trades.first.entryable.currency, date: date),
+ priority: 2,
+ source: "trade"
+ )
+ prices_by_date[date] = filled
+ # Indexed by its source too, as a lookup for one source reads it there
+ cached[:prices_by_date_and_source][[ date, filled.source ]] ||= filled
+ end
+ end
+
+ # Like #split_factor_between, but over every recorded split, future ones
+ # included: a future-dated trade's price is in the shares after a split
+ # before it, even one that has not taken effect yet.
+ def price_split_factor(security_id, from, to)
+ return Rational(1) if from >= to
+
+ all_splits.reduce(Rational(1)) do |factor, split|
+ next factor unless split.security_id == security_id
+ next factor unless split.ex_date > from && split.ex_date <= to
+
+ factor * split.ratio
+ end
+ end
+
+ def all_splits
+ @all_splits ||= Security::Split.where(security_id: @security_cache.keys).order(:ex_date).to_a
+ end
+
+ def split_recorded_on?(security_id, date)
+ all_splits.any? { |split| split.security_id == security_id && split.ex_date == date }
+ end
+
+ # The latest stored price of each security before `date`.
+ def latest_db_prices_before(date, security_ids)
+ return {} if security_ids.empty?
+
+ Security::Price.where(security_id: security_ids).where(date: ...date)
+ .select("DISTINCT ON (security_id) security_prices.*")
+ .order(:security_id, date: :desc)
+ .index_by(&:security_id)
+ end
+
+ # The nearest price before `date`, else after it, scaled across the splits
+ # in between. Looking forward, a day holding a trade at no price that might
+ # be a split is taken as zero even when another price outranks it there:
+ # that price can be in the shares after the split, by a ratio nothing here
+ # knows. A split recorded on that day gives the ratio, so the price is
+ # scaled across it instead.
+ def nearest_known_price(security, known, date, barrier_dates: Set.new)
+ later_index = known.bsearch_index { |known_date, _| known_date > date } || known.size
+
+ if later_index.positive?
+ known_date, nearest = known[later_index - 1]
+ factor = price_split_factor(security.id, known_date, date)
+ amount = factor == 1 ? nearest.price.price : Security::Split.unscale(nearest.price.price, factor)
+ elsif known.any?
+ known_date, nearest = known.first
+ factor = price_split_factor(security.id, date, known_date)
+ amount = if barrier_dates.include?(known_date) && !split_recorded_on?(security.id, known_date)
+ 0
+ else
+ factor == 1 ? nearest.price.price : Security::Split.scale(nearest.price.price, factor)
+ end
+ else
+ return nil
+ end
+
+ PriceWithPriority.new(
+ price: Security::Price.new(security: security, price: amount, currency: nearest.price.currency, date: date),
+ priority: nearest.priority,
+ source: nearest.source
+ )
end
end
diff --git a/test/models/holding/portfolio_cache_test.rb b/test/models/holding/portfolio_cache_test.rb
index 99fa86b9fe..2b44821d23 100644
--- a/test/models/holding/portfolio_cache_test.rb
+++ b/test/models/holding/portfolio_cache_test.rb
@@ -122,6 +122,436 @@ class Holding::PortfolioCacheTest < ActiveSupport::TestCase
assert_equal @trade.price, cache.get_price(@security.id, @trade.entry.date).price
end
+ test "an internal movement at no price takes the latest earlier price instead of zero" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: -0.5, date: 1.day.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal @trade.price, cache.get_price(@security.id, 1.day.ago.to_date).price
+ end
+
+ test "a first entry moved at no price takes the latest earlier price when a holding is dated before the stored one" do
+ @account = families(:empty).accounts.create!(name: "Transfers only", balance: 0, currency: "USD", accountable: Investment.new)
+ moved_on = 5.days.ago.to_date
+ Security::Price.delete_all
+ provider_holding(@security, date: moved_on - 6, price: 30)
+ Security::Price.create!(security: @security, date: moved_on - 3, price: 40, currency: "USD")
+ create_movement(@security, qty: 10, date: moved_on)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 40, cache.get_price(@security.id, moved_on).price
+ end
+
+ test "a stored price before the account's history outranks a holding price on the same day" do
+ @account = families(:empty).accounts.create!(name: "Transfers only", balance: 0, currency: "USD", accountable: Investment.new)
+ moved_on = 5.days.ago.to_date
+ Security::Price.delete_all
+ provider_holding(@security, date: moved_on - 3, price: 35)
+ Security::Price.create!(security: @security, date: moved_on - 3, price: 40, currency: "USD")
+ create_movement(@security, qty: 10, date: moved_on)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 40, cache.get_price(@security.id, moved_on).price
+ end
+
+ test "a price filled in for a day moved at no price is found when its source is asked for" do
+ Security::Price.delete_all
+ Entry.delete_all
+ provider_holding(@security, date: 1.day.ago.to_date, price: 50)
+ create_movement(@security, qty: 10, date: Date.current)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 50, cache.get_price(@security.id, Date.current, source: "holding").price
+ end
+
+ test "a first entry moved at no price takes the stored price from before the account's history" do
+ @account = families(:empty).accounts.create!(name: "Transfers only", balance: 0, currency: "USD", accountable: Investment.new)
+ moved_on = 5.days.ago.to_date
+ Security::Price.delete_all
+ Security::Price.create!(security: @security, date: moved_on - 3, price: 40, currency: "USD")
+ Security::Price.create!(security: @security, date: moved_on + 2, price: 90, currency: "USD")
+ create_movement(@security, qty: 10, date: moved_on)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 40, cache.get_price(@security.id, moved_on).price
+ end
+
+ test "a priced trade outranks an unpriced movement on the same day, whichever was recorded first" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 100, date: 1.day.ago.to_date)
+ create_trade(@security, account: @account, qty: -40, date: 1.day.ago.to_date, price: 50)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 50, cache.get_price(@security.id, 1.day.ago.to_date).price
+ end
+
+ test "an unpriced movement with no earlier price takes the next one" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal @trade.price, cache.get_price(@security.id, 3.days.ago.to_date).price
+ end
+
+ test "the price an unpriced movement takes is carried across a split" do
+ Security::Price.destroy_all
+ Security::Split.create!(security: @security, ex_date: 1.day.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ create_movement(@security, qty: 10, date: Date.current)
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal @trade.price / 2, cache.get_price(@security.id, Date.current).price
+ assert_equal @trade.price, cache.get_price(@security.id, 3.days.ago.to_date).price, "no split between it and the next price"
+ end
+
+ test "the next price an unpriced movement takes is carried back across a split" do
+ Security::Price.destroy_all
+ Security::Split.create!(security: @security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal @trade.price * 2, cache.get_price(@security.id, 3.days.ago.to_date).price, "a trade on the ex-date is in the new shares"
+ end
+
+ test "an unpriced movement keeps its zero when the security has no price at all" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 10, date: 1.day.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 0, cache.get_price(@security.id, 1.day.ago.to_date).price, "the day still has a price, so its holding records the quantity"
+ end
+
+ test "a calculated holding at no price is not read back as a price" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 10, date: 1.day.ago.to_date)
+ @account.holdings.create!(security: @security, date: 1.day.ago.to_date, qty: 11, price: 0, amount: 0, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal @trade.price, cache.get_price(@security.id, 1.day.ago.to_date).price
+ end
+
+ test "an unpriced movement takes no price from across a trade at no price" do
+ Security::Price.destroy_all
+ # A split booked as a trade: the new shares arrive at no price, and the
+ # prices on either side of it are in different shares
+ create_movement(@security, qty: 1, date: 1.day.ago.to_date, label: "Other")
+ create_movement(@security, qty: 1, date: Date.current)
+ create_movement(@security, qty: 1, date: 3.days.ago.to_date, label: "Other")
+ create_movement(@security, qty: 1, date: 4.days.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 0, cache.get_price(@security.id, Date.current).price, "not the price from before the split"
+ assert_equal 0, cache.get_price(@security.id, 4.days.ago.to_date).price, "not the price from after it"
+ end
+
+ # SnapTrade books a STOCK_DIVIDEND as a Dividend trade at 0: the shares
+ # arrive, and nobody observed a price.
+ test "a stock dividend at no price takes the nearest price and does not block a later movement's" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 1, date: 1.day.ago.to_date, label: "Dividend")
+ create_movement(@security, qty: 1, date: Date.current)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal @trade.price, cache.get_price(@security.id, 1.day.ago.to_date).price
+ assert_equal @trade.price, cache.get_price(@security.id, Date.current).price
+ end
+
+ test "a reinvestment at no price takes the nearest price and does not block a later movement's" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 1, date: 1.day.ago.to_date, label: "Reinvestment")
+ create_movement(@security, qty: 1, date: Date.current)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal @trade.price, cache.get_price(@security.id, 1.day.ago.to_date).price
+ assert_equal @trade.price, cache.get_price(@security.id, Date.current).price
+ end
+
+ test "an unlabelled trade at no price stays a price, as it might be a split" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 1, date: 1.day.ago.to_date, label: nil)
+ create_movement(@security, qty: 1, date: Date.current)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 0, cache.get_price(@security.id, Date.current).price
+ end
+
+ test "an earlier movement takes no price from across a possible split on a day that also has a quote" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 1, date: 4.days.ago.to_date)
+ create_movement(@security, qty: 1, date: 3.days.ago.to_date, label: "Other")
+ Security::Price.create!(security: @security, date: 3.days.ago.to_date, price: 100, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 0, cache.get_price(@security.id, 4.days.ago.to_date).price, "the quote may be in the shares after the split"
+ end
+
+ test "an earlier movement takes the quote across a possible split when the split is recorded" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 1, date: 4.days.ago.to_date)
+ create_movement(@security, qty: 1, date: 3.days.ago.to_date, label: "Other")
+ Security::Price.create!(security: @security, date: 3.days.ago.to_date, price: 100, currency: "USD")
+ Security::Split.create!(security: @security, ex_date: 3.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 200, cache.get_price(@security.id, 4.days.ago.to_date).price, "the quote is in the shares after the recorded split"
+ end
+
+ # On an earlier sync the movement's day took the next price, the only one
+ # known then, and its calculated holding kept that price. A quote from
+ # before it has arrived since.
+ test "a price filled in for a movement on an earlier sync is worked out again from the prices known now" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+ @account.holdings.create!(security: @security, date: 3.days.ago.to_date, qty: 10, price: @trade.price, amount: @trade.price * 10, currency: "USD")
+ Security::Price.create!(security: @security, date: 4.days.ago.to_date, price: 90, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, 3.days.ago.to_date).price
+ end
+
+ test "a later movement takes the quote from before a recorded split, not the zero of the trade booking it" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ Security::Price.create!(security: @security, date: 4.days.ago.to_date, price: 100, currency: "USD")
+ create_movement(@security, qty: 1, date: 3.days.ago.to_date, label: "Other")
+ Security::Split.create!(security: @security, ex_date: 3.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ create_movement(@security, qty: 1, date: 1.day.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 50, cache.get_price(@security.id, 1.day.ago.to_date).price, "carried across the recorded split"
+ end
+
+ test "an earlier movement takes the provider's price on a recorded split's day, though the trade booking the split outranks it" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 1, date: 4.days.ago.to_date)
+ create_movement(@security, qty: 1, date: 3.days.ago.to_date, label: "Other")
+ Security::Split.create!(security: @security, ex_date: 3.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ provider_holding(@security, date: 3.days.ago.to_date, price: 100)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 200, cache.get_price(@security.id, 4.days.ago.to_date).price, "the provider's post-split price, carried back across the recorded split"
+ end
+
+ test "an earlier movement takes a priced trade on a recorded split's day, though the trade booking the split wins their tie" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 1, date: 4.days.ago.to_date)
+ create_movement(@security, qty: 1, date: 3.days.ago.to_date, label: "Other")
+ create_trade(@security, account: @account, qty: -1, date: 3.days.ago.to_date, price: 100)
+ Security::Split.create!(security: @security, ex_date: 3.days.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 200, cache.get_price(@security.id, 4.days.ago.to_date).price, "the sale's post-split price, carried back across the recorded split"
+ end
+
+ # A calculated row is what an earlier sync derived from the prices known
+ # then; a quote that arrived since must be able to replace it.
+ test "a movement takes a quote over a later calculated holding priced on an earlier sync" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ @account.holdings.create!(security: @security, date: 2.days.ago.to_date, qty: 1, price: 80, amount: 80, currency: "USD")
+ Security::Price.create!(security: @security, date: 3.days.ago.to_date, price: 90, currency: "USD")
+ create_movement(@security, qty: 10, date: 1.day.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, 1.day.ago.to_date).price
+ end
+
+ # Before the materializer cleans up, a calculated row can share a day with
+ # the provider's snapshot in another currency; both rank the same.
+ test "a movement takes the provider's snapshot over a calculated row on the same day" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ @account.holdings.create!(security: @security, date: 2.days.ago.to_date, qty: 1, price: 80, amount: 80, currency: "USD")
+ provider_holding(@security, date: 2.days.ago.to_date, price: 120, currency: "CAD")
+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: 1.day.ago.to_date, rate: 0.5)
+ create_movement(@security, qty: 10, date: 1.day.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 60, cache.get_price(@security.id, 1.day.ago.to_date).price, "the provider's 120 CAD, not the calculated 80 USD"
+ end
+
+ # The reverse calculator prices today from holdings alone.
+ test "a calculated row passed over on a movement's day still answers a lookup for holding prices, at the day's price" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ @account.holdings.create!(security: @security, date: Date.current, qty: 10, price: 210, amount: 2100, currency: "USD")
+ Security::Price.create!(security: @security, date: 1.day.ago.to_date, price: 90, currency: "USD")
+ create_movement(@security, qty: 10, date: Date.current)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, Date.current, source: "holding")&.price, "today's price worked out again, not the row's 210"
+ end
+
+ test "a calculated row at no price passed over on a movement's day still answers a lookup for holding prices, at the day's price" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ @account.holdings.create!(security: @security, date: Date.current, qty: 10, price: 0, amount: 0, currency: "USD")
+ Security::Price.create!(security: @security, date: 1.day.ago.to_date, price: 90, currency: "USD")
+ create_movement(@security, qty: 10, date: Date.current)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, Date.current, source: "holding")&.price
+ end
+
+ # Each day after a movement up to the next price seen is filled in from the
+ # movement's price; once a later sync prices the movement differently, those
+ # rows are as out of date as the movement day's own.
+ test "calculated rows after a movement priced again on a later sync give way to its new price" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+ 3.downto(0) { |n| @account.holdings.create!(security: @security, date: n.days.ago.to_date, qty: 10, price: 80, amount: 800, currency: "USD") }
+ Security::Price.create!(security: @security, date: 4.days.ago.to_date, price: 90, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, 3.days.ago.to_date).price
+ assert_nil cache.get_price(@security.id, 2.days.ago.to_date), "the earlier sync's 80 gives way, so the movement's price carries forward"
+ assert_equal 90, cache.get_price(@security.id, Date.current, source: "holding")&.price, "today's holding price is the movement's new one"
+ end
+
+ test "today's holding price carried from a movement priced again follows a split in between" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+ Security::Split.create!(security: @security, ex_date: 1.day.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+ @account.holdings.create!(security: @security, date: Date.current, qty: 20, price: 40, amount: 800, currency: "USD")
+ Security::Price.create!(security: @security, date: 4.days.ago.to_date, price: 90, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 45, cache.get_price(@security.id, Date.current, source: "holding")&.price, "the movement's 90, halved by the split"
+ end
+
+ test "the price carried past a movement starts again from the next price seen" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+ create_trade(@security, account: @account, qty: 1, date: 1.day.ago.to_date, price: 100)
+ @account.holdings.create!(security: @security, date: 2.days.ago.to_date, qty: 10, price: 80, amount: 800, currency: "USD")
+ @account.holdings.create!(security: @security, date: Date.current, qty: 11, price: 100, amount: 1100, currency: "USD")
+ Security::Price.create!(security: @security, date: 4.days.ago.to_date, price: 90, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_nil cache.get_price(@security.id, 2.days.ago.to_date), "between the movement and the sale: gives way"
+ assert_equal 100, cache.get_price(@security.id, Date.current, source: "holding")&.price, "today's holding price carries the sale's"
+ end
+
+ # A quote for today can arrive between two runs on the same day.
+ test "today's calculated row after a movement gives way to a quote for today" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 10, date: 3.days.ago.to_date)
+ 2.downto(0) { |n| @account.holdings.create!(security: @security, date: n.days.ago.to_date, qty: 10, price: 80, amount: 800, currency: "USD") }
+ Security::Price.create!(security: @security, date: 4.days.ago.to_date, price: 80, currency: "USD")
+ Security::Price.create!(security: @security, date: Date.current, price: 95, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 95, cache.get_price(@security.id, Date.current, source: "holding")&.price
+ end
+
+ # The first sync priced the movement from a later snapshot; a quote dated
+ # between the two arrived since.
+ test "calculated rows after a quote that arrived since give way to it" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_movement(@security, qty: 10, date: 4.days.ago.to_date)
+ @account.holdings.create!(security: @security, date: 2.days.ago.to_date, qty: 10, price: 80, amount: 800, currency: "USD")
+ provider_holding(@security, date: 1.day.ago.to_date, price: 80)
+ Security::Price.create!(security: @security, date: 3.days.ago.to_date, price: 90, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, 4.days.ago.to_date).price
+ assert_nil cache.get_price(@security.id, 2.days.ago.to_date), "the earlier sync's 80 gives way, so the 90 carries forward"
+ end
+
+ test "a provider row with no units is not a price" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ Security::Price.create!(security: @security, date: 5.days.ago.to_date, price: 90, currency: "USD")
+ @provider_link ||= begin
+ item = @account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ AccountProvider.create!(account: @account, provider: item.coinstats_accounts.create!(name: "Provider", currency: "USD"))
+ end
+ @account.holdings.create!(security: @security, date: 2.days.ago.to_date, qty: 0, price: 0, amount: 0, currency: "USD", account_provider: @provider_link)
+ create_movement(@security, qty: 10, date: 1.day.ago.to_date)
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 90, cache.get_price(@security.id, 1.day.ago.to_date).price, "the stored 90, not the closure marker's 0"
+ end
+
+ # No movement that day: the row is passed over only for being at no price.
+ test "a calculated row at no price still answers a lookup for holding prices, at the day's price or else its own" do
+ Security::Price.destroy_all
+ Entry.delete_all
+ create_trade(@security, account: @account, qty: 1, date: 3.days.ago.to_date, price: 50)
+ @account.holdings.create!(security: @security, date: Date.current, qty: 1, price: 0, amount: 0, currency: "USD")
+ @account.holdings.create!(security: @security, date: 1.day.ago.to_date, qty: 1, price: 0, amount: 0, currency: "USD")
+ Security::Price.create!(security: @security, date: Date.current, price: 70, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account, use_holdings: true)
+
+ assert_equal 70, cache.get_price(@security.id, Date.current, source: "holding")&.price, "the day's price"
+ assert_equal 0, cache.get_price(@security.id, 1.day.ago.to_date, source: "holding")&.price, "no other price that day: the row's own, as before"
+ end
+
+ # A sale or an exchange at no price leaves the shares as they were.
+ { "Sell" => "a sale", "Exchange" => "an exchange" }.each do |label, trade|
+ test "an earlier movement takes the quote on a day with #{trade} at no price" do
+ Security::Price.destroy_all
+ create_movement(@security, qty: 1, date: 4.days.ago.to_date)
+ create_movement(@security, qty: -1, date: 3.days.ago.to_date, label: label)
+ Security::Price.create!(security: @security, date: 3.days.ago.to_date, price: 100, currency: "USD")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 100, cache.get_price(@security.id, 4.days.ago.to_date).price
+ end
+ end
+
+ test "a future price is scaled back across a split before it, even one not yet in effect" do
+ security = Security.create!(name: "Future Split", ticker: "FSPL", exchange_operating_mic: "TEST")
+ create_movement(security, qty: 1, date: Date.current)
+ create_trade(security, account: @account, qty: 1, date: 2.days.from_now.to_date, price: 50)
+ Security::Split.create!(security: security, ex_date: 1.day.from_now.to_date, numerator: 2, denominator: 1, source: "manual")
+
+ cache = Holding::PortfolioCache.new(@account)
+
+ assert_equal 100, cache.get_price(security.id, Date.current).price
+ end
+
test "converts historical prices using the requested date exchange rate" do
account = families(:empty).accounts.create!(
name: "CHF Brokerage",
@@ -157,4 +587,26 @@ class Holding::PortfolioCacheTest < ActiveSupport::TestCase
assert_equal BigDecimal("80.0"), converted_price.price
assert_equal "CHF", converted_price.currency
end
+
+ private
+ # A holding the provider reported, not one a sync calculated
+ def provider_holding(security, date:, price:, currency: "USD")
+ @provider_link ||= begin
+ item = @account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ AccountProvider.create!(account: @account, provider: item.coinstats_accounts.create!(name: "Provider", currency: "USD"))
+ end
+ @account.holdings.create!(security: security, date: date, qty: 1, price: price, amount: price, currency: currency, account_provider: @provider_link)
+ end
+
+ # Units moved in or out at no price, as a journal or a stock-plan deposit is
+ # recorded, or under another label, as a split booked as a trade is
+ def create_movement(security, qty:, date:, label: Trade::TRANSFER_LABEL)
+ @account.entries.create!(
+ name: label || "Trade",
+ date: date,
+ amount: 0,
+ currency: "USD",
+ entryable: Trade.new(qty: qty, security: security, price: 0, currency: "USD", investment_activity_label: label)
+ )
+ end
end