Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Store holding lots and re-key them on remap and reset (#4899)

jaysbeekaydfe6e87f1868
diff --git a/app/models/account.rb b/app/models/account.rb
index 83623bd3df..24c19d11c5 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -23,6 +23,7 @@ class Account < ApplicationRecord
has_many :valuations, through: :entries, source: :entryable, source_type: "Valuation"
has_many :trades, through: :entries, source: :entryable, source_type: "Trade"
has_many :holdings, dependent: :destroy
+ has_many :holding_lots
has_many :balances, dependent: :destroy
has_many :recurring_transactions, dependent: :destroy
has_many :goal_accounts, dependent: :destroy
diff --git a/app/models/holding.rb b/app/models/holding.rb
index 1a17094e37..b43ca390fb 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -321,8 +321,10 @@ class Holding < ApplicationRecord
end
end
- # Move all trades for old security to new security
+ # Move all trades for old security to new security, and their lots
account.trades.where(security: old_security).update_all(security_id: new_security.id)
+ lots = account.holding_lots.where(security: old_security)
+ HoldingLot.move!(derived: lots.derived, opening: lots.opening, to: new_security)
end
# Reload self to reflect changes (may raise RecordNotFound if self was destroyed)
@@ -351,6 +353,8 @@ class Holding < ApplicationRecord
transaction do
# Move trades back (see note above about limitation)
account.trades.where(security: current_security).update_all(security_id: original_security.id)
+ lots = account.holding_lots.where(security: current_security)
+ HoldingLot.move!(derived: lots.derived, opening: lots.opening.where(origin_security: original_security), to: original_security)
# Reset ALL holdings that were remapped from this provider_security
account.holdings.where(security: current_security, provider_security: original_security).find_each do |holding|
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index 33b7941d4b..6c7c9b439c 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -16,6 +16,15 @@ class Holding::ForwardCalculator
@transferred_security_ids = Set.new
end
+ # Every lot of each security, once #calculate has run.
+ def lots_by_security
+ lots_from(@lot_books)
+ end
+
+ def clamped_security_ids
+ Set.new
+ end
+
def calculate
Rails.logger.tagged("Holding::ForwardCalculator") do
current_portfolio = generate_starting_portfolio
diff --git a/app/models/holding/lot_book.rb b/app/models/holding/lot_book.rb
index 36d825be0b..2506d392fc 100644
--- a/app/models/holding/lot_book.rb
+++ b/app/models/holding/lot_book.rb
@@ -9,11 +9,13 @@
#
# The figure the calculators report, #average_cost, comes from a running pool
# of priced acquisitions rather than from the lots. The two agree, but pro-rata
-# lot quantities carry BigDecimal rounding the pool does not; relief now rounds
-# at the trade quantity scale and #rescale_lots puts the difference back, so
-# the open sum stays exact to the last digit and every stored figure is
-# computed from the pool. A transfer-in stays outside the pool; the calculators
-# report a position holding one as unknown.
+# lot quantities carry BigDecimal rounding the pool does not, and the pool is
+# what every stored figure is computed from. A transfer-in stays outside the
+# pool; the calculators report a position holding one as unknown.
+#
+# Lot quantities are kept at the precision they are stored at, and a sale
+# beyond the open lots is a shortfall the next acquisitions fill before they
+# open a lot, so the open lots always sum to the position.
#
# Buys add to the running cost and quantity. Sells relieve quantity at the
# current average cost (leaving the per-share average unchanged), and once the
@@ -26,10 +28,16 @@
class Holding::LotBook
Lot = Data.define(:source_id, :acquired_on, :qty, :unit_cost)
+ # A drift this small is the 18-place rounding of a split that does not
+ # divide evenly; anything wider is a real difference.
+ OPENING_RESIDUAL_BOUND = BigDecimal("1e-12")
+
attr_reader :lots
def initialize
@lots = []
+ @closed = []
+ @shortfall = BigDecimal("0")
reset
end
@@ -84,6 +92,7 @@ class Holding::LotBook
# is restated the same way.
def split(ratio)
@total_qty = Security::Split.scale(@total_qty, ratio)
+ @shortfall = Security::Split.scale(@shortfall, ratio)
rescale_lots(Security::Split.scale(open_qty, ratio)) do |lot|
lot.with(
qty: Security::Split.scale(lot.qty, ratio),
@@ -100,10 +109,30 @@ class Holding::LotBook
@total_cost / @total_qty
end
+ # Gives an open lot the drift between the open lots and `target`, the
+ # quantity they must add up to, when it is no more than `bound`: the opening
+ # lot, whose split round trip made it, or the last open lot once a sale has
+ # taken the opening one. The lot's quantity is restated, as #rescale_lots
+ # does, so no sale is recorded and no other lot moves.
+ def settle_opening(target, bound:)
+ drift = target.to_d - open_qty
+ return if drift.zero? || drift.abs > bound
+
+ index = @lots.index { |lot| lot.source_id.nil? } || (@lots.size - 1)
+ return if index.negative? || (@lots[index].qty + drift) <= 0
+
+ @lots[index] = @lots[index].with(qty: @lots[index].qty + drift)
+ end
+
def open_qty
@lots.sum(BigDecimal("0"), &:qty)
end
+ # Every lot booked, open or closed; a closed lot is at qty 0.
+ def ledger
+ @closed + @lots
+ end
+
private
def reset
@total_cost = BigDecimal("0")
@@ -112,16 +141,17 @@ class Holding::LotBook
end
def add_lot(source_id, acquired_on, qty, unit_cost)
- @lots << Lot.new(source_id: source_id, acquired_on: acquired_on, qty: qty, unit_cost: unit_cost)
+ filled = [ qty, @shortfall ].min
+ @shortfall -= filled
+ lot = Lot.new(source_id: source_id, acquired_on: acquired_on, qty: qty - filled, unit_cost: unit_cost)
+ lot.qty.positive? ? @lots << lot : @closed << lot
end
- # Pro-rata relief across every open lot; an oversell closes them all.
- # Rounding at the split scale, with #rescale_lots' drift correction, keeps
- # each quantity bounded and the open sum exact — without
- # it, repeated partial relief at non-terminating ratios grows each
- # quantity one decimal place per step.
+ # Pro-rata relief across every open lot; an oversell closes them all and
+ # leaves the excess as a shortfall.
def relieve_lots(qty)
open = open_qty
+ @shortfall += qty - open if qty > open
return if open.zero?
remaining = open - [ qty, open ].min
@@ -131,9 +161,10 @@ class Holding::LotBook
# Restates each lot, then settles whatever rounding is left from the last
# lot back, so the lots always sum to exactly `target`.
def rescale_lots(target)
- scaled = target.zero? ? [] : @lots.map { |lot| yield lot }
- settle_drift(scaled, target - scaled.sum(BigDecimal("0"), &:qty))
- @lots = scaled.select { |lot| lot.qty.positive? }
+ scaled = @lots.map { |lot| target.zero? ? lot.with(qty: BigDecimal("0")) : yield(lot) }
+ settle_drift(scaled, target - scaled.sum(BigDecimal("0"), &:qty)) if target.positive?
+ @lots, closed = scaled.partition { |lot| lot.qty.positive? }
+ @closed.concat(closed.map { |lot| lot.with(qty: BigDecimal("0")) })
end
# A negative drift can exceed the last lot, which may have rounded to zero,
diff --git a/app/models/holding/materializer.rb b/app/models/holding/materializer.rb
index fa14e45cff..1964e62b0e 100644
--- a/app/models/holding/materializer.rb
+++ b/app/models/holding/materializer.rb
@@ -17,6 +17,7 @@ class Holding::Materializer
Rails.logger.info("Persisting #{@holdings.size} holdings")
persist_holdings
+ persist_lots
if strategy == :forward && security_ids.nil?
purge_stale_holdings
@@ -46,7 +47,56 @@ class Holding::Materializer
attr_reader :account, :strategy, :security_ids
def calculate_holdings
- @holdings = calculator.calculate
+ @calculator = calculator
+ @holdings = @calculator.calculate
+ end
+
+ # Lot quantities and costs come from the calculator's lot books; a derived
+ # lot's cost is in the account's currency. An opening lot has no cost the
+ # trades know of, except on a position no trade explains, where it takes the
+ # provider's figure.
+ def persist_lots
+ rows = @calculator.lots_by_security.flat_map do |security_id, lots|
+ explained = lots.any?(&:source_id)
+ lots.map do |lot|
+ unit_cost, currency = (lot.source_id || explained) ? [ lot.unit_cost, account.currency ] : provider_unit_cost(security_id)
+ lot_row(security_id, lot.source_id, qty: lot.qty, acquired_on: lot.acquired_on, unit_cost: unit_cost, currency: currency)
+ end
+ end
+ rows += @calculator.clamped_security_ids.map { |security_id| lot_row(security_id, nil, qty: 0, clamped: true) }
+
+ # Only the reverse walk knows the units held before the trades.
+ HoldingLot.store!(account, rows, security_ids: security_ids, openings: strategy == :reverse)
+ end
+
+ def lot_row(security_id, source_entry_id, qty:, acquired_on: nil, unit_cost: nil, currency: account.currency, clamped: false)
+ {
+ account_id: account.id, security_id: security_id, source_entry_id: source_entry_id,
+ origin_security_id: source_entry_id ? nil : opening_origin(security_id), acquired_on: acquired_on,
+ qty: qty, unit_cost: unit_cost, currency: currency, clamped: clamped
+ }
+ end
+
+ # An opening lot comes from the security the provider reports. A position
+ # remapped to another security still names that one on its holdings, so a
+ # reset can take the lot back there. With several provider securities
+ # remapped onto one, it is the one behind the latest snapshot, which the
+ # opening lot is built from.
+ def opening_origin(security_id)
+ @provider_security_ids ||= account.holdings
+ .where.not(account_provider_id: nil)
+ .order(:date, :id)
+ .pluck(:security_id, :provider_security_id)
+ .to_h
+ @provider_security_ids[security_id] || security_id
+ end
+
+ # The latest provider cost for the security, restated for today's share count.
+ def provider_unit_cost(security_id)
+ date, cost_basis, currency = provider_cost_basis_snapshots[security_id].last
+ return [ nil, account.currency ] unless cost_basis
+
+ [ split_adjusted_cost_basis(cost_basis, security_id, date, Date.current), currency ]
end
def persist_holdings
@@ -283,9 +333,16 @@ class Holding::Materializer
end
end
+ # Lots can exist for a security with no calculated holdings (an old
+ # snapshot and no market prices), and they read the same provider costs
+ # and splits as the holdings do.
+ def costed_security_ids
+ @costed_security_ids ||= (@holdings.map(&:security_id) | @calculator.lots_by_security.keys)
+ end
+
def splits_by_security
@splits_by_security ||= Security::Split
- .where(security_id: @holdings.map(&:security_id).uniq)
+ .where(security_id: costed_security_ids)
.order(:ex_date)
.group_by(&:security_id)
.tap { |grouped| grouped.default = [] }
@@ -293,11 +350,10 @@ class Holding::Materializer
def provider_cost_basis_snapshots
@provider_cost_basis_snapshots ||= begin
- ids = @holdings.map(&:security_id).uniq
account.holdings
.where.not(account_provider_id: nil)
.where.not(cost_basis: nil)
- .where(security_id: ids)
+ .where(security_id: costed_security_ids)
.order(:date) # ascending required: carry_forward_provider_cost_basis scans and breaks on snap_date > holding.date
.pluck(:security_id, :currency, :date, :cost_basis)
.each_with_object(Hash.new { |h, k| h[k] = [] }) do |(security_id, currency, date, cost_basis), memo|
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index 9421994904..e5cfd8a410 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -9,6 +9,14 @@ class Holding::ReverseCalculator
@security_ids = security_ids
end
+ # Every lot of each security, the opening lot included, once #calculate has run.
+ def lots_by_security
+ lots_from(@lot_books)
+ end
+
+ # Securities whose provider quantity is below what their trades add up to.
+ attr_reader :clamped_security_ids
+
def calculate
Rails.logger.tagged("Holding::ReverseCalculator") do
precompute_cost_basis
@@ -135,6 +143,12 @@ class Holding::ReverseCalculator
# Re-sorting by date alone is unstable and could reorder same-day trades,
# which matters because the lot book is order-sensitive once sells relieve.
trades = portfolio_cache.get_trades
+ # A scheduled trade has not happened yet, so it explains none of today's
+ # position.
+ trades = trades.reject { |te| te.date > Date.current }
+ # A scoped run (a remap, a price sync) replays only its own securities;
+ # the cache holds every trade in the account.
+ trades = trades.select { |te| @security_ids.include?(te.entryable.security_id) } if @security_ids
events = replay_events(trades)
# A reverse-synced account can hold shares before its first imported trade,
@@ -157,6 +171,10 @@ class Holding::ReverseCalculator
positions[event.entryable.security_id] -= event.entryable.qty
end
end
+ # The snapshot covers the whole account; a scoped run books only its own.
+ baselines = snapshot.merge(positions)
+ baselines = baselines.slice(*@security_ids) if @security_ids
+ open_lots(baselines, traded: positions.keys)
events.each do |event|
if event.is_a?(Security::Split)
@@ -209,6 +227,33 @@ class Holding::ReverseCalculator
# Spans still open at the last trade stay unknown through to the present.
open_unknown_start.each { |security_id, start| @unknown_spans[security_id] << [ start, nil ] }
+
+ # Splitting the snapshot back and forward again rounds; the opening lot
+ # takes it (or the last open lot, once sold), so the lots add up to the
+ # provider's quantity.
+ snapshot.each do |security_id, qty|
+ next unless @lot_books.key?(security_id)
+
+ @lot_books[security_id].settle_opening(qty, bound: Holding::LotBook::OPENING_RESIDUAL_BOUND)
+ end
+ end
+
+ # Units held before the first imported trade (or, with no trades, all the
+ # provider reports) are the opening lot. Its cost is unknown to the trades,
+ # so it stays out of the average, and sales relieve it like any other lot.
+ # A traded position whose provider quantity is below its trades' total has
+ # nothing to open and is recorded as clamped. A shortfall within the drift a
+ # split's rounding leaves (OPENING_RESIDUAL_BOUND) is not one: there is
+ # nothing to open either, but the trades still explain the position.
+ def open_lots(baselines, traded:)
+ @clamped_security_ids = Set.new
+ baselines.each do |security_id, qty|
+ if qty <= -Holding::LotBook::OPENING_RESIDUAL_BOUND && traded.include?(security_id)
+ @clamped_security_ids << security_id
+ else
+ @lot_books[security_id].add_unknown(qty)
+ end
+ end
end
# Trades and splits in the order they took effect. A split goes first on its
diff --git a/app/models/holding/trade_calculator_helpers.rb b/app/models/holding/trade_calculator_helpers.rb
index e1d513e8aa..499b11dbdb 100644
--- a/app/models/holding/trade_calculator_helpers.rb
+++ b/app/models/holding/trade_calculator_helpers.rb
@@ -2,6 +2,11 @@
# Expects the including class to expose an `account` reader.
module Holding::TradeCalculatorHelpers
private
+ # A book that keeps no lots (the tracker before lots) has none to give.
+ def lots_from(books)
+ books.filter_map { |security_id, book| [ security_id, book.ledger ] if book.respond_to?(:ledger) }.to_h
+ end
+
# Converts a trade's price into the account's currency at the rate of the
# day it was made, or nil when there is no rate for that day.
def converted_trade_price(trade, date:)
diff --git a/app/models/holding_lot.rb b/app/models/holding_lot.rb
new file mode 100644
index 0000000000..e8bb54df4a
--- /dev/null
+++ b/app/models/holding_lot.rb
@@ -0,0 +1,59 @@
+# A parcel of one security in one account. A derived lot is acquired by a
+# trade (its source entry), which owns its quantity and date. The opening lot
+# holds the units no imported trade accounts for. Lots are written by the
+# holdings materializer from the calculators' lot books.
+class HoldingLot < ApplicationRecord
+ belongs_to :account
+ belongs_to :security
+ belongs_to :source_entry, class_name: "Entry", optional: true
+ belongs_to :origin_security, class_name: "Security", optional: true
+
+ scope :derived, -> { where.not(source_entry_id: nil) }
+ scope :opening, -> { where(source_entry_id: nil) }
+
+ def opening?
+ source_entry_id.nil?
+ end
+
+ class << self
+ # Replaces an account's lots with `rows`, within `security_ids` when given,
+ # keeping each lot's row (and id) by its key: the source entry for a derived
+ # lot, the position for the opening lot. An opening lot's origin follows the
+ # snapshot it is restated over.
+ # A caller that cannot see opening lots (`openings: false`) leaves them be.
+ def store!(account, rows, security_ids: nil, openings: true)
+ rows = rows.select { |row| security_ids.include?(row[:security_id]) } if security_ids
+ derived_rows, opening_rows = rows.partition { |row| row[:source_entry_id] }
+ scope = account.holding_lots
+ scope = scope.where(security_id: security_ids) if security_ids
+
+ transaction do
+ scope.derived.where.not(source_entry_id: derived_rows.pluck(:source_entry_id)).delete_all
+ scope.opening.where.not(security_id: opening_rows.pluck(:security_id)).delete_all if openings
+ if derived_rows.any?
+ upsert_all(derived_rows, unique_by: %i[account_id source_entry_id],
+ update_only: %i[security_id acquired_on qty unit_cost currency])
+ end
+ if opening_rows.any?
+ upsert_all(opening_rows, unique_by: :index_holding_lots_one_opening_lot_per_position,
+ update_only: %i[origin_security_id qty unit_cost currency clamped])
+ end
+ end
+ end
+
+ # Moves lots to another security with their trades. Lots are never merged:
+ # derived lots keep their own rows, and an opening lot moves only where the
+ # target has none, since the target's own is restated over the moved units
+ # at the next materialization.
+ def move!(derived:, opening:, to:)
+ derived.update_all(security_id: to.id, updated_at: Time.current)
+ opening.find_each do |lot|
+ if where(account_id: lot.account_id, security_id: to.id).opening.exists?
+ lot.delete
+ else
+ lot.update_columns(security_id: to.id, updated_at: Time.current)
+ end
+ end
+ end
+ end
+end
diff --git a/db/migrate/20261023090000_create_holding_lots.rb b/db/migrate/20261023090000_create_holding_lots.rb
new file mode 100644
index 0000000000..e5429c3488
--- /dev/null
+++ b/db/migrate/20261023090000_create_holding_lots.rb
@@ -0,0 +1,24 @@
+class CreateHoldingLots < ActiveRecord::Migration[8.1]
+ def change
+ create_table :holding_lots, id: :uuid do |t|
+ t.references :account, null: false, type: :uuid, index: false, foreign_key: { on_delete: :cascade }
+ t.references :security, null: false, type: :uuid, foreign_key: { on_delete: :cascade }
+ # The trade that acquired the lot; nil for the opening lot.
+ t.references :source_entry, type: :uuid, foreign_key: { to_table: :entries, on_delete: :cascade }
+ # The security an opening lot was opened under, so a reset can return it.
+ t.references :origin_security, type: :uuid, foreign_key: { to_table: :securities, on_delete: :nullify }
+ t.date :acquired_on
+ t.decimal :qty, precision: 34, scale: 18, null: false
+ t.decimal :unit_cost, precision: 25, scale: 10
+ t.string :currency, null: false
+ # The provider reported fewer units than the trades add up to.
+ t.boolean :clamped, null: false, default: false
+ t.timestamps
+ end
+
+ add_index :holding_lots, %i[account_id source_entry_id], unique: true
+ add_index :holding_lots, %i[account_id security_id], unique: true, where: "source_entry_id IS NULL",
+ name: "index_holding_lots_one_opening_lot_per_position"
+ add_check_constraint :holding_lots, "qty >= 0", name: "holding_lots_qty_non_negative"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 39a6d184c8..b4986ea825 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1189,6 +1189,26 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_080000) do
t.check_constraint "target_mode::text = ANY (ARRAY['fixed'::character varying::text, 'months_of_expenses'::character varying::text])", name: "chk_goals_target_mode_enum"
end
+ create_table "holding_lots", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.uuid "account_id", null: false
+ t.date "acquired_on"
+ t.boolean "clamped", default: false, null: false
+ t.datetime "created_at", null: false
+ t.string "currency", null: false
+ t.uuid "origin_security_id"
+ t.decimal "qty", precision: 34, scale: 18, null: false
+ t.uuid "security_id", null: false
+ t.uuid "source_entry_id"
+ t.decimal "unit_cost", precision: 25, scale: 10
+ t.datetime "updated_at", null: false
+ t.index ["account_id", "security_id"], name: "index_holding_lots_one_opening_lot_per_position", unique: true, where: "(source_entry_id IS NULL)"
+ t.index ["account_id", "source_entry_id"], name: "index_holding_lots_on_account_id_and_source_entry_id", unique: true
+ t.index ["origin_security_id"], name: "index_holding_lots_on_origin_security_id"
+ t.index ["security_id"], name: "index_holding_lots_on_security_id"
+ t.index ["source_entry_id"], name: "index_holding_lots_on_source_entry_id"
+ t.check_constraint "qty >= 0::numeric", name: "holding_lots_qty_non_negative"
+ end
+
create_table "holdings", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "account_id", null: false
t.uuid "account_provider_id"
@@ -3188,6 +3208,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_080000) do
add_foreign_key "goal_pledges", "goals", on_delete: :cascade
add_foreign_key "goal_pledges", "transactions", column: "matched_transaction_id", on_delete: :nullify
add_foreign_key "goals", "families", on_delete: :cascade
+ add_foreign_key "holding_lots", "accounts", on_delete: :cascade
+ add_foreign_key "holding_lots", "entries", column: "source_entry_id", on_delete: :cascade
+ add_foreign_key "holding_lots", "securities", column: "origin_security_id", on_delete: :nullify
+ add_foreign_key "holding_lots", "securities", on_delete: :cascade
add_foreign_key "holdings", "account_providers"
add_foreign_key "holdings", "accounts", on_delete: :cascade
add_foreign_key "holdings", "securities"
diff --git a/test/models/holding/lot_book_test.rb b/test/models/holding/lot_book_test.rb
index 6d62c22ea4..1682090501 100644
--- a/test/models/holding/lot_book_test.rb
+++ b/test/models/holding/lot_book_test.rb
@@ -67,6 +67,8 @@ class Holding::LotBookTest < ActiveSupport::TestCase
end
def add_unknown(*, **); end
+
+ def settle_opening(*, **); end
end
THIRD = BigDecimal("10") / 3
@@ -82,8 +84,8 @@ class Holding::LotBookTest < ActiveSupport::TestCase
[ :buy, 10, 10 ], [ :buy, BigDecimal("13.37"), 20 ], [ :sell, THIRD ], [ :split, Rational(3, 1) ],
[ :sell, THIRD ], [ :buy, BigDecimal("7.77"), 1 ], [ :split, Rational(1, 7) ], [ :sell, BigDecimal("0.123") ]
],
- "an unknown price, an oversell and a transfer lot" => [
- [ :buy, 10, 5 ], [ :unknown, 4 ], [ :buy, nil, 2 ], [ :sell, 3 ], [ :sell, 100 ], [ :buy, 9, 3 ],
+ "an unknown price and a transfer lot" => [
+ [ :buy, 10, 5 ], [ :unknown, 4 ], [ :buy, nil, 2 ], [ :sell, 3 ], [ :buy, 9, 3 ],
[ :unknown, 2 ], [ :sell, 1 ]
]
}.freeze
@@ -321,23 +323,37 @@ class Holding::LotBookTest < ActiveSupport::TestCase
end
end
+ # A short position has no open lots; the shortfall it leaves is filled before
+ # a later acquisition opens one.
test "sum of open lot qty equals the trade-driven position on every date" do
travel_to Time.zone.local(2024, 6, 10, 12) do
build_forward_fixture
- probe = PartitionProbe.new(@account, security_ids: [ @parcels.id, @transferred.id, @split.id ])
+ probe = PartitionProbe.new(@account, security_ids: [ @parcels.id, @transferred.id, @split.id, @negative.id ])
probe.calculate
- assert_equal (d(1)..d(10)).count * 3, probe.checks.size, "every date for each of the three positions"
+ assert_equal (d(1)..d(10)).count * 4, probe.checks.size, "every date for each of the four positions"
probe.checks.each do |date, security_id, position, open_qty|
- assert_equal position.to_d, open_qty, "#{Security.find(security_id).ticker} on #{date}"
+ assert_equal [ position.to_d, 0 ].max, open_qty, "#{Security.find(security_id).ticker} on #{date}"
end
+ assert(probe.checks.any? { |date, id, position, _| id == @negative.id && date == d(3) && position.zero? },
+ "the transfer brings the short position back to zero")
# Every movement kind is crossed: buy, sell, transfer, split.
assert(probe.checks.any? { |_, id, position, _| id == @split.id && position == 81 }, "after the 3-for-1 split and the sales")
assert(probe.checks.any? { |_, id, position, _| id == @transferred.id && position == 15 }, "the transfer lot is counted")
end
end
+ test "selling exactly to zero stays known — the reopen after a clean close is not unknown" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("10"), 5, source_id: "a", acquired_on: Date.new(2024, 1, 1))
+
+ book.apply(nil, -5)
+ book.apply(BigDecimal("20"), 1, source_id: "b", acquired_on: Date.new(2024, 2, 1))
+
+ assert_equal BigDecimal("20"), book.average_cost
+ end
+
test "relief that rounds a lot away keeps the open sum exact" do
tiny = BigDecimal("1e-18")
book = Holding::LotBook.new
@@ -379,6 +395,23 @@ class Holding::LotBookTest < ActiveSupport::TestCase
end
end
+ test "an uncovered sale leaves a shortfall that the next acquisition fills before any lot opens" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("10"), 5, source_id: "a", acquired_on: Date.new(2024, 1, 1))
+
+ book.apply(nil, -100)
+ assert_empty book.lots, "the ledger closes what it can"
+
+ book.apply(BigDecimal("12"), 3, source_id: "tiny", acquired_on: Date.new(2024, 2, 1))
+ assert_empty book.lots, "3 of the 95 missing units are absorbed, not opened"
+
+ book.apply(BigDecimal("12"), 100, source_id: "fill", acquired_on: Date.new(2024, 3, 1))
+ assert_equal [ BigDecimal("8") ], book.lots.map(&:qty), "only the remainder opens a lot: 100 minus the 92 still missing"
+ assert_equal BigDecimal("8"), book.open_qty
+ assert_equal %w[fill], book.lots.map(&:source_id)
+ assert_equal BigDecimal("12"), book.average_cost, "the filled units carry the filling trade's cost"
+ end
+
class PartitionProbe < Holding::ForwardCalculator
def checks
@checks ||= []
diff --git a/test/models/holding_lot_test.rb b/test/models/holding_lot_test.rb
new file mode 100644
index 0000000000..47616b1193
--- /dev/null
+++ b/test/models/holding_lot_test.rb
@@ -0,0 +1,666 @@
+require "test_helper"
+
+class HoldingLotTest < ActiveSupport::TestCase
+ include EntriesTestHelper
+
+ TODAY = Time.zone.local(2024, 6, 10, 12)
+ TWO_THIRDS_UP = BigDecimal("0.666666666666666667")
+ TWO_THIRDS_LAST = BigDecimal("0.666666666666666666")
+
+ # --- The book ---------------------------------------------------------------
+
+ test "a sale with nothing held, then a transfer-in, keeps the book's lots equal to the position" do
+ book = Holding::LotBook.new
+
+ book.apply(nil, -5)
+ book.add_unknown(5, source_id: "transfer")
+
+ assert_equal 0, book.open_qty, "the transfer fills the 5 already sold"
+
+ book.apply(BigDecimal("10"), 10, source_id: "buy")
+
+ assert_equal 10, book.open_qty
+ assert_equal [ [ "transfer", 0 ], [ "buy", 10 ] ], book.ledger.map { |lot| [ lot.source_id, lot.qty ] }
+ end
+
+ test "a split restates the shortfall with the position" do
+ book = Holding::LotBook.new
+ book.apply(nil, -6)
+ book.split(Rational(2, 1))
+
+ book.add_unknown(12, source_id: "transfer")
+
+ assert_equal 0, book.open_qty, "12 post-split units were already sold"
+ end
+
+ test "a pro-rata rounding residual lands on the last open lot of the book" do
+ book = Holding::LotBook.new
+ %w[a b c].each { |id| book.apply(BigDecimal("10"), 1, source_id: id) }
+
+ book.apply(nil, -1)
+
+ assert_equal [ TWO_THIRDS_UP, TWO_THIRDS_UP, TWO_THIRDS_LAST ], book.lots.map(&:qty)
+ end
+
+ # --- Stored lots ------------------------------------------------------------
+
+ test "a buy after lots exist adds one derived lot and leaves the earlier one alone" do
+ travel_to TODAY do
+ setup_account
+ security = priced_security("LOTA", 30)
+ trade(security, 60, 12, 2)
+ materialize(:forward)
+ first = HoldingLot.sole
+
+ assert_difference "HoldingLot.count", 1 do
+ trade(security, 40, 20, 4)
+ materialize(:forward)
+ end
+
+ first_after = HoldingLot.find(first.id)
+ assert_equal [ 60, 12, d(2) ], [ first_after.qty, first_after.unit_cost, first_after.acquired_on ]
+ assert_equal first.created_at, first_after.created_at
+ assert_equal [ 40, 20 ], HoldingLot.where.not(id: first.id).pick(:qty, :unit_cost)
+ end
+ end
+
+ # Rails' upsert with update_only moves updated_at only when a listed column
+ # changes, for both kinds of lot.
+ test "re-materializing moves a lot's updated_at only when the lot changes" do
+ travel_to TODAY do
+ build_reverse_fixture
+ materialize(:reverse)
+ derived = HoldingLot.derived.find_by!(security: @opening, acquired_on: d(3))
+ opening = HoldingLot.opening.find_by!(security: @opening)
+ stale = 1.day.ago.change(usec: 0)
+ HoldingLot.where(id: [ derived.id, opening.id ]).update_all(updated_at: stale)
+
+ materialize(:reverse)
+ assert_equal [ stale, stale ], [ derived.reload.updated_at, opening.reload.updated_at ], "nothing changed"
+
+ trade(@opening, -2, 30, 8)
+ @account.holdings.find_by!(security: @opening, date: d(10)).update!(qty: 12, amount: 360)
+ materialize(:reverse)
+ assert_operator derived.reload.updated_at, :>, stale, "the sale relieved the lot"
+ assert_operator opening.reload.updated_at, :>, stale, "the opening lot was restated"
+ end
+ end
+
+ test "a sale with nothing held, then a transfer-in, keeps the stored lots equal to the position" do
+ travel_to TODAY do
+ setup_account
+ security = priced_security("LOTC", 30)
+ trade(security, -5, 30, 2)
+ transfer = trade(security, 5, 30, 3, label: Trade::TRANSFER_LABEL)
+ trade(security, 10, 10, 4)
+
+ materialize(:forward)
+
+ assert_equal 10, holding_qty(security, d(10))
+ assert_equal 10, HoldingLot.where(security: security).sum(:qty)
+ assert_equal 0, HoldingLot.find_by!(source_entry: transfer).qty
+ end
+ end
+
+ test "a pro-rata rounding residual lands on the last open lot" do
+ travel_to TODAY do
+ setup_account
+ security = priced_security("LOTR", 30)
+ trade(security, 1, 10, 2)
+ trade(security, 1, 10, 3)
+ trade(security, 1, 10, 4)
+ trade(security, -1, 30, 5)
+
+ materialize(:forward)
+
+ assert_equal [ TWO_THIRDS_UP, TWO_THIRDS_UP, TWO_THIRDS_LAST ],
+ HoldingLot.where(security: security).order(:acquired_on).pluck(:qty)
+ end
+ end
+
+ test "sum of open lot qty equals snapshot qty on every date" do
+ setup_account
+ @parcels = priced_security("LOTP", 30)
+ @split = priced_security("LOTS", 30)
+ @moved = priced_security("LOTT", 30)
+ trade(@parcels, 60, 12, 2)
+ trade(@parcels, 40, 20, 4)
+ trade(@parcels, -40, 25, 6)
+ trade(@split, 10, 10, 2)
+ trade(@split, 20, BigDecimal("13.37"), 3)
+ Security::Split.create!(security: @split, ex_date: d(4), numerator: 3, denominator: 1, source: "manual")
+ trade(@split, -7, 30, 5)
+ trade(@moved, 5, 30, 3, label: Trade::TRANSFER_LABEL)
+ trade(@moved, 10, 10, 4)
+ trade(@moved, -4, 30, 8)
+
+ (2..10).each do |day|
+ travel_to Time.zone.local(2024, 6, day, 12) do
+ materialize(:forward)
+
+ [ @parcels, @split, @moved ].each do |security|
+ assert_equal holding_qty(security, d(day)), HoldingLot.where(security: security).sum(:qty),
+ "#{security.ticker} on #{d(day)}"
+ end
+ end
+ end
+ assert_equal 83, holding_qty(@split, d(10)), "the split and a sale are crossed"
+ end
+
+ # 10 / 1.5 rounds to 18 places and back to 10.000000000000000001; the
+ # opening lot takes that rounding, so the lots add up to the holding.
+ test "a split that does not divide evenly leaves the lots adding up to the provider's quantity" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ security = priced_security("SPL3", 30)
+ trade(security, 2, 10, 2)
+ Security::Split.create!(security: security, ex_date: d(4), numerator: 3, denominator: 2, source: "manual")
+ @account.holdings.create!(security: security, date: d(10), qty: 10, price: 30, amount: 300, currency: "USD", account_provider: @account_provider)
+
+ materialize(:reverse)
+
+ lots = HoldingLot.where(account: @account, security: security)
+ assert_equal BigDecimal("10"), lots.sum(:qty)
+ assert_equal [ BigDecimal("7"), BigDecimal("3") ], [ lots.opening.sole.qty, lots.derived.sole.qty ], "only the opening lot moved"
+ end
+ end
+
+ # Fixtures only ever leave 10^-18; a real gap is far wider and is not
+ # rounding, so it stays a difference the lots show.
+ test "the opening lot does not absorb a residual above the bound" do
+ book = Holding::LotBook.new
+ book.add_unknown(BigDecimal("10"))
+ book.apply(BigDecimal("10"), 2, source_id: "buy")
+
+ book.settle_opening(BigDecimal("12.000001"), bound: Holding::LotBook::OPENING_RESIDUAL_BOUND)
+ assert_equal [ BigDecimal("10"), BigDecimal("2") ], book.lots.map(&:qty), "above the bound"
+
+ book.settle_opening(BigDecimal("12.000000000001"), bound: Holding::LotBook::OPENING_RESIDUAL_BOUND)
+ assert_equal [ BigDecimal("10.000000000001"), BigDecimal("2") ], book.lots.map(&:qty), "at the bound"
+ end
+
+ # buy, sell and add_unknown all read their quantity through to_d.
+ test "the residual target is read as a decimal, as the other book entries are" do
+ book = Holding::LotBook.new
+ book.add_unknown(BigDecimal("12"))
+
+ book.settle_opening("12.000000000001", bound: Holding::LotBook::OPENING_RESIDUAL_BOUND)
+
+ assert_equal [ BigDecimal("12.000000000001") ], book.lots.map(&:qty)
+ end
+
+ test "the residual never takes a lot to nothing" do
+ book = Holding::LotBook.new
+ book.add_unknown(BigDecimal("1e-13"))
+
+ book.settle_opening(BigDecimal("0"), bound: Holding::LotBook::OPENING_RESIDUAL_BOUND)
+
+ assert_equal [ BigDecimal("1e-13") ], book.lots.map(&:qty)
+ end
+
+ test "sum of open lot qty equals the provider snapshot, opening lot included" do
+ travel_to TODAY do
+ build_reverse_fixture
+
+ materialize(:reverse)
+
+ { @provider_only => 10, @opening => 10 }.each do |security, provider_qty|
+ assert_equal provider_qty, HoldingLot.where(security: security).sum(:qty), security.ticker
+ assert_equal 1, HoldingLot.opening.where(security: security).count, security.ticker
+ end
+ end
+ end
+
+ test "provider-only position with no trades keeps its provider basis" do
+ travel_to TODAY do
+ build_reverse_fixture
+
+ materialize(:reverse)
+
+ holding = @account.holdings.find_by!(security: @provider_only, date: d(10))
+ assert_equal [ 50, "provider" ], [ holding.cost_basis, holding.cost_basis_source ]
+ lot = HoldingLot.where(security: @provider_only).sole
+ assert lot.opening?
+ assert_equal [ 10, 50, "USD", false ], [ lot.qty, lot.unit_cost, lot.currency, lot.clamped ]
+ end
+ end
+
+ # A snapshot two or more days old, with no market prices, leaves the
+ # position without calculated holdings; its opening lot still takes the
+ # provider's cost.
+ test "an opening lot takes the provider cost when the position has no calculated holdings" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ security = Security.create!(ticker: "LOTU", name: "LOTU")
+ @account.holdings.create!(
+ security: security, date: 5.days.ago.to_date, qty: 10, price: 100, amount: 1000, currency: "USD",
+ cost_basis: 50, cost_basis_source: "provider", account_provider: @account_provider
+ )
+
+ materialize(:reverse)
+
+ assert_equal 50, HoldingLot.opening.find_by!(security: security).unit_cost
+ end
+ end
+
+ # Today the figure averages the imported trades only: 10 @ 100, 4 sold, then
+ # 2 @ 110 is (600 + 220) / 8 = 102.5. The 2 units held before the first
+ # trade are the opening lot, which the sale relieves pro rata.
+ test "the opening lot does not move the calculated figure" do
+ travel_to TODAY do
+ build_reverse_fixture
+
+ materialize(:reverse)
+
+ assert_equal BigDecimal("102.5"), @account.holdings.find_by!(security: @opening, date: d(8)).cost_basis
+ opening = HoldingLot.opening.find_by!(security: @opening)
+ assert_equal [ BigDecimal("1.333333333333333333"), nil, @opening.id ], [ opening.qty, opening.unit_cost, opening.origin_security_id ]
+ assert_equal 2, HoldingLot.derived.where(security: @opening).count, "one per buy"
+ end
+ end
+
+ # The trades add up to 10 units and the provider reports 3.
+ test "provider quantity below trade-derived quantity clamps the opening lot and records it" do
+ travel_to TODAY do
+ build_reverse_fixture
+
+ materialize(:reverse)
+
+ clamped = 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"
+ end
+ end
+
+ # One share through a 1-for-3 split is stored as 0.333...3 to 18 places, and
+ # undoing the split gives 0.999...9: a baseline of -1e-18 that is rounding,
+ # not a short position, the same drift settle_opening tolerates.
+ test "split rounding does not clamp a position the trades fully explain" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ security = priced_security("ROUND", 30)
+ trade(security, 1, 30, 2)
+ security.splits.create!(ex_date: d(5), numerator: 1, denominator: 3, source: "manual")
+ provider_holding(security, BigDecimal("0.333333333333333333"), nil)
+
+ materialize(:reverse)
+
+ assert_not HoldingLot.where(security: security, clamped: true).exists?, "rounding read as a short position"
+ end
+ end
+
+ test "a clamped position that the provider brings back above its trades is unclamped" do
+ travel_to TODAY do
+ build_reverse_fixture
+ materialize(:reverse)
+ lot = HoldingLot.opening.find_by!(security: @gapped)
+ assert_equal [ 0, true ], [ lot.qty, lot.clamped ]
+
+ @account.holdings.find_by!(security: @gapped, date: d(10)).update!(qty: 12, amount: 360)
+ materialize(:reverse)
+
+ lot.reload
+ assert_equal [ 2, false ], [ lot.qty, lot.clamped ], "12 reported against 10 traded"
+ end
+ end
+
+ test "an unclamped position that the provider drops below its trades is clamped" do
+ travel_to TODAY do
+ build_reverse_fixture
+ materialize(:reverse)
+ lot = HoldingLot.opening.find_by!(security: @opening)
+ assert_equal [ BigDecimal("1.333333333333333333"), false ], [ lot.qty, lot.clamped ]
+
+ @account.holdings.find_by!(security: @opening, date: d(10)).update!(qty: 5, amount: 150)
+ materialize(:reverse)
+
+ lot.reload
+ assert_equal [ 0, true ], [ lot.qty, lot.clamped ], "5 reported against 8 traded"
+ end
+ end
+
+ test "an opening lot goes once the trades explain the whole position" do
+ travel_to TODAY do
+ build_reverse_fixture
+ materialize(:reverse)
+ assert HoldingLot.opening.exists?(security: @opening)
+
+ @account.holdings.find_by!(security: @opening, date: d(10)).update!(qty: 8, amount: 240)
+ materialize(:reverse)
+
+ assert_not HoldingLot.opening.exists?(security: @opening), "8 reported against 8 traded"
+ assert_equal 8, HoldingLot.where(security: @opening).sum(:qty)
+ end
+ end
+
+ # A scheduled sale has not happened, so it explains none of the position.
+ test "a scheduled sale does not open a lot" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ security = priced_security("LOTZ", 30)
+ trade(security, 60, 12, 2)
+ trade(security, 40, 20, 4)
+ trade(security, -40, 25, 6)
+ trade(security, -10, 30, 15)
+ provider_holding(security, 60, nil)
+
+ materialize(:reverse)
+
+ assert_not HoldingLot.opening.exists?(security: security)
+ assert_equal 60, HoldingLot.derived.where(security: security).sum(:qty)
+ end
+ end
+
+ # Unlinking an account turns its syncs forward, and the forward calculator
+ # knows nothing of units held before the trades.
+ test "a forward sync after unlinking leaves the opening lots alone" do
+ travel_to TODAY do
+ build_reverse_fixture
+ materialize(:reverse)
+ opening_ids = HoldingLot.opening.order(:id).pluck(:id)
+ assert_equal 3, opening_ids.size
+
+ @account_provider.destroy!
+ materialize(:forward)
+
+ assert_equal opening_ids, HoldingLot.opening.order(:id).pluck(:id)
+ assert_equal 4, HoldingLot.derived.count, "the derived lots are still the forward path's"
+ end
+ end
+
+ test "deleting a trade deletes its derived lot" do
+ travel_to TODAY do
+ setup_account
+ security = priced_security("LOTD", 30)
+ keep = trade(security, 10, 12, 2)
+ gone = trade(security, 5, 20, 4)
+ materialize(:forward)
+
+ gone.destroy!
+
+ assert_equal [ keep.id ], HoldingLot.pluck(:source_entry_id)
+ end
+ end
+
+ test "a buy edited into a sale loses its lot on the next materialization" do
+ travel_to TODAY do
+ setup_account
+ security = priced_security("LOTE", 30)
+ keep = trade(security, 10, 12, 2)
+ edited = trade(security, 5, 20, 4)
+ materialize(:forward)
+
+ edited.entryable.update!(qty: -5)
+ materialize(:forward)
+
+ assert_equal [ keep.id ], HoldingLot.pluck(:source_entry_id)
+ assert_equal 5, HoldingLot.sole.qty
+ end
+ end
+
+ # As SnaptradeAccount::SplitSecurityRepair and the security rake tasks do.
+ test "a trade moved to another security without its lot takes the lot along at the next materialization" do
+ travel_to TODAY do
+ setup_account
+ from = priced_security("LOTJ", 30)
+ to = priced_security("LOTK", 30)
+ entry = trade(from, 10, 12, 2)
+ materialize(:forward)
+ lot = HoldingLot.sole
+
+ Trade.where(id: entry.entryable_id).update_all(security_id: to.id)
+ materialize(:forward)
+
+ assert_equal [ lot.id, to.id ], HoldingLot.sole.then { |moved| [ moved.id, moved.security_id ] }
+ end
+ end
+
+ # --- Remap and reset --------------------------------------------------------
+
+ test "remap moves lots with their trades" do
+ travel_to TODAY do
+ setup_account
+ old_security = priced_security("LOTO", 30)
+ new_security = priced_security("LOTN", 30)
+ trade(old_security, 10, 40, 2)
+ trade(new_security, 5, 100, 2)
+ materialize(:forward)
+ ids = HoldingLot.order(:id).pluck(:id)
+
+ @account.holdings.find_by!(security: old_security, date: d(10)).remap_security!(new_security)
+
+ assert_equal [ new_security.id ], HoldingLot.distinct.pluck(:security_id), "moved with the trades, before any sync"
+
+ materialize(:forward, security_ids: [ new_security.id ])
+
+ assert_equal ids, HoldingLot.order(:id).pluck(:id), "re-keyed, not merged or rebuilt"
+ assert_equal 60, @account.holdings.find_by!(security: new_security, date: d(10)).cost_basis
+ end
+ end
+
+ test "reset returns lots to the provider security" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ original = priced_security("LOTX", 30)
+ replacement = priced_security("LOTY", 30)
+ trade(original, 10, 40, 3)
+ provider_row = provider_holding(original, 15, nil)
+ materialize(:reverse)
+ ids = HoldingLot.order(:id).pluck(:id)
+ assert_equal [ 5, 10 ], [ HoldingLot.opening.sole.qty, HoldingLot.derived.sole.qty ], "the 5 held before the trade open a lot"
+
+ provider_row.remap_security!(replacement)
+ assert_equal [ replacement.id ], HoldingLot.distinct.pluck(:security_id)
+ materialize(:reverse, security_ids: [ replacement.id ])
+
+ provider_row.reload.reset_security_to_provider!
+
+ assert_equal ids, HoldingLot.order(:id).pluck(:id)
+ assert_equal [ original.id ], HoldingLot.distinct.pluck(:security_id)
+ assert_equal original.id, HoldingLot.opening.sole.origin_security_id
+ end
+ end
+
+ # The opening lot first appears after the remap, under the replacement;
+ # it came from the provider's security, so a reset takes it back there.
+ test "an opening lot created after a remap belongs to the provider security" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ original = priced_security("LOTA2", 30)
+ replacement = priced_security("LOTB2", 30)
+ trade(original, 10, 40, 3)
+ provider_row = provider_holding(original, 10, nil)
+ materialize(:reverse)
+ assert_not HoldingLot.opening.exists?, "the trade explains the whole position"
+
+ provider_row.remap_security!(replacement)
+ provider_row.reload.update!(qty: 15, amount: 450)
+ materialize(:reverse)
+
+ assert_equal original.id, HoldingLot.opening.find_by!(security: replacement).origin_security_id
+
+ provider_row.reload.reset_security_to_provider!
+
+ assert_not HoldingLot.exists?(security: replacement)
+ assert_equal 5, HoldingLot.opening.find_by!(security: original).qty
+ end
+ end
+
+ # Two provider positions remapped onto one security on different days: the
+ # opening lot is built from the latest snapshot, so it comes from the
+ # provider security behind that snapshot, and resetting that one takes the
+ # lot back.
+ test "an opening lot comes from the provider security behind the latest snapshot" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ earlier = priced_security("LOTA3", 30)
+ latest = priced_security("LOTC3", 30)
+ target = priced_security("LOTB3", 30)
+ earlier_row = @account.holdings.create!(security: earlier, date: d(9), qty: 4, price: 30, amount: 120, currency: "USD",
+ account_provider: @account_provider)
+ latest_row = provider_holding(latest, 6, nil)
+
+ earlier_row.remap_security!(target)
+ latest_row.remap_security!(target)
+ materialize(:reverse)
+
+ assert_equal latest.id, HoldingLot.opening.find_by!(security: target).origin_security_id
+
+ latest_row.reload.reset_security_to_provider!
+
+ assert_equal 6, HoldingLot.opening.find_by!(security: latest).qty
+ end
+ end
+
+ # The opening lot already exists, from an earlier provider security, when a
+ # later snapshot arrives from another one remapped onto the same security:
+ # the lot is restated over that snapshot, so its origin follows it, and
+ # resetting the later security takes the lot back.
+ test "an existing opening lot takes its origin from a later snapshot's provider security" do
+ travel_to TODAY do
+ setup_account
+ link_account
+ earlier = priced_security("LOTA4", 30)
+ later = priced_security("LOTC4", 30)
+ target = priced_security("LOTB4", 30)
+ earlier_row = @account.holdings.create!(security: earlier, date: d(9), qty: 4, price: 30, amount: 120, currency: "USD",
+ account_provider: @account_provider)
+ earlier_row.remap_security!(target)
+ materialize(:reverse)
+ lot = HoldingLot.opening.find_by!(security: target)
+ assert_equal earlier.id, lot.origin_security_id
+
+ later_row = provider_holding(later, 6, nil)
+ later_row.remap_security!(target)
+ materialize(:reverse)
+
+ assert_equal [ lot.id, later.id ], HoldingLot.opening.where(security: target).pick(:id, :origin_security_id)
+
+ # The remap merged the later row into the target's row for that day.
+ @account.holdings.find_by!(security: target, provider_security: later).reset_security_to_provider!
+
+ assert_equal [ lot.id ], HoldingLot.opening.where(security: later).pluck(:id)
+ assert_not HoldingLot.exists?(security: target)
+ end
+ end
+
+ test "remap onto a position with its own opening lot leaves one opening lot there" do
+ setup_account
+ old_security = priced_security("LOTQ", 30)
+ new_security = priced_security("LOTW", 30)
+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 4, price: 30, amount: 120, currency: "USD")
+ moved = opening_lot(old_security, 4)
+ kept = opening_lot(new_security, 6)
+
+ holding.remap_security!(new_security)
+
+ assert_equal [ kept.id ], HoldingLot.opening.where(security: new_security).pluck(:id)
+ assert_not HoldingLot.exists?(moved.id), "restated into the target's opening lot by the next materialization"
+ end
+
+ # A run scoped to one security (a remap, a price sync) books lots for that
+ # security only: neither the provider snapshot, which covers the whole
+ # account, nor the account's other trades open a book.
+ test "a reverse run scoped to one security books lots for that security only" do
+ travel_to TODAY do
+ build_reverse_fixture
+ calculator = Holding::ReverseCalculator.new(@account.reload, portfolio_snapshot: Holding::PortfolioSnapshot.new(@account), security_ids: [ @opening.id ])
+ calculator.calculate
+
+ assert_equal [ @opening.id ], calculator.lots_by_security.keys
+ end
+ end
+
+ # A cost per unit in the account's currency can pass 10^9 where the trade's
+ # own currency is far stronger: one share at USD 700,000 in a VND account.
+ test "a position costing 10^9 or more a unit in the account's currency syncs and stores its lots" do
+ travel_to TODAY do
+ @account = families(:empty).accounts.create!(name: "VND", balance: 0, cash_balance: 0, currency: "VND", accountable: Investment.new)
+ security = Security.create!(ticker: "BRKV", name: "BRKV")
+ Security::Price.insert_all((d(1)..d(10)).map { |date| { security_id: security.id, date: date, price: 700_000, currency: "USD" } })
+ ExchangeRate.insert_all((d(1)..d(10)).map { |date| { from_currency: "USD", to_currency: "VND", date: date, rate: 25_000 } })
+ create_trade(security, account: @account, qty: 1, price: 700_000, currency: "USD", date: d(2))
+
+ materialize(:forward)
+
+ assert_equal BigDecimal("17500000000"), HoldingLot.find_by!(account: @account, security: security).unit_cost
+ assert_equal BigDecimal("17500000000"), @account.holdings.find_by!(security: security, date: d(10)).cost_basis
+ end
+ end
+
+ private
+ def d(day)
+ Date.new(2024, 6, day)
+ end
+
+ def setup_account
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Lots", balance: 20000, cash_balance: 20000, currency: "USD", accountable: Investment.new)
+ end
+
+ def link_account
+ coinstats_item = @family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
+ coinstats_account = coinstats_item.coinstats_accounts.create!(name: "Provider", currency: "USD")
+ @account_provider = AccountProvider.create!(account: @account, provider: coinstats_account)
+ end
+
+ def priced_security(ticker, price)
+ security = Security.create!(ticker: ticker, name: ticker)
+ Security::Price.insert_all((d(1)..d(10)).map { |date| { security_id: security.id, date: date, price: price, currency: "USD" } })
+ security
+ end
+
+ def trade(security, qty, price, day, label: nil)
+ entry = create_trade(security, account: @account, qty: qty, price: price, date: d(day))
+ entry.entryable.update!(investment_activity_label: label) if label
+ entry
+ end
+
+ def provider_holding(security, qty, basis)
+ @account.holdings.create!(
+ security: security, date: d(10), qty: qty, price: 30, amount: qty * 30, currency: "USD",
+ cost_basis: basis, cost_basis_source: basis && "provider", account_provider: @account_provider
+ )
+ end
+
+ def opening_lot(security, qty)
+ HoldingLot.create!(account: @account, security: security, origin_security: security, qty: qty, currency: "USD")
+ end
+
+ # A linked account: a provider-only position, a position with 2 units held
+ # before its first imported trade, and an import whose trades add up to
+ # more than the provider reports.
+ def build_reverse_fixture
+ setup_account
+ link_account
+ @provider_only = priced_security("LOTF", 30)
+ @opening = priced_security("LOTG", 30)
+ @gapped = priced_security("LOTH", 30)
+
+ trade(@opening, 10, 100, 3)
+ trade(@opening, -4, 30, 5)
+ trade(@opening, 2, 110, 7)
+ trade(@gapped, 5, 100, 2)
+ trade(@gapped, 5, 150, 4)
+
+ provider_holding(@provider_only, 10, 50)
+ provider_holding(@opening, 10, nil)
+ provider_holding(@gapped, 3, nil)
+ end
+
+ def materialize(strategy, security_ids: nil)
+ Holding::Materializer.new(@account.reload, strategy: strategy, security_ids: security_ids).materialize_holdings
+ end
+
+ def holding_qty(security, date)
+ @account.holdings.find_by!(security: security, date: date).qty
+ end
+end