Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loaders): serve adjusted prices on FMP and Tiingo paths

lorenzozaneee1a0932f483a
diff --git a/agent/backtest/loaders/fmp_loader.py b/agent/backtest/loaders/fmp_loader.py
index 706e63291..a66b42b0c 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-wide
minimum-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,
+adjClose, volume}, ...]`` in descending 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 register
logger = 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"
@@ -145,7 +146,10 @@ class DataLoader:
return result
def _fetch_one(
- self, code: str, start_date: str, end_date: str,
+ self,
+ code: str,
+ start_date: str,
+ end_date: str,
) -> Optional[pd.DataFrame]:
"""Fetch and parse one symbol's daily bars; ``None`` on no data.
@@ -171,10 +175,15 @@ class DataLoader:
return None
payload = 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,14 +191,27 @@ class DataLoader:
def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:
"""Convert an FMP historical-price body into an ascending OHLCV frame.
+ FMP's historical endpoint returns dividend- and split-adjusted prices via
+ ``adjClose`` (qfq caliber, matching eastmoney/tencent/yahoo/yfinance).
+ Scale OHLC by ``adjClose/close`` when present so backtests see total-return
+ prices rather than raw gaps.
+
Args:
payload: Decoded JSON body from the historical-price endpoint.
+ Accepts both the legacy ``{"historical": [...]}`` dict and the
+ Stable top-level ``[...]`` array.
Returns:
DataFrame indexed by ``trade_date`` with float ``open/high/low/close/
- volume`` columns, or ``None`` when no usable rows are present.
+ volume`` columns (adjusted), 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):
+ h = payload.get("historical")
+ historical = h if isinstance(h, list) else None
+ else:
+ historical = None
if not historical:
return None
@@ -197,12 +219,29 @@ def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:
for bar in historical:
if not isinstance(bar, dict) or "date" not in bar:
continue
- rows.append(
- {
- "trade_date": bar["date"],
- **{field: bar.get(field) for field in _OHLCV_FIELDS},
- }
- )
+ adj_close = bar.get("adjClose")
+ close_raw = bar.get("close")
+ ratio: Optional[float] = None
+ try:
+ if adj_close is not None and close_raw is not None:
+ ac = float(adj_close)
+ cr = float(close_raw)
+ if cr > 0 and ac > 0:
+ r = ac / cr
+ if 0.01 <= r <= 100:
+ ratio = r
+ except (TypeError, ValueError):
+ ratio = None
+ row = {"trade_date": bar["date"]}
+ for field in _OHLCV_FIELDS:
+ val = bar.get(field)
+ if field != "volume" and ratio is not None and val is not None:
+ try:
+ val = float(val) * ratio
+ except (TypeError, ValueError):
+ pass
+ row[field] = val
+ rows.append(row)
if not rows:
return None
diff --git a/agent/backtest/loaders/tiingo_loader.py b/agent/backtest/loaders/tiingo_loader.py
index cbc91c6d1..4cf6c0dfb 100644
--- a/agent/backtest/loaders/tiingo_loader.py
+++ b/agent/backtest/loaders/tiingo_loader.py
@@ -6,11 +6,15 @@ Tiingo serves end-of-day US-equity bars from a documented public endpoint:
?startDate=YYYY-MM-DD&endDate=YYYY-MM-DD&token={KEY}
The response is a JSON array of per-day objects, each carrying ``date`` plus
-``open``/``high``/``low``/``close``/``volume`` (and adjusted variants we ignore).
-A token is required; it is read from the ``TIINGO_API_KEY`` environment variable
-and is never hard-coded. Like every other ban-prone HTTP loader in this package,
-all requests route through :mod:`backtest.loaders._http` for per-host throttling
-and session reuse — Tiingo rate-limits by client and rejects unspaced bursts.
+``open``/``high``/``low``/``close``/``volume`` and split/dividend-adjusted
+variants ``adjOpen``/``adjHigh``/``adjLow``/``adjClose``/``adjVolume``. This
+loader prefers the adjusted OHLC (qfq caliber, matching yahoo/yfinance/
+eastmoney/tencent) so backtests see total-return prices. Volume stays raw per
+qfq convention. A token is required; it is read from the ``TIINGO_API_KEY``
+environment variable and is never hard-coded. Like every other ban-prone HTTP
+loader in this package, all requests route through :mod:`backtest.loaders._http`
+for per-host throttling and session reuse — Tiingo rate-limits by client and
+rejects unspaced bursts.
"""
from __future__ import annotations
@@ -82,27 +86,93 @@ def _to_tiingo_symbol(code: str) -> Optional[str]:
def _rows_to_frame(rows: List[dict]) -> Optional[pd.DataFrame]:
"""Convert Tiingo's per-day records into the normalized OHLCV frame.
+ Prefers Tiingo's adjusted OHLC (``adjOpen``/``adjHigh``/``adjLow``/
+ ``adjClose``) when present so the frame is dividend- and split-adjusted
+ (qfq). Falls back to raw ``open``/``high``/``low``/``close`` when adjusted
+ fields are absent, and to an ``adjClose/close`` ratio when only
+ ``adjClose`` is present.
+
Args:
rows: JSON array decoded from the prices endpoint; each item carries a
- ``date`` plus ``open``/``high``/``low``/``close``/``volume``.
+ ``date`` plus ``open``/``high``/``low``/``close``/``volume`` and
+ optionally ``adj*`` variants.
Returns:
A DataFrame indexed by a ``trade_date`` :class:`~pandas.DatetimeIndex`
- with float ``open``/``high``/``low``/``close``/``volume`` columns, or
- ``None`` when no usable bar is present.
+ with float ``open``/``high``/``low``/``close``/``volume`` columns
+ (adjusted when available), or ``None`` when no usable bar is present.
"""
parsed: List[dict] = []
for row in rows:
date = row.get("date")
if date is None:
continue
+ # Prefer fully adjusted OHLC when Tiingo provides them.
+ has_adj_ohlc = all(
+ row.get(k) is not None for k in ("adjOpen", "adjHigh", "adjLow", "adjClose")
+ )
+ if has_adj_ohlc:
+ o, h, lo, c = (
+ row.get("adjOpen"),
+ row.get("adjHigh"),
+ row.get("adjLow"),
+ row.get("adjClose"),
+ )
+ else:
+ # If only adjClose is present, derive the dividend/split factor and
+ # scale raw OHLC so high/low/open stay consistent with the adjusted close.
+ adj_close = row.get("adjClose")
+ raw_close = row.get("close")
+ ratio = None
+ try:
+ if adj_close is not None and raw_close is not None:
+ ac = float(adj_close)
+ rc = float(raw_close)
+ if rc > 0 and ac > 0:
+ r = ac / rc
+ if 0.01 <= r <= 100:
+ ratio = r
+ except (TypeError, ValueError):
+ ratio = None
+ if ratio is not None:
+ try:
+ o = (
+ float(row.get("open")) * ratio
+ if row.get("open") is not None
+ else None
+ )
+ h = (
+ float(row.get("high")) * ratio
+ if row.get("high") is not None
+ else None
+ )
+ lo = (
+ float(row.get("low")) * ratio
+ if row.get("low") is not None
+ else None
+ )
+ c = float(adj_close)
+ except (TypeError, ValueError):
+ o, h, lo, c = (
+ row.get("open"),
+ row.get("high"),
+ row.get("low"),
+ row.get("close"),
+ )
+ else:
+ o, h, lo, c = (
+ row.get("open"),
+ row.get("high"),
+ row.get("low"),
+ row.get("close"),
+ )
parsed.append(
{
"trade_date": date,
- "open": row.get("open"),
- "high": row.get("high"),
- "low": row.get("low"),
- "close": row.get("close"),
+ "open": o,
+ "high": h,
+ "low": lo,
+ "close": c,
"volume": row.get("volume"),
}
)
@@ -112,7 +182,9 @@ def _rows_to_frame(rows: List[dict]) -> Optional[pd.DataFrame]:
frame = pd.DataFrame(parsed)
# Tiingo stamps each bar with an ISO-8601 datetime (e.g.
# "2024-01-02T00:00:00.000Z"); normalize to a tz-naive midnight index.
- index = pd.DatetimeIndex(pd.to_datetime(frame["trade_date"], utc=True, errors="coerce"))
+ index = pd.DatetimeIndex(
+ pd.to_datetime(frame["trade_date"], utc=True, errors="coerce")
+ )
if getattr(index, "tz", None) is not None:
index = index.tz_convert(None)
frame = frame.drop(columns=["trade_date"])
@@ -200,16 +272,24 @@ class DataLoader:
start_date=start_date,
end_date=end_date,
fields=None,
- fetch=lambda code=code: self._fetch_one(code, start_date, end_date, key),
+ fetch=lambda code=code: self._fetch_one(
+ code, start_date, end_date, key
+ ),
)
if frame is not None and not frame.empty:
result[code] = frame
- except Exception as exc: # noqa: BLE001 - one symbol must not kill the batch
+ except (
+ Exception
+ ) as exc: # noqa: BLE001 - one symbol must not kill the batch
logger.warning("tiingo failed for %s: %s", code, exc)
return result
def _fetch_one(
- self, code: str, start_date: str, end_date: str, key: str,
+ self,
+ code: str,
+ start_date: str,
+ end_date: str,
+ key: str,
) -> Optional[pd.DataFrame]:
"""Fetch and normalize a single symbol's daily bars.
diff --git a/agent/tests/test_fmp_loader.py b/agent/tests/test_fmp_loader.py
index d972cf61e..8251a9fdb 100644
--- a/agent/tests/test_fmp_loader.py
+++ b/agent/tests/test_fmp_loader.py
@@ -119,17 +119,17 @@ 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"):
+ if kwargs.get("params", {}).get("symbol") == "BAD":
raise RuntimeError("boom")
return _body("AAPL", _AAPL_BARS)