"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(loader): invalidate stale tencent cache entries and harden empty-page handling
shadowinlife2856f7bc5ef9
diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.pyindex 45503c4d4..ce3f5abb5 100644--- a/agent/backtest/loaders/base.py+++ b/agent/backtest/loaders/base.py@@ -330,7 +330,9 @@ _LOADER_CACHE_TRUE_VALUES = {"1", "true", "yes", "on"}# v5: UK (.L) prices normalized from GBp to GBP (÷100) (#1206).# v6: LSE quote currency is fail-closed and per-symbol conversion provenance is# persisted. v5 USD/unknown .L entries must never be served as static GBP.-_LOADER_CACHE_VERSION = 6+# v7: tencent fqkline paginates backward (#1410) — entries cached under the+# forward walk hold tail-truncated multi-year series and must never be served.+_LOADER_CACHE_VERSION = 7_LOADER_FRAME_METADATA_ATTRS = ("quote_currency", "currency_conversion")diff --git a/agent/backtest/loaders/tencent_loader.py b/agent/backtest/loaders/tencent_loader.pyindex 42941ba34..7901a32e3 100644--- a/agent/backtest/loaders/tencent_loader.py+++ b/agent/backtest/loaders/tencent_loader.py@@ -143,6 +143,11 @@ class DataLoader:data = json.loads(raw)# Response: {"code":0,"data":{"sh601595":{"day":[["2026-06-01","21.32",...], ...]}}}+ if data.get("code") not in (0, None) and not data.get("data"):+ # An error-shaped reply is a failure, not an empty window: None+ # here would let a throttled reply end the walk mid-pagination+ # and serve (and cache) a truncated series as complete history.+ raise ValueError(f"tencent fqkline error reply: code={data.get('code')}")stock_data = data.get("data", {})if not stock_data:return None@@ -234,7 +239,22 @@ class DataLoader:) from last_errorif page is None or page.empty:- break+ if not chunks:+ break+ # A mid-walk empty page is ambiguous: the genuine start of+ # history, or a throttled reply. One re-request decides — a+ # transient glitch returns data, a genuine boundary stays+ # empty and terminates the walk.+ time.sleep(_PAGE_BACKOFF)+ try:+ page = self._request_page(code, start_date, cursor_end)+ except Exception as exc: # noqa: BLE001 - transient network jitter+ raise ValueError(+ f"incomplete tencent history: {code} re-request at "+ f"{cursor_end} failed: {exc}"+ ) from exc+ if page is None or page.empty:+ breakchunks.append(page)# A short page means the walk reached start_date.diff --git a/agent/tests/test_tencent_loader.py b/agent/tests/test_tencent_loader.pyindex 2fe61892d..4e34e73d3 100644--- a/agent/tests/test_tencent_loader.py+++ b/agent/tests/test_tencent_loader.py@@ -280,3 +280,63 @@ def test_a_bar_on_the_end_date_itself_is_not_dropped(monkeypatch) -> None:assert df.index.max() == history.index.max()assert len(df) == tencent_loader._PAGE_SIZE + 1+++def test_error_shaped_reply_raises_instead_of_returning_none(monkeypatch) -> None:+ """A non-zero-code reply with no payload is a failure, not an empty window."""+ loader = tencent_loader.DataLoader()+ payload = json.dumps({"code": 1, "msg": "rate limit"})++ def fake_urlopen(req, timeout=None, **kwargs): # noqa: ANN001, ANN002+ return _FakeResponse(payload)++ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)++ with pytest.raises(ValueError, match="error reply"):+ loader._request_page("600519.SH", "2024-01-01", "2024-06-30")+++def test_midwalk_empty_page_is_rerequested_before_truncating(monkeypatch) -> None:+ """A glitched empty mid-walk must not end the walk: one re-request decides."""+ loader = tencent_loader.DataLoader()+ history = _history("2020-01-01", tencent_loader._PAGE_SIZE + 10)+ calls = {"n": 0}+ sleeps: list[float] = []+ monkeypatch.setattr(tencent_loader.time, "sleep", sleeps.append)++ def fake_page(code, start, end): # noqa: ANN001+ calls["n"] += 1+ if calls["n"] == 1:+ return history.iloc[-tencent_loader._PAGE_SIZE:]+ if calls["n"] == 2:+ return None+ return history.iloc[: -tencent_loader._PAGE_SIZE]++ monkeypatch.setattr(loader, "_request_page", fake_page)+ df = loader._fetch_one("600519.SH", "2020-01-01", "2026-12-31")++ assert calls["n"] == 3+ assert len(df) == tencent_loader._PAGE_SIZE + 10+ assert df.index.is_monotonic_increasing+ assert sleeps == [tencent_loader._PAGE_BACKOFF]+++def test_midwalk_empty_page_that_persists_ends_the_walk(monkeypatch) -> None:+ """A genuine data start (e.g. a pre-IPO window) stays empty on re-request."""+ loader = tencent_loader.DataLoader()+ history = _history("2020-01-01", tencent_loader._PAGE_SIZE)+ calls = {"n": 0}+ sleeps: list[float] = []+ monkeypatch.setattr(tencent_loader.time, "sleep", sleeps.append)++ def fake_page(code, start, end): # noqa: ANN001+ calls["n"] += 1+ if calls["n"] == 1:+ return history.iloc[-tencent_loader._PAGE_SIZE:]+ return None++ monkeypatch.setattr(loader, "_request_page", fake_page)+ df = loader._fetch_one("600519.SH", "2019-01-01", "2026-12-31")++ assert calls["n"] == 3+ assert len(df) == tencent_loader._PAGE_SIZE