The personal finance app for everyone (by everyone)
Ruby
Import exchange rates for foreign security price currencies (#3812)
Niels Eulinkcdfc1fe431cb
diff --git a/app/models/account/market_data_importer.rb b/app/models/account/market_data_importer.rbindex cfe7e37116..3eff07d852 100644--- a/app/models/account/market_data_importer.rb+++ b/app/models/account/market_data_importer.rb@@ -5,9 +5,11 @@ class Account::MarketDataImporter@account = accountend+ # Prices are imported first so their currencies are known when deciding+ # which exchange rate pairs the account needs.def import_all- import_exchange_ratesimport_security_prices+ import_exchange_ratesenddef import_exchange_rates@@ -39,6 +41,14 @@ class Account::MarketDataImporterpair_dates[key] = [ pair_dates[key], account.start_date ].compact.minend+ # 3. SECURITY PRICE PAIRS – holdings convert each security price into the+ # account currency, so every foreign price currency needs rates from the+ # first date a price for that security is required.+ security_price_currency_start_dates.each do |source_currency, date|+ key = [ source_currency, account.currency ]+ pair_dates[key] = [ pair_dates[key], date ].compact.min+ end+pair_dates.each do |(source, target), start_date|ExchangeRate.import_provider_rates(from: source,@@ -60,7 +70,7 @@ class Account::MarketDataImportersecurities = Security.online.where(id: all_security_ids).index_by(&:id)- start_dates = batch_first_required_price_dates(all_security_ids)+ start_dates = first_required_price_dateshistorical_ids = traded_security_ids - current_security_ids.to_a# For securities no longer held, cap end_date at the last holding date so@@ -99,6 +109,33 @@ class Account::MarketDataImporterendprivate+ def security_ids+ @security_ids ||= (account.current_holdings.pluck(:security_id) | account.trades.pluck(:security_id))+ end++ def first_required_price_dates+ @first_required_price_dates ||= batch_first_required_price_dates(security_ids)+ end++ # Earliest required date per price currency that differs from the account currency.+ # Securities are shared across families, so a price's own date is not a bound.+ # Currencies whose prices all predate the account's first required date are skipped.+ def security_price_currency_start_dates+ @security_price_currency_start_dates ||= begin+ latest_foreign_price_dates = Security::Price.where(security_id: security_ids)+ .where.not(currency: account.currency)+ .group(:security_id, :currency)+ .maximum(:date)++ latest_foreign_price_dates.each_with_object({}) do |((security_id, currency), latest_date), dates|+ start_date = first_required_price_dates[security_id]+ next if latest_date < start_date++ dates[currency] = [ dates[currency], start_date ].compact.min+ end+ end+ end+# 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@@ -120,7 +157,7 @@ class Account::MarketDataImporterenddef needs_exchange_rates?- has_multi_currency_entries? || foreign_account?+ has_multi_currency_entries? || foreign_account? || security_price_currency_start_dates.any?enddef has_multi_currency_entries?diff --git a/test/models/account/market_data_importer_test.rb b/test/models/account/market_data_importer_test.rbindex 7f6ee0ba10..129ab38a23 100644--- a/test/models/account/market_data_importer_test.rb+++ b/test/models/account/market_data_importer_test.rb@@ -100,6 +100,98 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCaseAccount::MarketDataImporter.new(account).import_exchange_ratesend+ test "fetches rates from security price currencies into the account currency" do+ family = Family.create!(name: "Smith", currency: "EUR")++ account = family.accounts.create!(+ name: "Brokerage",+ currency: "EUR",+ balance: 0,+ accountable: Investment.new+ )++ security = Security.create!(ticker: "AAPL", exchange_operating_mic: "XNAS")++ # Securities are shared across families; prices older than this account's+ # first trade must not pull the exchange rate start date back.+ Security::Price.create!(security: security, date: 2.years.ago.to_date, price: 90, currency: "USD")++ trade_date = 10.days.ago.to_date+ trade = Trade.new(security: security, qty: 1, price: 100, currency: "EUR", investment_activity_label: "Buy")+ account.entries.create!(name: "Buy AAPL", date: trade_date, amount: 100, currency: "EUR", entryable: trade)++ end_date = Date.current.in_time_zone("America/New_York").to_date++ # Prices are imported before exchange rates so a first sync already knows the USD price currency+ fetch_sequence = sequence("fetch")++ @provider.expects(:fetch_security_prices)+ .with(symbol: security.ticker, exchange_operating_mic: security.exchange_operating_mic, start_date: anything, end_date: anything)+ .in_sequence(fetch_sequence)+ .returns(provider_success_response([+ OpenStruct.new(security: security, date: trade_date, price: 110, currency: "USD")+ ]))++ @provider.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Apple", logo_url: nil)))++ @provider.expects(:fetch_exchange_rates)+ .with(from: "USD", to: "EUR", start_date: trade_date - EXCHANGE_RATE_BUFFER, end_date: end_date)+ .once+ .in_sequence(fetch_sequence)+ .returns(provider_success_response([+ OpenStruct.new(from: "USD", to: "EUR", date: trade_date, rate: 0.9)+ ]))++ Account::MarketDataImporter.new(account).import_all++ assert ExchangeRate.where(from_currency: "USD", to_currency: "EUR", date: trade_date).exists?+ end++ test "ignores price currencies that only occur before the account needs prices" 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: "SHEL", exchange_operating_mic: "XLON")+ trade_date = 10.days.ago.to_date+ trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")+ account.entries.create!(name: "Buy SHEL", date: trade_date, amount: 100, currency: "USD", entryable: trade)++ # Older GBP prices from before this account traded the security, then USD prices+ Security::Price.create!(security: security, date: 2.years.ago.to_date, price: 20, currency: "GBP")+ Security::Price.create!(security: security, date: trade_date, price: 100, currency: "USD")++ @provider.expects(:fetch_exchange_rates).never++ Account::MarketDataImporter.new(account).import_exchange_rates+ end++ test "does not fetch exchange rates for security prices in the account currency" 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: "AAPL", exchange_operating_mic: "XNAS")+ trade = Trade.new(security: security, qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")+ account.entries.create!(name: "Buy AAPL", date: 10.days.ago.to_date, amount: 100, currency: "USD", entryable: trade)++ Security::Price.create!(security: security, date: 10.days.ago.to_date, price: 100, currency: "USD")++ @provider.expects(:fetch_exchange_rates).never++ Account::MarketDataImporter.new(account).import_exchange_rates+ end+test "syncs security prices for securities traded by the account" dofamily = Family.create!(name: "Smith", currency: "USD")