Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fall back to Yahoo Finance for securities providers without a key (#5318)

jaysbeekay44195def95ee
diff --git a/app/models/security/provided.rb b/app/models/security/provided.rb
index 7fae4ad528..f6fd1bf117 100644
--- a/app/models/security/provided.rb
+++ b/app/models/security/provided.rb
@@ -3,13 +3,25 @@ module Security::Provided
SecurityInfoMissingError = Class.new(StandardError)
+ # Needs no API key, so it can stand in for an enabled provider that can't be built
+ KEYLESS_FALLBACK_PROVIDER = "yahoo_finance"
+
class_methods do
- # Returns all enabled and configured securities providers
+ # Returns all enabled and configured securities providers. When the first
+ # enabled provider can't be built (e.g. no API key), the keyless Yahoo
+ # Finance provider takes its place, unless that is already enabled. Only
+ # the first position is substituted, so the substitute is always the
+ # default for securities without an assigned provider.
def providers
- Setting.enabled_securities_providers.filter_map do |name|
- Provider::Registry.for_concept(:securities).get_provider(name.to_sym)
- rescue Provider::Registry::Error
- nil
+ names = Setting.enabled_securities_providers
+ substitute = !names.include?(KEYLESS_FALLBACK_PROVIDER)
+
+ names.each_with_index.filter_map do |name, index|
+ provider = build_provider(name)
+ next provider if provider || !substitute || index.positive?
+
+ log_keyless_substitution(name)
+ build_provider(KEYLESS_FALLBACK_PROVIDER)
end
end
@@ -84,17 +96,26 @@ module Security::Provided
end
provider_key = provider_key_for(active_providers[idx])
+ # The keyless substitute's key is never stored, so a security found
+ # through it follows providers.first and moves to the configured
+ # provider once that can be built. Its ticker is stored without Yahoo's
+ # exchange suffix (SAP.DE becomes SAP on XETR), so that provider gets
+ # the symbol it expects; Yahoo re-adds the suffix from the MIC.
+ keyless_substitute = provider_key == KEYLESS_FALLBACK_PROVIDER && !Setting.enabled_securities_providers.include?(KEYLESS_FALLBACK_PROVIDER)
+ provider_key = nil if keyless_substitute
provider_results.each do |ps|
+ ticker = keyless_substitute ? strip_yahoo_suffix(ps[:symbol], ps[:exchange_operating_mic]) : ps[:symbol]
+
# Dedup key includes provider so the same ticker on the same exchange can
# appear once per provider — the user picks which provider's price feed
# they want and that choice is stored in price_provider.
- dedup_key = "#{ps[:symbol]}|#{ps[:exchange_operating_mic]}|#{provider_key}".upcase
+ dedup_key = "#{ticker}|#{ps[:exchange_operating_mic]}|#{provider_key}".upcase
next if seen_keys.include?(dedup_key)
seen_keys.add(dedup_key)
security = Security.new(
- ticker: ps[:symbol],
+ ticker: ticker,
name: ps[:name],
logo_url: ps[:logo_url],
exchange_operating_mic: ps[:exchange_operating_mic],
@@ -115,6 +136,24 @@ module Security::Provided
end
private
+ def build_provider(name)
+ Provider::Registry.for_concept(:securities).get_provider(name.to_sym)
+ rescue Provider::Registry::Error
+ nil
+ end
+
+ def strip_yahoo_suffix(symbol, exchange_operating_mic)
+ suffix = Provider::YahooFinance::EXCHANGE_CONFIG.dig(exchange_operating_mic, :yahoo_suffix)
+ suffix && symbol.end_with?(suffix) ? symbol.delete_suffix(suffix) : symbol
+ end
+
+ def log_keyless_substitution(name)
+ @logged_keyless_substitutions ||= Concurrent::Set.new
+ return unless @logged_keyless_substitutions.add?(name)
+
+ Rails.logger.info("Securities provider #{name} can't be built; using #{KEYLESS_FALLBACK_PROVIDER} in its place")
+ end
+
def provider_key_for(provider_instance)
provider_instance.class.name.demodulize.underscore
end
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index cabd4f5378..ed7b82098a 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -8,6 +8,25 @@ class FamilyTest < ActiveSupport::TestCase
@syncable = families(:dylan_family)
end
+ test "missing_data_provider? is false under the keyless securities fallback" do
+ family = Family.create!(name: "Fallback", currency: "USD")
+ account = family.accounts.create!(name: "Brokerage", currency: "USD", balance: 0, accountable: Investment.new)
+ trade = Trade.new(security: securities(:aapl), qty: 1, price: 100, currency: "USD", investment_activity_label: "Buy")
+ account.entries.create!(name: "Buy AAPL", date: 1.day.ago.to_date, amount: 100, currency: "USD", entryable: trade)
+
+ yahoo = mock("yahoo_finance")
+ yahoo.stubs(:class).returns(Provider::YahooFinance)
+ Provider::Registry.stubs(:yahoo_finance).returns(yahoo)
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
+ Setting.stubs(:twelve_data_api_key).returns(nil)
+
+ with_env_overrides("TWELVE_DATA_API_KEY" => nil) do
+ assert family.requires_securities_data_provider?
+ assert_not family.requires_exchange_rates_data_provider?
+ assert_not family.missing_data_provider?
+ end
+ end
+
test "local_date is the date in the family's zone" do
family = families(:dylan_family)
evening_utc = Time.utc(2026, 1, 15, 19, 0, 0)
diff --git a/test/models/market_data_importer_test.rb b/test/models/market_data_importer_test.rb
index 9e33f2bb17..ed85e57597 100644
--- a/test/models/market_data_importer_test.rb
+++ b/test/models/market_data_importer_test.rb
@@ -241,6 +241,30 @@ class MarketDataImporterTest < ActiveSupport::TestCase
MarketDataImporter.new(mode: :full).import_security_prices
end
+ test "imports security prices under the keyless fallback" do
+ security = 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")
+
+ yahoo = mock("yahoo_finance")
+ yahoo.stubs(:class).returns(Provider::YahooFinance)
+ Provider::Registry.any_instance.stubs(:get_provider).with(:twelve_data).returns(nil)
+ Provider::Registry.any_instance.stubs(:get_provider).with(:yahoo_finance).returns(yahoo)
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
+
+ yahoo.expects(:fetch_security_prices).returns(provider_success_response([
+ OpenStruct.new(security: security, date: snapshot_start_date, price: 100, currency: "USD")
+ ]))
+ yahoo.stubs(:fetch_security_info).returns(provider_success_response(OpenStruct.new(name: "Apple", logo_url: "logo")))
+
+ MarketDataImporter.new(mode: :snapshot).import_security_prices
+
+ assert_equal 1, Security::Price.where(security: security, date: snapshot_start_date).count
+ end
+
private
def snapshot_start_date
MarketDataImporter::SNAPSHOT_DAYS.days.ago.to_date
diff --git a/test/models/security/provided_test.rb b/test/models/security/provided_test.rb
index 13439bc041..5292f14d4e 100644
--- a/test/models/security/provided_test.rb
+++ b/test/models/security/provided_test.rb
@@ -5,6 +5,7 @@ class Security::ProvidedTest < ActiveSupport::TestCase
setup do
@security = securities(:aapl)
+ Security.instance_variable_set(:@logged_keyless_substitutions, nil)
end
# --- search_provider ---
@@ -33,6 +34,7 @@ class Security::ProvidedTest < ActiveSupport::TestCase
)
Security.stubs(:providers).returns([ provider_a, provider_b ])
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data", "yahoo_finance" ])
results = Security.search_provider("AAPL")
@@ -267,6 +269,165 @@ class Security::ProvidedTest < ActiveSupport::TestCase
assert_equal :ok, @security.provider_status
end
+ # --- keyless fallback ---
+
+ test "providers falls back to Yahoo Finance when no enabled provider can be built" do
+ yahoo = stub_yahoo_finance
+ Rails.logger.stubs(:info)
+ Rails.logger.expects(:info).with(regexp_matches(/twelve_data can't be built; using yahoo_finance/)).once
+
+ without_securities_keys([ "twelve_data" ]) do
+ assert_equal [ yahoo ], Security.providers
+ end
+ end
+
+ test "no fallback when a Twelve Data key is present" do
+ Provider::Registry.expects(:yahoo_finance).never
+ Rails.logger.stubs(:info)
+ Rails.logger.expects(:info).with(regexp_matches(/can't be built/)).never
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
+
+ with_env_overrides("TWELVE_DATA_API_KEY" => "test-key") do
+ assert_equal [ Provider::TwelveData ], Security.providers.map(&:class)
+ end
+ end
+
+ test "the substitute keeps the default's position" do
+ yahoo = stub_yahoo_finance
+
+ without_securities_keys([ "twelve_data", "binance_public" ]) do
+ providers = Security.providers
+
+ assert_equal yahoo, providers.first
+ assert_equal [ Provider::YahooFinance, Provider::BinancePublic ], providers.map(&:class)
+ end
+ end
+
+ test "only one substitute" do
+ yahoo = stub_yahoo_finance
+
+ without_securities_keys([ "twelve_data", "tiingo" ]) do
+ assert_equal [ yahoo ], Security.providers
+ end
+ end
+
+ test "no substitute when the unbuildable provider is not first" do
+ Provider::Registry.expects(:yahoo_finance).never
+ Rails.logger.stubs(:info)
+ Rails.logger.expects(:info).with(regexp_matches(/can't be built/)).never
+
+ without_securities_keys([ "mfapi", "twelve_data" ]) do
+ assert_equal [ Provider::Mfapi ], Security.providers.map(&:class)
+ end
+ end
+
+ test "the substitution is logged once per process" do
+ stub_yahoo_finance
+ messages = []
+ Rails.logger.stubs(:info).with { |message| messages << message }
+
+ without_securities_keys([ "twelve_data" ]) do
+ 3.times { Security.providers }
+ end
+
+ assert_equal 1, messages.grep(/twelve_data can't be built/).size
+ end
+
+ test "no substitute when Yahoo is explicitly enabled" do
+ yahoo = stub_yahoo_finance
+ yahoo.stubs(:search_securities).returns(provider_success_response([ search_result("AAPL") ]))
+
+ without_securities_keys([ "twelve_data", "yahoo_finance" ]) do
+ assert_equal [ yahoo ], Security.providers
+ assert_equal [ "yahoo_finance" ], Security.search_provider("AAPL").map(&:price_provider)
+ end
+ end
+
+ test "no fallback when the enabled list is explicitly empty" do
+ Provider::Registry.expects(:yahoo_finance).never
+
+ without_securities_keys([]) do
+ assert_equal [], Security.providers
+ end
+ end
+
+ test "search under the fallback stamps no price_provider" do
+ yahoo = stub_yahoo_finance
+ yahoo.stubs(:search_securities).returns(provider_success_response([ search_result("AAPL") ]))
+
+ without_securities_keys([ "twelve_data" ]) do
+ results = Security.search_provider("AAPL")
+
+ assert_equal [ "AAPL" ], results.map(&:ticker)
+ assert_nil results.first.price_provider
+ option = results.first.to_combobox_option
+ assert_equal "AAPL|XNAS|", option.id
+ end
+ end
+
+ test "search under the fallback stores a Yahoo-suffixed listing by its bare ticker" do
+ yahoo = stub_yahoo_finance
+ yahoo.stubs(:search_securities).returns(provider_success_response([
+ search_result("SAP.DE", mic: "XETR", country_code: "DE", currency: "EUR"),
+ search_result("BRK.B", mic: "XNYS")
+ ]))
+
+ without_securities_keys([ "twelve_data" ]) do
+ results = Security.search_provider("SAP").to_h { |s| [ s.exchange_operating_mic, s.ticker ] }
+
+ assert_equal({ "XETR" => "SAP", "XNYS" => "BRK.B" }, results)
+ end
+ end
+
+ test "an explicitly enabled Yahoo keeps its suffixed ticker" do
+ yahoo = stub_yahoo_finance
+ yahoo.stubs(:search_securities).returns(provider_success_response([
+ search_result("SAP.DE", mic: "XETR", country_code: "DE", currency: "EUR")
+ ]))
+
+ without_securities_keys([ "twelve_data", "yahoo_finance" ]) do
+ assert_equal [ "SAP.DE" ], Security.search_provider("SAP").map(&:ticker)
+ end
+ end
+
+ test "a keyless provider beside the substitute keeps its stamp" do
+ yahoo = stub_yahoo_finance
+ yahoo.stubs(:search_securities).returns(provider_success_response([ search_result("AAPL") ]))
+ mfapi = mock("mfapi")
+ mfapi.stubs(:class).returns(Provider::Mfapi)
+ mfapi.stubs(:search_securities).returns(provider_success_response([ search_result("AAPLMF") ]))
+ Provider::Registry.stubs(:mfapi).returns(mfapi)
+
+ without_securities_keys([ "twelve_data", "mfapi" ]) do
+ assert_equal [ yahoo, mfapi ], Security.providers
+
+ stamps = Security.search_provider("AAPL").to_h { |s| [ s.ticker, s.price_provider ] }
+ assert_equal({ "AAPL" => nil, "AAPLMF" => "mfapi" }, stamps)
+ end
+ end
+
+ test "an assigned twelve_data security stays unavailable under the fallback" do
+ stub_yahoo_finance
+ @security.update!(price_provider: "twelve_data")
+
+ without_securities_keys([ "twelve_data" ]) do
+ assert_nil @security.price_data_provider
+ assert_equal :provider_unavailable, @security.provider_status
+ end
+ end
+
+ test "the setting and configuration health are unchanged under the fallback" do
+ yahoo = stub_yahoo_finance
+ Setting.securities_providers = "twelve_data"
+ Setting.stubs(:twelve_data_api_key).returns(nil)
+
+ with_env_overrides("TWELVE_DATA_API_KEY" => nil, "SECURITIES_PROVIDERS" => nil, "SECURITIES_PROVIDER" => nil) do
+ assert_equal [ yahoo ], Security.providers
+ assert_equal [ "twelve_data" ], Setting.enabled_securities_providers
+ assert_equal :not_configured, ConfigurationHealth.new.securities.status
+ end
+ end
+
# --- rank_search_results ---
# Helper to build unsaved Security objects for ranking tests
@@ -283,6 +444,27 @@ class Security::ProvidedTest < ActiveSupport::TestCase
Security.send(:rank_search_results, results, query, country_code)
end
+ def stub_yahoo_finance
+ yahoo = mock("yahoo_finance")
+ yahoo.stubs(:class).returns(Provider::YahooFinance)
+ Provider::Registry.stubs(:yahoo_finance).returns(yahoo)
+ yahoo
+ end
+
+ def without_securities_keys(enabled, &block)
+ Setting.stubs(:enabled_securities_providers).returns(enabled)
+ Setting.stubs(:twelve_data_api_key).returns(nil)
+ Setting.stubs(:tiingo_api_key).returns(nil)
+ with_env_overrides("TWELVE_DATA_API_KEY" => nil, "TIINGO_API_KEY" => nil, &block)
+ end
+
+ def search_result(symbol, mic: "XNAS", country_code: "US", currency: "USD")
+ Provider::SecurityConcept::Security.new(
+ symbol: symbol, name: symbol, logo_url: nil,
+ exchange_operating_mic: mic, country_code: country_code, currency: currency
+ )
+ end
+
test "ranking: AAPL exact match ranks above AAPL-prefixed and unrelated" do
results = [
build_result(ticker: "AAPLX", name: "Some AAPL Fund"),
@@ -437,6 +619,9 @@ class Security::ProvidedTest < ActiveSupport::TestCase
]))
Security.stubs(:providers).returns([ without_isin, with_isin ])
+ # Yahoo is listed because it is enabled, not standing in for a keyless
+ # provider, so its ticker keeps the exchange suffix.
+ Setting.stubs(:enabled_securities_providers).returns([ "yahoo_finance", "eodhd" ])
results = Security.search_provider("IE00B579F325")
diff --git a/test/models/security/resolver_test.rb b/test/models/security/resolver_test.rb
index 34f9f4ae4a..2753a2b677 100644
--- a/test/models/security/resolver_test.rb
+++ b/test/models/security/resolver_test.rb
@@ -2,6 +2,8 @@ require "test_helper"
require "ostruct"
class Security::ResolverTest < ActiveSupport::TestCase
+ include ProviderTestHelper
+
test "resolves DB security" do
# Given an existing security in the DB that exactly matches the lookup params
db_security = Security.create!(ticker: "TSLA", exchange_operating_mic: "XNAS", country_code: "US")
@@ -498,4 +500,30 @@ class Security::ResolverTest < ActiveSupport::TestCase
assert_equal "NEOE", resolved.reload.exchange_operating_mic
end
end
+
+ test "a security resolved under the keyless fallback switches to Twelve Data once a key is added" do
+ yahoo = mock("yahoo_finance")
+ yahoo.stubs(:class).returns(Provider::YahooFinance)
+ yahoo.stubs(:search_securities).returns(provider_success_response([
+ Provider::SecurityConcept::Security.new(
+ symbol: "ZZYF", name: "Fallback Co", logo_url: nil,
+ exchange_operating_mic: "XNAS", country_code: "US", currency: "USD"
+ )
+ ]))
+ Provider::Registry.stubs(:yahoo_finance).returns(yahoo)
+ Setting.stubs(:enabled_securities_providers).returns([ "twelve_data" ])
+ Setting.stubs(:twelve_data_api_key).returns(nil)
+
+ resolved = with_env_overrides("TWELVE_DATA_API_KEY" => nil) do
+ Security::Resolver.new("ZZYF", exchange_operating_mic: "XNAS", country_code: "US").resolve.tap do |security|
+ assert_equal yahoo, security.price_data_provider
+ end
+ end
+
+ assert_nil resolved.reload.price_provider
+
+ with_env_overrides("TWELVE_DATA_API_KEY" => "test-key") do
+ assert_instance_of Provider::TwelveData, resolved.price_data_provider
+ end
+ end
end