"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(loaders): a BYMA line enters the ARS pool only when it is declared ARS (#1576)
Haozhe Wu83de3f435af5
diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.pyindex 25482d9b8..32784d093 100644--- a/agent/backtest/loaders/base.py+++ b/agent/backtest/loaders/base.py@@ -32,6 +32,12 @@ logger = logging.getLogger(__name__)_GBP_PENCE_CURRENCY = "GBp"_PRICE_COLUMNS = ("open", "high", "low", "close")_UK_EQUITY_PATTERN = re.compile(r"^[A-Z0-9&.\-]+\.L$", re.I)+# BYMA lists one issuer in pesos and again in dollars (GGAL.BA in ARS,+# GGALD.BA in USD -- Yahoo declares each; the trailing D is not a rule, since+# YPFD.BA is a peso line). The ar_equity pool is ARS, so the same contract as+# LSE applies: read the declared currency, admit only ARS.+_AR_EQUITY_PATTERN = re.compile(r"^[A-Z0-9&.\-]+\.BA$", re.I)+_AR_EQUITY_CURRENCY = "ARS"def is_lse_symbol(code: str) -> bool:@@ -67,6 +73,48 @@ def scale_pence_to_currency(return scaled, "GBp→GBP (÷100)"+def declared_currency_required(code: str) -> bool:+ """Return whether ``code``'s suffix names a venue that quotes in several currencies.++ A loader must read the source's declared currency for such a symbol and+ pass it to :func:`normalize_declared_quote_currency` before emitting bars.+ """+ code = str(code).strip()+ return bool(_UK_EQUITY_PATTERN.match(code) or _AR_EQUITY_PATTERN.match(code))+++def normalize_declared_quote_currency(+ frame: pd.DataFrame, code: str, currency: str | None+) -> pd.DataFrame:+ """Hold a frame to its market's currency contract and record the declared quote.++ Args:+ frame: Normalized OHLCV frame.+ code: The project symbol the frame belongs to.+ currency: Quote currency declared by the source, if any.++ Returns:+ The frame with ``attrs["quote_currency"]`` set whenever a currency was+ declared (GBP for an LSE line after pence scaling).++ Raises:+ ValueError: If an LSE line is not declared GBP/GBp, or a BYMA line is+ not declared ARS -- either would enter a single-currency pool in+ the wrong unit.+ """+ if is_lse_symbol(code):+ return normalize_lse_quote_currency(frame, currency)+ declared = currency.strip() if isinstance(currency, str) else ""+ if _AR_EQUITY_PATTERN.match(str(code).strip()) and declared != _AR_EQUITY_CURRENCY:+ raise ValueError(+ f"BYMA quote currency must be declared as {_AR_EQUITY_CURRENCY}; "+ f"got {declared or 'missing'!r}"+ )+ if declared:+ frame.attrs["quote_currency"] = declared+ return frame++def normalize_lse_quote_currency(frame: pd.DataFrame, currency: str | None) -> pd.DataFrame:diff --git a/agent/backtest/loaders/yahoo_loader.py b/agent/backtest/loaders/yahoo_loader.pyindex bc642ebc8..ffcf74111 100644--- a/agent/backtest/loaders/yahoo_loader.py+++ b/agent/backtest/loaders/yahoo_loader.py@@ -26,8 +26,7 @@ import pandas as pdfrom backtest.loaders import yahoo_clientfrom backtest.loaders.base import (cached_loader_fetch,- is_lse_symbol,- normalize_lse_quote_currency,+ normalize_declared_quote_currency,validate_date_range,)from backtest.loaders.registry import register@@ -287,8 +286,5 @@ class DataLoader:period2=period2,)frame = _rows_to_frame(rows, start_date, end_date, interval)- if is_lse_symbol(code):- frame = normalize_lse_quote_currency(frame, currency)- elif currency:- frame.attrs["quote_currency"] = currency+ frame = normalize_declared_quote_currency(frame, code, currency)return frame if not frame.empty else Nonediff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.pyindex 8a620730d..8cbc3d4a2 100644--- a/agent/backtest/loaders/yfinance_loader.py+++ b/agent/backtest/loaders/yfinance_loader.py@@ -10,10 +10,10 @@ import pandas as pdimport yfinance as yffrom backtest.loaders.base import (- is_lse_symbol,+ declared_currency_required,loader_cache_get,loader_cache_put,- normalize_lse_quote_currency,+ normalize_declared_quote_currency,validate_date_range,validate_ohlc,)@@ -350,13 +350,16 @@ class DataLoader:logger.warning("yfinance returned no usable data for %s", symbol)continue- # The engine currently has one static GBP pool for uk_equity.- # Normalize declared GBp/p to GBP, pass declared GBP unchanged,- # and reject USD/other/unknown .L lines before they can enter- # that pool. The suffix identifies LSE, never the currency.- if is_lse_symbol(symbol):+ # uk_equity is one static GBP pool and ar_equity one ARS pool,+ # while LSE and BYMA each list lines in other currencies. The+ # suffix identifies the venue, never the currency, so read the+ # declared one (a metadata request, made only for these venues)+ # and reject a line outside the pool's unit.+ if declared_currency_required(symbol):declared = _declared_currency(symbol)- normalized = normalize_lse_quote_currency(normalized, declared)+ normalized = normalize_declared_quote_currency(+ normalized, symbol, declared+ )loader_cache_put(source=self.name,diff --git a/agent/src/agent/grounding/evidence.py b/agent/src/agent/grounding/evidence.pyindex 07234ce27..72dedc9e6 100644--- a/agent/src/agent/grounding/evidence.py+++ b/agent/src/agent/grounding/evidence.py@@ -706,6 +706,15 @@ class _EvidenceMixin:and symbol_provenance.get("currency_conversion")else None)+ # The currency the source declared for this line wins over the+ # one its suffix implies: a venue can list lines in more than one+ # (#1566), and the answer is required to name this one.+ quote_currency = (+ str(symbol_provenance.get("quote_currency"))+ if isinstance(symbol_provenance, dict)+ and symbol_provenance.get("quote_currency")+ else _infer_currency(symbol)+ )for row in rows:if not isinstance(row, dict):continue@@ -727,7 +736,7 @@ class _EvidenceMixin:field=normalized_field,value=value,status="observed",- currency=_infer_currency(symbol),+ currency=quote_currency,venue=_infer_venue(symbol),currency_conversion=currency_conversion,)diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.pyindex 0a511ce2b..8bf702485 100644--- a/agent/src/agent/grounding/policies.py+++ b/agent/src/agent/grounding/policies.py@@ -76,6 +76,9 @@ _CURRENCY_ALIASES = {"KRW": ("krw", "韩元", "韩圜"),"INR": ("inr", "印度卢比", "卢比"),"CAD": ("cad", "c$", "加元", "加拿大元"),+ "GBP": ("gbp", "£", "英镑"),+ "VND": ("vnd", "₫", "越南盾"),+ "ARS": ("ars", "ar$", "阿根廷比索"),}# "元" counts as CNY only when no other currency's character precedes itdiff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex e9c17c185..65e5d6b8c 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -3406,3 +3406,50 @@ def test_crypto_pair_tables_match_the_resolver() -> None:# gold and forex are quoted in it too); grounding decides it by the base# whitelist instead, so it is the only permitted difference.assert set(g._CRYPTO_QUOTE_ASSETS) | {"USD"} == set(ss._CRYPTO_QUOTE_ASSETS)+++def _declared_currency_ledger(tmp_path: Path, symbol: str, quote_currency: str | None):+ """One two-bar quote for ``symbol``; provenance declares ``quote_currency`` if given."""+ payload = json.loads(_market_payload(symbol))+ if quote_currency is not None:+ payload["_provenance"][symbol]["quote_currency"] = quote_currency+ ledger = GroundingLedger(run_dir=tmp_path, user_message=f"{symbol} last close?")+ ledger.ingest_tool_result(+ tool_name="get_market_data",+ arguments={"codes": [symbol]},+ result=json.dumps(payload),+ call_id="prices",+ success=True,+ )+ return ledger+++def test_the_declared_quote_currency_is_the_one_an_answer_must_name(tmp_path: Path) -> None:+ """A venue can list one issuer in two currencies (GGAL.BA ARS, GGALD.BA USD, #1566)."""+ ledger = _declared_currency_ledger(tmp_path, "GGAL.BA", "USD")++ assert ledger.validate_final_answer(+ "GGAL.BA closed at 1.171 USD on 2026-06-24 (source: Yahoo)."+ ).valid+ wrong = ledger.validate_final_answer(+ "GGAL.BA closed at 1.171 ARS on 2026-06-24 (source: Yahoo)."+ )+ assert "currency_not_surfaced" in {issue["code"] for issue in wrong.issues}+++ ("symbol", "answer"),+ [+ ("VOD.L", "VOD.L closed at £1.171 on 2026-06-24 (source: Yahoo)."),+ ("VIC.VN", "VIC.VN closed at 1.171₫ on 2026-06-24 (source: Yahoo)."),+ ("GGAL.BA", "GGAL.BA closed at AR$1.171 on 2026-06-24 (source: Yahoo)."),+ ("GGAL.BA", "GGAL.BA 2026-06-24 收盘 1.171 阿根廷比索,数据来源:雅虎。"),+ ],+)+def test_a_currency_written_the_usual_way_counts_as_named(+ tmp_path: Path, symbol: str, answer: str+) -> None:+ """.L / .VN / .BA gained a currency, so its sign must satisfy the gate like $ or ¥ do."""+ result = _declared_currency_ledger(tmp_path, symbol, None).validate_final_answer(answer)++ assert result.valid is True, result.issuesdiff --git a/agent/tests/test_yahoo_loader.py b/agent/tests/test_yahoo_loader.pyindex b3a587ecb..49999ff4d 100644--- a/agent/tests/test_yahoo_loader.py+++ b/agent/tests/test_yahoo_loader.py@@ -9,6 +9,7 @@ import datetime as dtfrom unittest.mock import patchimport pandas as pd+import pytestfrom backtest.loaders.yahoo_loader import (DataLoader,@@ -412,3 +413,15 @@ class TestLoaderMetadata:}assert loader.requires_auth is Falseassert loader.is_available() is True++[email protected]("declared", ["USD", ""])+def test_fetch_rejects_a_byma_line_not_declared_in_pesos(declared: str) -> None:+ """GGALD.BA is BYMA's dollar line for Galicia; the ar_equity pool is ARS."""+ rows = [_row("2024-01-02", 4.1, 4.3, 4.0, 4.2, 1000)]+ with patch(+ "backtest.loaders.yahoo_loader.yahoo_client.get_chart",+ return_value=(rows, declared),+ ):+ out = DataLoader().fetch(["GGALD.BA"], "2024-01-01", "2024-01-31")+ assert "GGALD.BA" not in outdiff --git a/agent/tests/test_yfinance_uk_scale.py b/agent/tests/test_yfinance_uk_scale.pyindex a3b21cefe..d99fccd92 100644--- a/agent/tests/test_yfinance_uk_scale.py+++ b/agent/tests/test_yfinance_uk_scale.py@@ -161,3 +161,30 @@ def test_fetch_declared_currency_failure_is_fail_closed(monkeypatch.setattr(yfl.yf, "Ticker", raise_offline)assert yfl._declared_currency("VOD.L") is None++[email protected](("declared", "admitted"), [("ARS", True), ("USD", False), (None, False)])+def test_fetch_admits_only_a_peso_quoted_byma_line(+ monkeypatch: pytest.MonkeyPatch, declared: str | None, admitted: bool+) -> None:+ """BYMA lists GGAL.BA in ARS and GGALD.BA in USD; the ar_equity pool is ARS.++ Yahoo declared USD for SPYD.BA / GGALD.BA / AAPLD.BA (13.37 / 4.20 / 17.53,+ probed 2026-09-24) -- booked as pesos they are off by the exchange rate.+ """+ monkeypatch.delenv("VIBE_TRADING_DATA_CACHE", raising=False)+ asked: list[str] = []++ def declared_currency(symbol: str) -> str | None:+ asked.append(symbol)+ return declared++ monkeypatch.setattr(yfl, "_download_history", lambda *args: _download_frame())+ monkeypatch.setattr(yfl, "_declared_currency", declared_currency)++ result = yfl.DataLoader().fetch(["GGALD.BA"], "2025-01-01", "2025-01-03")++ assert asked == ["GGALD.BA"]+ assert ("GGALD.BA" in result) is admitted+ if admitted:+ assert result["GGALD.BA"].attrs["quote_currency"] == "ARS"