deterministic ISIN resolution via OpenFIGI (primary listing by country), ISIN-aware fallback
Browse files- README.md +2 -1
- src/portfolio.py +49 -3
- tests/test_validator.py +19 -0
README.md
CHANGED
|
@@ -93,7 +93,8 @@ entry price, quantity optional), and get:
|
|
| 93 |
US, UK (`.L`, quoted in pence β handled), Germany (`.DE`), Netherlands (`.AS`), France (`.PA`),
|
| 94 |
Switzerland (`.SW`), Italy (`.MI`), Denmark (`.CO`), India (`.NS`/`.BO`), Japan (`.T`), Korea (`.KS`)
|
| 95 |
and other Yahoo-suffixed exchanges. Inputs may be tickers, company names, Bloomberg-style codes
|
| 96 |
-
("VOD LN" β resolved with a listing check) or **ISINs**
|
|
|
|
| 97 |
(S&P 500, FTSE 100, STOXX Europe 600 for mixed European books, NIFTY, DAX, Nikkeiβ¦); European
|
| 98 |
books get UCITS instruments (gilts, physical gold, min-vol, all-world) and local-market ideas
|
| 99 |
verified live on the same exchanges. Tax notes apply US short/long-term rules only to US listings.
|
|
|
|
| 93 |
US, UK (`.L`, quoted in pence β handled), Germany (`.DE`), Netherlands (`.AS`), France (`.PA`),
|
| 94 |
Switzerland (`.SW`), Italy (`.MI`), Denmark (`.CO`), India (`.NS`/`.BO`), Japan (`.T`), Korea (`.KS`)
|
| 95 |
and other Yahoo-suffixed exchanges. Inputs may be tickers, company names, Bloomberg-style codes
|
| 96 |
+
("VOD LN" β resolved with a listing check) or **ISINs** (resolved deterministically via the
|
| 97 |
+
OpenFIGI mapping API to the primary listing β BA.L, SAP.DE, RELIANCE.NS, BRK-B β never by an LLM guess). Benchmarks follow the book's domicile
|
| 98 |
(S&P 500, FTSE 100, STOXX Europe 600 for mixed European books, NIFTY, DAX, Nikkeiβ¦); European
|
| 99 |
books get UCITS instruments (gilts, physical gold, min-vol, all-world) and local-market ideas
|
| 100 |
verified live on the same exchanges. Tax notes apply US short/long-term rules only to US listings.
|
src/portfolio.py
CHANGED
|
@@ -33,20 +33,66 @@ def _quote_exists(sym: str) -> dict | None:
|
|
| 33 |
return None
|
| 34 |
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
def resolve_symbol(query: str) -> dict:
|
| 37 |
-
"""Ticker or company name -> {symbol, name, price, data}. Raises ValueError with a
|
| 38 |
user-facing message when nothing real matches."""
|
| 39 |
q = (query or "").strip()
|
| 40 |
if not q or len(q) > 60:
|
| 41 |
-
raise ValueError("Enter a ticker (e.g. NVDA, RELIANCE.NS) or a company name.")
|
| 42 |
qU = q.upper()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
if _TICKER_RE.fullmatch(qU):
|
| 44 |
d = _quote_exists(qU)
|
| 45 |
if d:
|
| 46 |
return {"symbol": qU, "name": d.get("name"), "price": d["price"], "data": d}
|
| 47 |
# not a live ticker β treat as a company name/alias (or an outdated symbol)
|
| 48 |
attempts = [
|
| 49 |
-
(f"Company reference: {q!r}"
|
|
|
|
| 50 |
# the fast tier sometimes echoes a renamed/dead symbol back β escalate with context
|
| 51 |
(f"The symbol {q!r} returns NO live market quote β it is likely outdated, renamed "
|
| 52 |
f"or delisted (e.g. FB became META, SQ became XYZ). Identify the company and give "
|
|
|
|
| 33 |
return None
|
| 34 |
|
| 35 |
|
| 36 |
+
_ISIN_RE = re.compile(r"^[A-Z]{2}[A-Z0-9]{9}[0-9]$")
|
| 37 |
+
# ISIN country prefix β preferred OpenFIGI exchange codes (primary listing first) β Yahoo suffix
|
| 38 |
+
_ISIN_VENUES = {
|
| 39 |
+
"US": [("US", ""), ("UN", ""), ("UW", ""), ("UQ", "")], "GB": [("LN", ".L")], "IE": [("LN", ".L"), ("ID", ".IR")],
|
| 40 |
+
"DE": [("GY", ".DE"), ("GR", ".DE")], "NL": [("NA", ".AS")], "FR": [("FP", ".PA")], "CH": [("SE", ".SW"), ("SW", ".SW")],
|
| 41 |
+
"IT": [("IM", ".MI")], "ES": [("SM", ".MC")], "DK": [("DC", ".CO")], "SE": [("SS", ".ST")], "FI": [("FH", ".HE")],
|
| 42 |
+
"NO": [("NO", ".OL")], "BE": [("BB", ".BR")], "AT": [("AV", ".VI")], "PT": [("PL", ".LS")],
|
| 43 |
+
"IN": [("IN", ".NS"), ("IB", ".BO")], "JP": [("JT", ".T"), ("JP", ".T")], "KR": [("KS", ".KS")], "HK": [("HK", ".HK")],
|
| 44 |
+
"AU": [("AT", ".AX"), ("AU", ".AX")], "CA": [("CT", ".TO"), ("CN", ".TO")], "BR": [("BZ", ".SA")],
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def resolve_isin(isin: str) -> list[str]:
|
| 49 |
+
"""ISIN β candidate Yahoo symbols (primary listing first) via the OpenFIGI mapping API.
|
| 50 |
+
Deterministic β an LLM guessing ISINs is exactly the kind of thing that must not be."""
|
| 51 |
+
import json as _json
|
| 52 |
+
import urllib.request as _ur
|
| 53 |
+
from .llm import CTX
|
| 54 |
+
try:
|
| 55 |
+
body = _json.dumps([{"idType": "ID_ISIN", "idValue": isin}]).encode()
|
| 56 |
+
req = _ur.Request("https://api.openfigi.com/v3/mapping", data=body,
|
| 57 |
+
headers={"Content-Type": "application/json"})
|
| 58 |
+
with _ur.urlopen(req, timeout=20, context=CTX) as r:
|
| 59 |
+
rows = (_json.load(r)[0] or {}).get("data") or []
|
| 60 |
+
except Exception:
|
| 61 |
+
return []
|
| 62 |
+
rows = [x for x in rows if x.get("marketSector") == "Equity" and x.get("ticker")]
|
| 63 |
+
venues = _ISIN_VENUES.get(isin[:2], []) + [("US", ""), ("LN", ".L")]
|
| 64 |
+
out: list[str] = []
|
| 65 |
+
for code, sfx in venues:
|
| 66 |
+
for x in rows:
|
| 67 |
+
if x.get("exchCode") == code:
|
| 68 |
+
tk = str(x["ticker"]).upper().rstrip("/").replace("/", "-" if sfx == "" else "")
|
| 69 |
+
sym = tk + sfx
|
| 70 |
+
if sym not in out:
|
| 71 |
+
out.append(sym)
|
| 72 |
+
return out[:4]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
def resolve_symbol(query: str) -> dict:
|
| 76 |
+
"""Ticker, ISIN or company name -> {symbol, name, price, data}. Raises ValueError with a
|
| 77 |
user-facing message when nothing real matches."""
|
| 78 |
q = (query or "").strip()
|
| 79 |
if not q or len(q) > 60:
|
| 80 |
+
raise ValueError("Enter a ticker (e.g. NVDA, RELIANCE.NS), an ISIN, or a company name.")
|
| 81 |
qU = q.upper()
|
| 82 |
+
if _ISIN_RE.fullmatch(qU):
|
| 83 |
+
for sym in resolve_isin(qU):
|
| 84 |
+
d = _quote_exists(sym)
|
| 85 |
+
if d:
|
| 86 |
+
return {"symbol": sym, "name": d.get("name"), "price": d["price"], "data": d,
|
| 87 |
+
"resolved_from": q}
|
| 88 |
if _TICKER_RE.fullmatch(qU):
|
| 89 |
d = _quote_exists(qU)
|
| 90 |
if d:
|
| 91 |
return {"symbol": qU, "name": d.get("name"), "price": d["price"], "data": d}
|
| 92 |
# not a live ticker β treat as a company name/alias (or an outdated symbol)
|
| 93 |
attempts = [
|
| 94 |
+
(f"Company reference: {q!r}" + (" β this is an ISIN; identify the security and give its "
|
| 95 |
+
"PRIMARY exchange listing's Yahoo Finance symbol" if _ISIN_RE.fullmatch(qU) else ""), "fast"),
|
| 96 |
# the fast tier sometimes echoes a renamed/dead symbol back β escalate with context
|
| 97 |
(f"The symbol {q!r} returns NO live market quote β it is likely outdated, renamed "
|
| 98 |
f"or delisted (e.g. FB became META, SQ became XYZ). Identify the company and give "
|
tests/test_validator.py
CHANGED
|
@@ -83,3 +83,22 @@ def test_narrative_payload_is_percent_safe():
|
|
| 83 |
"orders": [{"delta_pct": -0.05}]})
|
| 84 |
assert p["outlook"]["current"]["expected_excess_12m"] == "7.1%"
|
| 85 |
assert p["orders"][0]["delta_pct"].endswith("of the book")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
"orders": [{"delta_pct": -0.05}]})
|
| 84 |
assert p["outlook"]["current"]["expected_excess_12m"] == "7.1%"
|
| 85 |
assert p["orders"][0]["delta_pct"].endswith("of the book")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def test_isin_resolution_prefers_primary_listing(monkeypatch):
|
| 89 |
+
from src import portfolio as PF
|
| 90 |
+
import json
|
| 91 |
+
rows = [{"ticker": "BSP", "exchCode": "GR", "marketSector": "Equity"},
|
| 92 |
+
{"ticker": "BA/", "exchCode": "LN", "marketSector": "Equity"},
|
| 93 |
+
{"ticker": "BAESY", "exchCode": "US", "marketSector": "Equity"}]
|
| 94 |
+
|
| 95 |
+
class _R:
|
| 96 |
+
def __init__(self, data): self.data = json.dumps([{"data": data}]).encode()
|
| 97 |
+
def read(self): return self.data
|
| 98 |
+
def __enter__(self): return self
|
| 99 |
+
def __exit__(self, *a): return False
|
| 100 |
+
monkeypatch.setattr(PF, "_quote_exists", lambda s: {"name": s, "price": 1.0} if s == "BA.L" else None)
|
| 101 |
+
import urllib.request
|
| 102 |
+
monkeypatch.setattr(urllib.request, "urlopen", lambda req, timeout=20, context=None: _R(rows))
|
| 103 |
+
assert PF.resolve_isin("GB0002634946")[0] == "BA.L"
|
| 104 |
+
assert PF.resolve_symbol("GB0002634946")["symbol"] == "BA.L"
|