The personal finance app for everyone (by everyone)
Ruby
require "test_helper"
class Balance::ChartSeriesBuilderTest < ActiveSupport::TestCase
include BalanceTestHelper, EntriesTestHelper
include EntriesTestHelper
setup do
end
test "balance series with fallbacks and gapfills" do
account = accounts(:depository)
account.balances.destroy_all
# With gaps
create_balance(account: account, date: 3.days.ago.to_date, balance: 1000)
create_balance(account: account, date: 1.day.ago.to_date, balance: 1100)
create_balance(account: account, date: Date.current, balance: 1200)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.last_30_days,
interval: "1 day"
)
assert_equal 31, builder.balance_series.size # Last 30 days == 31 total balances
assert_equal 0, builder.balance_series.first.value
expected = [
0, # No value, so fallback to 0
1000,
1000, # Last observation carried forward
1100,
1200
]
assert_equal expected, builder.balance_series.last(5).map { |v| v.value.amount }
end
test "exchange rates apply locf when missing" do
account = accounts(:depository)
account.balances.destroy_all
create_balance(account: account, date: 2.days.ago.to_date, balance: 1000)
create_balance(account: account, date: 1.day.ago.to_date, balance: 1100)
create_balance(account: account, date: Date.current, balance: 1200)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "EUR", # Will need to convert existing balances to EUR
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
# Only 1 rate in DB. We'll be missing the first and last days in the series.
# This rate should be applied to all days: LOCF for future dates, nearest future rate for earlier dates.
ExchangeRate.create!(date: 1.day.ago.to_date, from_currency: "USD", to_currency: "EUR", rate: 2)
expected = [
2000, # No prior rate, so use nearest future rate (2:1 from 1 day ago): 1000 * 2 = 2000
2200, # Rate available, so use 2:1 conversion (1100 USD = 2200 EUR)
2400 # Rate NOT available, but LOCF will use the last available rate, so use 2:1 conversion (1200 USD = 2400 EUR)
]
assert_equal expected, builder.balance_series.map { |v| v.value.amount }
end
test "strict currency conversion refuses a missing rate instead of assuming one" do
account = accounts(:depository)
account.balances.destroy_all
create_balance(account: account, date: Date.current, balance: 100)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ], currency: "EUR",
period: Period.custom(start_date: Date.current, end_date: Date.current),
strict_currency_conversion: true
)
error = assert_raises(Money::ConversionError) { builder.balance_series }
assert_equal "USD", error.from_currency
assert_equal "EUR", error.to_currency
end
test "strict currency conversion keeps history when a foreign balance is zero without a usable rate" do
foreign = accounts(:depository)
native = accounts(:credit_card)
foreign.balances.destroy_all
native.balances.destroy_all
native.update!(currency: "EUR")
create_balance(account: foreign, date: Date.current, balance: 0)
create_balance(account: native, date: Date.current, balance: 50)
# Zero and negative rates are rejected at write time, so absent is the only unusable rate.
ExchangeRate.where(from_currency: "USD", to_currency: "EUR").delete_all
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ foreign.id, native.id ], currency: "EUR",
period: Period.custom(start_date: Date.current, end_date: Date.current),
strict_currency_conversion: true
)
series = builder.balance_series
assert_equal 1, series.size
assert_equal(-50, series.first.value.amount)
assert_equal(-50, series.first.trend.previous.amount)
end
test "strict currency conversion uses historical rates without changing native balances" do
account = accounts(:depository)
account.balances.destroy_all
create_balance(account: account, date: 1.day.ago.to_date, balance: 100)
create_balance(account: account, date: Date.current, balance: 100)
ExchangeRate.create!(date: 1.day.ago.to_date, from_currency: "USD", to_currency: "EUR", rate: 2)
ExchangeRate.create!(date: Date.current, from_currency: "USD", to_currency: "EUR", rate: 3)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ], currency: "EUR",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
strict_currency_conversion: true
)
assert_equal [ 200, 300 ], builder.balance_series.map { |value| value.value.amount }
assert_equal [ 100, 100 ], account.balances.order(:date).pluck(:end_balance)
end
test "combines asset and liability accounts properly" do
asset_account = accounts(:depository)
liability_account = accounts(:credit_card)
Balance.destroy_all
create_balance(account: asset_account, date: 3.days.ago.to_date, balance: 500)
create_balance(account: asset_account, date: 1.day.ago.to_date, balance: 1000)
create_balance(account: asset_account, date: Date.current, balance: 1000)
create_balance(account: liability_account, date: 3.days.ago.to_date, balance: 200)
create_balance(account: liability_account, date: 2.days.ago.to_date, balance: 200)
create_balance(account: liability_account, date: Date.current, balance: 100)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ asset_account.id, liability_account.id ],
currency: "USD",
period: Period.custom(start_date: 4.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
expected = [
0, # No asset or liability balances - 4 days ago
300, # 500 - 200 = 300 - 3 days ago
300, # 500 - 200 = 300 (500 is locf) - 2 days ago
800, # 1000 - 200 = 800 (200 is locf) - 1 day ago
900 # 1000 - 100 = 900 - today
]
assert_equal expected, builder.balance_series.map { |v| v.value.amount }
end
test "account active until dates stop locf while preserving date rows" do
account = accounts(:depository)
account.balances.destroy_all
period = Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current)
create_balance(account: account, date: period.start_date, balance: 1000)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
account_active_until_dates: { account.id => 1.day.ago.to_date },
currency: "USD",
period: period,
interval: "1 day"
)
assert_equal [ 1000, 1000, 0 ], builder.balance_series.map { |v| v.value.amount }
end
test "when favorable direction is down balance signage inverts" do
account = accounts(:credit_card)
account.balances.destroy_all
create_balance(account: account, date: 1.day.ago.to_date, balance: 1000)
create_balance(account: account, date: Date.current, balance: 500)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
favorable_direction: "up"
)
# Since favorable direction is up and balances are liabilities, the values should be negative
expected = [ -1000, -500 ]
assert_equal expected, builder.balance_series.map { |v| v.value.amount }
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
favorable_direction: "down"
)
# Since favorable direction is down and balances are liabilities, the values should be positive
expected = [ 1000, 500 ]
assert_equal expected, builder.balance_series.map { |v| v.value.amount }
end
test "uses balances matching account currency for correct chart data" do
# This test verifies that chart data is built from balances with proper currency.
# Data integrity is maintained by:
# 1. Account.create_and_sync with skip_initial_sync: true for linked accounts
# 2. Migration cleanup_orphaned_currency_balances for existing data
account = accounts(:depository)
account.balances.destroy_all
# Account is in USD, create balances in USD
create_balance(account: account, date: 2.days.ago.to_date, balance: 1000)
create_balance(account: account, date: 1.day.ago.to_date, balance: 1500)
create_balance(account: account, date: Date.current, balance: 2000)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
series = builder.balance_series
assert_equal 3, series.size
assert_equal [ 1000, 1500, 2000 ], series.map { |v| v.value.amount }
end
test "balances are converted to target currency using exchange rates" do
# Create account with EUR currency
family = families(:dylan_family)
account = family.accounts.create!(
name: "EUR Account",
balance: 1000,
currency: "EUR",
accountable: Depository.new
)
account.balances.destroy_all
# Create balances in EUR (matching account currency)
create_balance(account: account, date: 1.day.ago.to_date, balance: 1000)
create_balance(account: account, date: Date.current, balance: 1200)
# Add exchange rate EUR -> USD
ExchangeRate.create!(date: 1.day.ago.to_date, from_currency: "EUR", to_currency: "USD", rate: 1.1)
# Request chart in USD (different from account's EUR)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
interval: "1 day"
)
series = builder.balance_series
# EUR balances converted to USD at 1.1 rate (LOCF for today)
assert_equal [ 1100, 1320 ], series.map { |v| v.value.amount }
end
# The series is the sum of every account's converted balance. An account in
# a currency with no rate on any date drops out of it rather than counting
# at 1 (#3640).
test "an account in a currency with no rate at all is left out of the series" do
family = families(:dylan_family)
usd = family.accounts.create!(name: "USD", balance: 100, currency: "USD", accountable: Depository.new)
krw = family.accounts.create!(name: "KRW", balance: 1_000_000, currency: "KRW", accountable: Depository.new)
[ usd, krw ].each { |account| account.balances.destroy_all }
create_balance(account: usd, date: Date.current, balance: 100)
create_balance(account: krw, date: Date.current, balance: 1_000_000)
series = Balance::ChartSeriesBuilder.new(
account_ids: [ usd.id, krw.id ],
currency: "USD",
period: Period.custom(start_date: Date.current, end_date: Date.current),
interval: "1 day"
).balance_series
assert_equal [ 100 ], series.map { |v| v.value.amount }
end
test "linked account with orphaned currency balances shows correct values after cleanup" do
# This test reproduces the original bug scenario:
# 1. Linked account created with initial sync before correct currency was known
# 2. Opening anchor and first sync created balances with wrong currency (USD)
# 3. Provider sync updated account to correct currency (EUR) and created new balances
# 4. Both USD and EUR balances existed - charts showed wrong values
#
# The fix:
# 1. skip_initial_sync prevents this going forward
# 2. Migration cleans up orphaned balances for existing linked accounts
# Use the connected (linked) account fixture
linked_account = accounts(:connected)
linked_account.balances.destroy_all
# Simulate the bug: account is now EUR but has old USD balances from initial sync
linked_account.update!(currency: "EUR")
# Create orphaned balances in wrong currency (USD) - from initial sync before currency was known
Balance.create!(
account: linked_account,
date: 3.days.ago.to_date,
balance: 1000,
cash_balance: 1000,
currency: "USD", # Wrong currency!
start_cash_balance: 1000,
start_non_cash_balance: 0,
cash_inflows: 0,
cash_outflows: 0,
non_cash_inflows: 0,
non_cash_outflows: 0,
net_market_flows: 0,
cash_adjustments: 0,
non_cash_adjustments: 0,
flows_factor: 1
)
Balance.create!(
account: linked_account,
date: 2.days.ago.to_date,
balance: 1100,
cash_balance: 1100,
currency: "USD", # Wrong currency!
start_cash_balance: 1100,
start_non_cash_balance: 0,
cash_inflows: 0,
cash_outflows: 0,
non_cash_inflows: 0,
non_cash_outflows: 0,
net_market_flows: 0,
cash_adjustments: 0,
non_cash_adjustments: 0,
flows_factor: 1
)
# Create correct balances in EUR - from provider sync after currency was known
create_balance(account: linked_account, date: 1.day.ago.to_date, balance: 5000)
create_balance(account: linked_account, date: Date.current, balance: 5500)
# Verify we have both currency balances (the bug state)
assert_equal 2, linked_account.balances.where(currency: "USD").count
assert_equal 2, linked_account.balances.where(currency: "EUR").count
# Simulate migration cleanup: delete orphaned balances with wrong currency
linked_account.balances.where.not(currency: linked_account.currency).delete_all
# Verify cleanup removed orphaned balances
assert_equal 0, linked_account.balances.where(currency: "USD").count
assert_equal 2, linked_account.balances.where(currency: "EUR").count
# Now chart should show correct EUR values
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ linked_account.id ],
currency: "EUR",
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
series = builder.balance_series
# After cleanup: only EUR balances exist, chart shows correct values
# Day 2 ago: 0 (no EUR balance), Day 1 ago: 5000, Today: 5500
assert_equal [ 0, 5000, 5500 ], series.map { |v| v.value.amount }
end
test "chart ignores orphaned currency balances via currency filter" do
# This test verifies the currency filter correctly ignores orphaned balances.
# The filter `b.currency = accounts.currency` ensures only valid balances are used.
#
# Bug scenario: Account currency changed from USD to EUR after initial sync,
# leaving orphaned USD balances. Without the filter, charts would show wrong values.
linked_account = accounts(:connected)
linked_account.balances.destroy_all
# Account is EUR but has orphaned USD balances (bug state)
linked_account.update!(currency: "EUR")
# Create orphaned USD balance (wrong currency)
Balance.create!(
account: linked_account,
date: 1.day.ago.to_date,
balance: 9999,
cash_balance: 9999,
currency: "USD", # Wrong currency - doesn't match account.currency (EUR)
start_cash_balance: 9999,
start_non_cash_balance: 0,
cash_inflows: 0,
cash_outflows: 0,
non_cash_inflows: 0,
non_cash_outflows: 0,
net_market_flows: 0,
cash_adjustments: 0,
non_cash_adjustments: 0,
flows_factor: 1
)
# Chart correctly ignores USD balance because account.currency is EUR
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ linked_account.id ],
currency: "EUR",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
interval: "1 day"
)
series = builder.balance_series
# Currency filter ensures orphaned USD balance (9999) is ignored
# Chart shows zeros because no EUR balances exist
assert_equal 2, series.size
assert_equal [ 0, 0 ], series.map { |v| v.value.amount }
# Verify the orphaned balance still exists in DB (migration will clean it up)
assert_equal 1, linked_account.balances.where(currency: "USD").count
assert_equal 0, linked_account.balances.where(currency: "EUR").count
end
test "gains series computes unrealized gains from holdings with locf" do
account = accounts(:investment)
account.holdings.destroy_all
security = securities(:aapl)
# 10 shares with avg cost of $90/share
create_holding(account: account, security: security, date: 3.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 110, cost_basis: 90)
create_holding(account: account, security: security, date: Date.current, qty: 10, price: 105, cost_basis: 90)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 4.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
expected = [
0, # No holdings yet
100, # 1000 - 900
100, # Last observation carried forward
200, # 1100 - 900
150 # 1050 - 900
]
assert_equal expected, builder.gains_series.map { |v| v.value.amount }
end
test "gains series treats unusable cost basis as zero gain" do
account = accounts(:investment)
account.holdings.destroy_all
# Unlocked zero cost basis (provider "unknown") -> no gain contribution
create_holding(account: account, security: securities(:aapl), date: Date.current, qty: 10, price: 100, cost_basis: 0)
# Nil cost basis -> no gain contribution
create_holding(account: account, security: securities(:msft), date: Date.current, qty: 5, price: 50, cost_basis: nil)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: Date.current, end_date: Date.current),
interval: "1 day"
)
assert_equal [ 0 ], builder.gains_series.map { |v| v.value.amount }
# Locked zero cost basis (e.g. airdrop) is trusted -> full amount is gain
account.holdings.where(security: securities(:aapl)).update_all(cost_basis_locked: true)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: Date.current, end_date: Date.current),
interval: "1 day"
)
assert_equal [ 1000 ], builder.gains_series.map { |v| v.value.amount }
end
# A zero the trades worked out (a lot the user says cost nothing) is a cost,
# unlike a provider's zero, which stands for unknown.
test "gains series counts a calculated zero cost basis" do
account = accounts(:investment)
account.holdings.destroy_all
create_holding(account: account, security: securities(:aapl), date: Date.current, qty: 10, price: 100, cost_basis: 0)
account.holdings.update_all(cost_basis_source: "calculated")
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: Date.current, end_date: Date.current),
interval: "1 day"
)
assert_equal [ 1000 ], builder.gains_series.map { |v| v.value.amount }
end
test "gains series converts holding gains to target currency with locf rates" do
family = families(:dylan_family)
account = family.accounts.create!(
name: "EUR Investment",
balance: 1000,
currency: "EUR",
accountable: Investment.new
)
security = securities(:aapl)
# Gains in EUR: 100 yesterday (1000 - 900), 200 today (1100 - 900)
create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 90)
create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: 90)
# Single EUR -> USD rate; LOCF applies it to today as well
ExchangeRate.create!(date: 1.day.ago.to_date, from_currency: "EUR", to_currency: "USD", rate: 1.1)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
interval: "1 day"
)
expected = [
110, # 100 EUR * 1.1
220 # 200 EUR * 1.1 (rate carried forward)
]
assert_equal expected, builder.gains_series.map { |v| v.value.amount }
end
test "gains series carries cost basis forward over gap-filled holdings" do
account = accounts(:investment)
account.holdings.destroy_all
security = securities(:aapl)
create_holding(account: account, security: security, date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
# Gap-filled rows (weekends, price gaps) are persisted without cost_basis
create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: nil)
create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: nil)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
expected = [
100, # 1000 - 900
100, # basis carried forward from 2 days ago, not zeroed
200 # 1100 - 900
]
assert_equal expected, builder.gains_series.map { |v| v.value.amount }
end
# A later row the materializer cleared as unknown (a transfer in: no cost,
# no source, not a provider's row) stops a calculated zero carrying, so the
# position's value is not all counted as gain.
test "gains series does not carry a calculated zero basis onto a later unknown one" do
account = accounts(:investment)
account.holdings.destroy_all
security = securities(:aapl)
create_holding(account: account, security: security, date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 0)
.update_columns(cost_basis_source: "calculated")
create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 15, price: 100, cost_basis: nil)
create_holding(account: account, security: security, date: Date.current, qty: 15, price: 110, cost_basis: nil)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
expected = [
1000, # 1000 - 0: a free acquisition's whole value is gain
0, # unknown basis, counted as no gain rather than 1500
0 # unknown basis, not 1650
]
assert_equal expected, builder.gains_series.map { |v| v.value.amount }
end
# The materializer leaves a provider's row alone, so a provider row with no
# cost after a free acquisition is not an unknown basis: the zero carries.
test "gains series carries a calculated zero basis onto a provider row without a cost" do
account = accounts(:investment)
account.holdings.destroy_all
security = securities(:aapl)
item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")
provider = AccountProvider.create!(account: account, provider: item.coinstats_accounts.create!(name: "Provider", currency: "USD"))
create_holding(account: account, security: security, date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 0)
.update_columns(cost_basis_source: "calculated")
create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 0)
.update_columns(cost_basis_source: "calculated")
create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: nil)
.update_columns(account_provider_id: provider.id)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
assert_equal [ 1000, 1000, 1100 ], builder.gains_series.map { |v| v.value.amount }
end
test "gains series values carry trend vs previous point" do
account = accounts(:investment)
account.holdings.destroy_all
security = securities(:aapl)
create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 90)
create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: 90)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: 1.day.ago.to_date, end_date: Date.current),
interval: "1 day"
)
series = builder.gains_series
# First point has no prior point, so trend is flat
assert_equal 100, series.values.first.trend.previous.amount
assert_equal 100, series.values.first.trend.current.amount
assert_equal 100, series.values.last.trend.previous.amount
assert_equal 200, series.values.last.trend.current.amount
end
# The membership rule below is the Holdings tab's (`Account#current_holdings`):
# once an account has a provider snapshot on or before a date, a security counts
# on that date only if that snapshot holds it. These tests write provider rows,
# as a provider sync does; calculated rows stand in for gap-fills between syncs.
test "gains series stops counting a security record the provider moved the position off" do
account = accounts(:investment)
account.holdings.destroy_all
link = link_provider(account)
old_record = Security.create!(ticker: "AAPL", name: "Apple Inc. (duplicate record)", exchange_operating_mic: "XXXX")
new_record = securities(:aapl)
# The provider reported the position on one record, then on another for the same ticker.
stale = create_provider_holding(account: account, link: link, security: old_record, date: 5.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
4.downto(0) do |days_ago|
create_provider_holding(account: account, link: link, security: new_record, date: days_ago.days.ago.to_date, qty: 10, price: 110, cost_basis: 90)
end
with_stale_row = gains_amounts(account, start_date: 5.days.ago.to_date)
stale.destroy!
without_stale_row = gains_amounts(account, start_date: 5.days.ago.to_date)
# The old record is held on the day it was reported, and on no later day.
assert_equal [ 100, 200, 200, 200, 200, 200 ], with_stale_row
assert_equal without_stale_row.drop(1), with_stale_row.drop(1)
end
test "gains series stops counting a position the provider stops reporting" do
account = accounts(:investment)
account.holdings.destroy_all
link = link_provider(account)
# MSFT drops out of the provider's snapshot after two days ago, with no zero-quantity row and no sell.
2.downto(0) do |days_ago|
create_provider_holding(account: account, link: link, security: securities(:aapl), date: days_ago.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
end
create_provider_holding(account: account, link: link, security: securities(:msft), date: 2.days.ago.to_date, qty: 5, price: 60, cost_basis: 50)
# AAPL 100 every day; MSFT 50 only on the day it was held.
assert_equal [ 150, 100, 100 ], gains_amounts(account, start_date: 2.days.ago.to_date)
end
test "gains series keeps counting every security in the latest provider snapshot across gap-filled days" do
account = accounts(:investment)
account.holdings.destroy_all
link = link_provider(account)
create_provider_holding(account: account, link: link, security: securities(:aapl), date: 2.days.ago.to_date, qty: 10, price: 102, cost_basis: 90)
create_provider_holding(account: account, link: link, security: securities(:msft), date: 2.days.ago.to_date, qty: 5, price: 60, cost_basis: 50)
# No sync since: calculated gap-fill rows carry no cost_basis, and the position is unchanged.
1.downto(0) do |days_ago|
create_holding(account: account, security: securities(:aapl), date: days_ago.days.ago.to_date, qty: 10, price: 100 + days_ago, cost_basis: nil)
end
create_holding(account: account, security: securities(:msft), date: 1.day.ago.to_date, qty: 5, price: 60, cost_basis: nil)
create_holding(account: account, security: securities(:msft), date: Date.current, qty: 5, price: 70, cost_basis: nil)
# AAPL 120, 110, 100; MSFT 50, 50, 100.
assert_equal [ 170, 160, 200 ], gains_amounts(account, start_date: 2.days.ago.to_date)
end
test "gains series carries the latest provider snapshot forward when the account has not synced since" do
account = accounts(:investment)
account.holdings.destroy_all
link = link_provider(account)
create_provider_holding(account: account, link: link, security: securities(:aapl), date: 3.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
create_provider_holding(account: account, link: link, security: securities(:msft), date: 3.days.ago.to_date, qty: 5, price: 60, cost_basis: 50)
# No rows after three days ago at all: that snapshot is still the account's position.
assert_equal [ 150, 150, 150, 150 ], gains_amounts(account, start_date: 3.days.ago.to_date)
end
test "gains series judges each account against its own provider snapshot" do
synced = accounts(:investment)
synced.holdings.destroy_all
behind = synced.family.accounts.create!(name: "Not synced lately", balance: 1000, currency: "USD", accountable: Investment.new)
synced_link = link_provider(synced)
behind_link = link_provider(behind, name: "Second link")
2.downto(0) do |days_ago|
create_provider_holding(account: synced, link: synced_link, security: securities(:aapl), date: days_ago.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
end
create_provider_holding(account: behind, link: behind_link, security: securities(:msft), date: 2.days.ago.to_date, qty: 5, price: 60, cost_basis: 50)
builder = Balance::ChartSeriesBuilder.new(
account_ids: [ synced.id, behind.id ],
currency: "USD",
period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),
interval: "1 day"
)
# The other account's later snapshot does not end this account's position.
assert_equal [ 150, 150, 150 ], builder.gains_series.map { |v| v.value.amount }
end
test "gains series counts a zero-quantity closing row as no gain" do
account = accounts(:investment)
account.holdings.destroy_all
create_holding(account: account, security: securities(:aapl), date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 90)
create_holding(account: account, security: securities(:aapl), date: 1.day.ago.to_date, qty: 0, price: 100, cost_basis: nil)
create_holding(account: account, security: securities(:aapl), date: Date.current, qty: 0, price: 100, cost_basis: nil)
assert_equal [ 100, 0, 0 ], gains_amounts(account, start_date: 2.days.ago.to_date)
end
# Plaid dates each holding by its own `institution_price_as_of`, so one sync
# can leave a security's provider row older than the rest. The Holdings tab
# (`Account#current_holdings`) and the reverse calculator's starting
# portfolio (`Holding::PortfolioSnapshot`) both take only the provider rows on
# the account's latest provider date, so that security is not part of the
# position they show. Today's gain must agree with the Holdings tab.
test "today's gain agrees with the Holdings tab when provider rows carry different dates" do
account = accounts(:investment)
account.holdings.destroy_all
account.entries.destroy_all
link = AccountProvider.create!(account: account, provider: plaid_accounts(:one))
[ [ securities(:aapl), Date.current, 10, 110, 90 ], [ securities(:msft), 2.days.ago.to_date, 5, 60, 50 ] ].each do |security, date, qty, price, basis|
account.holdings.create!(
security: security, date: date, qty: qty, price: price, amount: qty * price, currency: "USD",
cost_basis: basis, cost_basis_source: "provider", account_provider: link
)
end
Holding::Materializer.new(account, strategy: :reverse).materialize_holdings
tab_gain = account.current_holdings.sum { |h| h.amount - (h.cost_basis * h.qty) }
assert_equal [ securities(:aapl).id ], account.current_holdings.map(&:security_id)
assert_equal tab_gain, gains_amounts(account, start_date: Date.current).last
end
# A linked account's provider snapshot
# is dated before today, so the reverse calculator gap-fills calculated rows for
# its securities through today. When the next snapshot moves the position to
# another record, the old record's calculated row on today is not purged: the
# cleanup removes only rows for securities the new snapshot holds.
test "a calculated row for a security the latest provider snapshot dropped is not counted" do
account = accounts(:investment)
account.holdings.destroy_all
account.entries.destroy_all
link = link_provider(account)
old_record = Security.create!(ticker: "AAPL", name: "Apple Inc. (duplicate record)", exchange_operating_mic: "XXXX")
create_provider_holding(account: account, link: link, security: old_record, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 90)
Holding::Materializer.new(account, strategy: :reverse).materialize_holdings
create_provider_holding(account: account, link: link, security: securities(:aapl), date: Date.current, qty: 10, price: 110, cost_basis: 90)
Holding::Materializer.new(account, strategy: :reverse).materialize_holdings
assert account.holdings.exists?(security: old_record, date: Date.current, account_provider_id: nil),
"precondition: the old record's calculated row on today survives the second sync"
assert_equal [ securities(:aapl).id ], account.current_holdings.map(&:security_id)
tab_gain = account.current_holdings.sum { |h| h.amount - (h.cost_basis * h.qty) }
assert_equal [ 100, tab_gain ], gains_amounts(account, start_date: 1.day.ago.to_date)
end
# Editing one holding re-materializes
# only that security (HoldingsController -> Balance::Materializer with
# security_ids:), so its rows reach today while the others' end at the last full
# sync. An account with no provider snapshot keeps every security's latest row,
# as the Holdings tab does.
test "a manual account keeps a security whose rows end before another security's" do
account = accounts(:investment)
account.holdings.destroy_all
account.entries.destroy_all
create_trade(securities(:aapl), account: account, qty: 10, date: 5.days.ago.to_date, price: 100)
create_trade(securities(:msft), account: account, qty: 5, date: 5.days.ago.to_date, price: 50)
travel_to(1.day.ago) { Holding::Materializer.new(account, strategy: :forward).materialize_holdings }
Holding::Materializer.new(account, strategy: :forward, security_ids: [ securities(:msft).id ]).materialize_holdings
last_dates = account.holdings.group(:security_id).maximum(:date)
assert_equal 1.day.ago.to_date, last_dates[securities(:aapl).id], "precondition: AAPL's rows end at yesterday's full sync"
assert_equal Date.current, last_dates[securities(:msft).id], "precondition: MSFT's rows reach today"
assert_equal [ securities(:aapl).id, securities(:msft).id ].sort, account.current_holdings.map(&:security_id).sort
yesterday, today = gains_amounts(account, start_date: 1.day.ago.to_date)
assert yesterday.positive?, "precondition: the position shows a gain"
assert_equal yesterday, today
end
# Plaid dates a holding by its
# price, so a sync can report a position it has already sold at zero quantity
# on a snapshot dated before the sale. The reverse calculator reads that
# snapshot as today's position and undoes the sale, so the calculated rows
# after the snapshot carry the shares. The Holdings tab skips a zero-quantity
# provider row, and so must the chart.
test "a security the provider snapshot holds at zero quantity is not counted from later rows" do
account = accounts(:investment)
account.holdings.destroy_all
account.entries.destroy_all
link = link_provider(account)
sold = Security.create!(ticker: "SOLD", name: "Sold position", exchange_operating_mic: "XXXX")
0.upto(6) { |days_ago| Security::Price.create!(security: sold, date: days_ago.days.ago.to_date, price: 100, currency: "USD") }
create_trade(sold, account: account, qty: 5, date: 6.days.ago.to_date, price: 80)
create_trade(sold, account: account, qty: -5, date: Date.current, price: 100)
create_provider_holding(account: account, link: link, security: sold, date: 2.days.ago.to_date, qty: 0, price: 100, cost_basis: nil)
create_provider_holding(account: account, link: link, security: securities(:aapl), date: 2.days.ago.to_date, qty: 10, price: 110, cost_basis: 90)
Holding::Materializer.new(account, strategy: :reverse).materialize_holdings
assert_equal 5, account.holdings.find_by!(security: sold, date: 1.day.ago.to_date, account_provider_id: nil).qty,
"precondition: the calculated row after the snapshot carries the sold shares"
assert_equal [ securities(:aapl).id ], account.current_holdings.map(&:security_id)
with_sold = gains_amounts(account, start_date: 3.days.ago.to_date)
account.holdings.where(security: sold).delete_all
without_sold = gains_amounts(account, start_date: 3.days.ago.to_date)
# Before the snapshot the position is held: 5 x (100 - 80).
assert_equal 100, with_sold.first - without_sold.first
# From the snapshot on, it adds nothing.
assert_equal without_sold.drop(1), with_sold.drop(1)
end
test "a provider row's quantity decides whether the security's later rows count" do
account = accounts(:investment)
account.holdings.destroy_all
link = link_provider(account)
msft_snapshot = create_provider_holding(account: account, link: link, security: securities(:msft), date: 1.day.ago.to_date, qty: 0, price: 60, cost_basis: nil)
create_provider_holding(account: account, link: link, security: securities(:aapl), date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 90)
# Calculated rows after the snapshot, as the reverse calculator writes them.
create_holding(account: account, security: securities(:msft), date: Date.current, qty: 5, price: 60, cost_basis: 50)
create_holding(account: account, security: securities(:aapl), date: Date.current, qty: 10, price: 110, cost_basis: nil)
# MSFT is held at zero on the snapshot, so only AAPL counts: 100, then 200.
assert_equal [ 100, 200 ], gains_amounts(account, start_date: 1.day.ago.to_date)
# The same row holding shares keeps MSFT's later row counting: 5 x (60 - 50) on each day.
msft_snapshot.update!(qty: 5, amount: 300, cost_basis: 50)
assert_equal [ 150, 250 ], gains_amounts(account, start_date: 1.day.ago.to_date)
end
# Between two provider snapshots the reverse calculator rebuilds the position
# from trades. A security bought after the earlier snapshot is held from its
# trade on, so its gain counts on the days in between, not only from the next
# snapshot.
test "gains series counts a position bought between provider snapshots" do
account = accounts(:investment)
account.holdings.destroy_all
account.entries.destroy_all
link = AccountProvider.create!(account: account, provider: plaid_accounts(:one))
aapl = securities(:aapl)
msft = securities(:msft)
[ aapl, msft ].each do |security|
Security::Price.where(security: security).delete_all
(0..4).each { |days_ago| Security::Price.create!(security: security, date: days_ago.days.ago.to_date, price: security == aapl ? 100 : 60, currency: "USD") }
end
provider_row = ->(security, date, qty, basis) do
account.holdings.create!(security: security, date: date, qty: qty, price: security == aapl ? 100 : 60,
amount: qty * (security == aapl ? 100 : 60), currency: "USD",
cost_basis: basis, cost_basis_source: "provider", account_provider: link)
end
provider_row.(aapl, 4.days.ago.to_date, 10, 90)
create_trade(msft, account: account, qty: 5, price: 50, date: 3.days.ago.to_date)
provider_row.(aapl, Date.current, 10, 90)
provider_row.(msft, Date.current, 5, 50)
Holding::Materializer.new(account, strategy: :reverse).materialize_holdings
# AAPL 10 * (100 - 90) = 100 every day; MSFT 5 * (60 - 50) = 50 from its trade on.
assert_equal [ 100, 150, 150, 150, 150 ], gains_amounts(account, start_date: 4.days.ago.to_date)
end
private
def gains_amounts(account, start_date:)
Balance::ChartSeriesBuilder.new(
account_ids: [ account.id ],
currency: "USD",
period: Period.custom(start_date: start_date, end_date: Date.current),
interval: "1 day"
).gains_series.map { |v| v.value.amount }
end
def link_provider(account, name: "Provider")
item = account.family.coinstats_items.create!(name: name, api_key: "test-key")
AccountProvider.create!(account: account, provider: item.coinstats_accounts.create!(name: name, currency: account.currency))
end
def create_provider_holding(account:, link:, security:, date:, qty:, price:, cost_basis:)
account.holdings.create!(
security: security, date: date, qty: qty, price: price, amount: qty * price,
currency: account.currency, cost_basis: cost_basis, cost_basis_source: "provider", account_provider: link
)
end
def create_holding(account:, security:, date:, qty:, price:, cost_basis:)
Holding.create!(
account: account,
security: security,
date: date,
qty: qty,
price: price,
amount: qty * price,
currency: account.currency,
cost_basis: cost_basis
)
end
end