"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(loader): fail a truncated tencent window instead of returning it
Haozhe Wu43eff604e215
diff --git a/agent/backtest/loaders/tencent_loader.py b/agent/backtest/loaders/tencent_loader.pyindex 24adce04b..cca16bf2a 100644--- a/agent/backtest/loaders/tencent_loader.py+++ b/agent/backtest/loaders/tencent_loader.py@@ -96,9 +96,7 @@ class DataLoader:start_date=start_date,end_date=end_date,fields=None,- fetch=lambda code=code: self._fetch_one_paginated(- code, start_date, end_date- ),+ fetch=lambda code=code: self._fetch_one(code, start_date, end_date),)if df is not None and not df.empty:result[code] = df@@ -106,12 +104,6 @@ class DataLoader:logger.warning("tencent failed for %s: %s", code, exc)return result- def _fetch_one(- self, code: str, start_date: str, end_date: str,- ) -> Optional[pd.DataFrame]:- """Single-page fetch (backward compatible; used by tests)."""- return self._request_page(code, start_date, end_date)-def _request_page(self, code: str, start_date: str, end_date: str,) -> Optional[pd.DataFrame]:@@ -185,14 +177,16 @@ class DataLoader:)return df- def _fetch_one_paginated(+ def _fetch_one(self, code: str, start_date: str, end_date: str,) -> Optional[pd.DataFrame]:"""Paginate [start_date, end_date] in `_PAGE_SIZE`-bar windows.The Tencent API returns at most 500 bars per request regardless of therequested window, so a multi-year range is silently truncated unless we- advance the start date by one day past the last bar of each page.+ advance the start date by one day past the last bar of each page. A+ window this loader cannot serve in full raises instead of returning a+ quietly short series, matching the other bounded-window loaders."""chunks: List[pd.DataFrame] = []cursor = start_date@@ -200,35 +194,48 @@ class DataLoader:for _ in range(_MAX_PAGES):if cursor in seen_starts:- logger.warning("tencent paginate loop at %s; stopping", cursor)- break+ raise ValueError(+ f"incomplete tencent history: {code} stopped advancing at "+ f"{cursor} before reaching {end_date}"+ )seen_starts.add(cursor)page: Optional[pd.DataFrame] = None+ last_error: Optional[Exception] = Nonefor attempt in range(_PAGE_RETRIES):try:page = self._request_page(code, cursor, end_date)+ last_error = Nonebreakexcept Exception as exc: # noqa: BLE001 - transient network jitter+ last_error = excif attempt < _PAGE_RETRIES - 1:time.sleep(_PAGE_BACKOFF * (2 ** attempt))- else:- logger.warning(- "tencent page giveup %s@%s: %s", code, cursor, exc- )+ if last_error is not None:+ # Partial pages already collected would read as a complete+ # history downstream; a failed page is an error, not a series.+ raise ValueError(+ f"incomplete tencent history: {code} page at {cursor} failed "+ f"after {_PAGE_RETRIES} attempts: {last_error}"+ ) from last_errorif page is None or page.empty:breakchunks.append(page)- # Full page -> continue from the day after the last bar.+ # A short page means the window is exhausted.if len(page) < _PAGE_SIZE:breaklast = page.index.max()next_start = (last + pd.Timedelta(days=1)).strftime("%Y-%m-%d")- if next_start >= end_date:+ if next_start > end_date:breakcursor = next_start+ else:+ raise ValueError(+ f"incomplete tencent history: {code} hit {_MAX_PAGES} pages "+ f"without reaching {end_date}"+ )if not chunks:return Nonediff --git a/agent/tests/test_tencent_loader.py b/agent/tests/test_tencent_loader.pyindex 7b8ddccf9..1e90742b3 100644--- a/agent/tests/test_tencent_loader.py+++ b/agent/tests/test_tencent_loader.py@@ -6,6 +6,7 @@ import jsonimport urllib.requestimport pandas as pd+import pytestfrom backtest.loaders import tencent_loader@@ -117,3 +118,114 @@ def test_short_hk_code_is_zero_padded(monkeypatch) -> None:assert "param=hk00700,day," in urls[0]assert "700.HK" in result+++def _daily_page(dates: list[str]) -> pd.DataFrame:+ """Build a normalized daily frame indexed by trade date."""+ index = pd.to_datetime(dates)+ return pd.DataFrame(+ {+ "open": [1.0] * len(index),+ "high": [1.0] * len(index),+ "low": [1.0] * len(index),+ "close": [1.0] * len(index),+ "volume": [1.0] * len(index),+ },+ index=index,+ )+++def _full_page(start: str) -> pd.DataFrame:+ """A page of exactly _PAGE_SIZE bars, i.e. one the API truncated."""+ dates = pd.date_range(start, periods=tencent_loader._PAGE_SIZE, freq="D")+ return _daily_page([d.strftime("%Y-%m-%d") for d in dates])+++def test_pagination_walks_past_the_500_bar_cap(monkeypatch) -> None:+ """A multi-year window must not stop at the API's per-response cap."""+ loader = tencent_loader.DataLoader()+ requested: list[str] = []++ def fake_page(code, start, end): # noqa: ANN001+ requested.append(start)+ if len(requested) == 1:+ return _full_page("2020-01-01")+ return _daily_page(["2021-06-01", "2021-06-02"])++ monkeypatch.setattr(loader, "_request_page", fake_page)+ df = loader._fetch_one("600519.SH", "2020-01-01", "2021-12-31")++ assert len(requested) == 2+ # The second page resumes the day after the first page's last bar.+ assert requested[1] == "2021-05-15"+ assert len(df) == tencent_loader._PAGE_SIZE + 2+ assert df.index.is_monotonic_increasing+++def test_overlapping_pages_are_deduplicated(monkeypatch) -> None:+ """Rows repeated across pages must collapse, not double-count."""+ loader = tencent_loader.DataLoader()+ pages = [_full_page("2020-01-01"), _daily_page(["2021-05-14", "2021-05-15"])]++ monkeypatch.setattr(+ loader, "_request_page", lambda code, start, end: pages.pop(0),+ )+ df = loader._fetch_one("600519.SH", "2020-01-01", "2021-12-31")++ assert df.index.duplicated().sum() == 0+ assert len(df) == tencent_loader._PAGE_SIZE + 1+++def test_exhausting_the_page_cap_raises_instead_of_truncating(monkeypatch) -> None:+ """Hitting _MAX_PAGES must fail loudly, like the other bounded loaders."""+ loader = tencent_loader.DataLoader()+ starts = ["2000-01-01"]++ def fake_page(code, start, end): # noqa: ANN001+ page = _full_page(start)+ starts.append(start)+ return page++ monkeypatch.setattr(loader, "_request_page", fake_page)+ with pytest.raises(ValueError, match="incomplete tencent history"):+ loader._fetch_one("600519.SH", "2000-01-01", "2026-12-31")+++def test_a_failed_page_raises_instead_of_returning_partial_history(+ monkeypatch,+) -> None:+ """A network failure mid-walk must not read downstream as a short series."""+ loader = tencent_loader.DataLoader()+ calls = {"n": 0}+ sleeps: list[float] = []++ def fake_page(code, start, end): # noqa: ANN001+ calls["n"] += 1+ if calls["n"] == 1:+ return _full_page("2020-01-01")+ raise OSError("connection reset")++ monkeypatch.setattr(loader, "_request_page", fake_page)+ monkeypatch.setattr(tencent_loader.time, "sleep", sleeps.append)+ with pytest.raises(ValueError, match="incomplete tencent history"):+ loader._fetch_one("600519.SH", "2020-01-01", "2021-12-31")++ # One good page, then the retry budget spent on the failing one.+ assert calls["n"] == 1 + tencent_loader._PAGE_RETRIES+ assert len(sleeps) == tencent_loader._PAGE_RETRIES - 1+++def test_a_short_page_ends_the_walk(monkeypatch) -> None:+ """A page below the cap means the window is served; stop requesting."""+ loader = tencent_loader.DataLoader()+ calls: list[str] = []++ def fake_page(code, start, end): # noqa: ANN001+ calls.append(start)+ return _daily_page(["2026-01-05", "2026-01-06"])++ monkeypatch.setattr(loader, "_request_page", fake_page)+ df = loader._fetch_one("600519.SH", "2026-01-01", "2026-01-31")++ assert calls == ["2026-01-01"]+ assert len(df) == 2