The personal finance app for everyone (by everyone)
Ruby
feat(investments): add India investment subtypes and exchange support (#1659)
Abhinav Dhiman139c89d0f4e4
diff --git a/app/models/investment.rb b/app/models/investment.rbindex 937211a9bf..ffb6331b3f 100644--- a/app/models/investment.rb+++ b/app/models/investment.rb@@ -55,10 +55,40 @@ class Investment < ApplicationRecord"pillar_3a" => { short: "Pillar 3a", long: "Private Pension (Pillar 3a)", region: "eu", tax_treatment: :tax_deferred },"riester" => { short: "Riester", long: "Riester-Rente", region: "eu", tax_treatment: :tax_deferred },+ # === India ===+ # Pensions & insurance+ "nps" => { short: "NPS", long: "National Pension System", region: "in", tax_treatment: :tax_advantaged },+ "apy" => { short: "APY", long: "Atal Pension Yojana", region: "in", tax_treatment: :tax_advantaged },+ "life_insurance" => { short: "Life Insurance", long: "Life Insurance", region: "in", tax_treatment: :tax_advantaged },+ # Equity / market-linked+ "indian_stocks" => { short: "Indian Stocks", long: "Indian Stocks (Demat)", region: "in", tax_treatment: :taxable },+ "indian_equity" => { short: "Indian Equity", long: "Indian Equity", region: "in", tax_treatment: :taxable },+ "indian_etf" => { short: "Indian ETF", long: "Indian ETF", region: "in", tax_treatment: :taxable },+ # Fixed-income / small-savings+ "ppf" => { short: "PPF", long: "Public Provident Fund", region: "in", tax_treatment: :tax_exempt },+ "ssy" => { short: "SSY", long: "Sukanya Samriddhi Yojana", region: "in", tax_treatment: :tax_exempt },+ "nsc" => { short: "NSC", long: "National Savings Certificate", region: "in", tax_treatment: :tax_advantaged },+ "scss" => { short: "SCSS", long: "Senior Citizens' Savings Scheme", region: "in", tax_treatment: :taxable },+ "fd" => { short: "FD", long: "Fixed Deposit", region: "in", tax_treatment: :taxable },+ "rd" => { short: "RD", long: "Recurring Deposit", region: "in", tax_treatment: :taxable },+ "pomis" => { short: "POMIS", long: "Post Office Monthly Income Scheme", region: "in", tax_treatment: :taxable },+ "kvp" => { short: "KVP", long: "Kisan Vikas Patra", region: "in", tax_treatment: :taxable },+ # Bonds+ "g_sec" => { short: "G-Sec", long: "Government Securities (G-Secs)", region: "in", tax_treatment: :taxable },+ "sdl" => { short: "SDL", long: "State Development Loans (SDLs)", region: "in", tax_treatment: :taxable },+ "corporate_bond" => { short: "Corporate Bond", long: "Corporate Bond", region: "in", tax_treatment: :taxable },+ "infrastructure_bond" => { short: "Infra Bond", long: "Infrastructure Bond", region: "in", tax_treatment: :tax_advantaged },+ "tax_free_bond" => { short: "Tax-Free Bond", long: "Tax-Free Bond", region: "in", tax_treatment: :tax_exempt },+ # India-specific gold instruments+ "gold_etf" => { short: "Gold ETF", long: "Gold ETF", region: "in", tax_treatment: :taxable },+ "gold_mf" => { short: "Gold MF", long: "Gold Mutual Fund", region: "in", tax_treatment: :taxable },+ "sgb" => { short: "SGB", long: "Sovereign Gold Bond", region: "in", tax_treatment: :tax_advantaged },+# === Generic (available everywhere) ==="pension" => { short: "Pension", long: "Pension", region: nil, tax_treatment: :tax_deferred },"retirement" => { short: "Retirement", long: "Retirement Account", region: nil, tax_treatment: :tax_deferred },"mutual_fund" => { short: "Mutual Fund", long: "Mutual Fund", region: nil, tax_treatment: :taxable },+ "gold" => { short: "Gold", long: "Gold (physical or digital)", region: nil, tax_treatment: :taxable },"angel" => { short: "Angel", long: "Angel Investment", region: nil, tax_treatment: :taxable },"trust" => { short: "Trust", long: "Trust", region: nil, tax_treatment: :taxable },"other" => { short: "Other", long: "Other Investment", region: nil, tax_treatment: :taxable }@@ -92,7 +122,8 @@ class Investment < ApplicationRecord"CAD" => "ca","AUD" => "au","EUR" => "eu",- "CHF" => "eu"+ "CHF" => "eu",+ "INR" => "in"}.freeze# Returns subtypes grouped by region for use with grouped_options_for_select@@ -102,7 +133,7 @@ class Investment < ApplicationRecordgrouped = SUBTYPES.group_by { |_, v| v[:region] }# Build region order: user's region first (if known), then Generic, then others- other_regions = %w[us uk ca au eu] - [ user_region ].compact+ other_regions = %w[us uk ca au eu in] - [ user_region ].compactregion_order = if user_region[ user_region, nil, *other_regions ].uniqelsediff --git a/app/models/property.rb b/app/models/property.rbindex 6114a9f418..c04b68cdc5 100644--- a/app/models/property.rb+++ b/app/models/property.rb@@ -7,7 +7,11 @@ class Property < ApplicationRecord"condominium" => { short: "Condo", long: "Condominium" },"townhouse" => { short: "Townhouse", long: "Townhouse" },"investment_property" => { short: "Investment Property", long: "Investment Property" },- "second_home" => { short: "Second Home", long: "Second Home" }+ "second_home" => { short: "Second Home", long: "Second Home" },+ "apartment" => { short: "Apartment", long: "Apartment" },+ "plot" => { short: "Plot", long: "Plot / Land" },+ "commercial" => { short: "Commercial", long: "Commercial Property" },+ "agri_land" => { short: "Agri Land", long: "Agricultural Land" }}.freezehas_one :address, as: :addressable, dependent: :destroydiff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rbindex 5acb8d7cb4..36a983f936 100644--- a/app/models/provider/yahoo_finance.rb+++ b/app/models/provider/yahoo_finance.rb@@ -1,3 +1,5 @@+require "set"+class Provider::YahooFinance < Providerinclude ExchangeRateConcept, SecurityConceptextend SslConfigurable@@ -165,6 +167,8 @@ class Provider::YahooFinance < Provider)end+ securities = deduplicate_dual_listings(securities) unless exchange_operating_mic.present?+cache_result(cache_key, securities)securitiesend@@ -175,6 +179,8 @@ class Provider::YahooFinance < Providerdef fetch_security_info(symbol:, exchange_operating_mic:)with_provider_response do+ symbol = normalize_symbol(symbol, exchange_operating_mic)+# quoteSummary endpoint requires cookie/crumb authenticationthrottle_requestcookie, crumb = fetch_cookie_and_crumb@@ -227,6 +233,7 @@ class Provider::YahooFinance < Providerdef fetch_security_price(symbol:, exchange_operating_mic: nil, date:)with_provider_response do+ symbol = normalize_symbol(symbol, exchange_operating_mic)cache_key = "security_price_#{symbol}_#{exchange_operating_mic}_#{date}"if cached_result = get_cached_result(cache_key)cached_result@@ -263,6 +270,7 @@ class Provider::YahooFinance < Providerdef fetch_security_prices(symbol:, exchange_operating_mic: nil, start_date:, end_date:)with_provider_response do+ symbol = 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 timezonesperiod1 = start_date.to_time.utc.to_i@@ -285,7 +293,9 @@ class Provider::YahooFinance < Providercloses = quotes["close"] || []# Get currency from metadata- raw_currency = chart_data.dig("meta", "currency") || "USD"+ meta_exchange = chart_data.dig("meta", "exchangeName") || ""+ raw_currency = chart_data.dig("meta", "currency")+ raw_currency ||= default_currency_for_exchange(meta_exchange) || "USD"prices = []timestamps.each_with_index do |timestamp, index|@@ -321,6 +331,15 @@ class Provider::YahooFinance < Provider# Currency Normalization# ================================+ # Per-exchange configuration for Yahoo Finance. Each entry maps an ISO+ # MIC code to its Yahoo-specific symbol suffix, the default currency when+ # Yahoo omits one, and an optional dual-listing group with a preference+ # rank (lower = preferred). Adding a new market is a one-line hash entry.+ EXCHANGE_CONFIG = {+ "XNSE" => { yahoo_suffix: ".NS", default_currency: "INR", dual_list_group: :india, preference_rank: 0 },+ "XBOM" => { yahoo_suffix: ".BO", default_currency: "INR", dual_list_group: :india, preference_rank: 1 }+ }.freeze+# Yahoo Finance sometimes returns currencies in minor units (pence, cents)# This is not part of ISO 4217 but is a convention used by financial data providers# Mapping of Yahoo Finance minor unit codes to standard currency codes and conversion multipliers@@ -340,6 +359,42 @@ class Provider::YahooFinance < Providerendend+ # Appends the Yahoo Finance symbol suffix for exchanges that require one+ # (e.g. XNSE → ".NS", XBOM → ".BO"). Already-suffixed symbols pass through.+ def normalize_symbol(symbol, exchange_operating_mic)+ suffix = EXCHANGE_CONFIG.dig(exchange_operating_mic, :yahoo_suffix)+ return symbol if suffix.nil? || symbol.end_with?(suffix)+ "#{symbol}#{suffix}"+ end++ # Returns the default currency for a Yahoo exchange name (e.g. "NSE" → "INR")+ # by resolving through map_exchange_mic → EXCHANGE_CONFIG. Returns nil for+ # unknown exchanges so callers can fall back to their own default.+ def default_currency_for_exchange(yahoo_exchange_name)+ mic = map_exchange_mic(yahoo_exchange_name)+ EXCHANGE_CONFIG.dig(mic, :default_currency)+ end++ # De-duplicates dual-listed securities that share the same company name+ # and dual_list_group (e.g. NSE + BSE for India), keeping the exchange+ # with the lowest preference_rank. Preserves Yahoo's original relevance+ # ordering by removing duplicates in-place rather than reordering.+ def deduplicate_dual_listings(securities)+ dominated = Set.new++ securities+ .select { |s| EXCHANGE_CONFIG.dig(s.exchange_operating_mic, :dual_list_group) }+ .group_by { |s| [ EXCHANGE_CONFIG[s.exchange_operating_mic][:dual_list_group], s.name.to_s.strip.downcase ] }+ .each_value do |group|+ next unless group.size > 1+ preferred = group.min_by { |s| EXCHANGE_CONFIG[s.exchange_operating_mic][:preference_rank] }+ group.each { |s| dominated << s.object_id unless s.equal?(preferred) }+ end++ return securities if dominated.empty?+ securities.reject { |s| dominated.include?(s.object_id) }+ end+# ================================# Validation# ================================@@ -776,6 +831,10 @@ class Provider::YahooFinance < Provider"XJPX" # Japan Exchange Groupwhen "ASX""XASX" # Australian Securities Exchange+ when "NSE", "NSI"+ "XNSE" # National Stock Exchange of India+ when "BSE", "BOM"+ "XBOM" # BSE (Bombay Stock Exchange)elseexchange_code.upcaseenddiff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex a8691be111..852a2bc28f 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -138,6 +138,7 @@ en:ca: Canadaau: Australiaeu: Europe+ in: Indiageneric: Generalconfirm_unlink:title: Unlink account from provider?diff --git a/config/locales/views/investments/en.yml b/config/locales/views/investments/en.ymlindex 7a4875ba1b..63a12c0def 100644--- a/config/locales/views/investments/en.yml+++ b/config/locales/views/investments/en.yml@@ -100,6 +100,73 @@ en:riester:short: Riesterlong: Riester-Rente+ # India+ nps:+ short: NPS+ long: National Pension System+ apy:+ short: APY+ long: Atal Pension Yojana+ indian_stocks:+ short: Indian Stocks+ long: Indian Stocks (Demat)+ indian_equity:+ short: Indian Equity+ long: Indian Equity+ indian_etf:+ short: Indian ETF+ long: Indian ETF+ life_insurance:+ short: Life Insurance+ long: Life Insurance+ ppf:+ short: PPF+ long: Public Provident Fund+ ssy:+ short: SSY+ long: Sukanya Samriddhi Yojana+ nsc:+ short: NSC+ long: National Savings Certificate+ scss:+ short: SCSS+ long: Senior Citizens' Savings Scheme+ fd:+ short: FD+ long: Fixed Deposit+ rd:+ short: RD+ long: Recurring Deposit+ pomis:+ short: POMIS+ long: Post Office Monthly Income Scheme+ kvp:+ short: KVP+ long: Kisan Vikas Patra+ gold_etf:+ short: Gold ETF+ long: Gold ETF+ gold_mf:+ short: Gold MF+ long: Gold Mutual Fund+ sgb:+ short: SGB+ long: Sovereign Gold Bond+ g_sec:+ short: G-Sec+ long: Government Securities (G-Secs)+ sdl:+ short: SDL+ long: State Development Loans (SDLs)+ corporate_bond:+ short: Corporate Bond+ long: Corporate Bond+ infrastructure_bond:+ short: Infra Bond+ long: Infrastructure Bond+ tax_free_bond:+ short: Tax-Free Bond+ long: Tax-Free Bond# Genericpension:short: Pension@@ -110,6 +177,9 @@ en:mutual_fund:short: Mutual Fundlong: Mutual Fund+ gold:+ short: Gold+ long: Gold (physical or digital)angel:short: Angellong: Angel Investmentdiff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.ymlindex 289335bb82..bf0dd8d878 100644--- a/config/locales/views/properties/en.yml+++ b/config/locales/views/properties/en.yml@@ -30,3 +30,19 @@ en:trend: Trendunknown: Unknownyear_built: Year Built+ subtypes:+ apartment:+ short: Apartment+ long: Apartment+ plot:+ short: Plot+ long: Plot / Land+ commercial:+ short: Commercial+ long: Commercial Property+ rented:+ short: Rented+ long: Rented Property+ agri_land:+ short: Agri Land+ long: Agricultural Landdiff --git a/test/models/investment_test.rb b/test/models/investment_test.rbindex 83870d9ed0..34f047cc20 100644--- a/test/models/investment_test.rb+++ b/test/models/investment_test.rb@@ -133,11 +133,47 @@ class InvestmentTest < ActiveSupport::TestCaseendtest "all subtypes have valid region values" do- valid_regions = [ "us", "uk", "ca", "au", "eu", nil ]+ valid_regions = [ "us", "uk", "ca", "au", "eu", "in", nil ]Investment::SUBTYPES.each do |key, metadata|assert_includes valid_regions, metadata[:region],"Subtype #{key} has invalid region: #{metadata[:region]}"endend++ # India account types++ test "India pension subtypes have tax_advantaged treatment" do+ %w[nps apy].each do |subtype|+ investment = Investment.new(subtype: subtype)+ assert_equal :tax_advantaged, investment.tax_treatment, "Expected #{subtype} to be tax_advantaged"+ end+ end++ test "India equity subtypes are taxable" do+ %w[indian_stocks indian_equity indian_etf].each do |subtype|+ investment = Investment.new(subtype: subtype)+ assert_equal :taxable, investment.tax_treatment, "Expected #{subtype} to be taxable"+ end+ end++ test "life insurance is tax_advantaged" do+ investment = Investment.new(subtype: "life_insurance")+ assert_equal :tax_advantaged, investment.tax_treatment+ end++ test "India subtypes all belong to the 'in' region" do+ india_keys = Investment::SUBTYPES.keys.select { |k| Investment::SUBTYPES.dig(k, :region) == "in" }+ assert india_keys.any?, "Expected at least one India subtype"+ india_keys.each do |key|+ assert_equal "in", Investment::SUBTYPES.dig(key, :region), "Expected #{key} to have region 'in'"+ end+ end++ test "subtypes_grouped_for_select places India region first for INR users" do+ grouped = Investment.subtypes_grouped_for_select(currency: "INR")+ assert grouped.any?, "grouped should not be empty"+ first_group_label = grouped.first[0]+ assert_equal I18n.t("accounts.subtype_regions.in"), first_group_label+ endenddiff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rbindex 6dd0d30a20..da7ae6eb07 100644--- a/test/models/provider/yahoo_finance_test.rb+++ b/test/models/provider/yahoo_finance_test.rb@@ -367,4 +367,107 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCaseassert_equal "EUR", currencyassert_equal 75.75, priceend++ # ================================+ # Exchange Mapping Tests+ # ================================++ test "map_exchange_mic returns XNSE for NSE and NSI" do+ assert_equal "XNSE", @provider.send(:map_exchange_mic, "NSE")+ assert_equal "XNSE", @provider.send(:map_exchange_mic, "NSI")+ assert_equal "XNSE", @provider.send(:map_exchange_mic, "nse")+ end++ test "map_exchange_mic returns XBOM for BSE and BOM" do+ assert_equal "XBOM", @provider.send(:map_exchange_mic, "BSE")+ assert_equal "XBOM", @provider.send(:map_exchange_mic, "BOM")+ end++ test "map_country_code returns IN for Indian exchanges" do+ assert_equal "IN", @provider.send(:map_country_code, "NSE")+ assert_equal "IN", @provider.send(:map_country_code, "BSE")+ assert_equal "IN", @provider.send(:map_country_code, "MUMBAI")+ end++ # ================================+ # normalize_symbol Tests+ # ================================++ test "normalize_symbol appends configured suffix for known MICs" do+ assert_equal "RELIANCE.NS", @provider.send(:normalize_symbol, "RELIANCE", "XNSE")+ assert_equal "INFY.NS", @provider.send(:normalize_symbol, "INFY", "XNSE")+ assert_equal "500325.BO", @provider.send(:normalize_symbol, "500325", "XBOM")+ end++ test "normalize_symbol does not double-suffix already suffixed symbols" do+ assert_equal "RELIANCE.NS", @provider.send(:normalize_symbol, "RELIANCE.NS", "XNSE")+ assert_equal "500325.BO", @provider.send(:normalize_symbol, "500325.BO", "XBOM")+ end++ test "normalize_symbol leaves unconfigured MIC symbols unchanged" do+ assert_equal "AAPL", @provider.send(:normalize_symbol, "AAPL", "XNAS")+ assert_equal "BARC", @provider.send(:normalize_symbol, "BARC", "XLON")+ assert_equal "AAPL", @provider.send(:normalize_symbol, "AAPL", nil)+ end++ test "normalize_symbol appends suffix to dotted symbols that do not already end with the configured suffix" do+ assert_equal "BRK.A.NS", @provider.send(:normalize_symbol, "BRK.A", "XNSE")+ assert_equal "BRK.B.BO", @provider.send(:normalize_symbol, "BRK.B", "XBOM")+ end++ # ================================+ # default_currency_for_exchange Tests+ # ================================++ test "default_currency_for_exchange returns configured currency for known Yahoo exchange names" do+ assert_equal "INR", @provider.send(:default_currency_for_exchange, "NSE")+ assert_equal "INR", @provider.send(:default_currency_for_exchange, "BSE")+ end++ test "default_currency_for_exchange returns nil for unknown exchanges" do+ assert_nil @provider.send(:default_currency_for_exchange, "UNKNOWN")+ assert_nil @provider.send(:default_currency_for_exchange, "NMS")+ end++ # ================================+ # deduplicate_dual_listings Tests+ # ================================++ test "deduplicate_dual_listings keeps preferred exchange when both are present" do+ nse = Provider::SecurityConcept::Security.new(symbol: "RELIANCE.NS", name: "Reliance", logo_url: nil, exchange_operating_mic: "XNSE", country_code: "IN")+ bse = Provider::SecurityConcept::Security.new(symbol: "500325.BO", name: "Reliance", logo_url: nil, exchange_operating_mic: "XBOM", country_code: "IN")+ other = Provider::SecurityConcept::Security.new(symbol: "OTHER", name: "Other", logo_url: nil, exchange_operating_mic: "XNAS", country_code: "US")++ result = @provider.send(:deduplicate_dual_listings, [ nse, bse, other ])++ assert_equal "XNSE", result.first.exchange_operating_mic+ assert_not result.map(&:exchange_operating_mic).include?("XBOM"), "Lower-ranked exchange should be removed"+ assert result.map(&:exchange_operating_mic).include?("XNAS"), "Non-dual-listed exchanges should be preserved"+ end++ test "deduplicate_dual_listings preserves unrelated securities in the same dual_list_group" do+ reliance_nse = Provider::SecurityConcept::Security.new(symbol: "RELIANCE.NS", name: "Reliance Industries", logo_url: nil, exchange_operating_mic: "XNSE", country_code: "IN")+ reliance_bse = Provider::SecurityConcept::Security.new(symbol: "500325.BO", name: "Reliance Industries", logo_url: nil, exchange_operating_mic: "XBOM", country_code: "IN")+ infy_nse = Provider::SecurityConcept::Security.new(symbol: "INFY.NS", name: "Infosys", logo_url: nil, exchange_operating_mic: "XNSE", country_code: "IN")+ other = Provider::SecurityConcept::Security.new(symbol: "AAPL", name: "Apple", logo_url: nil, exchange_operating_mic: "XNAS", country_code: "US")++ result = @provider.send(:deduplicate_dual_listings, [ reliance_nse, reliance_bse, infy_nse, other ])++ symbols = result.map(&:symbol)+ assert_includes symbols, "RELIANCE.NS", "Preferred listing should be kept"+ assert_not_includes symbols, "500325.BO", "Duplicate listing should be removed"+ assert_includes symbols, "INFY.NS", "Unrelated security in same group should be preserved"+ assert_includes symbols, "AAPL", "Non-dual-listed security should be preserved"+ assert_equal 3, result.size+ end++ test "deduplicate_dual_listings returns original list when no dual-listed exchanges present" do+ securities = [+ Provider::SecurityConcept::Security.new(symbol: "AAPL", name: "Apple", logo_url: nil, exchange_operating_mic: "XNAS", country_code: "US"),+ Provider::SecurityConcept::Security.new(symbol: "MSFT", name: "Microsoft", logo_url: nil, exchange_operating_mic: "XNAS", country_code: "US")+ ]++ result = @provider.send(:deduplicate_dual_listings, securities)+ assert_equal securities, result+ endend