Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(provider): resolve Tiingo security currency from countryCode (#2692)

Jestin J Palamuttame32417016075
diff --git a/app/models/provider/tiingo.rb b/app/models/provider/tiingo.rb
index 97c998e969..2b011b6d70 100644
--- a/app/models/provider/tiingo.rb
+++ b/app/models/provider/tiingo.rb
@@ -83,15 +83,40 @@ class Provider::Tiingo < Provider
raise Error, "Unexpected response format from search endpoint"
end
+ # Tiingo's daily-price endpoints are looked up by ticker alone, so every
+ # result sharing a ticker resolves to the same priced entry (see
+ # best_match_for_ticker) and therefore the same currency. Resolve it once
+ # per unique ticker and reuse it both for caching (so fetch_security_prices
+ # can use it without a second search request) and for the Security objects
+ # below, so what's shown in search results always matches what
+ # fetch_security_prices will later return.
+ matches_by_ticker = parsed.filter_map { |security| security["ticker"] }.map(&:upcase).uniq.index_with do |ticker|
+ best_match_for_ticker(parsed, ticker)
+ end
+
+ currency_by_ticker = matches_by_ticker.transform_values { |match| currency_for_country(match&.dig("countryCode")) }
+
+ currency_by_ticker.each do |ticker, currency|
+ next if currency.blank?
+
+ cache_key = "tiingo:currency:#{ticker}"
+
+ # A ticker's daily-price endpoint is US-centric (see best_match_for_ticker),
+ # so a currency derived from a US match is authoritative. But a search
+ # query can return a result set that happens not to include the US
+ # cross-listing for an already-cached ticker (Tiingo's relevance ranking
+ # varies by query), and this loop runs on every search_securities call.
+ # Only overwrite a cached value when this result set's match is US, or
+ # nothing is cached yet - never downgrade a previously US-derived
+ # currency to one derived from a non-US match.
+ next if matches_by_ticker[ticker]&.dig("countryCode") != "US" && Rails.cache.read(cache_key).present?
+
+ Rails.cache.write(cache_key, currency, expires_in: 24.hours)
+ end
+
parsed.first(25).map do |security|
ticker = security["ticker"]
- currency = security["priceCurrency"]
-
- # Cache the API-returned currency so fetch_security_prices can use it
- # without making a second search request
- if currency.present? && ticker.present?
- Rails.cache.write("tiingo:currency:#{ticker.upcase}", currency, expires_in: 24.hours)
- end
+ currency = currency_by_ticker[ticker&.upcase]
Security.new(
symbol: ticker,
@@ -263,8 +288,8 @@ class Provider::Tiingo < Provider
check_api_error!(parsed)
if parsed.is_a?(Array)
- match = parsed.find { |s| s["ticker"]&.upcase == symbol.upcase }
- currency = match&.dig("priceCurrency")
+ match = best_match_for_ticker(parsed, symbol)
+ currency = currency_for_country(match&.dig("countryCode"))
if currency.present?
Rails.cache.write("tiingo:currency:#{symbol.upcase}", currency, expires_in: 24.hours)
@@ -280,6 +305,31 @@ class Provider::Tiingo < Provider
TIINGO_EXCHANGE_TO_MIC[exchange_name.strip] || exchange_name.strip
end
+ # Tiingo's search/utilities response never includes a priceCurrency field
+ # (confirmed against the live API), only countryCode. Resolve the currency
+ # via the countries gem's ISO 4217 data (already used for country
+ # resolution in Provider::TwelveData) instead of hand-maintaining a
+ # per-provider allowlist.
+ def currency_for_country(country_code)
+ return nil if country_code.blank?
+ ISO3166::Country.new(country_code.strip)&.currency_code
+ end
+
+ # Tiingo's search endpoint can return multiple entries sharing the exact
+ # same ticker - e.g. a US primary listing alongside a foreign
+ # cross-listing (confirmed live: searching "AAPL" returns both a US entry
+ # and a CA entry). The /tiingo/daily price endpoints this resolves
+ # currency for are US-centric (also confirmed live: a Canadian ticker
+ # like VFV has search metadata but no daily price history at all), so
+ # when a US entry exists for the ticker, that's the one actually backing
+ # the price data. Fall back to the first match otherwise.
+ def best_match_for_ticker(results, ticker)
+ return nil if ticker.blank?
+
+ matches = results.select { |s| s["ticker"]&.upcase == ticker.upcase }
+ matches.find { |s| s["countryCode"] == "US" } || matches.first
+ end
+
def check_api_error!(parsed)
return unless parsed.is_a?(Hash) && parsed["detail"].present?
diff --git a/test/models/provider/tiingo_test.rb b/test/models/provider/tiingo_test.rb
new file mode 100644
index 0000000000..506a19e28b
--- /dev/null
+++ b/test/models/provider/tiingo_test.rb
@@ -0,0 +1,265 @@
+require "test_helper"
+
+class Provider::TiingoTest < ActiveSupport::TestCase
+ setup do
+ @provider = Provider::Tiingo.new("test_api_key")
+ @provider.stubs(:throttle_request)
+ @provider.stubs(:track_symbol)
+ end
+
+ # Real response captured from Tiingo's /tiingo/utilities/search for VFV -
+ # note there is no priceCurrency field, only countryCode.
+ def vfv_search_body
+ [
+ {
+ "name" => "Vanguard S&P 500 Index ETF",
+ "ticker" => "VFV",
+ "permaTicker" => "CA000000140493",
+ "openFIGIComposite" => nil,
+ "assetType" => "ETF",
+ "isActive" => true,
+ "countryCode" => "CA"
+ }
+ ].to_json
+ end
+
+ def aapl_search_body
+ [
+ {
+ "name" => "Apple Inc",
+ "ticker" => "AAPL",
+ "permaTicker" => "US0000000123",
+ "assetType" => "Stock",
+ "isActive" => true,
+ "countryCode" => "US"
+ }
+ ].to_json
+ end
+
+ # Real response captured from Tiingo's /tiingo/utilities/search for AAPL -
+ # Tiingo returns two entries sharing the exact same ticker, a CA
+ # cross-listing (no openFIGIComposite) and the real US primary listing.
+ # The CA entry appears first in the array.
+ def aapl_duplicate_ticker_search_body
+ [
+ {
+ "name" => "Apple Inc",
+ "ticker" => "AAPL",
+ "permaTicker" => "CA000000137372",
+ "openFIGIComposite" => nil,
+ "assetType" => "Stock",
+ "isActive" => true,
+ "countryCode" => "CA"
+ },
+ {
+ "name" => "Apple Inc",
+ "ticker" => "AAPL",
+ "permaTicker" => "US000000000038",
+ "openFIGIComposite" => "BBG000B9XRY4",
+ "assetType" => "Stock",
+ "isActive" => true,
+ "countryCode" => "US"
+ }
+ ].to_json
+ end
+
+ def stub_client_get(body)
+ mock_response = mock
+ mock_response.stubs(:body).returns(body)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(mock_response)
+ mock_client
+ end
+
+ # ================================
+ # search_securities
+ # ================================
+
+ test "search_securities resolves USD for a US security with no priceCurrency field" do
+ stub_client_get(aapl_search_body)
+
+ result = @provider.search_securities("AAPL")
+
+ assert result.success?
+ security = result.data.first
+ assert_equal "AAPL", security.symbol
+ assert_equal "USD", security.currency
+ end
+
+ test "search_securities resolves CAD for a Canadian security via countryCode (VFV)" do
+ stub_client_get(vfv_search_body)
+
+ result = @provider.search_securities("VFV")
+
+ assert result.success?
+ security = result.data.first
+ assert_equal "VFV", security.symbol
+ assert_equal "CAD", security.currency
+ assert_equal "CA", security.country_code
+ end
+
+ test "search_securities resolves currency for a country outside the old hardcoded allowlist (FR)" do
+ body = [
+ { "name" => "Some Fund", "ticker" => "XYZ", "assetType" => "ETF", "isActive" => true, "countryCode" => "FR" }
+ ].to_json
+ stub_client_get(body)
+
+ result = @provider.search_securities("XYZ")
+
+ assert result.success?
+ assert_equal "EUR", result.data.first.currency
+ end
+
+ test "search_securities does not populate currency for an unrecognized country code" do
+ body = [
+ { "name" => "Some Fund", "ticker" => "XYZ", "assetType" => "ETF", "isActive" => true, "countryCode" => "ZZ" }
+ ].to_json
+ stub_client_get(body)
+
+ result = @provider.search_securities("XYZ")
+
+ assert result.success?
+ assert_nil result.data.first.currency
+ end
+
+ test "search_securities resolves the same US-listed currency for every entry sharing a ticker across multiple countries (AAPL)" do
+ stub_client_get(aapl_duplicate_ticker_search_body)
+
+ result = @provider.search_securities("AAPL")
+
+ assert result.success?
+ # Both the CA and US entries share ticker AAPL, and Tiingo's daily-price
+ # endpoint is looked up by ticker alone, so both must show the same
+ # currency that actually backs the price data (USD, from the US entry) -
+ # not each entry's own countryCode - otherwise the currency shown here
+ # would disagree with what fetch_security_prices later returns.
+ assert_equal [ "USD", "USD" ], result.data.map(&:currency)
+ end
+
+ test "search_securities caches the US-listed currency for a ticker with multiple country matches, not just the first array entry" do
+ # Test env uses cache_store = :null_store; swap in a real store to inspect
+ # what actually gets cached.
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ stub_client_get(aapl_duplicate_ticker_search_body)
+
+ @provider.search_securities("AAPL")
+
+ assert_equal "USD", Rails.cache.read("tiingo:currency:AAPL")
+ end
+
+ test "search_securities does not downgrade a cached US-derived currency when a later search for the same ticker omits the US entry" do
+ # Test env uses cache_store = :null_store; swap in a real store so the
+ # cache write from the first search actually persists for the second.
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+
+ stub_client_get(aapl_duplicate_ticker_search_body)
+ @provider.search_securities("AAPL") # caches USD from the US entry
+ assert_equal "USD", Rails.cache.read("tiingo:currency:AAPL")
+
+ # A later search for the same ticker returns a result set that only
+ # includes the CA cross-listing (e.g. a different query string surfaced
+ # by Tiingo's relevance ranking) - the cached USD (backing the real daily
+ # price data) must not be silently overwritten with CAD.
+ ca_only_body = [
+ {
+ "name" => "Apple Inc",
+ "ticker" => "AAPL",
+ "permaTicker" => "CA000000137372",
+ "openFIGIComposite" => nil,
+ "assetType" => "Stock",
+ "isActive" => true,
+ "countryCode" => "CA"
+ }
+ ].to_json
+ stub_client_get(ca_only_body)
+
+ result = @provider.search_securities("AAPL")
+
+ assert result.success?
+ assert_equal "USD", Rails.cache.read("tiingo:currency:AAPL")
+ end
+
+ # ================================
+ # fetch_security_prices
+ # ================================
+
+ test "fetch_security_prices resolves currency from the search-populated cache without a second request" do
+ # Test env uses cache_store = :null_store, so writes are no-ops - swap in a
+ # real in-memory store for this test to genuinely exercise the
+ # write-then-read cache path (matching real dev/production behavior),
+ # rather than always falling through to the fallback search.
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+
+ mock_client = stub_client_get(vfv_search_body)
+ @provider.search_securities("VFV") # populates the tiingo:currency:VFV cache entry
+
+ prices_body = [ { "date" => "2026-06-01T00:00:00.000Z", "close" => 100.5 } ].to_json
+ mock_response = mock
+ mock_response.stubs(:body).returns(prices_body)
+ # .expects(...).once (not .stubs) so this test fails loudly if a second
+ # request (the fallback search) is made - the cache hit should avoid it.
+ # client is private, so reuse the already-stubbed mock_client rather than
+ # calling @provider.client externally.
+ mock_client.expects(:get).once.returns(mock_response)
+
+ result = @provider.fetch_security_prices(symbol: "VFV", start_date: Date.new(2026, 6, 1), end_date: Date.new(2026, 6, 1))
+
+ assert result.success?, "expected success but got: #{result.error&.message}"
+ assert_equal "CAD", result.data.first.currency
+ end
+
+ test "fetch_security_prices falls back to a fresh search when the currency isn't cached, and resolves CAD for VFV" do
+ prices_body = [ { "date" => "2026-06-01T00:00:00.000Z", "close" => 100.5 } ].to_json
+ prices_response = mock
+ prices_response.stubs(:body).returns(prices_body)
+
+ search_response = mock
+ search_response.stubs(:body).returns(vfv_search_body)
+
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(prices_response).then.returns(search_response)
+
+ result = @provider.fetch_security_prices(symbol: "VFV", start_date: Date.new(2026, 6, 1), end_date: Date.new(2026, 6, 1))
+
+ assert result.success?, "expected success but got: #{result.error&.message}"
+ assert_equal "CAD", result.data.first.currency
+ end
+
+ test "fetch_security_prices resolves USD for AAPL via the fallback search even though the CA entry appears first" do
+ prices_body = [ { "date" => "2026-06-01T00:00:00.000Z", "close" => 200.0 } ].to_json
+ prices_response = mock
+ prices_response.stubs(:body).returns(prices_body)
+
+ search_response = mock
+ search_response.stubs(:body).returns(aapl_duplicate_ticker_search_body)
+
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(prices_response).then.returns(search_response)
+
+ result = @provider.fetch_security_prices(symbol: "AAPL", start_date: Date.new(2026, 6, 1), end_date: Date.new(2026, 6, 1))
+
+ assert result.success?, "expected success but got: #{result.error&.message}"
+ assert_equal "USD", result.data.first.currency
+ end
+
+ test "fetch_security_prices fails (does not raise, does not default to USD) when the country code is unrecognized" do
+ prices_body = [ { "date" => "2026-06-01T00:00:00.000Z", "close" => 42.0 } ].to_json
+ prices_response = mock
+ prices_response.stubs(:body).returns(prices_body)
+
+ unmapped_search_body = [
+ { "name" => "Some Fund", "ticker" => "ZZZ", "assetType" => "ETF", "isActive" => true, "countryCode" => "ZZ" }
+ ].to_json
+ search_response = mock
+ search_response.stubs(:body).returns(unmapped_search_body)
+
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(prices_response).then.returns(search_response)
+
+ result = @provider.fetch_security_prices(symbol: "ZZZ", start_date: Date.new(2026, 6, 1), end_date: Date.new(2026, 6, 1))
+
+ assert_not result.success?
+ assert_instance_of Provider::Tiingo::Error, result.error
+ assert_match "Could not determine currency", result.error.message
+ end
+end