"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(backtest): serve adjusted prices on the Yahoo loader paths
Yufeng He1fcab81d1b02
diff --git a/agent/backtest/loaders/yahoo_client.py b/agent/backtest/loaders/yahoo_client.pyindex ce5c7f186..af80668f2 100644--- a/agent/backtest/loaders/yahoo_client.py+++ b/agent/backtest/loaders/yahoo_client.py@@ -191,7 +191,9 @@ def get_chart(structurally unusable."""yahoo_symbol = map_symbol(symbol)- params: Dict[str, Any] = {"interval": interval}+ # events=div,splits makes Yahoo return the adjclose series next to the raw+ # quote, which is the only adjusted-caliber source on this endpoint.+ params: Dict[str, Any] = {"interval": interval, "events": "div,splits"}if range_:params["range"] = range_else:@@ -234,6 +236,12 @@ def _parse_chart(payload: Any, yahoo_symbol: str) -> Tuple[List[Dict[str, Any]],timestamps = result.get("timestamp") or []quotes = (((result.get("indicators") or {}).get("quote")) or [{}])[0] or {}+ # Every other loader on this chain serves adjusted prices (qfq), so the+ # raw quote would book splits as crashes and ex-dividend gaps as losses.+ # Scale to Yahoo's adjusted close when it is present, keeping raw volume.+ adjclose_series = (+ (((result.get("indicators") or {}).get("adjclose")) or [{}])[0] or {}+ ).get("adjclose")rows: List[Dict[str, Any]] = []for index, ts in enumerate(timestamps):@@ -241,8 +249,13 @@ def _parse_chart(payload: Any, yahoo_symbol: str) -> Tuple[List[Dict[str, Any]],# A non-trading slot leaves OHLC null; skip rather than emit a NaN bar.if any(values[field] is None for field in ("open", "high", "low", "close")):continue+ ratio = _adjust_ratio(_at(adjclose_series, index), values["close"])row: Dict[str, Any] = {"trade_date": ts}- row.update({field: _to_float(values[field]) for field in _QUOTE_FIELDS})+ for field in _QUOTE_FIELDS:+ value = _to_float(values[field])+ if value is not None and field != "volume" and ratio is not None:+ value *= ratio+ row[field] = valuerows.append(row)return rows, currency@@ -254,6 +267,22 @@ def _at(series: Any, index: int) -> Any:return None+def _adjust_ratio(adj_close: Any, raw_close: Any) -> Optional[float]:+ """Return adjclose/close when both are usable, else ``None`` (keep raw).++ A ratio that is missing, non-numeric, or wildly off (a bad tick, not a+ corporate action) must not corrupt the bar; raw is the safer fallback.+ """+ adj = _to_float(adj_close)+ raw = _to_float(raw_close)+ if adj is None or raw is None or raw <= 0 or adj <= 0:+ return None+ ratio = adj / raw+ if not 0.01 <= ratio <= 100:+ return None+ return ratio++def _to_float(value: Any) -> Optional[float]:"""Coerce a Yahoo numeric (or ``None``) to ``float``, ``None`` on failure."""if value is None:diff --git a/agent/backtest/loaders/yfinance_loader.py b/agent/backtest/loaders/yfinance_loader.pyindex 6a41a61fb..fd525c4d2 100644--- a/agent/backtest/loaders/yfinance_loader.py+++ b/agent/backtest/loaders/yfinance_loader.py@@ -134,7 +134,9 @@ def _download_history(start=start_date,end=end_date,interval=interval,- auto_adjust=False,+ # Adjusted OHLC like every other loader on the chain (qfq caliber);+ # volume stays raw on both sides of the comparison.+ auto_adjust=True,progress=False,)diff --git a/agent/tests/test_yahoo_client.py b/agent/tests/test_yahoo_client.pyindex 07857514a..57724738f 100644--- a/agent/tests/test_yahoo_client.py+++ b/agent/tests/test_yahoo_client.py@@ -112,7 +112,7 @@ class TestGetChart:rows, currency = yahoo_client.get_chart("AAPL.US", interval="1d", range_="5d")assert captured["url"].endswith("/AAPL")- assert captured["params"] == {"interval": "1d", "range": "5d"}+ assert captured["params"] == {"interval": "1d", "range": "5d", "events": "div,splits"}# No meta in this payload -> no declared currency.assert currency == ""# Third bar has null OHLC and must be dropped.@@ -127,6 +127,77 @@ class TestGetChart:}assert rows[1]["trade_date"] == 1700086400+ def test_adjclose_scales_ohlc_and_keeps_volume(self, monkeypatch):+ def fake_get_json(url, **kwargs):+ return {+ "chart": {+ "error": None,+ "result": [+ {+ "timestamp": [1700000000, 1700086400],+ "indicators": {+ "quote": [+ {+ "open": [400.0, 100.0],+ "high": [410.0, 105.0],+ "low": [390.0, 95.0],+ "close": [405.0, 100.0],+ "volume": [1000, 4000],+ }+ ],+ # A 4:1 split between the two bars: the raw+ # close halves but the adjusted close is level.+ "adjclose": [{"adjclose": [101.25, 100.0]}],+ },+ }+ ],+ }+ }++ monkeypatch.setattr(yahoo_client, "throttled_get_json", fake_get_json)++ rows, _ = yahoo_client.get_chart("AAPL.US", range_="5d")++ assert rows[0]["close"] == 405.0 * (101.25 / 405.0)+ assert rows[0]["high"] == 410.0 * (101.25 / 405.0)+ assert rows[1]["close"] == 100.0+ # Split-adjusted prices, raw volume on both bars.+ assert rows[0]["volume"] == 1000.0+ assert rows[1]["volume"] == 4000.0++ def test_missing_or_bad_adjclose_keeps_raw_prices(self, monkeypatch):+ def fake_get_json(url, **kwargs):+ return {+ "chart": {+ "error": None,+ "result": [+ {+ "timestamp": [1700000000, 1700086400, 1700172800],+ "indicators": {+ "quote": [+ {+ "open": [10.0, 11.0, 12.0],+ "high": [10.5, 11.5, 12.5],+ "low": [9.5, 10.5, 11.5],+ "close": [10.2, 11.2, 12.2],+ "volume": [100, 200, 300],+ }+ ],+ "adjclose": [{"adjclose": [None, 0.0, 12.2]}],+ },+ }+ ],+ }+ }++ monkeypatch.setattr(yahoo_client, "throttled_get_json", fake_get_json)++ rows, _ = yahoo_client.get_chart("AAPL.US", range_="5d")++ assert rows[0]["close"] == 10.2+ assert rows[1]["close"] == 11.2+ assert rows[2]["close"] == 12.2+def test_period_window_when_no_range(self, monkeypatch):captured: Dict[str, Any] = {}@@ -140,7 +211,7 @@ class TestGetChart:assert rows == []assert currency == ""- assert captured["params"] == {"interval": "1d", "period1": 100, "period2": 200}+ assert captured["params"] == {"interval": "1d", "period1": 100, "period2": 200, "events": "div,splits"}def test_chart_error_raises(self, monkeypatch):def fake_get_json(url, **kwargs):diff --git a/agent/tests/test_yfinance_auto_adjust.py b/agent/tests/test_yfinance_auto_adjust.pynew file mode 100644index 000000000..54b62c00e--- /dev/null+++ b/agent/tests/test_yfinance_auto_adjust.py@@ -0,0 +1,20 @@+"""yfinance download always requests the adjusted series (qfq caliber)."""++from __future__ import annotations++from backtest.loaders import yfinance_loader as yfl+++def test_download_history_requests_auto_adjust(monkeypatch):+ captured = {}++ def fake_download(tickers, **kwargs):+ captured.update(kwargs)+ return None++ monkeypatch.setattr(yfl.yf, "download", fake_download)++ yfl._download_history("AAPL", "2026-01-01", "2026-01-31", "1d")++ assert captured["auto_adjust"] is True+ assert captured["interval"] == "1d"