"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(fmp): use Stable endpoint and prevent silent fallback for explicit source
lorenzozaneec6ff4d233e1e
diff --git a/agent/backtest/loaders/fmp_loader.py b/agent/backtest/loaders/fmp_loader.pyindex 706e63291..e6f607a10 100644--- a/agent/backtest/loaders/fmp_loader.py+++ b/agent/backtest/loaders/fmp_loader.py@@ -6,12 +6,13 @@ routes through :mod:`backtest.loaders._http` so calls share one process-wideminimum-spacing gate and a reused session.API format (public, documented):- https://financialmodelingprep.com/api/v3/historical-price-full/{SYMBOL}- ?from=YYYY-MM-DD&to=YYYY-MM-DD&apikey=KEY+ https://financialmodelingprep.com/stable/historical-price-eod/full+ ?symbol=SYMBOL&from=YYYY-MM-DD&to=YYYY-MM-DD&apikey=KEY-The JSON body is ``{"symbol": "AAPL", "historical": [{date, open, high, low,-close, volume}, ...]}`` in descending date order; an unknown symbol or empty-window yields an empty/absent ``historical`` array.+The JSON body is a top-level array ``[{date, open, high, low, close,+volume}, ...]`` in ascending date order (legacy ``{"symbol": "AAPL",+"historical": [...]}`` shape is still accepted for compatibility); an unknown+symbol or empty window yields an empty array.Auth: set ``FMP_API_KEY`` in the environment. Covers US equities only."""@@ -30,7 +31,7 @@ from backtest.loaders.registry import registerlogger = logging.getLogger(__name__)_API_KEY_ENV = "FMP_API_KEY"-_BASE_URL = "https://financialmodelingprep.com/api/v3/historical-price-full"+_BASE_URL = "https://financialmodelingprep.com/stable/historical-price-eod/full"# Shared throttle/session bucket for every FMP request in this process._HOST_KEY = "fmp"@@ -171,10 +172,10 @@ class DataLoader:return Nonepayload = throttled_get_json(- f"{_BASE_URL}/{symbol}",+ _BASE_URL,host_key=_HOST_KEY,min_interval=_min_interval(),- params={"from": start_date, "to": end_date, "apikey": api_key},+ params={"symbol": symbol, "from": start_date, "to": end_date, "apikey": api_key},)return _parse_historical(payload)@@ -182,6 +183,9 @@ class DataLoader:def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:"""Convert an FMP historical-price body into an ascending OHLCV frame.+ Stable API returns a top-level array; legacy ``{"historical": [...]}``+ shape is accepted for compatibility.+Args:payload: Decoded JSON body from the historical-price endpoint.@@ -189,7 +193,12 @@ def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:DataFrame indexed by ``trade_date`` with float ``open/high/low/close/volume`` columns, or ``None`` when no usable rows are present."""- historical = (payload or {}).get("historical") if isinstance(payload, dict) else None+ if isinstance(payload, list):+ historical = payload+ elif isinstance(payload, dict):+ historical = payload.get("historical")+ else:+ historical = Noneif not historical:return Nonediff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 7e2298f51..57ee66cfe 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -128,7 +128,10 @@ def _ensure_registered() -> None:# An explicit ``local`` request that is unavailable is a config problem the user# must see, not something to paper over with a Yahoo/Tencent fetch.# ``tickerall`` joins for the same reason (explicit-only, the user's own broker key).-_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local", "qveris", "tickerall"}) # QVERIS-INTEGRATION+# ``fmp`` joins because an explicit ``source="fmp"`` request must not silently+# return data from a different source when the Stable endpoint 403s — the+# caller asked for FMP provenance, not a Yahoo fallback (issue #1270).+_NO_NETWORK_FALLBACK_SOURCES: frozenset[str] = frozenset({"local", "qveris", "tickerall", "fmp"}) # QVERIS-INTEGRATION# ---------------------------------------------------------------------------diff --git a/agent/src/market_data.py b/agent/src/market_data.pyindex b5b4a6512..b1e31ed3b 100644--- a/agent/src/market_data.py+++ b/agent/src/market_data.py@@ -218,19 +218,24 @@ def fetch_market_data(# sources: the override list IS the attempt order, so a user who put# tushare first actually starts there. Guards: explicit source# requests stay src-first; the fallback_chain_provider test hook wins;- # local:/qveris/tickerall keep their no-network entry point.- override = (- get_source_order_override(market)- if source == "auto"- and fallback_chain_provider is None- and src not in _NO_NETWORK_FALLBACK_SOURCES- else None- )- candidates = (- list(override)- if override is not None and src in override- else [src, *chain]- )+ # local:/qveris/tickerall/fmp keep their no-network entry point+ # (explicit fmp must not silently return yahoo on Stable 403 — issue #1270).+ # Sources in _NO_NETWORK_FALLBACK_SOURCES never walk the chain.+ if src in _NO_NETWORK_FALLBACK_SOURCES:+ candidates = [src]+ override = None+ else:+ override = (+ get_source_order_override(market)+ if source == "auto"+ and fallback_chain_provider is None+ else None+ )+ candidates = (+ list(override)+ if override is not None and src in override+ else [src, *chain]+ )# Deduplicate (preserving order), then cap the attempt budget.attempts: list[str] = []for candidate in candidates:diff --git a/agent/tests/test_fmp_loader.py b/agent/tests/test_fmp_loader.pyindex d972cf61e..761aecefb 100644--- a/agent/tests/test_fmp_loader.py+++ b/agent/tests/test_fmp_loader.py@@ -119,17 +119,18 @@ class TestFetch:out = DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")assert set(out) == {"AAPL.US"}assert len(out["AAPL.US"]) == 2- # .US suffix stripped in the request URL.+ # .US suffix stripped; Stable endpoint uses ?symbol= query param.url = mock_get.call_args[0][0]- assert url.endswith("/AAPL")+ assert url == "https://financialmodelingprep.com/stable/historical-price-eod/full"params = mock_get.call_args.kwargs["params"]- assert params == {"from": "2024-01-01", "to": "2024-01-31", "apikey": "secret"}+ assert params == {"symbol": "AAPL", "from": "2024-01-01", "to": "2024-01-31", "apikey": "secret"}def test_one_failing_symbol_does_not_abort_batch(self, monkeypatch):monkeypatch.setenv("FMP_API_KEY", "secret")def _side(url, **kwargs):- if url.endswith("/BAD"):+ params = kwargs.get("params", {})+ if params.get("symbol") == "BAD":raise RuntimeError("boom")return _body("AAPL", _AAPL_BARS)diff --git a/agent/tests/test_fmp_stable_regression.py b/agent/tests/test_fmp_stable_regression.pynew file mode 100644index 000000000..b2b99fc80--- /dev/null+++ b/agent/tests/test_fmp_stable_regression.py@@ -0,0 +1,91 @@+"""Regression for issue 1270: FMP Stable endpoint and no silent fallback for explicit source=fmp."""++import pandas as pd++from backtest.loaders.fmp_loader import _parse_historical+from backtest.loaders.base import NoAvailableSourceError+++def _stable_bars():+ return [+ {"date": "2024-01-03", "open": 1.0, "high": 2.0, "low": 0.5, "close": 1.5, "volume": 100.0},+ {"date": "2024-01-04", "open": 3.0, "high": 4.0, "low": 2.5, "close": 3.5, "volume": 200.0},+ ]+++def test_parse_stable_top_level_array():+ """Stable API returns a top-level array, not {"historical": [...]}."""+ payload = _stable_bars()+ df = _parse_historical(payload)+ assert df is not None+ assert len(df) == 2+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+++def test_parse_stable_empty_array_returns_none():+ assert _parse_historical([]) is None+++def test_explicit_fmp_does_not_fallback_to_yahoo(monkeypatch):+ """Explicit source=fmp must not silently return yahoo data when FMP 403s."""+ from src.market_data import fetch_market_data++ class FailFMP:+ name = "fmp"+ markets = {"us_equity"}+ def __init__(self): pass+ def is_available(self): return True+ def fetch(self, codes, start_date, end_date, interval="1D"):+ raise RuntimeError("FMP 403 legacy retired")++ class YahooOK:+ name = "yahoo"+ markets = {"us_equity"}+ def __init__(self): pass+ def is_available(self): return True+ def fetch(self, codes, start_date, end_date, interval="1D"):+ df = pd.DataFrame([{"trade_date": pd.Timestamp("2024-01-03"), "open": 1, "high": 1, "low": 1, "close": 1, "volume": 1}]).set_index("trade_date")+ return {codes[0]: df}++ def resolver(name):+ if name == "fmp":+ return FailFMP+ if name == "yahoo":+ return YahooOK+ class Fail:+ name = name+ markets = {"us_equity"}+ def __init__(self): pass+ def is_available(self): return False+ def fetch(self, *a, **kw): raise RuntimeError("unavailable")+ return Fail++ result = fetch_market_data(+ codes=["AAPL.US"],+ start_date="2024-01-01",+ end_date="2024-01-31",+ source="fmp",+ interval="1D",+ loader_resolver=resolver,+ include_provenance=True,+ )+ # Must not contain yahoo data+ assert "AAPL.US" not in result, "explicit fmp should not fallback to yahoo"+ assert "_unresolved" in result and "AAPL.US" in result["_unresolved"]+ # provenance must not claim yahoo+ prov = result.get("_provenance", {})+ assert not any(v.get("source") == "yahoo" for v in prov.values())+++def test_explicit_fmp_unavailable_raises_no_fallback(monkeypatch):+ """registry: explicit fmp unavailable must raise, not fallback to yahoo."""+ from backtest.loaders.registry import get_loader_cls_with_fallback+ from backtest.loaders import registry++ fmp_cls = registry.LOADER_REGISTRY["fmp"]+ monkeypatch.setattr(fmp_cls, "is_available", lambda self: False)+ try:+ get_loader_cls_with_fallback("fmp")+ assert False, "should have raised NoAvailableSourceError"+ except NoAvailableSourceError as exc:+ assert "does not fall back" in str(exc)