Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(securities): fall back to direct chart lookup when Yahoo search returns nothing (#3313)

jaysbeekay226d575b0a16
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rb
index a4aa8addb4..10ac95ac62 100644
--- a/app/models/provider/yahoo_finance.rb
+++ b/app/models/provider/yahoo_finance.rb
@@ -220,6 +220,12 @@ class Provider::YahooFinance < Provider
)
end
+ # Yahoo's search-suggest index has gaps for some instruments its own chart/quote
+ # backend still serves fine -- notably managed funds identified by codes like
+ # Australian APIR codes (e.g. VAN0111AU). When the index has nothing, try the
+ # query as a literal symbol against the chart endpoint before giving up.
+ securities = direct_symbol_fallback(symbol) if securities.empty?
+
securities = deduplicate_dual_listings(securities) unless exchange_operating_mic.present?
cache_result(cache_key, securities)
@@ -629,6 +635,69 @@ class Provider::YahooFinance < Provider
securities.reject { |s| dominated.include?(s.object_id) }
end
+ # Symbols Yahoo's search-suggest index simply doesn't carry (e.g. Australian
+ # APIR-coded managed funds like "VAN0111AU") still resolve fine against the
+ # chart endpoint used elsewhere in this class for price data. When the normal
+ # search returns nothing, treat the raw query as a literal symbol and see if
+ # Yahoo's chart backend recognizes it -- synthesizing a single search result
+ # from the chart's `meta` block if so, rather than reporting no match at all.
+ #
+ # Only attempted for query shapes that plausibly ARE a ticker (no spaces,
+ # reasonable length): a full-name search like "Vanguard High Growth Index"
+ # would just waste a request here since it was never going to resolve as a
+ # literal symbol either.
+ def direct_symbol_fallback(query)
+ symbol = query.to_s.strip.upcase
+ return [] if symbol.blank? || symbol.include?(" ") || !symbol.match?(/\A[A-Z0-9.\-]{1,20}\z/)
+
+ # Require an exchange-qualified symbol (e.g. "VAN0111AU.AX"), not a bare
+ # one (e.g. "XYZ"). A bare ticker missing from Yahoo's search index would
+ # normally mean "no match" -- but the chart endpoint resolves bare tickers
+ # too, and some of those are real, unrelated securities (e.g. "XYZ" is
+ # NYSE-listed Block, Inc.), which would surface as a surprising spurious
+ # match for what the user actually typed. A plain, indexable ticker like
+ # that already resolves via the primary search above; this fallback exists
+ # for suffixed, non-US-style symbols the index has gaps for.
+ return [] unless symbol.match?(/\A[A-Z0-9\-]+\.[A-Z0-9\-]+\z/)
+
+ throttle_request
+ data = fetch_authenticated_chart(symbol, { "interval" => "1d", "range" => "5d" })
+ return [] if data.dig("chart", "error").present?
+
+ meta = data.dig("chart", "result", 0, "meta")
+ return [] if meta.blank?
+
+ # "YHD" is Yahoo's generic placeholder exchange, used for many instruments
+ # (like managed funds) that aren't tied to a real exchange in Yahoo's data.
+ # map_exchange_mic maps "YHD" to "XNAS" (NASDAQ) as a guess for regular
+ # search results, on the assumption an unrecognized US-style ticker is
+ # probably NASDAQ-listed -- that assumption doesn't hold here, since this
+ # fallback exists specifically for non-US instruments the search index
+ # missed (e.g. an Australian managed fund). Leave the MIC nil instead of
+ # applying that guess. Security::Resolver already treats a blank MIC as
+ # "unknown", not as one that fails to match.
+ yahoo_exchange = meta["exchangeName"]
+ mic = yahoo_exchange == "YHD" ? nil : map_exchange_mic(yahoo_exchange)
+
+ [
+ Security.new(
+ symbol: meta["symbol"] || symbol,
+ name: meta["longName"] || meta["shortName"] || symbol,
+ logo_url: nil,
+ exchange_operating_mic: mic,
+ country_code: mic.present? ? ::Security::EXCHANGES.dig(mic, "country") : nil,
+ currency: meta["currency"]
+ )
+ ]
+ rescue => e
+ # Best-effort only: this fallback exists purely to find something the
+ # primary search missed. Any failure here (auth, rate limit, network,
+ # malformed response) should degrade to "no fallback match" rather than
+ # turn an otherwise-successful (if empty) search into an error response.
+ Rails.logger.warn("Yahoo Finance direct symbol fallback failed for #{symbol}: #{e.class} - #{e.message}")
+ []
+ end
+
# ================================
# Validation
# ================================
diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rb
index fab174fadd..107fa8bdb4 100644
--- a/test/models/provider/yahoo_finance_test.rb
+++ b/test/models/provider/yahoo_finance_test.rb
@@ -513,6 +513,116 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_equal "DE", results_by_symbol.fetch("FALLBACK").country_code
end
+ test "search_securities falls back to a direct chart lookup when the search index has no results" do
+ empty_search_response = mock
+ empty_search_response.stubs(:body).returns('{"quotes":[]}')
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(empty_search_response)
+
+ chart_response = mock
+ chart_response.stubs(:body).returns({
+ chart: {
+ result: [ {
+ meta: {
+ symbol: "VAN0111AU.AX",
+ exchangeName: "YHD",
+ currency: "AUD",
+ longName: "Vanguard High Growth Index"
+ }
+ } ]
+ }
+ }.to_json)
+ chart_client = mock
+ chart_client.expects(:get).with(regexp_matches(%r{/v8/finance/chart/VAN0111AU\.AX$})).returns(chart_response)
+ @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie", "crumb" ])
+ @provider.stubs(:authenticated_client).with("cookie").returns(chart_client)
+ @provider.stubs(:throttle_request)
+
+ response = @provider.search_securities("VAN0111AU.AX")
+
+ assert response.success?
+ security = response.data.sole
+ assert_equal "VAN0111AU.AX", security.symbol
+ assert_equal "Vanguard High Growth Index", security.name
+ assert_equal "AUD", security.currency
+ # "YHD" is Yahoo's generic placeholder exchange -- it must NOT be guessed
+ # as NASDAQ (map_exchange_mic's default for unrecognized US-style tickers)
+ # for a fallback result, since this path exists for non-US instruments.
+ assert_nil security.exchange_operating_mic
+ assert_nil security.country_code
+ end
+
+ test "search_securities direct chart fallback returns no results when the symbol doesn't exist" do
+ empty_search_response = mock
+ empty_search_response.stubs(:body).returns('{"quotes":[]}')
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(empty_search_response)
+
+ not_found_response = mock
+ not_found_response.stubs(:body).returns({ chart: { result: nil, error: { code: "Not Found" } } }.to_json)
+ chart_client = mock
+ chart_client.stubs(:get).returns(not_found_response)
+ @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie", "crumb" ])
+ @provider.stubs(:authenticated_client).with("cookie").returns(chart_client)
+ @provider.stubs(:throttle_request)
+
+ response = @provider.search_securities("NOTAREAL.XX")
+
+ assert response.success?
+ assert_equal [], response.data
+ end
+
+ test "search_securities does not attempt a direct chart fallback for a bare (non-exchange-qualified) symbol" do
+ empty_search_response = mock
+ empty_search_response.stubs(:body).returns('{"quotes":[]}')
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(empty_search_response)
+
+ # "XYZ" is a real, unrelated NYSE ticker (Block, Inc.) that the chart
+ # endpoint would happily resolve -- but a bare symbol missing from Yahoo's
+ # own search index should not surface a surprising spurious match. If the
+ # fallback fired here, this would raise (unstubbed method call) rather
+ # than silently pass.
+ @provider.expects(:fetch_cookie_and_crumb).never
+
+ response = @provider.search_securities("XYZ")
+
+ assert response.success?
+ assert_equal [], response.data
+ end
+
+ test "search_securities does not attempt a direct chart fallback for multi-word queries" do
+ empty_search_response = mock
+ empty_search_response.stubs(:body).returns('{"quotes":[]}')
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(empty_search_response)
+
+ # No chart client stub at all -- if the fallback fired for a multi-word
+ # query, this would raise (unstubbed method call) rather than silently pass.
+ @provider.expects(:fetch_cookie_and_crumb).never
+
+ response = @provider.search_securities("Vanguard High Growth Index")
+
+ assert response.success?
+ assert_equal [], response.data
+ end
+
+ test "search_securities does not run the direct chart fallback when normal search already found results" do
+ search_response = mock
+ search_response.stubs(:body).returns({
+ quotes: [ { symbol: "AAPL", shortname: "Apple", exchange: "NMS", exchDisp: "NASDAQ" } ]
+ }.to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(search_response)
+
+ @provider.expects(:fetch_cookie_and_crumb).never
+
+ response = @provider.search_securities("AAPL")
+
+ assert response.success?
+ assert_equal [ "AAPL" ], response.data.map(&:symbol)
+ end
+
# ================================
# Security Price Tests
# ================================