The personal finance app for everyone (by everyone)
Ruby
Date Yahoo Finance daily bars on the exchange's clock (#5122)
David Gil5de64a720fe7
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rbindex 2e24984b4e..0bcd1c8eb8 100644--- a/app/models/provider/yahoo_finance.rb+++ b/app/models/provider/yahoo_finance.rb@@ -334,14 +334,11 @@ class Provider::YahooFinance < Providerwith_provider_response dosymbol = normalize_symbol(symbol, exchange_operating_mic)validate_date_params!(start_date, end_date)- # Convert dates to Unix timestamps using UTC to ensure consistent epoch boundaries across timezones- period1 = start_date.to_time.utc.to_i- period2 = end_date.end_of_day.to_time.utc.to_i+ dates = start_date.to_date..end_date.to_datethrottle_requestdata = fetch_authenticated_chart(symbol, {- "period1" => period1,- "period2" => period2,+ **chart_period(dates),"interval" => "1d","includeAdjustedClose" => true})@@ -359,17 +356,21 @@ class Provider::YahooFinance < Providerraw_currency = chart_data.dig("meta", "currency")raw_currency ||= default_currency_for_exchange(meta_exchange) || "USD"+ zone = exchange_zone(chart_data)prices = []timestamps.each_with_index do |timestamp, index|close_price = closes[index]next if close_price.nil? # Skip days with no data (weekends, holidays)+ date = zone.at(timestamp).to_date+ next unless dates.cover?(date)+# Normalize currency and price to handle minor unitsnormalized_currency, normalized_price = normalize_currency_and_price(raw_currency, close_price.to_f)prices << Price.new(symbol: symbol,- date: Time.at(timestamp).utc.to_date,+ date: date,price: normalized_price,currency: normalized_currency,exchange_operating_mic: exchange_operating_mic@@ -820,9 +821,9 @@ class Provider::YahooFinance < Providerdef fetch_currency_pair_data(from, to, start_date, end_date)symbol = "#{from}#{to}=X"- fetch_chart_data(symbol, start_date, end_date, currency: to) do |timestamp, close_rate|+ fetch_chart_data(symbol, start_date, end_date, currency: to) do |date, close_rate|Rate.new(- date: Time.at(timestamp).utc.to_date,+ date: date,from: from,to: to,rate: close_rate.to_f@@ -832,9 +833,9 @@ class Provider::YahooFinance < Providerdef fetch_inverse_currency_pair_data(from, to, start_date, end_date)symbol = "#{to}#{from}=X"- rates = fetch_chart_data(symbol, start_date, end_date, currency: from) do |timestamp, close_rate|+ rates = fetch_chart_data(symbol, start_date, end_date, currency: from) do |date, close_rate|Rate.new(- date: Time.at(timestamp).utc.to_date,+ date: date,from: from,to: to,rate: (BigDecimal("1") / BigDecimal(close_rate.to_s)).round(12)@@ -889,17 +890,29 @@ class Provider::YahooFinance < Providerdataend+ # Yahoo reads the bounds as instants and picks sessions by their date, so+ # they are UTC midnights whatever the host's or the family's zone.+ def chart_period(dates)+ { "period1" => dates.begin.to_time(:utc).to_i, "period2" => dates.end.to_time(:utc).end_of_day.to_i }+ end++ # Yahoo stamps a daily bar with the time its session opens, which can fall+ # on the previous day in UTC: the ASX opens at 10:00 in Sydney, and London+ # FX sessions open at midnight local time, 23:00 UTC during summer time. A+ # bar's date is its date on the exchange's clock.+ def exchange_zone(chart_data)+ ActiveSupport::TimeZone[chart_data.dig("meta", "exchangeTimezoneName").to_s] || ActiveSupport::TimeZone["UTC"]+ end+# `currency` is what the quote must be in. Yahoo leaves it blank on some# scaled crosses: RUBGEL=X is GEL per 100 RUB, a 100x error once inverted.def fetch_chart_data(symbol, start_date, end_date, currency:, &block)- period1 = start_date.to_time.utc.to_i- period2 = end_date.end_of_day.to_time.utc.to_i+ dates = start_date.to_date..end_date.to_datebeginthrottle_requestdata = fetch_authenticated_chart(symbol, {- "period1" => period1,- "period2" => period2,+ **chart_period(dates),"interval" => "1d","includeAdjustedClose" => true})@@ -929,12 +942,16 @@ class Provider::YahooFinance < Providerquotes = chart_data.dig("indicators", "quote", 0) || {}closes = quotes["close"] || []+ zone = exchange_zone(chart_data)results = []timestamps.each_with_index do |timestamp, index|close_value = closes[index]next if close_value.nil? || close_value <= 0- results << block.call(timestamp, close_value)+ date = zone.at(timestamp).to_date+ next unless dates.cover?(date)++ results << block.call(date, close_value)endresults.sort_by(&:date)diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rbindex aef9893d75..04de7ab288 100644--- a/test/models/provider/yahoo_finance_test.rb+++ b/test/models/provider/yahoo_finance_test.rb@@ -414,6 +414,23 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCaseassert_in_delta 1 / 1.12, usd_eur.data.first.rate.to_f, 1e-9end+ # Yahoo stamps a daily bar with the time its session opens. London's FX+ # sessions open at midnight local time, which during summer time is 23:00 UTC+ # the day before.+ test "fetch_exchange_rates dates each bar on the exchange's calendar" do+ @provider.stubs(:throttle_request)+ chart = { "chart" => { "result" => [ {+ "meta" => { "currency" => "USD", "exchangeTimezoneName" => "Europe/London" },+ "timestamp" => [ Time.utc(2026, 6, 23, 23), Time.utc(2026, 6, 24, 23), Time.utc(2026, 6, 25, 23) ].map(&:to_i),+ "indicators" => { "quote" => [ { "close" => [ 1.11, 1.12, 1.13 ] } ] }+ } ] } }+ @provider.stubs(:fetch_authenticated_chart).with("EURUSD=X", anything).returns(chart)++ response = @provider.fetch_exchange_rates(from: "EUR", to: "USD", start_date: Date.new(2026, 6, 24), end_date: Date.new(2026, 6, 25))++ assert_equal [ [ Date.new(2026, 6, 24), 1.11 ], [ Date.new(2026, 6, 25), 1.12 ] ], response.data.map { |rate| [ rate.date, rate.rate.to_f ] }+ end+test "fetch_exchange_rates matches the quote currency regardless of case" do@provider.stubs(:throttle_request)date = Date.new(2026, 10, 22)@@ -753,6 +770,21 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCaseassert_instance_of Provider::YahooFinance::Error, response.errorend+ # The ASX opens at 10:00 in Sydney, 23:00 UTC the day before, and Yahoo+ # stamps each daily bar with that opening time.+ test "fetch_security_prices dates each bar on the exchange's calendar" do+ @provider.stubs(:throttle_request)+ @provider.stubs(:fetch_authenticated_chart).with("CBA.AX", anything).returns("chart" => { "result" => [ {+ "meta" => { "currency" => "AUD", "exchangeName" => "ASX", "exchangeTimezoneName" => "Australia/Sydney" },+ "timestamp" => [ Time.utc(2026, 11, 11, 23).to_i ],+ "indicators" => { "quote" => [ { "close" => [ 172.5 ] } ] }+ } ] })++ response = @provider.fetch_security_prices(symbol: "CBA.AX", start_date: Date.new(2026, 11, 12), end_date: Date.new(2026, 11, 12))++ assert_equal [ Date.new(2026, 11, 12) ], response.data.map(&:date)+ end+test "fetch_security_prices uses the Colombian Yahoo suffix once and COP fallback" dodate = Date.new(2024, 1, 15)chart_response = mock@@ -1315,7 +1347,7 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCasedef fx_chart(date, currency, close){ "chart" => { "result" => [ {"meta" => { "currency" => currency },- "timestamp" => [ date.to_time.utc.to_i ],+ "timestamp" => [ date.to_time(:utc).to_i ],"indicators" => { "quote" => [ { "close" => [ close ] } ] }} ] } }end