"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(data): fall back for missing symbols
xkam7ar89ac9eb89631
diff --git a/agent/backtest/runner.py b/agent/backtest/runner.pyindex b2e61c4b0..c1d88f7b2 100644--- a/agent/backtest/runner.py+++ b/agent/backtest/runner.py@@ -1094,26 +1094,46 @@ def _fetch_auto(codes: List[str], config: dict, interval: str = "1D") -> dict:src_name = getattr(loader, "name", "unknown")normalized_codes = _normalize_codes(market_codes, src_name)- result_codes = normalized_codesfields = config.get("extra_fields") if src_name == "tushare" else None- result = loader.fetch(normalized_codes, start_date, end_date, fields=fields, interval=interval)-- # Runtime fallback: try remaining sources when primary returns empty- if not result:- for fb_name in FALLBACK_CHAINS.get(market, []):- if fb_name == src_name or fb_name not in LOADER_REGISTRY:- continue- fb_loader = LOADER_REGISTRY[fb_name]()- if not fb_loader.is_available():- continue- fb_codes = _normalize_codes(market_codes, fb_name)- result = fb_loader.fetch(fb_codes, start_date, end_date, interval=interval)- if result:- result_codes = fb_codes- logger.info("Runtime fallback: %s -> %s for %s", src_name, fb_name, market)- break+ result = loader.fetch(+ normalized_codes,+ start_date,+ end_date,+ fields=fields,+ interval=interval,+ )+ market_result = _restore_original_codes(+ result, market_codes, normalized_codes+ )+ missing = [code for code in market_codes if code not in market_result]++ # Retry only missing symbols so a partial primary response does not+ # silently shrink the requested universe or refetch successful data.+ for fb_name in FALLBACK_CHAINS.get(market, []):+ if not missing:+ break+ if fb_name == src_name or fb_name not in LOADER_REGISTRY:+ continue+ fb_loader = LOADER_REGISTRY[fb_name]()+ if not fb_loader.is_available():+ continue+ fb_codes = _normalize_codes(missing, fb_name)+ fallback_result = fb_loader.fetch(+ fb_codes, start_date, end_date, interval=interval+ )+ mapped = _restore_original_codes(fallback_result, missing, fb_codes)+ if mapped:+ market_result.update(mapped)+ missing = [code for code in missing if code not in mapped]+ logger.info(+ "Runtime fallback: %s -> %s for %s", src_name, fb_name, market+ )- merged.update(_restore_original_codes(result, market_codes, result_codes))+ if missing:+ raise NoAvailableSourceError(+ f"incomplete data for {market}; missing symbols: {missing}"+ )+ merged.update(market_result)return merged@@ -1138,8 +1158,10 @@ def fetch_data_map(config: dict) -> DataFetchResult:if source == "auto":data_map = _fetch_auto(codes, config, interval)loader: Any = _AutoLoader(data_map)+ used_sources: list[str] = []else:codes = _normalize_codes(codes, source)+ primary_source = sourceloader = _get_loader(source)()data_map = loader.fetch(codes,@@ -1148,8 +1170,9 @@ def fetch_data_map(config: dict) -> DataFetchResult:fields=config.get("extra_fields") or None,interval=interval,)- if data_map and len(data_map) < len(codes):- missing = set(codes) - set(data_map)+ used_sources = [source] if data_map else []+ missing = [code for code in codes if code not in data_map]+ if missing:logger.warning("source=%s returned data for %d/%d symbols; missing: %s",source,@@ -1157,31 +1180,48 @@ def fetch_data_map(config: dict) -> DataFetchResult:len(codes),missing,)- if not data_map and codes:+ if missing:market = _detect_market(codes[0])for fallback_source in FALLBACK_CHAINS.get(market, []):- if fallback_source == source or fallback_source not in LOADER_REGISTRY:+ if not missing:+ break+ if (+ fallback_source == primary_source+ or fallback_source not in LOADER_REGISTRY+ ):continuefallback_loader = LOADER_REGISTRY[fallback_source]()if not fallback_loader.is_available():continue- fallback_codes = _normalize_codes(codes, fallback_source)- data_map = fallback_loader.fetch(+ fallback_codes = _normalize_codes(missing, fallback_source)+ fallback_result = fallback_loader.fetch(fallback_codes,config.get("start_date", ""),config.get("end_date", ""),interval=interval,)- if data_map:- logger.info("Runtime fallback: %s -> %s", source, fallback_source)- source = fallback_source- codes = fallback_codes- loader = fallback_loader- break+ mapped = _restore_original_codes(+ fallback_result, missing, fallback_codes+ )+ if mapped:+ data_map.update(mapped)+ missing = [code for code in missing if code not in mapped]+ if not used_sources:+ source = fallback_source+ loader = fallback_loader+ used_sources.append(fallback_source)+ logger.info(+ "Runtime fallback: %s -> %s", primary_source, fallback_source+ )++ if missing:+ raise NoAvailableSourceError(+ f"incomplete data for source={primary_source}; missing symbols: {missing}"+ )data_map = _sanitize_data_map(data_map)effective_sources = (- sorted(_group_codes_by_source(codes)) if source == "auto" else [source]+ sorted(_group_codes_by_source(codes)) if source == "auto" else used_sources)return DataFetchResult(data_map=data_map,diff --git a/agent/tests/test_ui_services.py b/agent/tests/test_ui_services.pyindex 244a56e87..785184388 100644--- a/agent/tests/test_ui_services.py+++ b/agent/tests/test_ui_services.py@@ -10,6 +10,7 @@ import pandas as pdimport pytestimport backtest.runner as runner+from backtest.loaders.base import NoAvailableSourceErrorfrom src.ui_services import reconstruct_price_series@@ -265,3 +266,125 @@ def test_fetch_auto_restores_original_crypto_symbol()assert list(result) == ["BTC/USDT"]+++def test_fetch_auto_falls_back_only_for_missing_symbols(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ frame = pd.DataFrame(+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0]},+ index=pd.DatetimeIndex([pd.Timestamp("2026-01-01")]),+ )+ calls: list[tuple[str, list[str]]] = []++ class PrimaryLoader:+ name = "primary"++ def fetch(self, codes, start_date, end_date, **kwargs):+ del start_date, end_date, kwargs+ calls.append((self.name, list(codes)))+ return {"AAPL.US": frame}++ class BackupLoader:+ name = "backup"++ def is_available(self):+ return True++ def fetch(self, codes, start_date, end_date, **kwargs):+ del start_date, end_date, kwargs+ calls.append((self.name, list(codes)))+ return {code: frame for code in codes}++ monkeypatch.setattr(runner, "resolve_loader", lambda market: PrimaryLoader())+ monkeypatch.setitem(runner.FALLBACK_CHAINS, "us_equity", ["primary", "backup"])+ monkeypatch.setitem(runner.LOADER_REGISTRY, "backup", BackupLoader)++ result = runner._fetch_auto(+ ["AAPL.US", "MSFT.US"],+ {"start_date": "2026-01-01", "end_date": "2026-01-02"},+ )++ assert list(result) == ["AAPL.US", "MSFT.US"]+ assert calls == [+ ("primary", ["AAPL.US", "MSFT.US"]),+ ("backup", ["MSFT.US"]),+ ]+++def test_explicit_fetch_falls_back_only_for_missing_symbols(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ frame = pd.DataFrame(+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0]},+ index=pd.DatetimeIndex([pd.Timestamp("2026-01-01")]),+ )+ calls: list[tuple[str, list[str]]] = []++ class PrimaryLoader:+ def fetch(self, codes, start_date, end_date, **kwargs):+ del start_date, end_date, kwargs+ calls.append(("primary", list(codes)))+ return {"AAPL.US": frame}++ class BackupLoader:+ def is_available(self):+ return True++ def fetch(self, codes, start_date, end_date, **kwargs):+ del start_date, end_date, kwargs+ calls.append(("backup", list(codes)))+ return {code: frame for code in codes}++ monkeypatch.setattr(runner, "_get_loader", lambda source: PrimaryLoader)+ monkeypatch.setitem(runner.FALLBACK_CHAINS, "us_equity", ["backup"])+ monkeypatch.setitem(runner.LOADER_REGISTRY, "backup", BackupLoader)++ result = runner.fetch_data_map(+ {+ "codes": ["AAPL.US", "MSFT.US"],+ "start_date": "2026-01-01",+ "end_date": "2026-01-02",+ "source": "primary",+ }+ )++ assert list(result.data_map) == ["AAPL.US", "MSFT.US"]+ assert result.effective_sources == ["primary", "backup"]+ assert calls == [+ ("primary", ["AAPL.US", "MSFT.US"]),+ ("backup", ["MSFT.US"]),+ ]+++def test_fetch_stops_when_fallbacks_leave_symbols_missing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ frame = pd.DataFrame(+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0]},+ index=pd.DatetimeIndex([pd.Timestamp("2026-01-01")]),+ )++ class PartialLoader:+ name = "primary"++ def fetch(self, codes, start_date, end_date, **kwargs):+ del codes, start_date, end_date, kwargs+ return {"AAPL.US": frame}++ config = {"start_date": "2026-01-01", "end_date": "2026-01-02"}+ monkeypatch.setattr(runner, "resolve_loader", lambda market: PartialLoader())+ monkeypatch.setitem(runner.FALLBACK_CHAINS, "us_equity", [])++ with pytest.raises(NoAvailableSourceError, match="MSFT.US"):+ runner._fetch_auto(["AAPL.US", "MSFT.US"], config)++ monkeypatch.setattr(runner, "_get_loader", lambda source: PartialLoader)+ with pytest.raises(NoAvailableSourceError, match="MSFT.US"):+ runner.fetch_data_map(+ {+ **config,+ "codes": ["AAPL.US", "MSFT.US"],+ "source": "primary",+ }+ )