Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(loader): paginate tencent history backward — the API serves the LAST 500 bars per window

shadowinlife940f57a8dedb
diff --git a/agent/backtest/loaders/tencent_loader.py b/agent/backtest/loaders/tencent_loader.py
index cca16bf2a..42941ba34 100644
--- a/agent/backtest/loaders/tencent_loader.py
+++ b/agent/backtest/loaders/tencent_loader.py
@@ -27,9 +27,13 @@ logger = logging.getLogger(__name__)
_BASE_URL = "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get"
-# Tencent fqkline caps a single response at `_PAGE_SIZE` bars. Requests for a
-# multi-year window (e.g. 2018-2025 daily) silently truncate at 500 bars
-# (roughly the first 2 years) unless we paginate by advancing the start date.
+# Tencent fqkline caps a single response at `_PAGE_SIZE` bars and serves the
+# LAST bars of the requested window (ending at the `end` parameter), not the
+# first — verified empirically 2026-09-11: a 2018-01-01..2026-06-30 request
+# returned 500 bars spanning 2024-06-06..2026-06-30, while a window holding
+# fewer than 500 trading days was served in full from its start (the start
+# clamp is honoured). Multi-year windows therefore paginate BACKWARD: see
+# `_fetch_one`.
_PAGE_SIZE = 500
# 12 pages * 500 bars = 6000 bars ≈ 24 trading years; a hard cap also guards
# against pathological loop behavior if the API ever stops advancing.
@@ -183,28 +187,37 @@ class DataLoader:
"""Paginate [start_date, end_date] in `_PAGE_SIZE`-bar windows.
The Tencent API returns at most 500 bars per request regardless of the
- requested 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. A
- window this loader cannot serve in full raises instead of returning a
+ requested window, and those are the LAST bars ending at the requested
+ end date (see the `_PAGE_SIZE` comment for the verified semantics).
+ Pagination therefore walks BACKWARD: start_date stays fixed and the end
+ cursor moves to the day before each page's oldest bar, until a short
+ page (< `_PAGE_SIZE`) or an exhausted cursor signals the window is
+ served in full. Walking forward instead — advancing the start cursor
+ past each page's newest bar — silently degrades any window longer than
+ one page to its most recent ~500 bars: the first response already ends
+ at end_date, the advanced cursor steps past the window, the next page
+ is empty, and the loop exits cleanly with a tail-only series.
+
+ 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
- seen_starts: set[str] = set()
+ cursor_end = end_date
+ seen_ends: set[str] = set()
for _ in range(_MAX_PAGES):
- if cursor in seen_starts:
+ if cursor_end in seen_ends:
raise ValueError(
f"incomplete tencent history: {code} stopped advancing at "
- f"{cursor} before reaching {end_date}"
+ f"{cursor_end} before reaching {start_date}"
)
- seen_starts.add(cursor)
+ seen_ends.add(cursor_end)
page: Optional[pd.DataFrame] = None
last_error: Optional[Exception] = None
for attempt in range(_PAGE_RETRIES):
try:
- page = self._request_page(code, cursor, end_date)
+ page = self._request_page(code, start_date, cursor_end)
last_error = None
break
except Exception as exc: # noqa: BLE001 - transient network jitter
@@ -215,26 +228,27 @@ class DataLoader:
# 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}"
+ f"incomplete tencent history: {code} page ending at "
+ f"{cursor_end} failed after {_PAGE_RETRIES} attempts: "
+ f"{last_error}"
) from last_error
if page is None or page.empty:
break
chunks.append(page)
- # A short page means the window is exhausted.
+ # A short page means the walk reached start_date.
if len(page) < _PAGE_SIZE:
break
- last = page.index.max()
- next_start = (last + pd.Timedelta(days=1)).strftime("%Y-%m-%d")
- if next_start > end_date:
+ first = page.index.min()
+ next_end = (first - pd.Timedelta(days=1)).strftime("%Y-%m-%d")
+ if next_end < start_date:
break
- cursor = next_start
+ cursor_end = next_end
else:
raise ValueError(
f"incomplete tencent history: {code} hit {_MAX_PAGES} pages "
- f"without reaching {end_date}"
+ f"without reaching {start_date}"
)
if not chunks:
diff --git a/agent/tests/test_tencent_loader.py b/agent/tests/test_tencent_loader.py
index b43c3c90a..2fe61892d 100644
--- a/agent/tests/test_tencent_loader.py
+++ b/agent/tests/test_tencent_loader.py
@@ -135,42 +135,87 @@ def _daily_page(dates: list[str]) -> pd.DataFrame:
)
-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")
+def _history(start: str, n_days: int) -> pd.DataFrame:
+ """A synthetic daily history of `n_days` consecutive calendar days."""
+ dates = pd.date_range(start, periods=n_days, 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 _last500_api(history: pd.DataFrame, requested_ends: list[str] | None = None):
+ """Fake `_request_page` honouring the REAL Tencent fqkline contract.
+
+ The API serves the LAST ≤_PAGE_SIZE bars of [start, end], not the first
+ (verified live 2026-09-11). The previous mocks in this file encoded the
+ opposite first-500 assumption, which is why tail truncation passed CI.
+ """
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"])
+ if requested_ends is not None:
+ requested_ends.append(end)
+ window = history.loc[
+ (history.index >= pd.Timestamp(start))
+ & (history.index <= pd.Timestamp(end))
+ ]
+ return window.iloc[-tencent_loader._PAGE_SIZE:]
+
+ return fake_page
+
+
+def test_multiyear_window_is_served_in_full(monkeypatch) -> None:
+ """Regression: a >500-bar window must not degrade to its most recent 500.
+
+ Under the real last-500 semantics, forward pagination (advancing the
+ start cursor) exits after one page holding only the window's tail. The
+ backward walk must serve every bar from start_date through end_date.
+ """
+ loader = tencent_loader.DataLoader()
+ history = _history("2018-01-01", 1500)
+ end_date = history.index.max().strftime("%Y-%m-%d")
+ ends: list[str] = []
+ monkeypatch.setattr(loader, "_request_page", _last500_api(history, ends))
+
+ df = loader._fetch_one("600519.SH", "2018-01-01", end_date)
+
+ assert len(df) == 1500
+ assert df.index.min() == pd.Timestamp("2018-01-01")
+ assert df.index.max() == history.index.max()
+ assert df.index.is_monotonic_increasing
+ assert len(ends) == 3
+ assert ends[0] == end_date
+ assert ends[1] < ends[0]
+ assert ends[2] < ends[1]
+
+
+def test_pagination_moves_the_end_cursor_behind_each_page(monkeypatch) -> None:
+ """Next request's end = the day before the current page's oldest bar."""
+ loader = tencent_loader.DataLoader()
+ history = _history("2020-01-01", tencent_loader._PAGE_SIZE + 2)
+ ends: list[str] = []
+ monkeypatch.setattr(loader, "_request_page", _last500_api(history, ends))
- 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
+ first_page_oldest = history.index[-tencent_loader._PAGE_SIZE]
+ expected_next_end = first_page_oldest - pd.Timedelta(days=1)
+ assert ends[1] == expected_next_end.strftime("%Y-%m-%d")
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"])]
+ history = _history("2020-01-01", tencent_loader._PAGE_SIZE)
+ calls = {"n": 0}
- monkeypatch.setattr(
- loader, "_request_page", lambda code, start, end: pages.pop(0),
- )
- df = loader._fetch_one("600519.SH", "2020-01-01", "2021-12-31")
+ def fake_page(code, start, end): # noqa: ANN001
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return history.iloc[-tencent_loader._PAGE_SIZE:]
+ older = _daily_page(["2019-12-31"])
+ return pd.concat([older, history.iloc[:2]])
+
+ monkeypatch.setattr(loader, "_request_page", fake_page)
+ df = loader._fetch_one("600519.SH", "2019-12-01", "2021-12-31")
assert df.index.duplicated().sum() == 0
assert len(df) == tencent_loader._PAGE_SIZE + 1
@@ -179,16 +224,11 @@ def test_overlapping_pages_are_deduplicated(monkeypatch) -> None:
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
+ endless = _history("1990-01-01", 20000)
+ monkeypatch.setattr(loader, "_request_page", _last500_api(endless))
- 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")
+ loader._fetch_one("600519.SH", "1990-01-01", "2026-12-31")
def test_a_failed_page_raises_instead_of_returning_partial_history(
@@ -196,13 +236,14 @@ def test_a_failed_page_raises_instead_of_returning_partial_history(
) -> None:
"""A network failure mid-walk must not read downstream as a short series."""
loader = tencent_loader.DataLoader()
+ history = _history("2020-01-01", tencent_loader._PAGE_SIZE + 10)
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")
+ return history.iloc[-tencent_loader._PAGE_SIZE:]
raise OSError("connection reset")
monkeypatch.setattr(loader, "_request_page", fake_page)
@@ -218,36 +259,24 @@ def test_a_failed_page_raises_instead_of_returning_partial_history(
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"])
+ history = _history("2026-01-05", 2)
+ ends: list[str] = []
+ monkeypatch.setattr(loader, "_request_page", _last500_api(history, ends))
- 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 ends == ["2026-01-31"]
assert len(df) == 2
def test_a_bar_on_the_end_date_itself_is_not_dropped(monkeypatch) -> None:
- """When the next start lands exactly on end_date, that day still counts."""
+ """A bar dated exactly end_date must be part of the served series."""
loader = tencent_loader.DataLoader()
- first = _full_page("2020-01-01")
- boundary = first.index.max() + pd.Timedelta(days=1)
- end_date = boundary.strftime("%Y-%m-%d")
- requested: list[str] = []
-
- def fake_page(code, start, end): # noqa: ANN001
- requested.append(start)
- if len(requested) == 1:
- return first
- return _daily_page([end_date])
+ history = _history("2020-01-01", tencent_loader._PAGE_SIZE + 1)
+ end_date = history.index.max().strftime("%Y-%m-%d")
+ monkeypatch.setattr(loader, "_request_page", _last500_api(history))
- monkeypatch.setattr(loader, "_request_page", fake_page)
df = loader._fetch_one("600519.SH", "2020-01-01", end_date)
- assert requested == ["2020-01-01", end_date]
+ assert df.index.max() == history.index.max()
assert len(df) == tencent_loader._PAGE_SIZE + 1
- assert df.index.max() == boundary