Spaces:
Runtime error
Runtime error
Download engine/currency.py from BNAmericas/ComparerTool: direct link, hf CLI and curl.
- Browser
- Download file 16.3 kB
-
https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/currency.py
- Command line
-
hf download hf://spaces/BNAmericas/ComparerTool/engine/currency.py
-
curl -L -o currency.py https://huggingface.co/spaces/BNAmericas/ComparerTool/resolve/main/engine/currency.py
16.3 kB
| """ | |
| Currency detection + USD conversion for Capex values. | |
| Pipeline (per TIE Logics): | |
| 1. Detect currency from the Agentic AI Capex string (USD, US$, BRL, R$, EUR, €, etc.) | |
| 2. Parse the numeric amount and the unit multiplier (mn, bn, mil, mil millones, raw). | |
| 3. Convert non-USD amounts to USD using the FX rate for the source publication | |
| date. If that date is missing, use the BNA 'Last expert review' date. | |
| 4. Express the result in MILLIONS of USD (BNA always uses USD millions). | |
| 5. Round and format per the requested output language. | |
| FX rates resolution order: | |
| a) TIE 'FX Rates' sheet — exact (currency, date) match. | |
| b) TIE 'FX Rates' sheet — closest date (same currency). | |
| c) Live API call to frankfurter.app (works for major world currencies). | |
| d) Hard-coded last-resort approximate rate. | |
| The TIE sheet is the editable source of truth. Researchers can add rows there | |
| without touching code. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import re | |
| import urllib.request | |
| from datetime import datetime | |
| from typing import Dict, List, Optional, Tuple | |
| # ---------- Currency detection ---------- | |
| # Covers every currency that appears in the BNAmericas currency dropdown, | |
| # plus a few common majors (GBP/CAD/AUD/JPY/CNY). Order matters: longer / | |
| # more specific patterns first so 'CL$' matches as CLP before generic '$'. | |
| CURRENCY_SYMBOLS = [ | |
| (r"US\s*\$|USD\b|U\.S\.\s*Dollars?\b", "USD"), | |
| (r"R\$|BRL\b|reais\b|reais?\b", "BRL"), | |
| (r"€|EUR\b|euros?\b", "EUR"), | |
| (r"£|GBP\b|pounds?\s+sterling\b", "GBP"), | |
| (r"AR\$|ARS\b|argentine\s+pesos?\b", "ARS"), | |
| (r"CL\$|CLP\b|chilean\s+pesos?\b", "CLP"), | |
| (r"CO\$|COP\b|colombian\s+pesos?\b", "COP"), | |
| (r"MX\$|MXN\b|mexican\s+pesos?\b", "MXN"), | |
| (r"PEN\b|S/\.|soles?\b|peruvian\s+sol\b", "PEN"), | |
| (r"BOB\b|bolivian(?:os)?\b", "BOB"), | |
| (r"PYG\b|guaran[ií]?es?\b", "PYG"), | |
| (r"UYU\b|uruguayan\s+pesos?\b", "UYU"), | |
| (r"VEF\b|venezuelan\s+bol[íi]var(?:\s+fuerte)?\b", "VEF"), | |
| (r"VES\b|bol[íi]var(?:es)?(?:\s+soberano)?\b", "VES"), | |
| (r"XCD\b|east\s+caribbean\s+dollars?\b", "XCD"), | |
| (r"BSD\b|bahamian\s+dollars?\b", "BSD"), | |
| (r"BBD\b|barbadian\s+dollars?\b|bds\$", "BBD"), | |
| (r"CRC\b|costa\s+rican\s+col[óo]n(?:es)?\b", "CRC"), | |
| (r"CUC\b|cuban\s+convertible\s+pesos?\b", "CUC"), | |
| (r"GTQ\b|guatemalan\s+quetzal(?:es)?\b|quetzal(?:es)?\b", "GTQ"), | |
| (r"GYD\b|guyanese\s+dollars?\b", "GYD"), | |
| (r"HTG\b|haitian\s+gourdes?\b|gourdes?\b", "HTG"), | |
| (r"HNL\b|honduran\s+lempiras?\b|lempiras?\b", "HNL"), | |
| (r"BMD\b|bermudian\s+dollars?\b|bermudan\s+dollars?\b", "BMD"), | |
| (r"KYD\b|cayman\s+islands?\s+dollars?\b", "KYD"), | |
| (r"FKP\b|falkland\s+islands?\s+pounds?\b", "FKP"), | |
| (r"JMD\b|jamaican\s+dollars?\b|J\$", "JMD"), | |
| (r"NIO\b|nicaraguan\s+c[óo]rdobas?\b|c[óo]rdobas?\b", "NIO"), | |
| (r"PAB\b|panamanian\s+balboas?\b|balboas?\b", "PAB"), | |
| (r"DOP\b|dominican\s+pesos?\b|RD\$", "DOP"), | |
| (r"SRD\b|surinamese\s+dollars?\b|SR\$", "SRD"), | |
| (r"TTD\b|trinidad(?:\s+and\s+tobago)?\s+dollars?\b|TT\$", "TTD"), | |
| (r"BZD\b|belize(?:an)?\s+dollars?\b|BZ\$", "BZD"), | |
| (r"CAD\b|canadian\s+dollars?\b", "CAD"), | |
| (r"AUD\b|australian\s+dollars?\b", "AUD"), | |
| (r"JPY\b|yen\b", "JPY"), | |
| (r"CNY\b|RMB\b|yuan\b", "CNY"), | |
| # Generic "$" defaults to USD UNLESS preceded by a country code. | |
| (r"\$", "USD"), | |
| ] | |
| # Unit multipliers expressed as "amount × multiplier = raw units" | |
| # We always normalize to RAW UNITS first, then divide by 1e6 to get millions. | |
| # Patterns handle English / Spanish / Portuguese with accents (ã, õ, ñ, é). | |
| # Short-scale 'illion' multipliers. Listed largest→smallest so the regex | |
| # engine sees the longer token first ('quattuordecillion' before | |
| # 'decillion'). Each multiplier is 10^(3n+3) per the short scale. | |
| UNIT_PATTERNS = [ | |
| # 10^54 — septemdecillion | |
| (r"(?i)\bseptem(?:de)?cilli\w*\b", 10**54), | |
| # 10^51 — sexdecillion | |
| (r"(?i)\bsex(?:de)?cilli\w*\b", 10**51), | |
| # 10^48 — quindecillion | |
| (r"(?i)\bquin(?:de)?cilli\w*\b", 10**48), | |
| # 10^45 — quattuordecillion | |
| (r"(?i)\bquattuor(?:de)?cilli\w*\b", 10**45), | |
| # 10^42 — tredecillion | |
| (r"(?i)\btredecilli\w*\b", 10**42), | |
| # 10^39 — duodecillion | |
| (r"(?i)\bduodecilli\w*\b", 10**39), | |
| # 10^36 — undecillion | |
| (r"(?i)\bundecilli\w*\b", 10**36), | |
| # 10^33 — decillion | |
| (r"(?i)\bdecilli\w*\b", 10**33), | |
| # 10^30 — nonillion | |
| (r"(?i)\bnonilli\w*\b", 10**30), | |
| # 10^27 — octillion | |
| (r"(?i)\boctilli\w*\b", 10**27), | |
| # 10^24 — septillion | |
| (r"(?i)\bseptilli\w*\b", 10**24), | |
| # 10^21 — sextillion | |
| (r"(?i)\bsextilli\w*\b", 10**21), | |
| # 10^18 — quintillion | |
| (r"(?i)\bquintilli\w*\b", 10**18), | |
| # 10^15 — quadrillion | |
| (r"(?i)\bquadrilli\w*\b|\bcuatrill[oó]n(?:es)?\b", 10**15), | |
| # 10^12 — trillion (es: trillón / pt: trilhão also = 10^12 short scale) | |
| (r"(?i)(?:\btrillions?\b|\btn\b|\btrillon[eé]?s?\b|\btrilh\w*\b)", 10**12), | |
| # 10^9 — billion / bn / b / mil millones / bilhão | |
| (r"(?i)(?:\bbillions?\b|\bbn\b|\bb\b|\bmil\s+millones\b|\bbillon[eé]?s?\b|\bbilh\w*\b)", 10**9), | |
| # 10^6 — million / mn / mm / m / millón / milhão | |
| (r"(?i)(?:\bmillions?\b|\bmillon[eé]?s?\b|\bmn\b|\bmm\b|\bmilh\w*\b|\bm\b)", 10**6), | |
| # 10^3 — thousand / k / mil / miles | |
| (r"(?i)(?:\bthousands?\b|\bmiles\b|\bmil\b|\bk\b)", 10**3), | |
| ] | |
| def _detect_currency(s): | |
| """Return ISO code for the currency in the string, or 'USD' if a generic | |
| '$' appears, or None if no currency token is present.""" | |
| if not s: return None | |
| for pat, code in CURRENCY_SYMBOLS: | |
| if re.search(pat, s, re.IGNORECASE): | |
| return code | |
| return None | |
| def _detect_unit_multiplier(s): | |
| """Return integer multiplier (e.g. 1_000_000 for 'million'). Defaults to 1.""" | |
| if not s: return 1 | |
| low = s.lower() | |
| for pat, mult in UNIT_PATTERNS: | |
| if re.search(pat, low, re.IGNORECASE): | |
| return mult | |
| return 1 | |
| def _parse_numeric(s): | |
| """Pull the FIRST decimal/integer number from a string. Handles: | |
| - Plain integers of any length: '838000000' -> 838000000 | |
| - Grouped with thousands separators: '1,234,567' / '1.234.567' | |
| - Mixed grouped + decimal: '1.234.567,89' or '1,234,567.89' | |
| - Plain decimals: '1234.56' | |
| The grouped pattern is tried FIRST so '1,234' parses as 1234 (US | |
| thousands) rather than 1.234 (European decimal); if not grouped, | |
| plain integer/decimal fallback runs.""" | |
| if s is None: return None | |
| if isinstance(s, (int, float)): return float(s) | |
| text = re.sub(r"[A-Za-z$€£¥/\\]", " ", str(s)) | |
| text = re.sub(r"\s+", " ", text).strip() | |
| m = re.search( | |
| r"-?(?:\d{1,3}(?:[.,\s]\d{3})+(?:[.,]\d+)?|\d+(?:[.,]\d+)?)", | |
| text) | |
| if not m: return None | |
| raw = m.group(0) | |
| has_comma = "," in raw | |
| has_dot = "." in raw | |
| if has_comma and has_dot: | |
| # Whichever comes LAST is the decimal sep | |
| if raw.rfind(",") > raw.rfind("."): | |
| raw = raw.replace(".", "").replace(",", ".") | |
| else: | |
| raw = raw.replace(",", "") | |
| elif has_comma: | |
| # If exactly two digits after the last comma → decimal; else thousands | |
| last = raw.rsplit(",", 1) | |
| if len(last) == 2 and 1 <= len(last[1]) <= 2: | |
| raw = raw.replace(",", ".") | |
| else: | |
| raw = raw.replace(",", "") | |
| raw = raw.replace(" ", "") | |
| try: return float(raw) | |
| except ValueError: return None | |
| def parse_capex_value(s): | |
| """Parse '2,000 US$ mn' / '1.5 bilhões R$' / '€ 100 mn' style strings. | |
| Returns dict {currency, amount_raw_units, amount, multiplier} or None. | |
| """ | |
| if s is None or str(s).strip() == "": return None | |
| text = str(s).strip() | |
| currency = _detect_currency(text) or "USD" | |
| multiplier = _detect_unit_multiplier(text) | |
| amount = _parse_numeric(text) | |
| if amount is None: return None | |
| raw_units = amount * multiplier | |
| return { | |
| "currency": currency, | |
| "amount": amount, | |
| "multiplier": multiplier, | |
| "raw_units": raw_units, | |
| } | |
| # ---------- FX rate resolution ---------- | |
| # Last-resort approximate rates (updated periodically). Only used when both | |
| # the TIE sheet and the API are unreachable. | |
| FALLBACK_RATES = { | |
| "USD": 1.0, | |
| "BRL": 0.18, # Brazilian Real | |
| "ARS": 0.001, # Argentine Peso | |
| "CLP": 0.001, # Chilean Peso | |
| "COP": 0.00024, # Colombian Peso | |
| "MXN": 0.05, # Mexican Peso | |
| "PEN": 0.27, # Peruvian Sol | |
| "EUR": 1.07, | |
| "GBP": 1.26, | |
| "BOB": 0.145, | |
| "PYG": 0.00013, | |
| "UYU": 0.025, | |
| "VES": 0.027, # Bolívar Soberano | |
| "VEF": 0.0000001, # Bolívar Fuerte (legacy, hyperinflated) | |
| "XCD": 0.37, # East Caribbean Dollar (pegged ~2.70/USD) | |
| "BSD": 1.0, # Bahamian Dollar (pegged 1:1 USD) | |
| "BBD": 0.50, # Barbadian Dollar (pegged 2:1) | |
| "CRC": 0.0019, # Costa Rican Colón | |
| "CUC": 1.0, # Cuban Convertible (legacy 1:1) | |
| "GTQ": 0.13, # Guatemalan Quetzal | |
| "GYD": 0.0048, # Guyanese Dollar | |
| "HTG": 0.0076, # Haitian Gourde | |
| "HNL": 0.040, # Honduran Lempira | |
| "BMD": 1.0, # Bermudian Dollar (pegged 1:1) | |
| "KYD": 1.20, # Cayman Islands Dollar (pegged ~1.20) | |
| "FKP": 1.26, # Falkland Pound (pegged to GBP) | |
| "JMD": 0.0064, # Jamaican Dollar | |
| "NIO": 0.027, # Nicaraguan Córdoba | |
| "PAB": 1.0, # Panamanian Balboa (pegged 1:1) | |
| "DOP": 0.017, # Dominican Peso | |
| "SRD": 0.027, # Surinamese Dollar | |
| "TTD": 0.15, # Trinidad & Tobago Dollar | |
| "BZD": 0.50, # Belize Dollar (pegged 2:1) | |
| "CAD": 0.73, | |
| "AUD": 0.65, | |
| "JPY": 0.0067, | |
| "CNY": 0.14, | |
| } | |
| def _parse_date(s): | |
| if not s: return None | |
| if isinstance(s, datetime): return s | |
| s = str(s).strip() | |
| if not s: return None | |
| s = re.sub(r"T\d{2}:\d{2}.*$", "", s) | |
| for fmt in ("%Y-%m-%d","%Y/%m/%d","%Y.%m.%d","%d-%m-%Y","%d/%m/%Y","%d.%m.%Y"): | |
| try: return datetime.strptime(s, fmt) | |
| except ValueError: pass | |
| # Try month-name parsing (e.g. "March 2024") | |
| months = {"january":1,"february":2,"march":3,"april":4,"may":5,"june":6, | |
| "july":7,"august":8,"september":9,"october":10,"november":11,"december":12, | |
| "jan":1,"feb":2,"mar":3,"apr":4,"jun":6,"jul":7,"aug":8,"sep":9,"sept":9, | |
| "oct":10,"nov":11,"dec":12, | |
| "enero":1,"febrero":2,"marzo":3,"abril":4,"mayo":5,"junio":6,"julio":7, | |
| "agosto":8,"septiembre":9,"octubre":10,"noviembre":11,"diciembre":12} | |
| tokens = re.findall(r"[A-Za-zÀ-ÿ]+|\d+", s) | |
| month = year = None | |
| for t in tokens: | |
| tl = t.lower() | |
| if tl in months: month = months[tl] | |
| elif t.isdigit() and len(t) == 4: year = int(t) | |
| if month and year: | |
| try: return datetime(year, month, 1) | |
| except ValueError: return None | |
| return None | |
| # In-process cache: (currency, yyyy-mm-dd) -> rate | |
| _RATE_CACHE: Dict[Tuple[str, str], float] = {} | |
| def _rate_from_tie(currency, date_str, tie): | |
| """Look up the rate from the TIE 'FX Rates' sheet. Tries exact match | |
| first, then nearest date for the same currency.""" | |
| if tie is None: return None | |
| rates: List[Tuple[str, datetime, float]] = getattr(tie, "fx_rates", None) or [] | |
| if not rates: return None | |
| cur = (currency or "").upper() | |
| target_dt = _parse_date(date_str) | |
| if target_dt: | |
| for c, dt, rate in rates: | |
| if c.upper() == cur and dt.date() == target_dt.date(): | |
| return rate | |
| same = [(dt, rate) for c, dt, rate in rates if c.upper() == cur] | |
| if same and target_dt: | |
| same.sort(key=lambda x: abs((x[0] - target_dt).days)) | |
| return same[0][1] | |
| if same: | |
| return same[0][1] | |
| return None | |
| def _rate_from_frankfurter(currency, date_str): | |
| """Try multiple free FX APIs in order. Returns rate to multiply | |
| `currency` by to get USD, or None if all sources fail. | |
| Sources, in order: | |
| 1. fawazahmed0/currency-api (broad coverage: COP, ARS, MXN, CLP, | |
| PEN, etc. — historical via /YYYY-MM-DD/ or /latest/) | |
| 2. Frankfurter (only ~33 majors — fallback for the few it covers) | |
| """ | |
| cur = (currency or "").upper() | |
| if cur == "USD": return 1.0 | |
| dt = _parse_date(date_str) | |
| date_iso = dt.strftime("%Y-%m-%d") if dt else None | |
| # Source 1: fawazahmed0 currency-api (covers ALL BNA dropdown currencies) | |
| cur_lower = cur.lower() | |
| urls_1 = [] | |
| if date_iso: | |
| urls_1 += [ | |
| f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@{date_iso}/v1/currencies/{cur_lower}.json", | |
| f"https://{date_iso}.currency-api.pages.dev/v1/currencies/{cur_lower}.json", | |
| ] | |
| urls_1 += [ | |
| f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{cur_lower}.json", | |
| f"https://latest.currency-api.pages.dev/v1/currencies/{cur_lower}.json", | |
| ] | |
| for url in urls_1: | |
| try: | |
| with urllib.request.urlopen(url, timeout=8) as resp: | |
| data = json.loads(resp.read().decode("utf-8")) | |
| rate = data.get(cur_lower, {}).get("usd") | |
| if rate is not None: | |
| return float(rate) | |
| except Exception: | |
| continue | |
| # Source 2: Frankfurter (limited to majors but reliable) | |
| if date_iso: | |
| url = f"https://api.frankfurter.app/{date_iso}?from={cur}&to=USD" | |
| else: | |
| url = f"https://api.frankfurter.app/latest?from={cur}&to=USD" | |
| try: | |
| with urllib.request.urlopen(url, timeout=8) as resp: | |
| data = json.loads(resp.read().decode("utf-8")) | |
| rate = data.get("rates", {}).get("USD") | |
| if rate is not None: | |
| return float(rate) | |
| except Exception: | |
| pass | |
| return None | |
| def get_fx_rate(currency, date_str, tie=None): | |
| """Return the rate to multiply the source amount by to get USD. | |
| Order: | |
| 1. Live frankfurter.app for the EXACT requested date — primary | |
| source so historical rates align with the publication / review | |
| date instead of being capped by stale TIE-sheet entries. | |
| 2. TIE 'FX Rates' sheet — used only if the API call fails (e.g. | |
| no internet, currency unsupported by Frankfurter). | |
| 3. Hard-coded fallback rate. | |
| The rate for each (currency, date) is cached per-process so we don't | |
| hit the API repeatedly inside a single run.""" | |
| cur = (currency or "USD").upper() | |
| cache_key = (cur, str(date_str or "")) | |
| if cache_key in _RATE_CACHE: | |
| return _RATE_CACHE[cache_key] | |
| rate = _rate_from_frankfurter(cur, date_str) | |
| if rate is None: | |
| rate = _rate_from_tie(cur, date_str, tie) | |
| if rate is None: | |
| rate = FALLBACK_RATES.get(cur) | |
| if rate is not None: | |
| _RATE_CACHE[cache_key] = float(rate) | |
| return rate | |
| def to_usd_millions(parsed, date_for_fx, tie=None): | |
| """Convert a parsed Capex dict to a USD millions float.""" | |
| if not parsed: return None, None, "could not parse amount" | |
| raw_units = parsed["raw_units"] | |
| cur = parsed["currency"] | |
| rate = get_fx_rate(cur, date_for_fx, tie) | |
| if rate is None: | |
| return None, None, f"no FX rate for {cur} on {date_for_fx}" | |
| usd_units = raw_units * rate | |
| usd_millions = usd_units / 1_000_000.0 | |
| return usd_millions, rate, f"{cur}->USD @ {rate:.6f}" | |
| def fmt_usd_millions(value, lang): | |
| """Format the USD-millions number with the language-specific thousands / | |
| decimal separator. Always appends 'US$ mn' to match BNAmericas style.""" | |
| if value is None: return "" | |
| decimals = 0 if abs(value) >= 100 else (1 if abs(value) >= 1 else 2) | |
| s = f"{value:,.{decimals}f}" | |
| if lang in ("es", "pt"): | |
| s = s.replace(",", "§").replace(".", ",").replace("§", ".") | |
| return f"{s} US$ mn" | |
| def normalize_to_usd_mn(value_str, date_for_fx=None, tie=None, lang="en"): | |
| """Parse any capex string and return it formatted as a USD-millions | |
| string. If parsing fails, return the original string.""" | |
| if value_str is None: return "" | |
| s = str(value_str).strip() | |
| if not s: return "" | |
| parsed = parse_capex_value(s) | |
| if not parsed: return s | |
| usd_mn, rate, src = to_usd_millions(parsed, date_for_fx, tie) | |
| if usd_mn is None: return s | |
| return fmt_usd_millions(usd_mn, lang) | |