The personal finance app for everyone (by everyone)
Ruby
class ExchangeRate::Importer
MissingExchangeRateError = Class.new(StandardError)
MissingStartRateError = Class.new(StandardError)
PROVISIONAL_LOOKBACK_DAYS = 5
def initialize(exchange_rate_provider:, from:, to:, start_date:, end_date:, clear_cache: false, provider_name: ExchangeRate.provider_name)
@exchange_rate_provider = exchange_rate_provider
@current_provider_name = provider_name
@from = from
@to = to
@start_date = start_date
@end_date = normalize_end_date(end_date)
@clear_cache = clear_cache
end
def import_provider_rates
if !clear_cache && all_rates_exist?
Rails.logger.info("No new rates to sync for #{from} to #{to} between #{start_date} and #{end_date}, skipping")
backfill_inverse_rates_if_needed
return
end
if provider_rates.empty?
Rails.logger.warn("Could not fetch rates for #{from} to #{to} between #{start_date} and #{end_date} because provider returned no rates")
return
end
prev_rate_value = start_rate_value
# Always find the earliest valid provider rate for pair metadata tracking.
# record_first_provider_rate_on's atomic guard prevents moving the date forward.
earliest_valid_provider_date = provider_rates.values
.select { |r| r.rate.present? && r.rate.to_f > 0 }
.min_by(&:date)&.date
# When no anchor rate exists, advance the loop start to the earliest provider rate
loop_start_date = fill_start_date
if prev_rate_value.blank? && earliest_valid_provider_date
earliest_rate = provider_rates[earliest_valid_provider_date]
Rails.logger.info(
"#{from}->#{to}: no provider rate on or before #{start_date}; " \
"advancing gapfill start to earliest valid provider date #{earliest_valid_provider_date}"
)
prev_rate_value = earliest_rate.rate
loop_start_date = earliest_valid_provider_date
end
unless prev_rate_value.present?
error = MissingStartRateError.new("Could not find a start rate for #{from} to #{to} between #{start_date} and #{end_date}")
Rails.logger.error(error.message)
Sentry.capture_exception(error)
return
end
# Gapfill with LOCF strategy (last observation carried forward):
# when the provider returns nothing for weekends/holidays, carry the previous rate.
gapfilled_rates = loop_start_date.upto(end_date).map do |date|
db_rate_value = db_rates[date]&.rate
provider_rate_value = provider_rates[date]&.rate
# A cache clear replaces the stored rates the provider covers, so the
# dates it skips carry its last rate forward rather than keep the old
# value. Stored history before the provider's first rate is kept.
replace_db_rate = clear_cache && earliest_valid_provider_date.present? && date >= earliest_valid_provider_date
chosen_rate = if provider_rate_value.present? && provider_rate_value.to_f > 0
provider_rate_value
elsif !replace_db_rate && db_rate_value.present? && db_rate_value.to_f > 0
db_rate_value
else
prev_rate_value
end
prev_rate_value = chosen_rate
{
from_currency: from,
to_currency: to,
date: date,
rate: chosen_rate
}
end
upsert_rows(gapfilled_rates)
# Compute and upsert inverse rates (e.g., EUR→USD from USD→EUR) to avoid
# separate API calls for the reverse direction.
inverse_rates = gapfilled_rates.filter_map do |row|
next if row[:rate].to_f <= 0
inverse = inverse_rate(row[:rate])
next unless inverse
{
from_currency: row[:to_currency],
to_currency: row[:from_currency],
date: row[:date],
rate: inverse
}
end
upsert_rows(inverse_rates)
# Backfill inverse rows for any forward rates that existed in the DB
# before the loop range (i.e. dates not covered by gapfilled_rates).
backfill_inverse_rates_if_needed
if earliest_valid_provider_date.present?
ExchangeRatePair.record_first_provider_rate_on(
from: from, to: to, date: earliest_valid_provider_date,
provider_name: current_provider_name
)
end
ensure
# Rows already written stay written, so on every way out.
refresh_balances
end
private
attr_reader :exchange_rate_provider, :from, :to, :start_date, :end_date, :clear_cache, :current_provider_name
def upsert_rows(rows)
batch_size = 200
total_upsert_count = 0
rows.each_slice(batch_size) do |batch|
# xmax is 0 only on a row the upsert inserted rather than updated.
upserted = ExchangeRate.upsert_all(
batch,
unique_by: %i[from_currency to_currency date],
returning: Arel.sql("from_currency, to_currency, date, created_at, (xmax = 0) AS inserted")
)
upserted.each do |row|
next unless ActiveModel::Type::Boolean.new.cast(row["inserted"])
inserted_rates << {
from: row["from_currency"], to: row["to_currency"], date: row["date"].to_date,
stored_at: ExchangeRate.type_for_attribute(:created_at).deserialize(row["created_at"])
}
end
total_upsert_count += upserted.count
end
total_upsert_count
end
def inserted_rates
@inserted_rates ||= []
end
# A rate stored where there was none is one a balance had to do without
# (ExchangeRate::BalanceRefresh). An updated row was already usable: the
# table refuses a rate that is not positive.
def refresh_balances
return if inserted_rates.empty?
ExchangeRate::BalanceRefresh.enqueue(inserted_rates, source: "ExchangeRate::Importer", provider: current_provider_name)
end
def start_rate_value
if fill_start_date == start_date
provider_rate_value = latest_valid_provider_rate(before_or_on: start_date)
db_rate_value = db_rates[start_date]&.rate
return provider_rate_value if provider_rate_value.present?
return db_rate_value if db_rate_value.present? && db_rate_value.to_f > 0
return nil
end
cutoff_date = fill_start_date
provider_rate_value = latest_valid_provider_rate(before: cutoff_date)
return provider_rate_value if provider_rate_value.present?
ExchangeRate
.where(from_currency: from, to_currency: to)
.where("date < ?", cutoff_date)
.where("rate > 0")
.order(date: :desc)
.limit(1)
.pick(:rate)
end
# Scans provider_rates for the most recent entry with a positive rate,
# rather than just picking the latest row (which could be zero/nil).
def latest_valid_provider_rate(before_or_on: nil, before: nil)
cutoff = before_or_on || before
comparator = before_or_on ? :<= : :<
provider_rates
.select { |date, r| date.send(comparator, cutoff) && r.rate.present? && r.rate.to_f > 0 }
.max_by { |date, _| date }&.last&.rate
end
def clamped_start_date
@clamped_start_date ||= begin
listed = exchange_rate_pair.first_provider_rate_on
listed.present? && listed > start_date ? listed : start_date
end
end
def exchange_rate_pair
@exchange_rate_pair ||= ExchangeRatePair.for_pair(from: from, to: to, provider_name: current_provider_name)
end
def fill_start_date
@fill_start_date ||= [ provider_fetch_start_date, effective_start_date ].max
end
def provider_fetch_start_date
@provider_fetch_start_date ||= begin
base = effective_start_date - PROVISIONAL_LOOKBACK_DAYS.days
max_days = exchange_rate_provider.respond_to?(:max_history_days) ? exchange_rate_provider.max_history_days : nil
if max_days && (end_date - base).to_i > max_days
clamped = end_date - max_days.days
Rails.logger.info(
"#{exchange_rate_provider.class.name} max history is #{max_days} days; " \
"clamping #{from}->#{to} start_date from #{base} to #{clamped}"
)
clamped
else
base
end
end
end
def effective_start_date
return start_date if clear_cache
(clamped_start_date..end_date).detect { |d| !db_rates.key?(d) } || end_date
end
def provider_rates
@provider_rates ||= begin
provider_response = exchange_rate_provider.fetch_exchange_rates(
from: from,
to: to,
start_date: provider_fetch_start_date,
end_date: end_date
)
if provider_response.success? && provider_response.data.present?
ExchangeRatePair.record_direct_quote(from: from, to: to, provider_name: current_provider_name)
Rails.logger.debug("Fetched #{provider_response.data.size} rates from #{exchange_rate_provider.class.name} for #{from}/#{to} between #{provider_fetch_start_date} and #{end_date}")
provider_response.data.index_by(&:date)
elsif (crossed = usd_cross_rates(provider_response.error)).any?
crossed.index_by(&:date)
elsif provider_response.success?
{} # No rates at all; import_provider_rates logs that.
else
message = "#{exchange_rate_provider.class.name} could not fetch exchange rate pair from: #{from} to: #{to} between: #{effective_start_date} and: #{Date.current}. Provider error: #{provider_response.error.message}"
Rails.logger.warn(message)
Sentry.capture_exception(MissingExchangeRateError.new(message), level: :warning)
{}
end
end
end
# The provider has no such pair, but it may still quote both USD legs.
def usd_cross_rates(error)
ExchangeRate::UsdCross.new(exchange_rate_provider)
.rates(from: from, to: to, start_date: provider_fetch_start_date, end_date: end_date, error: error)
end
def backfill_inverse_rates_if_needed
existing_inverse_dates = ExchangeRate.where(from_currency: to, to_currency: from, date: clamped_start_date..end_date).pluck(:date).to_set
return if existing_inverse_dates.size >= expected_count
inverse_rows = db_rates.filter_map do |_date, rate|
next if existing_inverse_dates.include?(rate.date)
next if rate.rate.to_f <= 0
inverse = inverse_rate(rate.rate)
next unless inverse
{
from_currency: to,
to_currency: from,
date: rate.date,
rate: inverse
}
end
upsert_rows(inverse_rows) if inverse_rows.any?
end
# Inverses are stored to 12 decimal places, so a forward rate above 1e12
# rounds its inverse to zero. That pair is skipped rather than stored as the
# zero rate ExchangeRate.valid_rate? rejects.
def inverse_rate(rate)
inverse = (BigDecimal("1") / BigDecimal(rate.to_s)).round(12)
inverse if ExchangeRate.valid_rate?(inverse)
end
def all_rates_exist?
db_count == expected_count
end
def expected_count
(clamped_start_date..end_date).count
end
def db_count
ExchangeRate
.where(from_currency: from, to_currency: to, date: clamped_start_date..end_date)
.count
end
def db_rates
@db_rates ||= ExchangeRate.where(from_currency: from, to_currency: to, date: start_date..end_date)
.order(:date)
.to_a
.index_by(&:date)
end
# Normalizes an end date so that it never exceeds today's date in the
# America/New_York timezone.
def normalize_end_date(requested_end_date)
today_est = Date.current.in_time_zone("America/New_York").to_date
[ requested_end_date, today_est ].min
end
end