Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
26.5 KB
Raw Blame
require "test_helper"

class Holding::ForwardCalculatorTest < ActiveSupport::TestCase
  include EntriesTestHelper

  setup do
    @account = families(:empty).accounts.create!(
      name: "Test",
      balance: 20000,
      cash_balance: 20000,
      currency: "USD",
      accountable: Investment.new
    )
  end

  test "no holdings" do
    calculated = Holding::ForwardCalculator.new(@account).calculate
    assert_equal [], calculated
  end

  test "holding generation respects user timezone and last generated date is current user date" do
    # Simulate user in EST timezone
    Time.use_zone("America/New_York") do
      # Set current time to 1am UTC on Jan 5, 2025
      # This would be 8pm EST on Jan 4, 2025 (user's time, and the last date we should generate holdings for)
      travel_to Time.utc(2025, 01, 05, 1, 0, 0)

      voo = Security.create!(ticker: "VOO", name: "Vanguard S&P 500 ETF")
      Security::Price.create!(security: voo, date: "2025-01-02", price: 500)
      Security::Price.create!(security: voo, date: "2025-01-03", price: 500)
      Security::Price.create!(security: voo, date: "2025-01-04", price: 500)
      create_trade(voo, qty: 10, date: "2025-01-03", price: 500, account: @account)

      expected = [ [ "2025-01-02", 0 ], [ "2025-01-03", 5000 ], [ "2025-01-04", 5000 ] ]
      calculated = Holding::ForwardCalculator.new(@account).calculate

      assert_equal expected, calculated.map { |b| [ b.date.to_s, b.amount ] }
    end
  end

  test "forward portfolio calculation" do
    load_prices

    # Build up to 10 shares of VOO (current value $5000)
    create_trade(@voo, qty: 20, date: 3.days.ago.to_date, price: 470, account: @account)
    create_trade(@voo, qty: -15, date: 2.days.ago.to_date, price: 480, account: @account)
    create_trade(@voo, qty: 5, date: 1.day.ago.to_date, price: 490, account: @account)

    # Amazon won't exist in current holdings because qty is zero, but should show up in historical portfolio
    create_trade(@amzn, qty: 1, date: 2.days.ago.to_date, price: 200, account: @account)
    create_trade(@amzn, qty: -1, date: 1.day.ago.to_date, price: 200, account: @account)

    # Build up to 100 shares of WMT (current value $10000)
    create_trade(@wmt, qty: 100, date: 1.day.ago.to_date, price: 100, account: @account)

    expected = [
      # 4 days ago
      Holding.new(security: @voo, date: 4.days.ago.to_date, qty: 0, price: 460, amount: 0),
      Holding.new(security: @wmt, date: 4.days.ago.to_date, qty: 0, price: 100, amount: 0),
      Holding.new(security: @amzn, date: 4.days.ago.to_date, qty: 0, price: 200, amount: 0),

      # 3 days ago
      Holding.new(security: @voo, date: 3.days.ago.to_date, qty: 20, price: 470, amount: 9400),
      Holding.new(security: @wmt, date: 3.days.ago.to_date, qty: 0, price: 100, amount: 0),
      Holding.new(security: @amzn, date: 3.days.ago.to_date, qty: 0, price: 200, amount: 0),

      # 2 days ago
      Holding.new(security: @voo, date: 2.days.ago.to_date, qty: 5, price: 480, amount: 2400),
      Holding.new(security: @wmt, date: 2.days.ago.to_date, qty: 0, price: 100, amount: 0),
      Holding.new(security: @amzn, date: 2.days.ago.to_date, qty: 1, price: 200, amount: 200),

      # 1 day ago
      Holding.new(security: @voo, date: 1.day.ago.to_date, qty: 10, price: 490, amount: 4900),
      Holding.new(security: @wmt, date: 1.day.ago.to_date, qty: 100, price: 100, amount: 10000),
      Holding.new(security: @amzn, date: 1.day.ago.to_date, qty: 0, price: 200, amount: 0),

      # Today
      Holding.new(security: @voo, date: Date.current, qty: 10, price: 500, amount: 5000),
      Holding.new(security: @wmt, date: Date.current, qty: 100, price: 100, amount: 10000),
      Holding.new(security: @amzn, date: Date.current, qty: 0, price: 200, amount: 0)
    ]

    calculated = Holding::ForwardCalculator.new(@account).calculate

    assert_equal expected.length, calculated.length
    assert_holdings(expected, calculated)
  end

  # Carries the previous record forward if no holding exists for a date
  # to ensure that net worth historical rollups have a value for every date
  test "uses locf to fill missing holdings" do
    load_prices

    create_trade(@wmt, qty: 100, date: 1.day.ago.to_date, price: 100, account: @account)

    expected = [
      Holding.new(security: @wmt, date: 2.days.ago.to_date, qty: 0, price: 100, amount: 0),
      Holding.new(security: @wmt, date: 1.day.ago.to_date, qty: 100, price: 100, amount: 10000),
      Holding.new(security: @wmt, date: Date.current, qty: 100, price: 100, amount: 10000)
    ]

    # Price missing today, so we should carry forward the holding from 1 day ago
    Security.stubs(:find).returns(@wmt)
    Security::Price.stubs(:find_price).with(security: @wmt, date: 2.days.ago.to_date).returns(Security::Price.new(price: 100))
    Security::Price.stubs(:find_price).with(security: @wmt, date: 1.day.ago.to_date).returns(Security::Price.new(price: 100))
    Security::Price.stubs(:find_price).with(security: @wmt, date: Date.current).returns(nil)

    calculated = Holding::ForwardCalculator.new(@account).calculate

    assert_equal expected.length, calculated.length
    assert_holdings(expected, calculated)
  end

  # Cost basis is a per-share weighted average that only changes on buy trades,
  # so it must carry forward (LOCF) onto gap-filled non-trade dates rather than
  # resetting to nil/zero.
  test "carries cost basis forward onto gap-filled dates" do
    load_prices

    create_trade(@wmt, qty: 100, date: 3.days.ago.to_date, price: 100, account: @account)

    calculated = Holding::ForwardCalculator.new(@account).calculate

    wmt_holdings = calculated.select { |h| h.security_id == @wmt.id && h.qty.positive? }

    assert wmt_holdings.any?, "expected WMT holdings to be generated"
    wmt_holdings.each do |holding|
      assert_equal 100, holding.cost_basis, "Cost basis should carry forward on #{holding.date}"
    end
  end

  # Regression: selling a position to zero must relieve the cost-basis tracker so
  # that a later repurchase is not averaged against the already-sold lots.
  test "cost basis resets after a position is fully sold and repurchased" do
    load_prices

    create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
    create_trade(@voo, qty: -10, date: 3.days.ago.to_date, price: 480, account: @account) # fully sold
    create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 490, account: @account)    # repurchased

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    # Only the repurchased lot is held, so cost basis is $490 — not the
    # buggy (460 + 490) / 2 = $475 averaged over the sold-off shares.
    assert_equal BigDecimal("490"), current.cost_basis
  end

  # An outbound transfer removes units without a cost; it must relieve the tracker
  # (not stay in the average) while leaving the basis known, unlike an inbound one.
  test "an outbound transfer relieves the tracker instead of contaminating a later buy" do
    load_prices

    create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
    transfer_out = create_trade(@voo, qty: -10, date: 3.days.ago.to_date, price: 470, account: @account)
    transfer_out.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # transferred out, not sold
    create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 490, account: @account)

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    # Repurchased lot stands alone at $490, not (460 + 490) / 2 = $475.
    assert_equal BigDecimal("490"), current.cost_basis
    assert_not current.cost_basis_unknown, "an outbound-only transfer should not mark the basis unknown"
  end

  # An inbound transfer marks the basis unknown while those units are held, but once
  # the position is fully closed and repurchased the new lot must read as known again.
  test "an inbound transfer stops shadowing the basis once the position is closed and repurchased" do
    load_prices

    create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
    transfer_in = create_trade(@voo, qty: 5, date: 3.days.ago.to_date, price: 470, account: @account)
    transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL) # moved in, unknown cost
    create_trade(@voo, qty: -15, date: 2.days.ago.to_date, price: 480, account: @account) # fully closed
    create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 490, account: @account)     # repurchased

    calculated = Holding::ForwardCalculator.new(@account).calculate

    # While the transferred-in units are held, the basis is unknown.
    while_held = calculated.find { |h| h.security_id == @voo.id && h.date == 3.days.ago.to_date }
    assert while_held.cost_basis_unknown
    assert_nil while_held.cost_basis

    # After the position is fully closed and bought again, the new lot is known.
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }
    assert_not current.cost_basis_unknown
    assert_equal BigDecimal("490"), current.cost_basis
  end

  # A same-day sell-to-zero and repurchase nets back to a positive end-of-day
  # quantity, so the release has to run per trade, not just on the day's net.
  test "an inbound transfer is released even when the position crosses zero within a day" do
    load_prices

    create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 460, account: @account)
    # All on the same day: transfer in, sell the whole position to zero, buy back.
    transfer_in = create_trade(@voo, qty: 5, date: 2.days.ago.to_date, price: 480, account: @account)
    transfer_in.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
    create_trade(@voo, qty: -15, date: 2.days.ago.to_date, price: 480, account: @account)
    create_trade(@voo, qty: 10, date: 2.days.ago.to_date, price: 480, account: @account)

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    # The intra-day liquidation released the mark, so the repurchase is known.
    assert_not current.cost_basis_unknown
    assert_equal BigDecimal("480"), current.cost_basis
  end

  # A batch import stamps every row with one created_at, so only the ids, which
  # mean nothing, would order a day's trades: a sale could replay before the
  # purchase it sells from. With nothing else to go on, the purchase goes first.
  test "a same-day sale and purchase stamped together replay the purchase first" do
    load_prices

    create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
    sale = create_trade(@voo, qty: -10, date: 2.days.ago.to_date, price: 480, account: @account)
    purchase = create_trade(@voo, qty: 10, date: 2.days.ago.to_date, price: 200, account: @account)
    stamp_together(sale, purchase)

    current = Holding::ForwardCalculator.new(@account).calculate
      .find { |h| h.security_id == @voo.id && h.date == Date.current }

    # 10 at 100 and 10 at 200 average to 150; selling 10 leaves 10 at 150. Had
    # the sale replayed first it would have sold the 100s and left 10 at 200.
    assert_equal BigDecimal("150"), current.cost_basis
  end

  test "a same-day sale entered before a purchase replays first when their created_at differ" do
    load_prices

    create_trade(@voo, qty: 10, date: 4.days.ago.to_date, price: 100, account: @account)
    sale = create_trade(@voo, qty: -10, date: 2.days.ago.to_date, price: 480, account: @account)
    purchase = create_trade(@voo, qty: 10, date: 2.days.ago.to_date, price: 200, account: @account)
    Entry.where(id: sale.id).update_all(created_at: 2.hours.ago)
    Entry.where(id: purchase.id).update_all(created_at: 1.hour.ago)

    current = Holding::ForwardCalculator.new(@account).calculate
      .find { |h| h.security_id == @voo.id && h.date == Date.current }

    # The order the user entered them in is theirs to set.
    assert_equal BigDecimal("200"), current.cost_basis
  end

  # An acquisition fee is part of what the units cost, so it belongs in the
  # basis. Providers already record it on the trade; nothing used to read it.
  test "an acquisition fee is part of the cost basis" do
    load_prices

    create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 460, fee: 20, account: @account)

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    # 10 * 460 + 20 = 4,620 for 10 units
    assert_equal BigDecimal("462"), current.cost_basis
  end

  # A basis is what was paid on the day. Converted at today's rate it would
  # drift with every move in the exchange rate since.
  test "a foreign-currency price and fee are converted at the trade's own rate" do
    load_prices
    trade_date = 1.day.ago.to_date
    ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: trade_date, rate: 2.0)
    ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.0)

    create_trade(@voo, qty: 10, date: trade_date, price: 100, fee: 10, currency: "EUR", account: @account)

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    # (10 * 100 + 10) EUR at 2.0 = 2,020 USD for 10 units, not 1,010 at today's rate
    assert_equal BigDecimal("202"), current.cost_basis
  end

  # No rate for the trade's day means its cost in the account's currency is
  # unknown. Counting it at 1:1 would report 1,010 for a purchase that cost
  # 2,020 at the real rate, and nothing would mark the figure as a guess.
  test "a foreign purchase with no rate for its day leaves the basis unknown" do
    load_prices
    ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)

    create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 100, fee: 10, currency: "EUR", account: @account)

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    assert_nil current.cost_basis
  end

  # A rate the trade carries itself (IBKR's fx_rate_to_base) is a rate for its
  # day, so the basis is known even when the rates table has a gap.
  test "a foreign purchase converts at the rate it carries when the table has none" do
    load_prices
    ExchangeRate.stubs(:find_or_fetch_rate).returns(nil)

    entry = create_trade(@voo, qty: 10, date: 1.day.ago.to_date, price: 100, fee: 10, currency: "EUR", account: @account)
    entry.entryable.update!(exchange_rate: 2.0)

    calculated = Holding::ForwardCalculator.new(@account).calculate
    current = calculated.find { |h| h.security_id == @voo.id && h.date == Date.current }

    # (10 * 100 + 10) EUR at the trade's own 2.0 = 2,020 USD for 10 units
    assert_equal BigDecimal("202"), current.cost_basis
  end

  # The tracker never reads a disposal's price, so this cannot be observed
  # through the basis; it is pinned on the helper directly.
  test "a disposal's price is returned without its fee" do
    load_prices

    sell = create_trade(@voo, qty: -5, date: 1.day.ago.to_date, price: 480, fee: 30, account: @account)

    price = Holding::ForwardCalculator.new(@account)
      .send(:effective_trade_price, sell.entryable, date: sell.date)

    assert_equal BigDecimal("480"), price
  end

  test "offline tickers sync holdings based on most recent trade price" do
    offline_security = Security.create!(ticker: "OFFLINE", name: "Offline Ticker")

    create_trade(offline_security, qty: 1, date: 3.days.ago.to_date, price: 90, account: @account)
    create_trade(offline_security, qty: 1, date: 1.day.ago.to_date, price: 100, account: @account)

    expected = [
      Holding.new(security: offline_security, date: 3.days.ago.to_date, qty: 1, price: 90, amount: 90),
      Holding.new(security: offline_security, date: 2.days.ago.to_date, qty: 1, price: 90, amount: 90),
      Holding.new(security: offline_security, date: 1.day.ago.to_date, qty: 2, price: 100, amount: 200),
      Holding.new(security: offline_security, date: Date.current, qty: 2, price: 100, amount: 200)
    ]

    calculated = Holding::ForwardCalculator.new(@account).calculate

    assert_equal expected.length, calculated.length
    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 }

        assert_equal expected_entry.qty, calculated_entry.qty, "Qty mismatch for security_id=#{expected_entry.security_id} on #{expected_entry.date}"
        assert_equal expected_entry.price, calculated_entry.price, "Price mismatch for security_id=#{expected_entry.security_id} on #{expected_entry.date}"
        assert_equal expected_entry.amount, calculated_entry.amount, "Amount mismatch for security_id=#{expected_entry.security_id} on #{expected_entry.date}"
      end
    end

    # Gives the two entries one created_at and ids that sort sale-first, as a
    # batch import with unlucky UUIDs would.
    def stamp_together(sale, purchase)
      Entry.where(id: [ sale.id, purchase.id ]).update_all(created_at: Time.zone.parse("2026-01-01 10:00:00"))
      Entry.where(id: sale.id).update_all(id: "00000000-0000-0000-0000-000000000001")
      Entry.where(id: purchase.id).update_all(id: "ffffffff-ffff-ffff-ffff-ffffffffffff")
    end

    def load_prices
      @voo = Security.create!(ticker: "VOO", name: "Vanguard S&P 500 ETF")
      Security::Price.create!(security: @voo, date: 4.days.ago.to_date, price: 460)
      Security::Price.create!(security: @voo, date: 3.days.ago.to_date, price: 470)
      Security::Price.create!(security: @voo, date: 2.days.ago.to_date, price: 480)
      Security::Price.create!(security: @voo, date: 1.day.ago.to_date, price: 490)
      Security::Price.create!(security: @voo, date: Date.current, price: 500)

      @wmt = Security.create!(ticker: "WMT", name: "Walmart Inc.")
      Security::Price.create!(security: @wmt, date: 4.days.ago.to_date, price: 100)
      Security::Price.create!(security: @wmt, date: 3.days.ago.to_date, price: 100)
      Security::Price.create!(security: @wmt, date: 2.days.ago.to_date, price: 100)
      Security::Price.create!(security: @wmt, date: 1.day.ago.to_date, price: 100)
      Security::Price.create!(security: @wmt, date: Date.current, price: 100)

      @amzn = Security.create!(ticker: "AMZN", name: "Amazon.com Inc.")
      Security::Price.create!(security: @amzn, date: 4.days.ago.to_date, price: 200)
      Security::Price.create!(security: @amzn, date: 3.days.ago.to_date, price: 200)
      Security::Price.create!(security: @amzn, date: 2.days.ago.to_date, price: 200)
      Security::Price.create!(security: @amzn, date: 1.day.ago.to_date, price: 200)
      Security::Price.create!(security: @amzn, date: Date.current, price: 200)
    end
end