Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Apply stock splits to holdings (#3850)

jaysbeekayd0cbff3dec70
diff --git a/app/models/holding/cost_basis_tracker.rb b/app/models/holding/cost_basis_tracker.rb
index ceaed8f884..771b7ce14f 100644
--- a/app/models/holding/cost_basis_tracker.rb
+++ b/app/models/holding/cost_basis_tracker.rb
@@ -50,6 +50,12 @@ class Holding::CostBasisTracker
reset if @total_qty <= 0
end
+ # A split changes the share count and not the money invested, so total cost
+ # stays and the per-share average moves by the inverse of the ratio.
+ def split(ratio)
+ @total_qty = Security::Split.scale(@total_qty, ratio)
+ end
+
# Current weighted-average cost per share, or nil when nothing is held.
def average_cost
return nil if @total_qty.zero?
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index fd7ac425f1..2ba5ee814c 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -23,7 +23,7 @@ class Holding::ForwardCalculator
account.start_date.upto(Date.current).each do |date|
trades = portfolio_cache.get_trades(date: date)
- next_portfolio = apply_trades(current_portfolio, trades)
+ next_portfolio = apply_trades(apply_splits(current_portfolio, date), trades)
holdings.concat(build_holdings(next_portfolio, date))
current_portfolio = next_portfolio
end
@@ -71,6 +71,19 @@ class Holding::ForwardCalculator
end.compact
end
+ # A split takes effect at the open of its ex-date, before that day's trades,
+ # which are already in post-split shares (#249). It scales the position and
+ # its cost-basis tracker together, so total cost carries across unchanged.
+ def apply_splits(opening_portfolio, date)
+ opening_portfolio.to_h do |security_id, qty|
+ ratio = portfolio_cache.get_split_ratio(security_id, date)
+ next [ security_id, qty ] unless ratio
+
+ @cost_basis_trackers[security_id].split(ratio)
+ [ security_id, Security::Split.scale(qty, ratio) ]
+ end
+ end
+
# Applies the day's trades in order and returns the resulting portfolio, so the
# caller does not walk the same trades again to compute quantities.
#
diff --git a/app/models/holding/gapfillable.rb b/app/models/holding/gapfillable.rb
index f841bbc930..f9a8661a23 100644
--- a/app/models/holding/gapfillable.rb
+++ b/app/models/holding/gapfillable.rb
@@ -4,6 +4,7 @@ module Holding::Gapfillable
class_methods do
def gapfill(holdings)
filled_holdings = []
+ splits = splits_for(holdings)
holdings.group_by { |h| h.security_id }.each do |security_id, security_holdings|
next if security_holdings.empty?
@@ -19,7 +20,17 @@ module Holding::Gapfillable
filled_holdings << holding
previous_holding = holding
else
- # Create a new holding based on the previous day's data
+ # Carry the previous day forward, through any split going ex today.
+ #
+ # A day with no price emits no holding, so a split on such a day
+ # used to be filled over with the pre-split share count and
+ # per-share cost -- and stayed that way for every day after it,
+ # which for a security whose prices have stopped means forever.
+ # A split moves no money: the count scales, the per-share price and
+ # cost move by the inverse, and the position's value is unchanged.
+ ratio = splits[[ security_id, date ]]
+ previous_holding = carry_through_split(previous_holding, ratio) if ratio
+
filled_holdings << Holding::HoldingData.new(
account_id: previous_holding.account_id,
security_id: previous_holding.security_id,
@@ -37,5 +48,37 @@ module Holding::Gapfillable
filled_holdings
end
+
+ private
+ # The splits these holdings could be filled across, by security and
+ # ex-date. One query for the whole set rather than one per filled day.
+ def splits_for(holdings)
+ return {} if holdings.empty?
+
+ Security::Split
+ .where(security_id: holdings.map(&:security_id).uniq, ex_date: holdings.min_by(&:date).date..Date.current)
+ .to_h { |split| [ [ split.security_id, split.ex_date ], split.ratio ] }
+ end
+
+ # The same holding restated in post-split terms. `amount` is deliberately
+ # recomputed from the scaled count and the inverse-scaled price rather
+ # than carried, so the two cannot drift apart at the rounding the stored
+ # scale imposes.
+ def carry_through_split(holding, ratio)
+ qty = Security::Split.scale(holding.qty, ratio)
+ price = Security::Split.unscale(holding.price, ratio)
+
+ Holding::HoldingData.new(
+ account_id: holding.account_id,
+ security_id: holding.security_id,
+ date: holding.date,
+ qty: qty,
+ price: price,
+ currency: holding.currency,
+ amount: qty * price,
+ cost_basis: holding.cost_basis && Security::Split.unscale(holding.cost_basis, ratio),
+ cost_basis_unknown: holding.cost_basis_unknown
+ )
+ end
end
end
diff --git a/app/models/holding/materializer.rb b/app/models/holding/materializer.rb
index 599a799791..c6b5a92c77 100644
--- a/app/models/holding/materializer.rb
+++ b/app/models/holding/materializer.rb
@@ -246,6 +246,7 @@ class Holding::Materializer
return nil unless result
cost_basis, snap_currency, snap_date = result
+ cost_basis = split_adjusted_cost_basis(cost_basis, holding.security_id, snap_date, holding.date)
return cost_basis if snap_currency == holding.currency
Money.new(cost_basis, snap_currency).exchange_to(holding.currency, date: snap_date).amount
@@ -253,6 +254,39 @@ class Holding::Materializer
nil
end
+ # The snapshot's per-share cost, restated for the share count the holding
+ # is on.
+ #
+ # The figure carried forward is per share, and a split changes how many
+ # shares the same money bought: a $100 basis across a 2-for-1 split is $50
+ # a share afterwards, on twice as many shares, for the same $1,000 total.
+ # Carried across unchanged it doubled every position's recorded cost, and
+ # every gain and return computed from it, without anything looking wrong.
+ def split_adjusted_cost_basis(cost_basis, security_id, snap_date, holding_date)
+ factor = cumulative_split_factor(security_id, snap_date, holding_date)
+ return cost_basis if factor == 1
+
+ Security::Split.unscale(cost_basis, factor)
+ end
+
+ def cumulative_split_factor(security_id, from, to)
+ return Rational(1) if from.nil? || to.nil? || from >= to
+
+ splits_by_security[security_id].reduce(Rational(1)) do |factor, split|
+ next factor unless split.ex_date > from && split.ex_date <= to
+
+ factor * split.ratio
+ end
+ end
+
+ def splits_by_security
+ @splits_by_security ||= Security::Split
+ .where(security_id: @holdings.map(&:security_id).uniq)
+ .order(:ex_date)
+ .group_by(&:security_id)
+ .tap { |grouped| grouped.default = [] }
+ end
+
def provider_cost_basis_snapshots
@provider_cost_basis_snapshots ||= begin
ids = @holdings.map(&:security_id).uniq
diff --git a/app/models/holding/portfolio_cache.rb b/app/models/holding/portfolio_cache.rb
index 014c7ceb76..acbd632521 100644
--- a/app/models/holding/portfolio_cache.rb
+++ b/app/models/holding/portfolio_cache.rb
@@ -57,9 +57,61 @@ class Holding::PortfolioCache
@security_cache.map { |_, v| v[:security] }
end
+ # The ratio of the split a security goes ex on this date, or nil when it
+ # has none. Nil, not 1, so a caller can leave an unsplit position untouched.
+ def get_split_ratio(security_id, date)
+ split_ratios[[ security_id, date ]]
+ end
+
+ # Every split within the account's history, oldest first.
+ def get_splits
+ splits
+ end
+
+ # How many shares one share held at the close of `from` has become by the
+ # close of `to`: the product of the ratios of the splits in between. 1 when
+ # there are none, so a caller can multiply unconditionally.
+ #
+ # Reads every split up to today, not only those within the account's
+ # history: a provider snapshot can be older than the account's first entry
+ # (an account with no entries starts yesterday), and a split between the
+ # snapshot and that start still changed the count it reported.
+ def split_factor_between(security_id, from, to)
+ return Rational(1) if from.nil? || to.nil? || from >= to
+
+ splits_through_today.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
+
private
PriceWithPriority = Data.define(:price, :priority, :source)
+ # Only splits the holdings can see: from the account's start date, when
+ # its holdings begin, to today. A split announced for a future ex-date is
+ # not applied early; it takes effect when that date arrives.
+ def splits
+ @splits ||= Security::Split
+ .where(security_id: @security_cache.keys, ex_date: account.start_date..Date.current)
+ .order(:ex_date)
+ .to_a
+ end
+
+ # Every split up to today, however early, for carrying a snapshot forward.
+ def splits_through_today
+ @splits_through_today ||= Security::Split
+ .where(security_id: @security_cache.keys, ex_date: ..Date.current)
+ .order(:ex_date)
+ .to_a
+ end
+
+ def split_ratios
+ @split_ratios ||= splits.to_h { |split| [ [ split.security_id, split.ex_date ], split.ratio ] }
+ end
+
def trades
@trades ||= account.entries.includes(entryable: :security).trades.chronological.to_a
end
diff --git a/app/models/holding/portfolio_snapshot.rb b/app/models/holding/portfolio_snapshot.rb
index 2bf140efaa..5d1904f46c 100644
--- a/app/models/holding/portfolio_snapshot.rb
+++ b/app/models/holding/portfolio_snapshot.rb
@@ -10,22 +10,38 @@ class Holding::PortfolioSnapshot
# Returns a hash of {security_id => qty} representing today's starting portfolio.
# Includes all securities from trades (with 0 qty if no holdings exist).
def to_h
- @portfolio ||= build_portfolio
+ build
+ @portfolio
+ end
+
+ # The date each quantity in #to_h was actually observed on, by security id.
+ #
+ # A provider snapshot can be days old -- a sync that failed, retried late, or
+ # ran against a provider that had not refreshed -- and the reverse calculator
+ # starts these quantities at today. Without knowing when each was true it
+ # cannot tell a quantity that is current from one that predates a corporate
+ # action. Securities present only through trades have no observed quantity
+ # and no date.
+ def effective_dates
+ build
+ @effective_dates
end
private
- def build_portfolio
+ def build
+ return if defined?(@portfolio) && @portfolio
+
# Start with all securities from trades initialized to 0
- portfolio = account.trades
+ @portfolio = account.trades
.pluck(:security_id)
.uniq
.each_with_object({}) { |security_id, hash| hash[security_id] = 0 }
+ @effective_dates = {}
latest_holdings_scope.each do |holding|
- portfolio[holding.security_id] = holding.qty
+ @portfolio[holding.security_id] = holding.qty
+ @effective_dates[holding.security_id] = holding.date
end
-
- portfolio
end
def latest_holdings_scope
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index 6cf08b043a..e29e795182 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -26,15 +26,16 @@ class Holding::ReverseCalculator
end
def calculate_holdings
- # Start with the portfolio snapshot passed in from the materializer
- current_portfolio = portfolio_snapshot.to_h
+ # Start with the portfolio snapshot passed in from the materializer,
+ # brought forward to today first (see #starting_portfolio).
+ current_portfolio = starting_portfolio
previous_portfolio = {}
holdings = []
Date.current.downto(account.start_date).each do |date|
today_trades = portfolio_cache.get_trades(date: date)
- previous_portfolio = transform_portfolio(current_portfolio, today_trades, direction: :reverse)
+ previous_portfolio = undo_splits(transform_portfolio(current_portfolio, today_trades, direction: :reverse), date)
# If current day, always use holding prices (since that's what Plaid gives us). For historical values, use market data (since Plaid doesn't supply historical prices)
holdings.concat(build_holdings(current_portfolio, date, price_source: date == Date.current ? "holding" : nil))
@@ -44,6 +45,35 @@ class Holding::ReverseCalculator
holdings
end
+ # The snapshot as it stands today.
+ #
+ # The walk below starts at `Date.current` and undoes its way back, so it
+ # reads the snapshot as today's position. A provider snapshot is often
+ # older than that -- a sync that failed and retried late, or a provider
+ # that had not refreshed -- and a split that went ex in between has already
+ # changed the share count the provider reported. Left alone, today's
+ # holding kept the pre-split quantity, and the walk then *undid* that same
+ # split on the way past, so the history came out short as well.
+ #
+ # Each quantity is carried forward by the splits between the day it was
+ # observed and today. Trades in that window are a separate, older gap: this
+ # calculator has always assumed the snapshot already includes them, and
+ # nothing here changes that.
+ def starting_portfolio
+ # A snapshot that reports no dates is read as current, which is what this
+ # did before there were any.
+ @starting_portfolio ||= begin
+ dates = portfolio_snapshot.effective_dates || {}
+
+ portfolio_snapshot.to_h.to_h do |security_id, qty|
+ factor = portfolio_cache.split_factor_between(security_id, dates[security_id], Date.current)
+ next [ security_id, qty ] if factor == 1
+
+ [ security_id, Security::Split.scale(qty, factor) ]
+ end
+ end
+ end
+
def transform_portfolio(previous_portfolio, trade_entries, direction: :forward)
new_quantities = previous_portfolio.dup
@@ -58,6 +88,16 @@ class Holding::ReverseCalculator
new_quantities
end
+ # Walking back from the close of `date` to the close of the day before: once
+ # the day's trades are undone, a split that went ex on `date` is undone too,
+ # since it took effect at that day's open (#249).
+ def undo_splits(portfolio, date)
+ portfolio.to_h do |security_id, qty|
+ ratio = portfolio_cache.get_split_ratio(security_id, date)
+ [ security_id, ratio ? Security::Split.unscale(qty, ratio) : qty ]
+ end
+ end
+
def build_holdings(portfolio, date, price_source: nil)
portfolio.map do |security_id, qty|
next if @security_ids && !@security_ids.include?(security_id)
@@ -94,19 +134,41 @@ class Holding::ReverseCalculator
# Re-sorting by date alone is unstable and could reorder same-day trades,
# which matters because the tracker is order-sensitive once sells relieve.
trades = portfolio_cache.get_trades
+ events = replay_events(trades)
# A reverse-synced account can hold shares before its first imported trade,
# because the provider gives current holdings rather than full history. Seed
- # each running position from the snapshot minus the net imported trades, so
- # "position back at zero" reflects the real position, not just the trades we
- # happen to have.
- net_qty = Hash.new(0)
- trades.each { |te| net_qty[te.entryable.security_id] += te.entryable.qty }
- snapshot = portfolio_snapshot.to_h
+ # each running position by walking the snapshot back through every imported
+ # trade and split, so "position back at zero" reflects the real position,
+ # not just the trades we happen to have. Across a split, "snapshot minus
+ # net trades" is not that: the trades before it are in pre-split shares.
+ # The walk undoes every split up to today, so it starts from the snapshot
+ # brought forward to today, as #calculate_holdings does.
+ snapshot = starting_portfolio
positions = Hash.new(0)
- net_qty.each_key { |security_id| positions[security_id] = (snapshot[security_id] || 0) - net_qty[security_id] }
+ trades.each { |te| positions[te.entryable.security_id] = snapshot[te.entryable.security_id] || 0 }
+ events.reverse_each do |event|
+ if event.is_a?(Security::Split)
+ next unless positions.key?(event.security_id)
- trades.each do |trade_entry|
+ positions[event.security_id] = Security::Split.unscale(positions[event.security_id], event.ratio)
+ else
+ positions[event.entryable.security_id] -= event.entryable.qty
+ end
+ end
+
+ events.each do |event|
+ if event.is_a?(Security::Split)
+ security_id = event.security_id
+ next unless positions.key?(security_id)
+
+ positions[security_id] = Security::Split.scale(positions[security_id], event.ratio)
+ trackers[security_id].split(event.ratio)
+ @cost_basis_snapshots[security_id] << [ event.ex_date, trackers[security_id].average_cost ]
+ next
+ end
+
+ trade_entry = event
trade = trade_entry.entryable
security_id = trade.security_id
previous_position = positions[security_id]
@@ -147,6 +209,15 @@ class Holding::ReverseCalculator
open_unknown_start.each { |security_id, start| @unknown_spans[security_id] << [ start, nil ] }
end
+ # Trades and splits in the order they took effect. A split goes first on its
+ # ex-date: it happens at the open, and that day's trades are already in
+ # post-split shares. `trades` is chronological and kept in its own order.
+ def replay_events(trades)
+ events = trades.each_with_index.map { |entry, index| [ entry.date, 1, index, entry ] }
+ events += portfolio_cache.get_splits.map { |split| [ split.ex_date, 0, 0, split ] }
+ events.sort_by { |date, kind, index, _| [ date, kind, index ] }.map(&:last)
+ end
+
def transferred_by?(security_id, date)
@unknown_spans[security_id].any? { |start, stop| start <= date && (stop.nil? || date < stop) }
end
diff --git a/app/models/security.rb b/app/models/security.rb
index 1a1343da83..e69813c225 100644
--- a/app/models/security.rb
+++ b/app/models/security.rb
@@ -88,6 +88,7 @@ class Security < ApplicationRecord
has_many :trades, dependent: :nullify, class_name: "Trade"
has_many :prices, dependent: :destroy
+ has_many :splits, dependent: :destroy
validates :ticker, presence: true
validates :ticker, uniqueness: { scope: :exchange_operating_mic, case_sensitive: false }
@@ -254,6 +255,13 @@ class Security < ApplicationRecord
Money.new(@current_price.price, @current_price.currency)
end
+ # How many shares one share held at the close of `from` has become by the
+ # close of `to`: the product of the ratios of splits whose ex-date falls
+ # after `from` and on or before `to`. 1 when there are none.
+ def split_factor_between(from, to)
+ splits.where(ex_date: (from + 1)..to).reduce(Rational(1)) { |factor, split| factor * split.ratio }
+ end
+
def to_combobox_option
ComboboxOption.new(
symbol: ticker,
diff --git a/app/models/security/split.rb b/app/models/security/split.rb
new file mode 100644
index 0000000000..41c2c3ccc7
--- /dev/null
+++ b/app/models/security/split.rb
@@ -0,0 +1,55 @@
+# A change in a security's share count that no trade made: a 2-for-1 split
+# turns 10 shares into 20 on its ex-date, and a 1-for-10 reverse split turns
+# 100 into 10. The money invested does not change, so cost per share moves by
+# the inverse of the ratio.
+#
+# The holding calculators apply it at the open of the ex-date, before that
+# day's trades (#249).
+class Security::Split < ApplicationRecord
+ belongs_to :security
+
+ validates :ex_date, :source, presence: true
+ validates :numerator, :denominator, numericality: { only_integer: true, greater_than: 0 }
+ validates :ex_date, uniqueness: { scope: :security_id }
+ validate :changes_the_share_count
+
+ # New shares per old, exact.
+ def ratio
+ Rational(numerator, denominator)
+ end
+
+ # The scale of the `qty` columns on `holdings` and `trades`. A quantity this
+ # code hands around has to be one the database can hold: anything finer is a
+ # number no position can actually be in.
+ QTY_SCALE = 18
+
+ # A share count after a split of `ratio`, and before it. Multiplying a
+ # BigDecimal by a Rational rounds at 32 digits, so 3 shares through a
+ # 1-for-3 split came out 0.999...; multiplying by the numerator and then
+ # dividing by the denominator is exact whenever the answer is.
+ #
+ # When the answer doesn't terminate -- 10 shares through a 1-for-3 split is
+ # 3.333... -- the result is rounded to the stored scale. Carrying the extra
+ # digits instead left a position that had been sold in full holding about
+ # 3e-31 of a share: the seller can only sell what the column can hold, so the
+ # subtraction missed exact zero, the cost-basis tracker never reset, and an
+ # inbound transfer's "cost unknown" mark survived a full liquidation.
+ #
+ # The cost of rounding here is that scaling and unscaling back can land one
+ # unit in the last place away from where it started. That is the floor the
+ # column imposes anyway.
+ def self.scale(qty, ratio)
+ (qty.to_d * ratio.numerator / ratio.denominator).round(QTY_SCALE)
+ end
+
+ def self.unscale(qty, ratio)
+ (qty.to_d * ratio.denominator / ratio.numerator).round(QTY_SCALE)
+ end
+
+ private
+ # A 1:1 "split" changes nothing, and the DB refuses it too. Reuses Rails'
+ # own `other_than` message, so no new string is needed.
+ def changes_the_share_count
+ errors.add(:denominator, :other_than, count: numerator) if numerator.present? && numerator == denominator
+ end
+end
diff --git a/db/migrate/20260928100000_create_security_splits.rb b/db/migrate/20260928100000_create_security_splits.rb
new file mode 100644
index 0000000000..eb0e8b26fe
--- /dev/null
+++ b/db/migrate/20260928100000_create_security_splits.rb
@@ -0,0 +1,27 @@
+class CreateSecuritySplits < ActiveRecord::Migration[8.1]
+ def change
+ # Stored per security, beside its prices, not per account: a split is a fact
+ # about the instrument, and securities are shared across families (#249).
+ create_table :security_splits, id: :uuid do |t|
+ t.references :security, null: false, type: :uuid, foreign_key: { on_delete: :cascade }
+
+ # The first trading day on the new share count. The holding calculators
+ # apply the split at the open of this day, before its trades.
+ t.date :ex_date, null: false
+
+ # New shares per old: a 2-for-1 split is 2/1, a 1-for-10 reverse split
+ # is 1/10. Kept as two integers so the ratio stays exact.
+ t.integer :numerator, null: false
+ t.integer :denominator, null: false
+
+ t.string :source, null: false
+
+ t.timestamps
+ end
+
+ add_index :security_splits, [ :security_id, :ex_date ], unique: true
+
+ add_check_constraint :security_splits, "numerator > 0 AND denominator > 0", name: "security_splits_positive_terms"
+ add_check_constraint :security_splits, "numerator <> denominator", name: "security_splits_not_one_to_one"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 3b3752fa5a..4f76c9406c 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2332,6 +2332,20 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_08_090000) do
t.index ["security_id"], name: "index_security_prices_on_security_id"
end
+ create_table "security_splits", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
+ t.datetime "created_at", null: false
+ t.integer "denominator", null: false
+ t.date "ex_date", null: false
+ t.integer "numerator", null: false
+ t.uuid "security_id", null: false
+ t.string "source", null: false
+ t.datetime "updated_at", null: false
+ t.index ["security_id", "ex_date"], name: "index_security_splits_on_security_id_and_ex_date", unique: true
+ t.index ["security_id"], name: "index_security_splits_on_security_id"
+ t.check_constraint "numerator <> denominator", name: "security_splits_not_one_to_one"
+ t.check_constraint "numerator > 0 AND denominator > 0", name: "security_splits_positive_terms"
+ end
+
create_table "sessions", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
t.uuid "active_impersonator_session_id"
t.datetime "created_at", null: false
@@ -3076,6 +3090,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_08_090000) do
add_foreign_key "rule_runs", "rules"
add_foreign_key "rules", "families"
add_foreign_key "security_prices", "securities"
+ add_foreign_key "security_splits", "securities", on_delete: :cascade
add_foreign_key "sessions", "impersonation_sessions", column: "active_impersonator_session_id", on_delete: :nullify
add_foreign_key "sessions", "users"
add_foreign_key "simplefin_accounts", "simplefin_items"
diff --git a/test/models/holding/cost_basis_tracker_test.rb b/test/models/holding/cost_basis_tracker_test.rb
index bdf8117c61..5a2657541f 100644
--- a/test/models/holding/cost_basis_tracker_test.rb
+++ b/test/models/holding/cost_basis_tracker_test.rb
@@ -63,4 +63,50 @@ class Holding::CostBasisTrackerTest < ActiveSupport::TestCase
assert_equal BigDecimal("300"), @tracker.average_cost
end
+
+ # A split changes how many shares the money bought, not how much it cost.
+ # Quantity is read back by selling down: the position empties (and the
+ # average resets to nil) on exactly the last share, and not one before it.
+ test "a 2-for-1 split doubles the shares, keeps the total cost and halves the average" do
+ @tracker.apply(BigDecimal("100"), BigDecimal("10")) # 1,000 for 10
+
+ @tracker.split(2)
+
+ assert_equal BigDecimal("50"), @tracker.average_cost
+ @tracker.apply(BigDecimal("1"), BigDecimal("-19"))
+ assert_equal BigDecimal("50"), @tracker.average_cost, "20 shares after the split, so 19 sold leaves one"
+ @tracker.apply(BigDecimal("1"), BigDecimal("-1"))
+ assert_nil @tracker.average_cost
+ end
+
+ test "a 1-for-10 reverse split cuts the shares and keeps the total cost" do
+ @tracker.apply(BigDecimal("5"), BigDecimal("100")) # 500 for 100
+
+ @tracker.split(Rational(1, 10))
+
+ assert_equal BigDecimal("50"), @tracker.average_cost
+ @tracker.apply(BigDecimal("1"), BigDecimal("-9"))
+ assert_equal BigDecimal("50"), @tracker.average_cost, "10 shares after the split, so 9 sold leaves one"
+ @tracker.apply(BigDecimal("1"), BigDecimal("-1"))
+ assert_nil @tracker.average_cost
+ end
+
+ # Multiplying a BigDecimal by Rational(1, 3) rounds at 32 digits: three
+ # shares became 0.999..., and the average 30.000...03. (A sale would not
+ # show it: the over-sell guard clears the position either way.)
+ test "a 1-for-3 reverse split of three shares leaves exactly one, at exactly three times the cost" do
+ @tracker.apply(BigDecimal("10"), BigDecimal("3"))
+
+ @tracker.split(Rational(1, 3))
+
+ assert_equal BigDecimal("30"), @tracker.average_cost
+ end
+
+ test "a split with nothing held leaves nothing held" do
+ @tracker.split(2)
+
+ assert_nil @tracker.average_cost
+ @tracker.apply(BigDecimal("30"), BigDecimal("1"))
+ assert_equal BigDecimal("30"), @tracker.average_cost
+ end
end
diff --git a/test/models/holding/forward_calculator_test.rb b/test/models/holding/forward_calculator_test.rb
index 36fa1b7d63..4f8c4ad688 100644
--- a/test/models/holding/forward_calculator_test.rb
+++ b/test/models/holding/forward_calculator_test.rb
@@ -271,7 +271,147 @@ class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
assert_holdings(expected, calculated)
end
+ # --- Stock splits (#249) ---------------------------------------------------
+
+ test "a 2-for-1 split doubles the shares from the ex-date and halves the cost per share" do
+ security = split_security(before: 100, after: 50)
+ create_trade(security, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+
+ day_before = holding_on(security, 3.days.ago.to_date)
+ ex_day = holding_on(security, 2.days.ago.to_date)
+
+ assert_equal [ 10, 20 ], [ day_before.qty, ex_day.qty ]
+ assert_equal [ 100, 50 ], [ day_before.cost_basis, ex_day.cost_basis ]
+ assert_equal day_before.qty * day_before.cost_basis, ex_day.qty * ex_day.cost_basis, "total cost is unchanged by a split"
+ assert_equal 20, holding_on(security, Date.current).qty
+ end
+
+ test "a trade on the ex-date is in post-split shares, applied after the split" do
+ security = split_security(before: 100, after: 50)
+ create_trade(security, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ create_trade(security, qty: 5, date: 2.days.ago.to_date, price: 50, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+
+ ex_day = holding_on(security, 2.days.ago.to_date)
+
+ # 10 become 20 at the open, then 5 are bought: 25 shares that cost 1,250.
+ assert_equal 25, ex_day.qty
+ assert_equal 50, ex_day.cost_basis
+ end
+
+ test "a 1-for-10 reverse split cuts the shares from the ex-date and keeps the total cost" do
+ security = split_security(before: 5, after: 50)
+ create_trade(security, qty: 100, date: 4.days.ago.to_date, price: 5, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 1, denominator: 10)
+
+ day_before = holding_on(security, 3.days.ago.to_date)
+ ex_day = holding_on(security, 2.days.ago.to_date)
+
+ assert_equal [ 100, 10 ], [ day_before.qty, ex_day.qty ]
+ assert_equal [ 5, 50 ], [ day_before.cost_basis, ex_day.cost_basis ]
+ end
+
+ test "a 1-for-3 reverse split of three shares leaves exactly one" do
+ security = split_security(before: 10, after: 30)
+ create_trade(security, qty: 3, date: 4.days.ago.to_date, price: 10, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 1, denominator: 3)
+
+ assert_equal BigDecimal("1"), holding_on(security, 2.days.ago.to_date).qty
+ end
+
+ # Splits belong to the security, and every family's accounts read them
+ # (Production Readiness Review on #253): each account holding it applies the
+ # split once, to its own shares.
+ test "a split on a security held in two accounts applies once in each" do
+ security = split_security(before: 100, after: 50)
+ other = families(:dylan_family).accounts.create!(name: "Other", balance: 0, cash_balance: 0, currency: "USD", accountable: Investment.new)
+ create_trade(security, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ create_trade(security, qty: 3, date: 4.days.ago.to_date, price: 100, account: other)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+
+ other_on = ->(date) { Holding::ForwardCalculator.new(other).calculate.find { |h| h.security_id == security.id && h.date == date } }
+
+ assert_equal [ 10, 20 ], [ holding_on(security, 3.days.ago.to_date).qty, holding_on(security, 2.days.ago.to_date).qty ]
+ assert_equal [ 3, 6 ], [ other_on.call(3.days.ago.to_date).qty, other_on.call(2.days.ago.to_date).qty ]
+ assert_equal [ 100, 50 ], [ other_on.call(3.days.ago.to_date).cost_basis, other_on.call(2.days.ago.to_date).cost_basis ]
+ end
+
+ test "a split on one security leaves every other security's holdings as they were" do
+ load_prices
+ create_trade(@voo, qty: 10, date: 3.days.ago.to_date, price: 470, account: @account)
+ create_trade(@wmt, qty: 100, date: 3.days.ago.to_date, price: 100, account: @account)
+ voo_rows = ->(holdings) { holdings.select { |h| h.security_id == @voo.id }.map { |h| [ h.date, h.qty, h.amount, h.cost_basis ] } }
+
+ before = voo_rows.call(Holding::ForwardCalculator.new(@account).calculate)
+ add_split(@wmt, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+ after = Holding::ForwardCalculator.new(@account).calculate
+
+ assert_equal before, voo_rows.call(after)
+ assert_equal 200, after.find { |h| h.security_id == @wmt.id && h.date == Date.current }.qty, "the split security itself did change"
+ end
+
+ # A day with no price emits no holding, so gapfill copies the last one it has
+ # forward. Before this the copy was made in pre-split terms: the split had
+ # already scaled the portfolio, but the day it went ex had no price, so what
+ # was carried into today was the old share count and the old cost per share —
+ # and for a security whose prices have stopped, that is what the user sees
+ # from then on.
+ test "a split still lands when the ex-date and every day after it has no price" do
+ security = Security.create!(ticker: "GAPS", name: "Gapfill Split")
+ Security::Price.create!(security: security, date: 5.days.ago.to_date, price: 100)
+ create_trade(security, qty: 10, date: 5.days.ago.to_date, price: 100, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+
+ today = holding_on(security, Date.current)
+
+ assert_equal 20, today.qty, "the split doubled the position even though no price was published"
+ assert_equal 50, today.price, "a split moves no money, so the carried price halves with the count"
+ assert_equal 50, today.cost_basis
+ assert_equal 1000, today.amount, "the position is worth what it was worth before the split"
+ end
+
+ # Security::Split.scale used to keep more precision than the qty column can
+ # hold, so a position sold down to the last share the column can express kept
+ # about 3e-31 of a share. The forward calculator decides a liquidation by an
+ # exact zero, so the transfer's "cost unknown" mark never cleared and the
+ # repurchase inherited it.
+ test "selling every representable share of a split position clears the unknown basis" do
+ security = Security.create!(ticker: "FRAC", name: "Fractional")
+ (6.days.ago.to_date..Date.current).each do |date|
+ Security::Price.create!(security: security, date: date, price: 150)
+ end
+
+ transfer_in = create_trade(security, qty: 10, date: 6.days.ago.to_date, price: 10, account: @account)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # moved in, unknown cost
+ add_split(security, ex_date: 4.days.ago.to_date, numerator: 1, denominator: 3)
+ create_trade(security, qty: -BigDecimal("3.333333333333333333"), date: 2.days.ago.to_date, price: 150, account: @account)
+ create_trade(security, qty: 1, date: 1.day.ago.to_date, price: 150, account: @account)
+
+ today = holding_on(security, Date.current)
+
+ assert_equal BigDecimal("1"), today.qty, "the sell cleared the position exactly"
+ assert_equal 150, today.cost_basis, "the repurchase starts from a clean basis"
+ assert_not today.cost_basis_unknown, "the transfer's mark is released once the position is closed"
+ end
+
private
+ def split_security(before:, after:)
+ security = Security.create!(ticker: "SPLT", name: "Split Test")
+ (4.days.ago.to_date..Date.current).each do |date|
+ Security::Price.create!(security: security, date: date, price: date < 2.days.ago.to_date ? before : after)
+ end
+ security
+ end
+
+ def add_split(security, ex_date:, numerator:, denominator:)
+ Security::Split.create!(security: security, ex_date: ex_date, numerator: numerator, denominator: denominator, source: "manual")
+ end
+
+ def holding_on(security, date)
+ Holding::ForwardCalculator.new(@account).calculate.find { |h| h.security_id == security.id && h.date == date }
+ end
+
def assert_holdings(expected, calculated)
expected.each do |expected_entry|
calculated_entry = calculated.find { |c| c.security_id == expected_entry.security_id && c.date == expected_entry.date }
diff --git a/test/models/holding/materializer_test.rb b/test/models/holding/materializer_test.rb
index 890d0ba562..a59a77bbbb 100644
--- a/test/models/holding/materializer_test.rb
+++ b/test/models/holding/materializer_test.rb
@@ -10,6 +10,45 @@ class Holding::MaterializerTest < ActiveSupport::TestCase
@msft = securities(:msft)
end
+ # The figure carried past a provider's last snapshot is per share, and a
+ # split changes how many shares the same money bought. Carried across a
+ # 2-for-1 unchanged, every row after the split recorded twice the cost the
+ # position actually has — and every gain and return computed from it.
+ test "a cost basis carried past a split is restated per post-split share" do
+ security = Security.create!(ticker: "CBSP", name: "Carried Basis Split")
+ (4.days.ago.to_date..Date.current).each do |date|
+ Security::Price.create!(security: security, date: date, price: date < 1.day.ago.to_date ? 200 : 100)
+ end
+
+ # An entry so materialisation reaches back past the snapshot's own day;
+ # account history starts the day before the first entry.
+ @account.entries.create!(
+ name: "Opening", date: 4.days.ago.to_date, amount: 20000, currency: "USD",
+ entryable: Valuation.new(kind: "opening_anchor")
+ )
+
+ 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)
+
+ # The provider's last snapshot, before the split: 10 shares at $100 each.
+ @account.holdings.create!(
+ security: security, date: 3.days.ago.to_date, qty: 10, price: 200, amount: 2000,
+ currency: "USD", cost_basis: 100, cost_basis_source: "provider", account_provider: account_provider
+ )
+ Security::Split.create!(security: security, ex_date: 1.day.ago.to_date, numerator: 2, denominator: 1, source: "manual")
+
+ Holding::Materializer.new(@account, strategy: :reverse).materialize_holdings
+
+ after_split = @account.holdings.find_by!(security: security, date: Date.current)
+ before_split = @account.holdings.find_by!(security: security, date: 2.days.ago.to_date)
+
+ assert_equal 100, before_split.cost_basis.to_d, "the snapshot's own terms are untouched before the split"
+ assert_equal 50, after_split.cost_basis.to_d, "the same money over twice the shares"
+ assert_equal before_split.qty * before_split.cost_basis, after_split.qty * after_split.cost_basis,
+ "a split moves no money, so total recorded cost is unchanged"
+ end
+
test "syncs holdings" do
create_trade(@aapl, account: @account, qty: 1, price: 200, date: Date.current)
diff --git a/test/models/holding/reverse_calculator_test.rb b/test/models/holding/reverse_calculator_test.rb
index 223541aad2..76bcdc8296 100644
--- a/test/models/holding/reverse_calculator_test.rb
+++ b/test/models/holding/reverse_calculator_test.rb
@@ -361,7 +361,257 @@ class Holding::ReverseCalculatorTest < ActiveSupport::TestCase
assert_nil cost_basis_for(calc, security, Date.current)
end
+ # --- Stock splits (#249) ---------------------------------------------------
+
+ test "walking back past a 2-for-1 split halves the provider's share count" do
+ security = split_security(before: 100, after: 50)
+ create_trade(security, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+
+ holdings = reverse_holdings(security, today_qty: 20)
+
+ assert_equal 20, holdings[Date.current].qty
+ assert_equal 20, holdings[2.days.ago.to_date].qty
+ assert_equal 10, holdings[3.days.ago.to_date].qty
+ assert_equal 0, holdings[5.days.ago.to_date].qty, "the buy is undone in pre-split shares"
+ end
+
+ test "the cost per share halves at the split and the total cost does not move" do
+ security = split_security(before: 100, after: 50)
+ create_trade(security, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+
+ holdings = reverse_holdings(security, today_qty: 20)
+ day_before = holdings[3.days.ago.to_date]
+ ex_day = holdings[2.days.ago.to_date]
+
+ assert_equal [ 100, 50 ], [ day_before.cost_basis, ex_day.cost_basis ]
+ assert_equal day_before.qty * day_before.cost_basis, ex_day.qty * ex_day.cost_basis
+ end
+
+ test "walking back past a 1-for-10 reverse split multiplies the share count" do
+ security = split_security(before: 5, after: 50)
+ create_trade(security, qty: 100, date: 4.days.ago.to_date, price: 5, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 1, denominator: 10)
+
+ holdings = reverse_holdings(security, today_qty: 10)
+
+ assert_equal [ 100, 10 ], [ holdings[3.days.ago.to_date].qty, holdings[2.days.ago.to_date].qty ]
+ assert_equal [ 5, 50 ], [ holdings[3.days.ago.to_date].cost_basis, holdings[2.days.ago.to_date].cost_basis ]
+ end
+
+ # The walk starts at today and undoes its way back, so it reads whatever the
+ # snapshot holds as today's position. A provider snapshot is regularly older
+ # than that — a sync that failed and retried, or a provider that had not
+ # refreshed — and a split in between has already changed the count it
+ # reported. Read as current, the pre-split count became today's holding and
+ # the walk then undid the same split again on the way past.
+ test "a provider snapshot older than the split is brought forward before the walk" do
+ security = Security.create!(ticker: "STAL", name: "Stale Snapshot")
+ Security::Price.create!(security: security, date: 2.days.ago.to_date, price: 100)
+ Security::Price.create!(security: security, date: 1.day.ago.to_date, price: 50)
+ Security::Price.create!(security: security, date: Date.current, price: 50)
+
+ # An entry so the walk reaches back past the snapshot's own day; account
+ # history starts the day before the first entry.
+ @account.entries.create!(
+ name: "Opening", date: 4.days.ago.to_date, amount: 20000, currency: "USD",
+ entryable: Valuation.new(kind: "opening_anchor")
+ )
+
+ coinstats_item = @account.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)
+ @account.holdings.create!(
+ security: security, date: 2.days.ago.to_date, qty: 10, price: 100, amount: 1000,
+ currency: "USD", account_provider: account_provider
+ )
+
+ add_split(security, ex_date: 1.day.ago.to_date, numerator: 2, denominator: 1)
+
+ holdings = Holding::ReverseCalculator
+ .new(@account, portfolio_snapshot: Holding::PortfolioSnapshot.new(@account))
+ .calculate
+ .select { |h| h.security_id == security.id }
+ .index_by(&:date)
+
+ assert_equal 20, holdings[Date.current].qty, "the split the provider has already applied"
+ assert_equal 1000, holdings[Date.current].amount, "20 shares at the post-split price"
+ assert_equal 10, holdings[2.days.ago.to_date].qty, "the day the provider actually reported"
+ end
+
+ # An account with no entries starts yesterday, so its own history has no
+ # splits before then. A provider snapshot from ten days ago, before a split
+ # five days ago, still has to be brought through that split: the provider's
+ # 10 shares are 20 today.
+ test "a provider snapshot older than the account's history is still brought through a split" do
+ security = Security.create!(ticker: "PRE", name: "Pre-start Split")
+ Security::Price.create!(security: security, date: 1.day.ago.to_date, price: 50)
+ Security::Price.create!(security: security, date: Date.current, price: 50)
+
+ coinstats_item = @account.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)
+ @account.holdings.create!(
+ security: security, date: 10.days.ago.to_date, qty: 10, price: 100, amount: 1000,
+ currency: "USD", account_provider: account_provider
+ )
+ add_split(security, ex_date: 5.days.ago.to_date, numerator: 2, denominator: 1)
+ assert_equal 1.day.ago.to_date, @account.start_date, "the split is before the account's history"
+
+ holdings = Holding::ReverseCalculator
+ .new(@account, portfolio_snapshot: Holding::PortfolioSnapshot.new(@account))
+ .calculate
+ .select { |h| h.security_id == security.id }
+ .index_by(&:date)
+
+ assert_equal 20, holdings[Date.current].qty
+ end
+
+ test "walking back past a 1-for-3 reverse split of one share gives exactly three" do
+ security = split_security(before: 10, after: 30)
+ create_trade(security, qty: 3, date: 4.days.ago.to_date, price: 10, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 1, denominator: 3)
+
+ holdings = reverse_holdings(security, today_qty: 1)
+
+ assert_equal BigDecimal("3"), holdings[3.days.ago.to_date].qty
+ # The cost-basis replay walks the same split both ways; 30.000...03 here
+ # means it rounded.
+ assert_equal BigDecimal("30"), holdings[2.days.ago.to_date].cost_basis
+ end
+
+ # The replay that tracks cost basis starts from the position before the first
+ # trade, worked out from today's snapshot. Across a split that has to undo the
+ # split too: 10 shares today, back through a rebuy of 10, a sale of 30, a
+ # 2-for-1 split, a transfer in of 5 and a buy of 10, is 0 -- not the 15 that
+ # "snapshot minus net trades" gives. From 15, the sale leaves 30 and the
+ # transferred-in units are never cleared.
+ test "a transferred-in position sold down after a split becomes known again on the rebuy" do
+ security = Security.create!(ticker: "TST", name: "Test")
+ buy_date = 12.days.ago.to_date
+ transfer_date = 9.days.ago.to_date
+ ex_date = 7.days.ago.to_date
+ close_date = 5.days.ago.to_date
+ rebuy_date = 3.days.ago.to_date
+
+ calc = calculator_with_trades(security) do
+ create_trade(security, account: @account, qty: 10, price: 100, date: buy_date)
+ transfer_in = create_trade(security, account: @account, qty: 5, price: 120, date: transfer_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ add_split(security, ex_date: ex_date, numerator: 2, denominator: 1)
+ create_trade(security, account: @account, qty: -30, price: 65, date: close_date) # all 30 post-split shares
+ create_trade(security, account: @account, qty: 10, price: 150, date: rebuy_date)
+ end
+
+ assert_nil cost_basis_for(calc, security, close_date - 1)
+ assert_in_delta 150.0, cost_basis_for(calc, security, rebuy_date).to_f, 1e-6
+ end
+
+ # The replay decides a transferred-in position is sold out when it reaches
+ # zero, so a split that leaves 1e-32 behind keeps the span unknown for ever.
+ # 1-for-3 is undone to 3.000...03 by a Rational division (the seed walk), and
+ # 2-for-3 applied to 2.000...01 by a Rational multiply (the replay).
+ test "a transferred-in position sold to exactly zero after an uneven split becomes known again on the rebuy" do
+ { [ 1, 3 ] => 1, [ 2, 3 ] => 2 }.each do |(numerator, denominator), sold|
+ security = Security.create!(ticker: "TS#{numerator}", name: "Test #{numerator}-for-#{denominator}")
+ close_date = 5.days.ago.to_date
+ rebuy_date = 3.days.ago.to_date
+
+ calc = calculator_with_trades(security) do
+ transfer_in = create_trade(security, account: @account, qty: 3, price: 120, date: 9.days.ago.to_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ add_split(security, ex_date: 7.days.ago.to_date, numerator: numerator, denominator: denominator)
+ create_trade(security, account: @account, qty: -sold, price: 65, date: close_date)
+ create_trade(security, account: @account, qty: 10, price: 150, date: rebuy_date)
+ end
+
+ assert_in_delta 150.0, cost_basis_for(calc, security, rebuy_date).to_f, 1e-6, "#{numerator}-for-#{denominator}"
+ end
+ end
+
+ # The seed walk starts from the same position as the holdings walk: the
+ # snapshot brought forward to today. Here the provider reported 10 shares the
+ # day before a 2-for-1 split, so today is 20. Read as today's count, 10 was
+ # halved back through the split to 5 and the seed came out at -5. The sale of
+ # the transferred-in units then went from 0 to -5, never crossed zero, and the
+ # rebuy stayed unknown for good.
+ test "a provider snapshot older than the split seeds the cost-basis replay from today's count" do
+ security = Security.create!(ticker: "STSD", name: "Stale Seed")
+ transfer_date = 9.days.ago.to_date
+ close_date = 8.days.ago.to_date
+ rebuy_date = 7.days.ago.to_date
+
+ transfer_in = create_trade(security, account: @account, qty: 5, price: 120, date: transfer_date)
+ transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ create_trade(security, account: @account, qty: -5, price: 130, date: close_date)
+ create_trade(security, account: @account, qty: 10, price: 150, date: rebuy_date)
+ add_split(security, ex_date: 4.days.ago.to_date, numerator: 2, denominator: 1)
+
+ snapshot = OpenStruct.new(to_h: { security.id => 10 }, effective_dates: { security.id => 6.days.ago.to_date })
+ calc = Holding::ReverseCalculator.new(@account, portfolio_snapshot: snapshot)
+ calc.send(:precompute_cost_basis)
+
+ assert_nil cost_basis_for(calc, security, transfer_date)
+ assert_in_delta 150.0, cost_basis_for(calc, security, rebuy_date).to_f, 1e-6
+ assert_in_delta 75.0, cost_basis_for(calc, security, Date.current).to_f, 1e-6
+ end
+
+ # The provider reports nothing held today: the whole post-split position was
+ # sold on the ex-date (Production Readiness Review on #253). Walking back, the
+ # sale is undone first, in post-split shares, and then the split.
+ test "a split and a sale of everything on the ex-date walk back to the pre-split position" do
+ security = split_security(before: 100, after: 50)
+ create_trade(security, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ add_split(security, ex_date: 2.days.ago.to_date, numerator: 2, denominator: 1)
+ create_trade(security, qty: -20, date: 2.days.ago.to_date, price: 50, account: @account)
+
+ holdings = reverse_holdings(security, today_qty: 0)
+
+ assert_equal 0, holdings[2.days.ago.to_date].qty
+ assert_equal 10, holdings[3.days.ago.to_date].qty, "20 sold, then halved back to 10"
+ assert_equal 0, holdings[5.days.ago.to_date].qty
+ end
+
+ test "a split on one security leaves every other security's history as it was" do
+ load_today_portfolio
+ create_trade(@voo, qty: 5, date: 3.days.ago.to_date, price: 470, account: @account)
+ create_trade(@wmt, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
+ wmt_split_date = 2.days.ago.to_date
+ voo_rows = ->(holdings) { holdings.select { |h| h.security_id == @voo.id }.map { |h| [ h.date, h.qty, h.amount, h.cost_basis ] }.sort }
+ snapshot = OpenStruct.new(to_h: { @voo.id => 10, @wmt.id => 100 })
+
+ before = voo_rows.call(Holding::ReverseCalculator.new(@account, portfolio_snapshot: snapshot).calculate)
+ add_split(@wmt, ex_date: wmt_split_date, numerator: 2, denominator: 1)
+ after = Holding::ReverseCalculator.new(@account, portfolio_snapshot: snapshot).calculate
+
+ assert_equal before, voo_rows.call(after)
+ assert_equal 50, after.find { |h| h.security_id == @wmt.id && h.date == wmt_split_date - 1 }.qty, "the split security itself did change"
+ end
+
private
+ def split_security(before:, after:)
+ security = Security.create!(ticker: "SPLT", name: "Split Test")
+ (5.days.ago.to_date..Date.current).each do |date|
+ Security::Price.create!(security: security, date: date, price: date < 2.days.ago.to_date ? before : after)
+ end
+ security
+ end
+
+ def add_split(security, ex_date:, numerator:, denominator:)
+ Security::Split.create!(security: security, ex_date: ex_date, numerator: numerator, denominator: denominator, source: "manual")
+ end
+
+ # Today's row comes from the provider, as it does in a real reverse sync.
+ def reverse_holdings(security, today_qty:)
+ price = Security::Price.find_by!(security: security, date: Date.current).price
+ @account.holdings.create!(security: security, date: Date.current, qty: today_qty, price: price, amount: today_qty * price, currency: "USD")
+ snapshot = OpenStruct.new(to_h: { security.id => today_qty })
+ Holding::ReverseCalculator.new(@account, portfolio_snapshot: snapshot).calculate
+ .select { |h| h.security_id == security.id }
+ .index_by(&:date)
+ end
+
def assert_holdings(expected, calculated)
expected.each do |expected_entry|
calculated_entry = calculated.find { |c| c.security_id == expected_entry.security_id && c.date == expected_entry.date }
diff --git a/test/models/security/split_test.rb b/test/models/security/split_test.rb
new file mode 100644
index 0000000000..044cb97bb5
--- /dev/null
+++ b/test/models/security/split_test.rb
@@ -0,0 +1,55 @@
+require "test_helper"
+
+class Security::SplitTest < ActiveSupport::TestCase
+ setup do
+ @security = Security.create!(ticker: "SPLT", name: "Split Test")
+ @ex_date = Date.new(2025, 6, 10)
+ end
+
+ test "a split needs positive terms that are not one-for-one" do
+ [ [ 0, 1 ], [ 2, 0 ], [ -2, 1 ], [ 3, 3 ] ].each do |numerator, denominator|
+ split = @security.splits.new(ex_date: @ex_date, numerator: numerator, denominator: denominator, source: "manual")
+
+ assert_not split.valid?, "#{numerator}:#{denominator} should be refused"
+ end
+
+ assert @security.splits.new(ex_date: @ex_date, numerator: 1, denominator: 10, source: "manual").valid?
+ end
+
+ test "one split per security per ex-date" do
+ @security.splits.create!(ex_date: @ex_date, numerator: 2, denominator: 1, source: "manual")
+
+ assert_not @security.splits.new(ex_date: @ex_date, numerator: 3, denominator: 1, source: "manual").valid?
+ assert Security.create!(ticker: "OTHR", name: "Other").splits.new(ex_date: @ex_date, numerator: 3, denominator: 1, source: "manual").valid?
+ end
+
+ test "the database refuses a zero term that bypasses the model" do
+ split = @security.splits.create!(ex_date: @ex_date, numerator: 2, denominator: 1, source: "manual")
+
+ assert_raises(ActiveRecord::StatementInvalid) { split.update_columns(denominator: 0) }
+ end
+
+ test "the ratio is exact" do
+ split = @security.splits.new(ex_date: @ex_date, numerator: 1, denominator: 3, source: "manual")
+
+ assert_equal Rational(1, 3), split.ratio
+ end
+
+ test "deleting the security deletes its splits" do
+ @security.splits.create!(ex_date: @ex_date, numerator: 2, denominator: 1, source: "manual")
+
+ assert_difference "Security::Split.count", -1 do
+ @security.destroy
+ end
+ end
+
+ test "the split factor between two dates takes the splits after the first and on or before the second" do
+ @security.splits.create!(ex_date: @ex_date, numerator: 2, denominator: 1, source: "manual")
+ @security.splits.create!(ex_date: @ex_date + 30, numerator: 3, denominator: 1, source: "manual")
+
+ assert_equal 1, @security.split_factor_between(@ex_date - 10, @ex_date - 1)
+ assert_equal 2, @security.split_factor_between(@ex_date - 1, @ex_date)
+ assert_equal 1, @security.split_factor_between(@ex_date, @ex_date + 29)
+ assert_equal 6, @security.split_factor_between(@ex_date - 1, @ex_date + 30)
+ end
+end