Spaces:
Configuration error
Configuration error
Niranjan-Murugarasu024
feat: TradeSense AI Chairman Edition production release ready for Hugging Face Spaces
0125724 Download backend/data/resolution/resolver.py from BlueMen/tradesenseAi: direct link, hf CLI and curl.
- Browser
- Download file 29.1 kB
-
https://huggingface.co/spaces/BlueMen/tradesenseAi/resolve/main/backend/data/resolution/resolver.py
- Command line
-
hf download hf://spaces/BlueMen/tradesenseAi/backend/data/resolution/resolver.py
-
curl -L -o resolver.py https://huggingface.co/spaces/BlueMen/tradesenseAi/resolve/main/backend/data/resolution/resolver.py
29.1 kB
| """ | |
| TradeSense AI — Institutional Instrument Resolution Engine (Module 01) | |
| Provides deterministic, multi-stage instrument identity resolution across | |
| symbol formats, company names, exchange prefixes, ISINs, and dynamic upstream search. | |
| """ | |
| import re | |
| import json | |
| import time | |
| import logging | |
| import urllib.request | |
| import urllib.parse | |
| from typing import Dict, List, Optional, Tuple, Any | |
| from pydantic import BaseModel, Field | |
| from backend.domain.instrument import ( | |
| CanonicalInstrument, | |
| AssetClass, | |
| InstrumentStatus, | |
| ExchangeCode, | |
| ) | |
| logger = logging.getLogger("tradesense.data.resolution") | |
| class ResolutionMatch(BaseModel): | |
| """Result of an instrument resolution attempt with confidence scoring and scope taxonomy.""" | |
| instrument: Optional[CanonicalInstrument] = None | |
| confidence: float = Field(..., ge=0.0, le=1.0) | |
| match_stage: str | |
| is_ambiguous: bool = False | |
| is_supported: bool = True | |
| status: str = "SUPPORTED" # "SUPPORTED", "UNSUPPORTED_MARKET", "INVALID_INSTRUMENT" | |
| unsupported_reason: Optional[str] = None | |
| detected_exchange: Optional[str] = None | |
| detected_country: Optional[str] = None | |
| alternative_candidates: List[CanonicalInstrument] = Field(default_factory=list) | |
| class InstrumentResolver: | |
| """ | |
| Production-grade financial instrument resolution engine. | |
| Ensures that any valid Indian security resolves into a single, | |
| deterministic CanonicalInstrument identity with appropriate provider mappings. | |
| Foreign equities (NASDAQ, NYSE, LSE, etc.) are strictly rejected at the domain boundary. | |
| """ | |
| def __init__(self): | |
| # In-memory instrument catalog keyed by instrument_id | |
| self._catalog: Dict[str, CanonicalInstrument] = {} | |
| # In-memory indexes for sub-millisecond lookups | |
| self._symbol_index: Dict[str, List[str]] = {} # symbol.upper() -> [instrument_id, ...] | |
| self._isin_index: Dict[str, str] = {} # isin.upper() -> instrument_id | |
| self._provider_map_index: Dict[str, str] = {} # "provider:symbol" -> instrument_id | |
| self._alias_index: Dict[str, str] = {} # alias.lower() -> instrument_id | |
| self._dynamic_cache: Dict[str, Tuple[float, Any]] = {} | |
| self._seed_initial_catalog() | |
| def _seed_initial_catalog(self): | |
| """Seeds the catalog with prominent bellwethers, common indices, and verified BSE/NSE securities.""" | |
| seed_data = [ | |
| # Indices (Indian Market Benchmarks) | |
| ("IN_IDX_NIFTY50", "NIFTY50", "NIFTY 50", "NIFTY 50 Index", "INDEX", "IN", "INR", AssetClass.INDEX, None, "Indices", {"yfinance": "^NSEI", "nse": "NIFTY 50"}, ["nifty", "nifty 50", "nse 50"]), | |
| ("IN_IDX_BANKNIFTY", "BANKNIFTY", "BANK NIFTY", "Nifty Bank Index", "INDEX", "IN", "INR", AssetClass.INDEX, None, "Indices", {"yfinance": "^NSEBANK", "nse": "NIFTY BANK"}, ["bank nifty", "banknifty"]), | |
| ("IN_IDX_SENSEX", "SENSEX", "SENSEX", "BSE SENSEX Benchmark", "INDEX", "IN", "INR", AssetClass.INDEX, None, "Indices", {"yfinance": "^BSESN", "bse": "SENSEX"}, ["sensex", "bse 30"]), | |
| ("IN_IDX_INDIAVIX", "INDIAVIX", "INDIA VIX", "India Volatility Index", "INDEX", "IN", "INR", AssetClass.INDEX, None, "Indices", {"yfinance": "^INDIAVIX", "nse": "INDIA VIX"}, ["vix", "india vix"]), | |
| # Prominent Indian Bellwethers (NSE) | |
| ("IN_EQ_RELIANCE", "RELIANCE", "RELIANCE", "Reliance Industries Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE002A01018", "Energy & Power", {"yfinance": "RELIANCE.NS", "nse": "RELIANCE", "bse": "RELIANCE.BO"}, ["ril", "reliance industries", "mukesh ambani"]), | |
| ("IN_EQ_TCS", "TCS", "TCS", "Tata Consultancy Services Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE467B01029", "IT & Software", {"yfinance": "TCS.NS", "nse": "TCS", "bse": "TCS.BO"}, ["tata consultancy", "tata tcs"]), | |
| ("IN_EQ_INFY", "INFY", "INFY", "Infosys Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE009A01021", "IT & Software", {"yfinance": "INFY.NS", "nse": "INFY", "bse": "INFY.BO"}, ["infosys", "infy"]), | |
| ("IN_EQ_HDFCBANK", "HDFCBANK", "HDFCBANK", "HDFC Bank Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE040A01034", "Banking & Finance", {"yfinance": "HDFCBANK.NS", "nse": "HDFCBANK", "bse": "HDFCBANK.BO"}, ["hdfc", "hdfc bank"]), | |
| ("IN_EQ_ICICIBANK", "ICICIBANK", "ICICIBANK", "ICICI Bank Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE090A01021", "Banking & Finance", {"yfinance": "ICICIBANK.NS", "nse": "ICICIBANK", "bse": "ICICIBANK.BO"}, ["icici", "icici bank"]), | |
| ("IN_EQ_SBIN", "SBIN", "SBIN", "State Bank of India", "NSE", "IN", "INR", AssetClass.EQUITY, "INE062A01020", "Banking & Finance", {"yfinance": "SBIN.NS", "nse": "SBIN", "bse": "SBIN.BO"}, ["sbi", "state bank"]), | |
| ("IN_EQ_BHARTIARTL", "BHARTIARTL", "BHARTIARTL", "Bharti Airtel Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE397D01024", "Telecom & Digital", {"yfinance": "BHARTIARTL.NS", "nse": "BHARTIARTL", "bse": "BHARTIARTL.BO"}, ["airtel", "bharti airtel"]), | |
| ("IN_EQ_ITC", "ITC", "ITC", "ITC Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE154A01025", "FMCG & Consumer", {"yfinance": "ITC.NS", "nse": "ITC", "bse": "ITC.BO"}, ["itc", "itc limited"]), | |
| ("IN_EQ_LT", "LT", "LT", "Larsen & Toubro Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE018A01030", "Metals & Infra", {"yfinance": "LT.NS", "nse": "LT", "bse": "LT.BO"}, ["l&t", "larsen and toubro", "larsen & toubro"]), | |
| ("IN_EQ_HINDUNILVR", "HINDUNILVR", "HINDUNILVR", "Hindustan Unilever Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE030A01027", "FMCG & Consumer", {"yfinance": "HINDUNILVR.NS", "nse": "HINDUNILVR", "bse": "HINDUNILVR.BO"}, ["hul", "hindustan unilever", "unilever"]), | |
| ("IN_EQ_TATAMOTORS", "TATAMOTORS", "TATAMOTORS", "Tata Motors Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE155A01022", "Automobile", {"yfinance": "TATAMOTORS.NS", "nse": "TATAMOTORS", "bse": "TATAMOTORS.BO"}, ["tata motors", "tml", "jlr"]), | |
| ("IN_EQ_JSWSTEEL", "JSWSTEEL", "JSWSTEEL", "JSW Steel Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE019A01038", "Metals & Infra", {"yfinance": "JSWSTEEL.NS", "nse": "JSWSTEEL", "bse": "JSWSTEEL.BO"}, ["jsw", "jsw steel", "jindal south west"]), | |
| # Healthcare & Audit Target (Kovai Medical) | |
| ("IN_EQ_KOVAI", "KOVAI", "KOVAI", "Kovai Medical Center and Hospital Ltd.", "NSE", "IN", "INR", AssetClass.EQUITY, "INE348C01021", "Pharma & Health", {"yfinance": "KOVAI.NS", "nse": "KOVAI", "bse": "KOVAI.BO"}, ["kovai", "kovai medical", "kmch", "kovai hospital", "kovai medical and health center", "kovai medical & health center"]), | |
| # Prominent BSE Equities | |
| ("IN_EQ_BSE_BOMDYEING", "BOMDYEING", "BOMDYEING", "Bombay Dyeing & Mfg. Co. Ltd.", "BSE", "IN", "INR", AssetClass.EQUITY, "INE032A01023", "Consumer", {"yfinance": "BOMDYEING.BO", "bse": "500020"}, ["bombay dyeing"]), | |
| ("IN_EQ_BSE_TATAPOWER", "TATAPOWER", "TATAPOWER", "Tata Power Co. Ltd.", "BSE", "IN", "INR", AssetClass.EQUITY, "INE245A01021", "Utilities", {"yfinance": "TATAPOWER.BO", "bse": "500400"}, ["tata power", "tatapower"]), | |
| ] | |
| for item in seed_data: | |
| inst = CanonicalInstrument( | |
| instrument_id=item[0], | |
| symbol=item[1], | |
| display_symbol=item[2], | |
| company_name=item[3], | |
| exchange=item[4], | |
| country=item[5], | |
| currency=item[6], | |
| asset_class=item[7], | |
| isin=item[8], | |
| sector=item[9], | |
| provider_mappings=item[10], | |
| aliases=item[11], | |
| ) | |
| self.register_instrument(inst) | |
| def register_instrument(self, inst: CanonicalInstrument) -> bool: | |
| """Registers a canonical instrument. Enforces TradeSense India-only market scope invariant.""" | |
| if not inst.is_supported_market(): | |
| logger.warning( | |
| f"Scope boundary violation: Rejected registration of non-Indian instrument '{inst.symbol}' " | |
| f"(exchange={inst.exchange}, country={inst.country})" | |
| ) | |
| return False | |
| self._catalog[inst.instrument_id] = inst | |
| # Symbol index | |
| sym_key = inst.symbol.upper() | |
| if sym_key not in self._symbol_index: | |
| self._symbol_index[sym_key] = [] | |
| if inst.instrument_id not in self._symbol_index[sym_key]: | |
| self._symbol_index[sym_key].append(inst.instrument_id) | |
| # ISIN index | |
| if inst.isin: | |
| self._isin_index[inst.isin.upper()] = inst.instrument_id | |
| # Provider mappings index | |
| for prov_name, prov_sym in inst.provider_mappings.items(): | |
| lookup_key = f"{prov_name.lower()}:{prov_sym.upper()}" | |
| self._provider_map_index[lookup_key] = inst.instrument_id | |
| # Also register raw provider symbol if unique | |
| self._provider_map_index[prov_sym.upper()] = inst.instrument_id | |
| # Aliases index | |
| for alias in inst.aliases: | |
| self._alias_index[alias.lower().strip()] = inst.instrument_id | |
| # Company name full and simplified | |
| clean_company = re.sub(r'[^a-zA-Z0-9\s]', '', inst.company_name).lower() | |
| self._alias_index[clean_company] = inst.instrument_id | |
| def resolve( | |
| self, | |
| query: str, | |
| exchange_hint: Optional[str] = None, | |
| allow_dynamic_search: bool = True | |
| ) -> Optional[ResolutionMatch]: | |
| """ | |
| Executes deterministic multi-stage instrument resolution. | |
| Priority: | |
| 1. Exact instrument_id | |
| 2. Exact ISIN | |
| 3. Exact exchange-qualified symbol (e.g. NSE:KOVAI, BSE:532159) | |
| 4. Exact canonical symbol | |
| 5. Exact provider mapping (e.g. KOVAI.NS) | |
| 6. Exact alias / company name | |
| 7. Fuzzy prefix / substring | |
| 8. Dynamic upstream provider query | |
| """ | |
| if not query or not query.strip(): | |
| return None | |
| raw = query.strip() | |
| upper = raw.upper() | |
| lower = raw.lower() | |
| ex_hint = exchange_hint.upper().strip() if exchange_hint and exchange_hint.upper() != "ALL" else None | |
| # Stage 1: Exact instrument_id | |
| if upper in self._catalog: | |
| return ResolutionMatch( | |
| instrument=self._catalog[upper], | |
| confidence=1.0, | |
| match_stage="EXACT_INSTRUMENT_ID" | |
| ) | |
| # Stage 2: Exact ISIN | |
| # Stage 2: Exact ISIN | |
| # Check ISIN country prefix: Indian ISINs start with 'INE' or 'INF'. | |
| if len(upper) == 12 and re.match(r'^[A-Z]{2}[A-Z0-9]{9}[0-9]$', upper): | |
| country_prefix = upper[:2] | |
| if country_prefix != "IN": | |
| return ResolutionMatch( | |
| instrument=None, | |
| confidence=1.0, | |
| match_stage="FOREIGN_ISIN_REJECTION", | |
| is_supported=False, | |
| status="UNSUPPORTED_MARKET", | |
| unsupported_reason=f"ISIN '{upper}' belongs to country code '{country_prefix}'. TradeSense AI supports Indian securities on NSE and BSE only.", | |
| detected_country=country_prefix, | |
| ) | |
| if upper in self._isin_index: | |
| inst_id = self._isin_index[upper] | |
| return ResolutionMatch( | |
| instrument=self._catalog[inst_id], | |
| confidence=1.0, | |
| match_stage="EXACT_ISIN", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| # Stage 3: Exchange-qualified symbol (e.g. NSE:KOVAI, BSE:JSWSTEEL, NASDAQ:AAPL) | |
| if ":" in upper: | |
| parts = upper.split(":", 1) | |
| prefix_ex, sym = parts[0].strip(), parts[1].strip() | |
| # Domain Boundary Scope Rejection: Non-Indian Exchanges | |
| if prefix_ex not in ("NSE", "BSE", "INDEX"): | |
| return ResolutionMatch( | |
| instrument=None, | |
| confidence=1.0, | |
| match_stage="EXCHANGE_QUALIFIED_REJECTION", | |
| is_supported=False, | |
| status="UNSUPPORTED_MARKET", | |
| unsupported_reason=f"Exchange '{prefix_ex}' is not supported. TradeSense AI supports Indian securities on NSE and BSE only.", | |
| detected_exchange=prefix_ex, | |
| ) | |
| if sym in self._symbol_index: | |
| for inst_id in self._symbol_index[sym]: | |
| inst = self._catalog[inst_id] | |
| if inst.exchange == prefix_ex or prefix_ex in ("NSE", "BSE"): | |
| return ResolutionMatch( | |
| instrument=inst, | |
| confidence=0.99, | |
| match_stage="EXCHANGE_QUALIFIED", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| # Stage 4: Provider-specific ticker formats (e.g. KOVAI.NS, TCS.BO, ^NSEI) | |
| if upper in self._provider_map_index: | |
| inst_id = self._provider_map_index[upper] | |
| return ResolutionMatch( | |
| instrument=self._catalog[inst_id], | |
| confidence=0.98, | |
| match_stage="EXACT_PROVIDER_MAP", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| # Check stripping of standard suffixes (.NS, .BO) | |
| stripped_sym = upper | |
| derived_ex = None | |
| if upper.endswith(".NS"): | |
| stripped_sym = upper[:-3] | |
| derived_ex = "NSE" | |
| elif upper.endswith(".BO"): | |
| stripped_sym = upper[:-3] | |
| derived_ex = "BSE" | |
| # Deterministic Domain Scope Rejection for known foreign bellwethers | |
| KNOWN_FOREIGN_TICKERS = { | |
| "AAPL": ("NASDAQ", "US"), | |
| "MSFT": ("NASDAQ", "US"), | |
| "NVDA": ("NASDAQ", "US"), | |
| "TSLA": ("NASDAQ", "US"), | |
| "AMZN": ("NASDAQ", "US"), | |
| "GOOGL": ("NASDAQ", "US"), | |
| "GOOG": ("NASDAQ", "US"), | |
| "META": ("NASDAQ", "US"), | |
| "SPY": ("NYSE", "US"), | |
| "QQQ": ("NASDAQ", "US"), | |
| "NFLX": ("NASDAQ", "US"), | |
| "AMD": ("NASDAQ", "US"), | |
| "INTC": ("NASDAQ", "US"), | |
| "BABA": ("NYSE", "US"), | |
| } | |
| if stripped_sym in KNOWN_FOREIGN_TICKERS: | |
| f_ex, f_country = KNOWN_FOREIGN_TICKERS[stripped_sym] | |
| return ResolutionMatch( | |
| instrument=None, | |
| confidence=1.0, | |
| match_stage="FOREIGN_SCOPE_BOUNDARY", | |
| is_supported=False, | |
| status="UNSUPPORTED_MARKET", | |
| unsupported_reason=f"Security '{stripped_sym}' is listed on foreign exchange '{f_ex}'. TradeSense AI supports Indian securities on NSE and BSE only.", | |
| detected_exchange=f_ex, | |
| detected_country=f_country, | |
| ) | |
| # Stage 5: Canonical Symbol Match | |
| target_ex = derived_ex or ex_hint | |
| if stripped_sym in self._symbol_index: | |
| candidates = [self._catalog[iid] for iid in self._symbol_index[stripped_sym]] | |
| if len(candidates) == 1: | |
| return ResolutionMatch( | |
| instrument=candidates[0], | |
| confidence=0.95, | |
| match_stage="EXACT_SYMBOL", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| if target_ex: | |
| for c in candidates: | |
| if c.exchange == target_ex: | |
| return ResolutionMatch( | |
| instrument=c, | |
| confidence=0.96, | |
| match_stage="EXACT_SYMBOL_EXCHANGE", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| return ResolutionMatch( | |
| instrument=candidates[0], | |
| confidence=0.90, | |
| match_stage="EXACT_SYMBOL_DEFAULT", | |
| is_ambiguous=True, | |
| is_supported=True, | |
| status="SUPPORTED", | |
| alternative_candidates=candidates[1:] | |
| ) | |
| # Stage 6: Exact Alias or Clean Company Name | |
| clean_q = re.sub(r'[^a-zA-Z0-9\s]', '', lower).strip() | |
| if clean_q in self._alias_index: | |
| inst_id = self._alias_index[clean_q] | |
| return ResolutionMatch( | |
| instrument=self._catalog[inst_id], | |
| confidence=0.92, | |
| match_stage="EXACT_ALIAS", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| # Stage 7: Substring / Fuzzy Alias Match across existing catalog | |
| fuzzy_matches = [] | |
| for alias, inst_id in self._alias_index.items(): | |
| if clean_q in alias or alias in clean_q: | |
| fuzzy_matches.append(self._catalog[inst_id]) | |
| if fuzzy_matches: | |
| # Deduplicate by instrument_id | |
| seen = set() | |
| unique_fuzzy = [] | |
| for fm in fuzzy_matches: | |
| if fm.instrument_id not in seen: | |
| seen.add(fm.instrument_id) | |
| unique_fuzzy.append(fm) | |
| return ResolutionMatch( | |
| instrument=unique_fuzzy[0], | |
| confidence=0.82, | |
| match_stage="FUZZY_ALIAS", | |
| is_ambiguous=len(unique_fuzzy) > 1, | |
| is_supported=True, | |
| status="SUPPORTED", | |
| alternative_candidates=unique_fuzzy[1:] | |
| ) | |
| # Stage 8: Dynamic Upstream Provider Search (Yahoo Search API) | |
| if allow_dynamic_search: | |
| res_tuple = self._discover_upstream_instrument(raw, target_ex) | |
| if res_tuple: | |
| dynamic_inst, disc_status, disc_ex, disc_country = res_tuple | |
| if disc_status == "UNSUPPORTED_MARKET": | |
| return ResolutionMatch( | |
| instrument=None, | |
| confidence=0.90, | |
| match_stage="DYNAMIC_UPSTREAM_DISCOVERY_UNSUPPORTED", | |
| is_supported=False, | |
| status="UNSUPPORTED_MARKET", | |
| unsupported_reason=( | |
| f"Security '{raw}' is listed on foreign exchange '{disc_ex}' ({disc_country}). " | |
| f"TradeSense AI supports Indian securities on NSE and BSE only." | |
| ), | |
| detected_exchange=disc_ex, | |
| detected_country=disc_country, | |
| ) | |
| elif dynamic_inst and dynamic_inst.is_supported_market(): | |
| # Register in local catalog for instant future hits | |
| self.register_instrument(dynamic_inst) | |
| return ResolutionMatch( | |
| instrument=dynamic_inst, | |
| confidence=0.85, | |
| match_stage="DYNAMIC_UPSTREAM_DISCOVERY", | |
| is_supported=True, | |
| status="SUPPORTED" | |
| ) | |
| return None | |
| def _discover_upstream_instrument( | |
| self, | |
| query: str, | |
| exchange_hint: Optional[str] = None | |
| ) -> Optional[Tuple[Optional[CanonicalInstrument], str, Optional[str], Optional[str]]]: | |
| """ | |
| Dynamically discovers an unknown financial instrument via upstream market provider (Yahoo Finance Search API). | |
| Returns: | |
| Tuple[CanonicalInstrument | None, status, exchange, country] | |
| where status is 'SUPPORTED', 'UNSUPPORTED_MARKET', or 'INVALID_INSTRUMENT'. | |
| """ | |
| clean_q = query.strip() | |
| cache_key = f"{clean_q.lower()}_{exchange_hint or 'ALL'}" | |
| now_ts = time.time() | |
| if cache_key in self._dynamic_cache: | |
| ts, res = self._dynamic_cache[cache_key] | |
| if (now_ts - ts) < 300.0: # 5 min cache | |
| return res | |
| try: | |
| url = f"https://query2.finance.yahoo.com/v1/finance/search?q={urllib.parse.quote(clean_q)}"esCount=10&newsCount=0" | |
| req = urllib.request.Request( | |
| url, | |
| headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"} | |
| ) | |
| with urllib.request.urlopen(req, timeout=3.0) as response: | |
| payload = json.loads(response.read().decode("utf-8")) | |
| quotes = payload.get("quotes", []) | |
| for q in quotes: | |
| raw_sym = q.get("symbol", "").upper() | |
| if not raw_sym: | |
| continue | |
| name = q.get("longname") or q.get("shortname") or raw_sym | |
| sector = q.get("sector") or q.get("industry") or "Equities" | |
| quote_type = q.get("quoteType", "EQUITY") | |
| # Exchange detection & India Scope Gate | |
| if raw_sym.endswith(".NS"): | |
| clean_sym = raw_sym[:-3] | |
| ex = "NSE" | |
| country = "IN" | |
| currency = "INR" | |
| elif raw_sym.endswith(".BO"): | |
| clean_sym = raw_sym[:-3] | |
| ex = "BSE" | |
| country = "IN" | |
| currency = "INR" | |
| elif raw_sym.startswith("^") and ("NSE" in raw_sym or "BSE" in raw_sym or "INDIA" in raw_sym): | |
| clean_sym = raw_sym | |
| ex = "INDEX" | |
| country = "IN" | |
| currency = "INR" | |
| else: | |
| # US / Foreign Equities (e.g. AAPL, MSFT, BABA) | |
| ex = q.get("exchange", "FOREIGN") | |
| country = "US" if ex in ("NASDAQ", "NYSE", "NMS", "NYQ") else "FOREIGN" | |
| result_tuple = (None, "UNSUPPORTED_MARKET", ex, country) | |
| self._dynamic_cache[cache_key] = (now_ts, result_tuple) | |
| return result_tuple | |
| if exchange_hint and exchange_hint != "ALL" and ex != exchange_hint: | |
| continue | |
| inst_id = f"{country}_{'IDX' if quote_type == 'INDEX' else 'EQ'}_{clean_sym}" | |
| # Create CanonicalInstrument for valid Indian security | |
| discovered = CanonicalInstrument( | |
| instrument_id=inst_id, | |
| symbol=clean_sym, | |
| display_symbol=clean_sym, | |
| company_name=name, | |
| exchange=ex, | |
| country=country, | |
| currency=currency, | |
| asset_class=AssetClass.INDEX if quote_type == "INDEX" else AssetClass.EQUITY, | |
| sector=sector, | |
| provider_mappings={"yfinance": raw_sym}, | |
| aliases=[name.lower(), clean_sym.lower()] | |
| ) | |
| result_tuple = (discovered, "SUPPORTED", ex, country) | |
| self._dynamic_cache[cache_key] = (now_ts, result_tuple) | |
| return result_tuple | |
| except Exception as e: | |
| logger.warning(f"Dynamic instrument discovery failed for '{clean_q}': {e}") | |
| self._dynamic_cache[cache_key] = (now_ts, None) | |
| return None | |
| def search( | |
| self, | |
| query: str, | |
| exchange: str = "ALL", | |
| limit: int = 10 | |
| ) -> List[Dict[str, Any]]: | |
| """ | |
| Searches the instrument universe returning structured autocomplete candidates. | |
| Enforces India-only market scope: foreign securities (NASDAQ, NYSE, etc.) are strictly excluded. | |
| """ | |
| if not query or not query.strip(): | |
| return [] | |
| clean_q = query.strip() | |
| q_lower = clean_q.lower() | |
| ex_filter = exchange.upper().strip() | |
| results: List[Dict[str, Any]] = [] | |
| seen_ids = set() | |
| # 1. Search existing catalog (already 100% Indian securities) | |
| for inst in self._catalog.values(): | |
| if not inst.is_supported_market(): | |
| continue | |
| if ex_filter != "ALL" and inst.exchange != ex_filter: | |
| continue | |
| score = 0 | |
| if inst.symbol.lower() == q_lower: | |
| score = 100 | |
| elif inst.symbol.lower().startswith(q_lower): | |
| score = 90 | |
| elif q_lower in inst.company_name.lower(): | |
| score = 80 | |
| elif any(q_lower in a.lower() for a in inst.aliases): | |
| score = 75 | |
| elif q_lower in inst.symbol.lower(): | |
| score = 65 | |
| if score > 0: | |
| seen_ids.add(inst.instrument_id) | |
| summary = inst.to_summary_dict() | |
| summary["score"] = score | |
| summary["ticker_full"] = inst.get_provider_symbol("yfinance") | |
| results.append(summary) | |
| # 2. If results are few, supplement with dynamic upstream discovery (INDIAN CANDIDATES ONLY) | |
| if len(results) < limit: | |
| try: | |
| url = f"https://query2.finance.yahoo.com/v1/finance/search?q={urllib.parse.quote(clean_q)}"esCount=10&newsCount=0" | |
| req = urllib.request.Request( | |
| url, | |
| headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"} | |
| ) | |
| with urllib.request.urlopen(req, timeout=3.0) as response: | |
| payload = json.loads(response.read().decode("utf-8")) | |
| quotes = payload.get("quotes", []) | |
| for q in quotes: | |
| raw_sym = q.get("symbol", "").upper() | |
| if not raw_sym: | |
| continue | |
| # HARD INDIA SCOPE GATE: Only accept NSE (.NS), BSE (.BO), or Indian benchmark indices | |
| if raw_sym.endswith(".NS"): | |
| clean_sym = raw_sym[:-3] | |
| ex = "NSE" | |
| country = "IN" | |
| currency = "INR" | |
| elif raw_sym.endswith(".BO"): | |
| clean_sym = raw_sym[:-3] | |
| ex = "BSE" | |
| country = "IN" | |
| currency = "INR" | |
| elif raw_sym.startswith("^") and ("NSE" in raw_sym or "BSE" in raw_sym or "INDIA" in raw_sym): | |
| clean_sym = raw_sym | |
| ex = "INDEX" | |
| country = "IN" | |
| currency = "INR" | |
| else: | |
| # Foreign security! Drop immediately — never populate autocomplete with foreign assets | |
| continue | |
| if ex_filter != "ALL" and ex != ex_filter: | |
| continue | |
| inst_id = f"{country}_{'IDX' if q.get('quoteType') == 'INDEX' else 'EQ'}_{clean_sym}" | |
| if inst_id in seen_ids: | |
| continue | |
| name = q.get("longname") or q.get("shortname") or clean_sym | |
| discovered = CanonicalInstrument( | |
| instrument_id=inst_id, | |
| symbol=clean_sym, | |
| display_symbol=clean_sym, | |
| company_name=name, | |
| exchange=ex, | |
| country=country, | |
| currency=currency, | |
| asset_class=AssetClass.INDEX if q.get("quoteType") == "INDEX" else AssetClass.EQUITY, | |
| sector=q.get("sector", "Equities"), | |
| provider_mappings={"yfinance": raw_sym}, | |
| aliases=[name.lower(), clean_sym.lower()] | |
| ) | |
| self.register_instrument(discovered) | |
| seen_ids.add(inst_id) | |
| summary = discovered.to_summary_dict() | |
| summary["score"] = 55 | |
| summary["ticker_full"] = raw_sym | |
| results.append(summary) | |
| except Exception as e: | |
| logger.warning(f"Upstream autocomplete query failed: {e}") | |
| # Sort: highest score first, then shorter symbol | |
| results.sort(key=lambda x: (-x.get("score", 0), len(x["symbol"]))) | |
| return results[:limit] | |
| # Global Singleton Resolver Instance | |
| instrument_resolver = InstrumentResolver() | |