"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(market-data): retry unresolved symbols down the fallback chain
Yufeng He157f27f81d6d
diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex b5b4a6512..78a19ea80 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -204,13 +204,16 @@ def fetch_market_data(def _fetch_via_chain(src: str, market: str, src_codes: list[str]- ) -> tuple[dict[str, Any], str | None, type | None]:- """Run the ordered source chain for one group.-- Returns ``(data_map, used_source, provider_cls)`` — ``data_map`` keyed- by requested symbol -> OHLCV frame (possibly empty), the source name- that actually served it, and the serving loader class (both ``None``- when every attempt failed).+ ) -> tuple[dict[str, Any], str | None, type | None, dict[str, tuple[str, type]]]:+ """Run the ordered source chain for one group, per symbol.++ Returns ``(data_map, used_source, provider_cls, symbol_sources)`` —+ ``data_map`` keyed by requested symbol -> OHLCV frame (possibly+ empty), ``used_source``/``provider_cls`` the first source that served+ anything (``None`` when every attempt failed), and ``symbol_sources``+ mapping each served symbol to the source that actually served it. A+ partially successful attempt no longer stops the walk: symbols the+ loader omitted are retried down the chain and merged in."""chain = _chain_for(src, market)# An env-configured order override (MARKET_DATA_ORDER_<MARKET>, set@@ -239,9 +242,13 @@ def fetch_market_data(attempts = attempts[: max(1, max_fallback_attempts)]data_map: dict[str, Any] = {}+ symbol_sources: dict[str, tuple[str, type]] = {}used_source: str | None = Noneprovider_cls: type | None = None+ remaining = list(dict.fromkeys(src_codes))for attempt_src in attempts:+ if not remaining:+ breaktry:loader_cls = loader_resolver(attempt_src)except NoAvailableSourceError as exc:@@ -252,24 +259,37 @@ def fetch_market_data(continuetry:loader = loader_cls()- data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)- used_source = attempt_src- provider_cls = loader_cls- if data_map:- break+ partial = loader.fetch(remaining, start_date, end_date, interval=interval)except Exception as exc: # noqa: BLE001 — contained per-symbol fallbacklogger.error("market-data loader %r failed for %s; trying next source in chain: %s",- attempt_src, src_codes, exc,+ attempt_src, remaining, exc,)continue+ if not partial:+ continue+ if used_source is None:+ used_source = attempt_src+ provider_cls = loader_cls+ for symbol, df in partial.items():+ data_map[symbol] = df+ symbol_sources[symbol] = (attempt_src, loader_cls)+ remaining = [symbol for symbol in remaining if symbol not in partial]if used_source and used_source != src:logger.info("market-data source %r unavailable for %s; fell back to %r",src, src_codes, used_source,)- return data_map, used_source, provider_cls+ served_elsewhere = sorted(+ {serve_src for serve_src, _ in symbol_sources.values()} - {used_source}+ )+ if served_elsewhere:+ logger.info(+ "market-data per-symbol fallback: %s served the remaining symbols %r could not",+ served_elsewhere, src,+ )+ return data_map, used_source, provider_cls, symbol_sourcesdef _emit(symbol: str,@@ -310,11 +330,17 @@ def fetch_market_data(provenance[symbol] = entryfor (src, market), src_codes in groups.items():- data_map, used_source, provider_cls = _fetch_via_chain(src, market, src_codes)+ data_map, used_source, provider_cls, symbol_sources = _fetch_via_chain(+ src, market, src_codes+ )for symbol, df in data_map.items():+ symbol_source, symbol_provider_cls = symbol_sources.get(+ symbol, (used_source, provider_cls)+ )_emit(symbol, df,- src=src, used_source=used_source, provider_cls=provider_cls, market=market,+ src=src, used_source=symbol_source, provider_cls=symbol_provider_cls,+ market=market,)unresolved = [@@ -365,7 +391,7 @@ def fetch_market_data(continue# Sibling not already resolved — targeted re-fetch of just that# symbol through the same market's source chain.- sibling_data, used_source, provider_cls = _fetch_via_chain(+ sibling_data, used_source, provider_cls, _ = _fetch_via_chain(src, market, [sibling])if sibling_data:diff --git a/agent/tests/test_market_data.py b/agent/tests/test_market_data.pyindex ddd5e2470..5c2017920 100644--- a/agent/tests/test_market_data.py+++ b/agent/tests/test_market_data.py@@ -405,12 +405,24 @@ def test_fetch_loader_error_falls_through_to_unresolved() -> None:def test_fetch_missing_symbol_listed_as_unresolved() -> None:+ class _OnlyALoader:+ """Serves A.US on every source; B.US fails everywhere down the chain."""++ def fetch(self, codes, start_date, end_date, interval="1D"):+ idx = pd.to_datetime(["2026-01-01"])+ idx.name = "trade_date"+ return {+ code: pd.DataFrame({"close": [1.0]}, index=idx)+ for code in codes+ if code == "A.US"+ }+out = fetch_market_data(codes=["A.US", "B.US"],start_date="2026-01-01",end_date="2026-01-02",source="yahoo",- loader_resolver=lambda src: _PartialLoader,+ loader_resolver=lambda src: _OnlyALoader,)assert "A.US" in outassert out["_unresolved"] == ["B.US"]@@ -501,10 +513,10 @@ def test_fetch_canadian_aliases_sibling_already_resolved() -> None:assert "HIVE.V" in out and "HIVE.TO" in outassert out["HIVE.V"] == out["HIVE.TO"] # aliased — identical bars# The .V symbol must be aliased from the already-resolved .TO sibling:- # exactly one group fetch (both codes together), no separate re-fetch of- # the sibling after the fact.- assert len(calls) == 1+ # the group fetch covered both codes, and any later chain attempts for the+ # missing .V sibling returned nothing, so the alias is the only resolution.assert set(calls[0]) == {"HIVE.V", "HIVE.TO"}+ assert all(call == ["HIVE.V"] for call in calls[1:])assert out["_provenance"]["HIVE.V"]["resolved_symbol"] == "HIVE.TO"assert out["_provenance"]["HIVE.V"]["venue_fallback"] is True@@ -704,3 +716,79 @@ def test_fetch_json_rejects_nan_via_allow_nan_false() -> None:)parsed = json.loads(payload)assert parsed["A.US"][0]["close"] is None+++def test_fetch_auto_partial_batch_retries_missing_symbols_down_chain() -> None:+ """One 404 out of five must not strand the rest in _unresolved.++ yahoo serves four of five US symbols and omits the fifth; the chain walk+ must keep going with only the missing symbol so stooq can serve it, and+ provenance must name the source each symbol actually came from.+ """+ idx = pd.to_datetime(["2026-01-01"])+ idx.name = "trade_date"+ stooq_calls: list[list[str]] = []++ class _YahooPartialLoader:+ def fetch(self, codes, start_date, end_date, interval="1D"):+ return {+ code: pd.DataFrame({"close": [1.0]}, index=idx)+ for code in codes+ if code != "MSFT.US"+ }++ class _StooqLoader:+ def fetch(self, codes, start_date, end_date, interval="1D"):+ stooq_calls.append(list(codes))+ return {code: pd.DataFrame({"close": [2.0]}, index=idx) for code in codes}++ def resolver(src: str):+ return {"yahoo": _YahooPartialLoader, "stooq": _StooqLoader}[src]++ out = fetch_market_data(+ codes=["AAPL.US", "MSFT.US", "NVDA.US", "AMZN.US", "META.US"],+ start_date="2026-01-01",+ end_date="2026-01-02",+ source="auto",+ loader_resolver=resolver,+ include_provenance=True,+ )++ prov = out["_provenance"]+ assert "_unresolved" not in out+ assert "MSFT.US" in out+ assert stooq_calls == [["MSFT.US"]]+ assert prov["MSFT.US"]["source"] == "stooq"+ assert prov["MSFT.US"]["fallback_used"] is True+ assert prov["AAPL.US"]["source"] == "yahoo"+++def test_fetch_auto_full_batch_never_touches_the_next_source() -> None:+ """When the chain head serves everything, the walk stops as before."""+ stooq_calls: list[list[str]] = []++ class _YahooFullLoader:+ def fetch(self, codes, start_date, end_date, interval="1D"):+ idx = pd.to_datetime(["2026-01-01"])+ idx.name = "trade_date"+ return {code: pd.DataFrame({"close": [1.0]}, index=idx) for code in codes}++ class _StooqLoader:+ def fetch(self, codes, start_date, end_date, interval="1D"):+ stooq_calls.append(list(codes))+ idx = pd.to_datetime(["2026-01-01"])+ idx.name = "trade_date"+ return {code: pd.DataFrame({"close": [2.0]}, index=idx) for code in codes}++ def resolver(src: str):+ return {"yahoo": _YahooFullLoader, "stooq": _StooqLoader}[src]++ out = fetch_market_data(+ codes=["AAPL.US", "NVDA.US"],+ start_date="2026-01-01",+ end_date="2026-01-02",+ source="auto",+ loader_resolver=resolver,+ )+ assert stooq_calls == []+ assert "AAPL.US" in out and "NVDA.US" in out