The personal finance app for everyone (by everyone)
Ruby
Stop fetching prices for securities no account still holds (#3888)
jaysbeekay947ea9721a58
diff --git a/app/models/account/market_data_importer.rb b/app/models/account/market_data_importer.rbindex 3eff07d852..8dd606af02 100644--- a/app/models/account/market_data_importer.rb+++ b/app/models/account/market_data_importer.rb@@ -62,59 +62,30 @@ class Account::MarketDataImporterdef import_security_pricesreturn unless Security.provider- current_security_ids = account.current_holdings.pluck(:security_id).to_set- traded_security_ids = account.trades.pluck(:security_id).uniq-- all_security_ids = (current_security_ids | traded_security_ids)- return if all_security_ids.empty?-- securities = Security.online.where(id: all_security_ids).index_by(&:id)-- start_dates = first_required_price_dates- historical_ids = traded_security_ids - current_security_ids.to_a-- # For securities no longer held, cap end_date at the last holding date so- # all_prices_exist? stays stable and we don't call the provider every sync.- last_holding_date = account.holdings- .where(security_id: historical_ids)- .group(:security_id)- .maximum(:date)-- # import_market_data runs before materialize_balances in Account::Syncer, so- # current_holdings can reflect a stale pre-trade snapshot. If a historical- # security has a trade newer than its last holding date the position was- # reopened this sync; fetch prices through today so the forthcoming- # materialization has a price available.- latest_trade_date = account.trades- .where(security_id: historical_ids)- .group(:security_id)- .maximum("entries.date")-- all_security_ids.each do |security_id|+ return if price_windows.empty?++ securities = Security.online.where(id: price_windows.keys).index_by(&:id)++ price_windows.each do |security_id, window|security = securities[security_id]next unless security- end_date = if current_security_ids.include?(security_id)- Date.current- else- holding_date = last_holding_date[security_id]- trade_date = latest_trade_date[security_id]- reopened = trade_date && holding_date && trade_date > holding_date- reopened ? Date.current : (holding_date || Date.current)- end-- security.import_provider_prices(start_date: start_dates[security_id], end_date: end_date)+ security.import_provider_prices(start_date: window.start_date, end_date: window.end_date)security.import_provider_detailsendendprivate+ def price_windows+ @price_windows ||= Security::Price::ImportWindows.new(account).to_h+ end+def security_ids- @security_ids ||= (account.current_holdings.pluck(:security_id) | account.trades.pluck(:security_id))+ price_windows.keysenddef first_required_price_dates- @first_required_price_dates ||= batch_first_required_price_dates(security_ids)+ price_windows.transform_values(&:start_date)end# Earliest required date per price currency that differs from the account currency.@@ -136,26 +107,6 @@ class Account::MarketDataImporterendend- # Replaces 2-queries-per-security with 3 queries total.- def batch_first_required_price_dates(security_ids)- # account.trades is a has_many :through :entries, so entries is already joined- trade_start_dates = account.trades.group(:security_id).minimum("entries.date")-- provider_holding_security_ids = account.holdings- .where(security_id: security_ids)- .where.not(account_provider_id: nil)- .pluck(:security_id)- .to_set-- account_start_date = account.start_date-- security_ids.each_with_object({}) do |security_id, hash|- trade_date = trade_start_dates[security_id]- holding_date = provider_holding_security_ids.include?(security_id) ? account_start_date : nil- hash[security_id] = [ trade_date, holding_date ].compact.min || account_start_date- end- end-def needs_exchange_rates?has_multi_currency_entries? || foreign_account? || security_price_currency_start_dates.any?enddiff --git a/app/models/market_data_importer.rb b/app/models/market_data_importer.rbindex 742e88fc30..0b483f5484 100644--- a/app/models/market_data_importer.rb+++ b/app/models/market_data_importer.rb@@ -22,14 +22,24 @@ class MarketDataImporterreturnend- # Import all securities that aren't marked as "offline" (i.e. they're available from the provider)- Security.online.find_each do |security|+ # A security may be shared by accounts with different holding periods. Merge+ # their required ranges before calling the provider once per security.+ windows = required_security_price_windows++ Security.online.where(id: windows.keys).find_each do |security|+ window = windows.fetch(security.id)+ next if snapshot? && window.end_date < default_start_date+security.import_provider_prices(- start_date: get_first_required_price_date(security),- end_date: end_date,+ start_date: snapshot? ? [ window.start_date, default_start_date ].max : window.start_date,+ end_date: window.end_date,clear_cache: clear_cache)+ end+ # Details are metadata rather than prices, and import_provider_details skips+ # the provider once a security has them, so every online security keeps them.+ Security.online.find_each do |security|security.import_provider_details(clear_cache: clear_cache)endend@@ -57,6 +67,29 @@ class MarketDataImporterprivateattr_reader :mode, :clear_cache+ def required_security_price_windows+ windows = {}+ # Account status does not close a position; retained holdings still count.+ accounts_with_securities = Account.where(id: Holding.select(:account_id))+ .or(Account.where(id: Entry.where(entryable_type: "Trade").select(:account_id)))++ accounts_with_securities.find_each do |account|+ Security::Price::ImportWindows.new(account, today: end_date).to_h.each do |security_id, window|+ previous = windows[security_id]+ windows[security_id] = if previous+ Security::Price::ImportWindows::Window.new(+ start_date: [ previous.start_date, window.start_date ].min,+ end_date: [ previous.end_date, window.end_date ].max+ )+ else+ window+ end+ end+ end++ windows+ end+def snapshot?mode.to_sym == :snapshotend@@ -115,12 +148,6 @@ class MarketDataImporterendend- def get_first_required_price_date(security)- return default_start_date if snapshot?-- Trade.with_entry.where(security: security).minimum(:date) || default_start_date- end-# An approximation that grabs more than we likely need, but simplifies the logicdef get_first_required_exchange_rate_date(from_currency:)return default_start_date if snapshot?diff --git a/app/models/security/price/import_windows.rb b/app/models/security/price/import_windows.rbnew file mode 100644index 0000000000..49ff0de409--- /dev/null+++ b/app/models/security/price/import_windows.rb@@ -0,0 +1,100 @@+class Security::Price::ImportWindows+ Window = Data.define(:start_date, :end_date)++ def initialize(account, today: Date.current)+ @account = account+ @today = today+ end++ def to_h+ current_ids = account.current_holdings.pluck(:security_id).to_set+ first_trade_dates = {}+ last_trade_dates = {}+ last_buy_dates = {}+ last_trade_changed_at = {}+ trade_quantities = {}+ account.trades.group(:security_id).pluck(+ :security_id,+ Arel.sql("MIN(entries.date)"),+ Arel.sql("MAX(entries.date) FILTER (WHERE trades.qty <> 0)"),+ Arel.sql("MAX(entries.date) FILTER (WHERE trades.qty > 0)"),+ Arel.sql("MAX(GREATEST(entries.updated_at, trades.updated_at)) FILTER (WHERE trades.qty <> 0)"),+ Arel.sql("SUM(trades.qty)")+ ).each do |security_id, first_date, last_date, last_buy_date, trade_changed_at, qty|+ first_trade_dates[security_id] = first_date+ last_trade_dates[security_id] = last_date+ last_buy_dates[security_id] = last_buy_date+ last_trade_changed_at[security_id] = trade_changed_at+ trade_quantities[security_id] = qty+ end++ first_held_dates = {}+ last_held_dates = {}+ last_holding_dates = {}+ last_holding_updated_at = {}+ last_provider_dates = {}+ provider_holding_ids = Set.new+ account.holdings.group(:security_id).pluck(+ :security_id,+ Arel.sql("MIN(holdings.date) FILTER (WHERE holdings.qty > 0)"),+ Arel.sql("MAX(holdings.date) FILTER (WHERE holdings.qty > 0)"),+ Arel.sql("MAX(holdings.date)"),+ Arel.sql("MAX(holdings.updated_at)"),+ Arel.sql("MAX(holdings.date) FILTER (WHERE holdings.account_provider_id IS NOT NULL)")+ ).each do |security_id, first_date, last_date, holding_date, holding_updated_at, provider_date|+ first_held_dates[security_id] = first_date if first_date+ last_held_dates[security_id] = last_date if last_date+ last_holding_dates[security_id] = holding_date+ last_holding_updated_at[security_id] = holding_updated_at+ if provider_date+ provider_holding_ids.add(security_id)+ last_provider_dates[security_id] = provider_date+ end+ end++ # A manual position can reopen before holdings are rematerialized: a new+ # trade, a backdated one, or an edit to an existing one. Net quantity in+ # either direction counts, because the materializer writes holdings with+ # upsert_all, so a short is not stopped by Holding's qty >= 0 validation.+ # A zero holding written after every trade change is authoritative even+ # when raw trade quantities disagree (for example, after a reverse split).+ # A deleted trade leaves no row to compare, so deleting a closing trade is+ # picked up on the next sync, once holdings are rebuilt.+ manual_open_ids = trade_quantities.filter_map do |id, qty|+ next if qty.nil? || qty.zero? || provider_holding_ids.include?(id)++ last_holding_date = last_holding_dates[id]+ changed_at = last_trade_changed_at[id]+ id if last_holding_date.nil? ||+ (last_trade_dates[id] && last_trade_dates[id] > last_holding_date) ||+ (changed_at && changed_at > last_holding_updated_at[id])+ end.to_set+ provider_reopened_ids = provider_holding_ids.filter_map do |id|+ id if last_buy_dates[id] && last_buy_dates[id] > last_provider_dates[id]+ end.to_set++ ids = current_ids | manual_open_ids | provider_reopened_ids | first_trade_dates.keys | first_held_dates.keys+ return {} if ids.empty?++ account_start_date = account.start_date++ ids.each_with_object({}) do |security_id, windows|+ start_date = [+ first_trade_dates[security_id],+ first_held_dates[security_id],+ (account_start_date if provider_holding_ids.include?(security_id))+ ].compact.min || account_start_date++ end_date = if current_ids.include?(security_id) || manual_open_ids.include?(security_id) || provider_reopened_ids.include?(security_id)+ today+ else+ [ last_trade_dates[security_id], last_held_dates[security_id] ].compact.max+ end++ windows[security_id] = Window.new(start_date: start_date, end_date: end_date) if end_date+ end+ end++ private+ attr_reader :account, :today+enddiff --git a/test/models/account/market_data_importer_test.rb b/test/models/account/market_data_importer_test.rbindex 129ab38a23..7f75ae7eb1 100644--- a/test/models/account/market_data_importer_test.rb+++ b/test/models/account/market_data_importer_test.rb@@ -242,7 +242,7 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCaseassert_equal 1, Security::Price.where(security: security, date: trade_date).countend- test "caps end_date at last holding date for securities no longer held" do+ test "caps a sold security at its closing trade despite later zero holdings" dofamily = Family.create!(name: "Smith", currency: "USD")account = family.accounts.create!(@@ -262,13 +262,16 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCasetrade = Trade.new(security: sec, qty: 10, price: 100, currency: "USD", investment_activity_label: "Buy")account.entries.create!(name: "Buy #{sec.ticker}", date: trade_date, amount: 1000, currency: "USD", entryable: trade)end+ account.entries.create!(name: "Sell HIST", date: sold_date, amount: 1100, currency: "USD",+ entryable: Trade.new(security: historical_sec, qty: -10, price: 110, currency: "USD", investment_activity_label: "Sell"))# Current: most-recent holding has qty > 0 — shows up in current_holdingsaccount.holdings.create!(security: current_sec, date: Date.current, qty: 10, price: 110, amount: 1100, currency: "USD")- # Historical: most-recent holding has qty == 0 (sold) — excluded from current_holdings+ # Historical: zero-quantity holdings continue through today after the sale.account.holdings.create!(security: historical_sec, date: 10.days.ago.to_date, qty: 10, price: 105, amount: 1050, currency: "USD")account.holdings.create!(security: historical_sec, date: sold_date, qty: 0, price: 0, amount: 0, currency: "USD")+ account.holdings.create!(security: historical_sec, date: Date.current, qty: 0, price: 0, amount: 0, currency: "USD")expected_start_date = trade_date - SECURITY_PRICE_BUFFER@@ -292,6 +295,38 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCaseAccount::MarketDataImporter.new(account).import_allend+ test "a closed account stays quiet after another account extends the shared prices" do+ security = Security.create!(ticker: "SHARED", exchange_operating_mic: "XNAS")+ closed_account = Family.create!(name: "Closed", currency: "USD").accounts.create!(+ name: "Sold", currency: "USD", balance: 0, accountable: Investment.new+ )+ open_account = Family.create!(name: "Open", currency: "USD").accounts.create!(+ name: "Held", currency: "USD", balance: 0, accountable: Investment.new+ )+ buy_date = 30.days.ago.to_date+ sold_date = 5.days.ago.to_date++ closed_account.entries.create!(name: "Buy", date: buy_date, amount: 1000, currency: "USD",+ entryable: Trade.new(security: security, qty: 10, price: 100, currency: "USD", investment_activity_label: "Buy"))+ closed_account.entries.create!(name: "Sell", date: sold_date, amount: 1100, currency: "USD",+ entryable: Trade.new(security: security, qty: -10, price: 110, currency: "USD", investment_activity_label: "Sell"))+ closed_account.holdings.create!(security: security, date: sold_date - 1.day, qty: 10, price: 105, amount: 1050, currency: "USD")+ closed_account.holdings.create!(security: security, date: Date.current, qty: 0, price: 0, amount: 0, currency: "USD")+ open_account.holdings.create!(security: security, date: Date.current, qty: 1, price: 120, amount: 120, currency: "USD")++ # The open account's last sync carried the shared prices past the sale, up to+ # yesterday. Today's price is still missing: only the open account needs it.+ ((buy_date - SECURITY_PRICE_BUFFER)..Date.yesterday).each do |date|+ Security::Price.create!(security: security, date: date, price: 100, currency: "USD", provisional: false)+ end++ @provider.expects(:fetch_security_prices).never+ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Shared", logo_url: "logo")))+ @provider.stubs(:fetch_exchange_rates).returns(provider_success_response([]))++ Account::MarketDataImporter.new(closed_account).import_all+ end+test "fetches prices through today when a sold security is repurchased before holdings are rematerialized" dofamily = Family.create!(name: "Smith", currency: "USD")@@ -318,6 +353,7 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCase# Stale materialized holdings — qty=0 means current_holdings excludes this securityaccount.holdings.create!(security: security, date: sold_date, qty: 0, price: 0, amount: 0, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 0, amount: 0, currency: "USD")# Repurchase trade added after last materialization — holdings haven't been rematerialized yetrepurchase = Trade.new(security: security, qty: 5, price: 130, currency: "USD", investment_activity_label: "Buy")@@ -480,6 +516,34 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCaseassert_equal 1, Security::Price.where(security: security, date: account.start_date).countend+ test "backfills a closed provider-held position once and then skips it" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: "OLDPROV", exchange_operating_mic: "XNAS")+ provider_item = family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")+ provider_account = provider_item.coinstats_accounts.create!(name: "Provider", currency: "USD")+ account_provider = AccountProvider.create!(account: account, provider: provider_account)+ held_date = 10.days.ago.to_date++ account.holdings.create!(security: security, date: held_date, qty: 1, price: 100, amount: 100,+ currency: "USD", account_provider: account_provider)+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 100, amount: 0,+ currency: "USD", account_provider: account_provider)++ @provider.expects(:fetch_security_prices)+ .with(symbol: security.ticker, exchange_operating_mic: "XNAS",+ start_date: held_date - SECURITY_PRICE_BUFFER, end_date: held_date)+ .once+ .returns(provider_success_response([+ OpenStruct.new(security: security, date: held_date, price: 100, currency: "USD")+ ]))+ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Old", logo_url: "logo")))++ 2.times { Account::MarketDataImporter.new(account).import_security_prices }++ assert Security::Price.exists?(security: security, date: held_date)+ end+test "handles provider error response gracefully for exchange rates" dofamily = Family.create!(name: "Smith", currency: "USD")diff --git a/test/models/market_data_importer_test.rb b/test/models/market_data_importer_test.rbindex 1a85c3c5be..93e70344cf 100644--- a/test/models/market_data_importer_test.rb+++ b/test/models/market_data_importer_test.rb@@ -97,6 +97,11 @@ class MarketDataImporterTest < ActiveSupport::TestCasetest "syncs security prices" dosecurity = Security.create!(ticker: "AAPL", exchange_operating_mic: "XNAS")+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")+ account.entries.create!(name: "Buy AAPL", date: 40.days.ago.to_date, amount: 100, currency: "USD", entryable: trade)+ account.holdings.create!(security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "USD")expected_start_date = SNAPSHOT_START_DATE - SECURITY_PRICE_BUFFERend_date = Date.current.in_time_zone("America/New_York").to_date@@ -124,4 +129,114 @@ class MarketDataImporterTest < ActiveSupport::TestCaseassert_equal 1, Security::Price.where(security: security, date: SNAPSHOT_START_DATE).countend++ test "fetches no prices for online securities without holdings or trades" do+ security = Security.create!(ticker: "UNUSED", exchange_operating_mic: "XNAS")++ @provider.expects(:fetch_security_prices).never+ @provider.expects(:fetch_security_info)+ .with(symbol: "UNUSED", exchange_operating_mic: "XNAS")+ .once+ .returns(provider_success_response(OpenStruct.new(name: "Unused", logo_url: "logo")))++ MarketDataImporter.new(mode: :full).import_security_prices++ assert_equal "Unused", security.reload.name+ end++ test "stops the global price range at a sale despite zero holdings through today" do+ security = Security.create!(ticker: "HIST", exchange_operating_mic: "XNAS")+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ buy_date = 30.days.ago.to_date+ sell_date = 5.days.ago.to_date++ account.entries.create!(name: "Buy", date: buy_date, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy"))+ account.entries.create!(name: "Sell", date: sell_date, amount: 110, currency: "USD",+ entryable: Trade.new(security: security, qty: -1, price: 110, currency: "USD", investment_activity_label: "Sell"))+ account.holdings.create!(security: security, date: sell_date - 1.day, qty: 1, price: 105, amount: 105, currency: "USD")+ account.holdings.create!(security: security, date: sell_date, qty: 0, price: 105, amount: 0, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 105, amount: 0, currency: "USD")++ @provider.expects(:fetch_security_prices)+ .with(symbol: "HIST", exchange_operating_mic: "XNAS",+ start_date: buy_date - SECURITY_PRICE_BUFFER, end_date: sell_date)+ .once+ .returns(provider_success_response([]))+ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Historic", logo_url: "logo")))++ MarketDataImporter.new(mode: :full).import_security_prices+ end++ test "does not refetch a complete sold position on later daily imports" do+ security = Security.create!(ticker: "CLOSED", exchange_operating_mic: "XNAS")+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ buy_date = 12.days.ago.to_date+ sell_date = 5.days.ago.to_date++ account.entries.create!(name: "Buy", date: buy_date, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy"))+ account.entries.create!(name: "Sell", date: sell_date, amount: 110, currency: "USD",+ entryable: Trade.new(security: security, qty: -1, price: 110, currency: "USD", investment_activity_label: "Sell"))+ account.holdings.create!(security: security, date: sell_date - 1.day, qty: 1, price: 105, amount: 105, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 105, amount: 0, currency: "USD")++ (buy_date..sell_date).each do |date|+ Security::Price.create!(security: security, date: date, price: 100, currency: "USD", provisional: false)+ end++ @provider.expects(:fetch_security_prices).never+ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Closed", logo_url: "logo")))++ 2.times { MarketDataImporter.new(mode: :full).import_security_prices }+ end++ test "snapshot cache clearing skips a position closed before the snapshot" do+ security = Security.create!(ticker: "OLD", exchange_operating_mic: "XNAS")+ account = Family.create!(name: "Smith", currency: "USD").accounts.create!(+ name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new+ )+ buy_date = 90.days.ago.to_date+ sell_date = 60.days.ago.to_date++ account.entries.create!(name: "Buy", date: buy_date, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy"))+ account.entries.create!(name: "Sell", date: sell_date, amount: 110, currency: "USD",+ entryable: Trade.new(security: security, qty: -1, price: 110, currency: "USD", investment_activity_label: "Sell"))+ account.holdings.create!(security: security, date: sell_date - 1.day, qty: 1, price: 105, amount: 105, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 110, amount: 0, currency: "USD")++ @provider.expects(:fetch_security_prices).never+ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Old", logo_url: "logo")))++ MarketDataImporter.new(mode: :snapshot, clear_cache: true).import_security_prices+ end++ test "keeps a shared security current while another account holds it" do+ security = Security.create!(ticker: "SHARED", exchange_operating_mic: "XNAS")+ first_family = Family.create!(name: "First", currency: "USD")+ second_family = Family.create!(name: "Second", currency: "USD")+ sold_account = first_family.accounts.create!(name: "Sold", currency: "USD", balance: 0, accountable: Investment.new)+ open_account = second_family.accounts.create!(name: "Open", currency: "USD", balance: 0, accountable: Investment.new)+ first_buy = 40.days.ago.to_date++ sold_account.entries.create!(name: "Buy", date: first_buy, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy"))+ sold_account.entries.create!(name: "Sell", date: 5.days.ago.to_date, amount: 110, currency: "USD",+ entryable: Trade.new(security: security, qty: -1, price: 110, currency: "USD", investment_activity_label: "Sell"))+ sold_account.holdings.create!(security: security, date: Date.current, qty: 0, price: 110, amount: 0, currency: "USD")+ open_account.holdings.create!(security: security, date: Date.current, qty: 1, price: 120, amount: 120, currency: "USD")++ @provider.expects(:fetch_security_prices)+ .with(symbol: "SHARED", exchange_operating_mic: "XNAS",+ start_date: first_buy - SECURITY_PRICE_BUFFER,+ end_date: Date.current.in_time_zone("America/New_York").to_date)+ .once+ .returns(provider_success_response([]))+ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Shared", logo_url: "logo")))++ MarketDataImporter.new(mode: :full).import_security_prices+ endenddiff --git a/test/models/security/price/import_windows_test.rb b/test/models/security/price/import_windows_test.rbnew file mode 100644index 0000000000..7fa7f65e9e--- /dev/null+++ b/test/models/security/price/import_windows_test.rb@@ -0,0 +1,142 @@+require "test_helper"++class Security::Price::ImportWindowsTest < ActiveSupport::TestCase+ setup do+ Security::Price.delete_all+ Trade.delete_all+ Holding.delete_all+ Security.delete_all+ end++ test "uses the last positive holding for a closed position without trades" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: "HIST", exchange_operating_mic: "XNAS")+ held_date = 10.days.ago.to_date++ account.holdings.create!(security: security, date: held_date, qty: 2, price: 100, amount: 200, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 100, amount: 0, currency: "USD")++ window = Security::Price::ImportWindows.new(account).to_h.fetch(security.id)++ assert_equal held_date, window.start_date+ assert_equal held_date, window.end_date+ end++ test "recognizes a new manual buy before holdings are rematerialized" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: "REOPEN", exchange_operating_mic: "XNAS")+ buy_date = 20.days.ago.to_date++ account.entries.create!(name: "Buy", date: buy_date, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy"))+ account.entries.create!(name: "Sell", date: 10.days.ago.to_date, amount: 110, currency: "USD",+ entryable: Trade.new(security: security, qty: -1, price: 110, currency: "USD", investment_activity_label: "Sell"))+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 110, amount: 0, currency: "USD")++ account.entries.create!(name: "Rebuy", date: 2.days.ago.to_date, amount: 120, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 120, currency: "USD", investment_activity_label: "Buy"))++ window = Security::Price::ImportWindows.new(account).to_h.fetch(security.id)++ assert_equal buy_date, window.start_date+ assert_equal Date.current, window.end_date+ end++ test "a materialized zero holding closes a position even when raw trade quantities are positive" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: "SPLIT", exchange_operating_mic: "XNAS")+ buy_date = 30.days.ago.to_date+ sell_date = 5.days.ago.to_date++ account.entries.create!(name: "Buy", date: buy_date, amount: 1000, currency: "USD",+ entryable: Trade.new(security: security, qty: 10, price: 100, currency: "USD", investment_activity_label: "Buy"))+ # A 1-for-10 reverse split leaves one share to sell. The split is reflected+ # in the materialized holdings, not in the original trade quantities.+ account.entries.create!(name: "Sell", date: sell_date, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: -1, price: 100, currency: "USD", investment_activity_label: "Sell"))+ account.holdings.create!(security: security, date: sell_date - 1.day, qty: 1, price: 100, amount: 100, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 100, amount: 0, currency: "USD")++ assert_equal 9, account.trades.sum(:qty)+ assert_equal sell_date, Security::Price::ImportWindows.new(account).to_h.fetch(security.id).end_date+ end++ test "recognizes a buy after a closed provider snapshot" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: "LINKED", exchange_operating_mic: "XNAS")+ provider_item = family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")+ provider_account = provider_item.coinstats_accounts.create!(name: "Provider", currency: "USD")+ account_provider = AccountProvider.create!(account: account, provider: provider_account)+ first_held_date = 20.days.ago.to_date+ sold_date = 10.days.ago.to_date++ account.holdings.create!(security: security, date: first_held_date, qty: 1, price: 100, amount: 100,+ currency: "USD", account_provider: account_provider)+ account.holdings.create!(security: security, date: sold_date, qty: 0, price: 110, amount: 0,+ currency: "USD", account_provider: account_provider)+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 110, amount: 0, currency: "USD")++ account.entries.create!(name: "Buy", date: 2.days.ago.to_date, amount: 120, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 120, currency: "USD", investment_activity_label: "Buy"))++ window = Security::Price::ImportWindows.new(account).to_h.fetch(security.id)++ assert_equal first_held_date, window.start_date+ assert_equal Date.current, window.end_date+ end+ # Editing the closing trade reopens the position before holdings are+ # rebuilt. The edit changes no buy, so only the trade's own update time shows it.+ test "an edited closing trade reopens the position before holdings are rematerialized" do+ account, security = closed_manual_position("EDITED")+ sell = account.trades.find_by!(security: security, qty: -10)++ travel 1.second do+ sell.update!(qty: -5)+ assert_equal Date.current, Security::Price::ImportWindows.new(account).to_h.fetch(security.id).end_date+ end+ end++ # A short sale after a closed position: net quantity negative, so a check for+ # a net-positive (long) reopen alone never fires.+ test "a short sale after a closed position reopens it before rematerialization" do+ account, security = closed_manual_position("SHORTED")++ travel 1.second do+ account.entries.create!(name: "Short", date: 2.days.ago.to_date, amount: -500, currency: "USD",+ entryable: Trade.new(security: security, qty: -5, price: 100, currency: "USD", investment_activity_label: "Sell"))+ assert_equal Date.current, Security::Price::ImportWindows.new(account).to_h.fetch(security.id).end_date+ end+ end++ # trades.qty is nullable in the schema even though Trade validates it; a+ # legacy NULL must not abort the window for every other security.+ test "a trade with no quantity does not abort the windows" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: "NULLQTY", exchange_operating_mic: "XNAS")+ entry = account.entries.create!(name: "Buy", date: 10.days.ago.to_date, amount: 100, currency: "USD",+ entryable: Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy"))+ entry.entryable.update_column(:qty, nil)++ assert_nothing_raised { Security::Price::ImportWindows.new(account).to_h }+ end++ private+ # Bought 10, sold 10, and holdings already rebuilt to zero through today.+ def closed_manual_position(ticker)+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)+ security = Security.create!(ticker: ticker, exchange_operating_mic: "XNAS")+ account.entries.create!(name: "Buy", date: 20.days.ago.to_date, amount: 1000, currency: "USD",+ entryable: Trade.new(security: security, qty: 10, price: 100, currency: "USD", investment_activity_label: "Buy"))+ account.entries.create!(name: "Sell", date: 10.days.ago.to_date, amount: -1100, currency: "USD",+ entryable: Trade.new(security: security, qty: -10, price: 110, currency: "USD", investment_activity_label: "Sell"))+ account.holdings.create!(security: security, date: 15.days.ago.to_date, qty: 10, price: 105, amount: 1050, currency: "USD")+ account.holdings.create!(security: security, date: Date.current, qty: 0, price: 110, amount: 0, currency: "USD")+ [ account, security ]+ end+end