Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(longbridge): enforce complete historical data contracts

Haozhe Wudde6e13a76c3
diff --git a/agent/SKILL.md b/agent/SKILL.md
index 43d3645a8..0b2df5505 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -1,7 +1,7 @@
---
name: vibe-trading
version: 0.1.11
-description: Professional finance research toolkit — backtesting (8 engines + benchmark comparison panel), factor analysis, Alpha Zoo (461 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 87 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 20 market-data sources (tushare, yfinance, okx, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, india_broker, qveris, plus optional-key finnhub/alphavantage/tiingo/fmp).
+description: Professional finance research toolkit — backtesting (8 engines + benchmark comparison panel), factor analysis, Alpha Zoo (461 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 87 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 21 market-data sources (tushare, yfinance, okx, akshare, baostock, tencent, mootdx, ccxt, futu, local, eastmoney, sina, stooq, yahoo, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).
dependencies:
python: ">=3.11"
pip:
@@ -74,7 +74,7 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent
5. `scan_shadow_signals` — list today's symbols that match your shadow's entry cadence (research only).
### Backtesting
-Create and run quantitative strategies across 8 engines (ChinaA, GlobalEquity, IndiaEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 20 market-data sources (auto-detect + ordered fallback):
+Create and run quantitative strategies across 8 engines (ChinaA, GlobalEquity, IndiaEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 21 market-data sources (auto-detect + ordered fallback):
- **HK/US equities** via yfinance / stooq / yahoo (free, no API key)
- **India equities (NSE/BSE)** via yahoo / yfinance using `<SYMBOL>.NS` (NSE, e.g. `RELIANCE.NS`) or `<SCRIP>.BO` (BSE, e.g. `500325.BO`) — free, no API key. The `IndiaEquityEngine` models T+1 delivery, no overnight shorts (set `allow_short` for intraday), configurable circuit bands, 1-share lots, and the STT/stamp-duty/exchange/GST cost stack. Optionally back-fill from your live broker via the `india_broker` source (Shoonya/Dhan; requires broker login).
- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)
@@ -143,7 +143,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.
| `factor_analysis` | IC/IR analysis + layered backtest | None* |
| `analyze_options` | Black-Scholes price + Greeks | None |
| `pattern_recognition` | Detect chart patterns (H&S, double top, etc.) | None |
-| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 20 sources) | None* |
+| `get_market_data` | Fetch OHLCV data (auto-detect + ordered fallback across 21 sources) | None* |
| `get_fund_flow` | Capital fund-flow (main/retail net inflow) | None* |
| `get_dragon_tiger` | Dragon-tiger list (龙虎榜) top buyer/seller seats | None* |
| `get_northbound_flow` | Northbound (Stock Connect) net flow | None* |
diff --git a/agent/backtest/loaders/longbridge.py b/agent/backtest/loaders/longbridge.py
index b15e29c2c..334b35f4f 100644
--- a/agent/backtest/loaders/longbridge.py
+++ b/agent/backtest/loaders/longbridge.py
@@ -14,8 +14,8 @@ historical bars are identical regardless of source account.
The LongPort ``history_candlesticks_by_date`` endpoint caps responses at
~1000 bars per call. Date ranges longer than ~4 years of daily bars are
-automatically split into sequential 180-day windows so full history is
-retrieved without silent truncation.
+automatically split into sequential 180-day windows. Requests wider than the
+bounded window budget fail explicitly instead of returning truncated history.
This module is for backtest data only; live trading uses the separate
``src.trading.connectors.longbridge.sdk`` module.
@@ -47,7 +47,6 @@ _INTERVAL_MAP: dict[str, str] = {
"1M": "Month",
"1H": "Min_60",
"1h": "Min_60",
- "4h": "Min_60", # LongPort has no 4H; closest is 60M
"1m": "Min_1",
"5m": "Min_5",
"15m": "Min_15",
@@ -76,7 +75,7 @@ def _require_longbridge():
except ImportError as exc:
raise LongbridgeDependencyError(
"The 'longbridge' SDK is not installed. "
- "Run: pip install longbridge"
+ "Run: pip install 'vibe-trading-ai[longbridge]'"
) from exc
return openapi
@@ -107,12 +106,24 @@ def _to_longport_period(interval: str):
"""Map a project interval string to a LongPort ``Period`` enum value.
Lazy-imports the SDK so this module can be imported without it installed.
- Unknown intervals fall back to ``Day``.
+ Unsupported intervals fail explicitly so requested bar fidelity is never
+ changed silently.
"""
openapi = _require_longbridge()
period_cls = getattr(openapi, "Period")
- attr = _INTERVAL_MAP.get(interval.strip(), "Day")
- return getattr(period_cls, attr, getattr(period_cls, "Day"))
+ token = interval.strip()
+ attr = _INTERVAL_MAP.get(token)
+ if attr is None:
+ raise NoAvailableSourceError(
+ f"unsupported Longbridge interval: {interval!r}; "
+ f"supported intervals: {sorted(_INTERVAL_MAP)}"
+ )
+ try:
+ return getattr(period_cls, attr)
+ except AttributeError as exc:
+ raise NoAvailableSourceError(
+ f"installed Longbridge SDK does not expose Period.{attr}"
+ ) from exc
def _date_windows(start: dt.date, end: dt.date) -> list[tuple[dt.date, dt.date]]:
@@ -122,6 +133,14 @@ def _date_windows(start: dt.date, end: dt.date) -> list[tuple[dt.date, dt.date]]
Each window spans at most ``_MAX_WINDOW_DAYS`` days. Windows are capped
at ``_MAX_WINDOWS`` so a pathological request cannot loop forever.
"""
+ requested_days = (end - start).days + 1
+ maximum_days = _MAX_WINDOW_DAYS * _MAX_WINDOWS
+ if requested_days > maximum_days:
+ raise NoAvailableSourceError(
+ f"Longbridge date range spans {requested_days} days and exceeds "
+ f"the {maximum_days}-day window limit"
+ )
+
windows: list[tuple[dt.date, dt.date]] = []
cursor = start
while cursor <= end and len(windows) < _MAX_WINDOWS:
@@ -161,9 +180,10 @@ def _normalize_frame(bars: list[Any]) -> pd.DataFrame:
result.index.name = "trade_date"
result = result[_OHLCV_COLUMNS].copy()
- # Standardise to timezone-naive (LongPort returns UTC timestamps).
+ # Standardise to timezone-naive UTC. Aware timestamps may be represented
+ # in an exchange timezone by SDK versions even when the instant is UTC.
if isinstance(result.index, pd.DatetimeIndex) and result.index.tz is not None:
- result.index = result.index.tz_localize(None)
+ result.index = result.index.tz_convert("UTC").tz_localize(None)
result = result.dropna(subset=["open", "high", "low", "close"])
result["volume"] = result["volume"].fillna(0.0)
@@ -193,21 +213,14 @@ class LongbridgeLoader:
def is_available(self) -> bool:
"""Return True if the LongPort SDK is installed and credentials exist.
- Performs a lightweight probe (``candlesticks`` for ``AAPL.US``) to
- validate the credentials and connectivity.
+ Availability checks are side-effect free: they validate configured
+ credentials and SDK importability without consuming quote API quota.
"""
if not (self._app_key and self._app_secret and self._access_token):
return False
try:
- openapi = _require_longbridge()
- cfg = openapi.Config(
- self._app_key, self._app_secret, self._access_token,
- )
- ctx = openapi.QuoteContext(cfg)
- # Lightweight probe — validates token + connectivity.
- # AAPL.US is the most universally available LongPort symbol.
- bars = ctx.candlesticks("AAPL.US", openapi.Period.Day, 1, openapi.AdjustType.NoAdjust)
- return bars is not None
+ _require_longbridge()
+ return True
except Exception:
return False
@@ -265,6 +278,13 @@ class LongbridgeLoader:
if not pending:
return results
+ if not (self._app_key and self._app_secret and self._access_token):
+ raise NoAvailableSourceError(
+ "Longbridge credentials are not configured; set "
+ "LONGBRIDGE_APP_KEY, LONGBRIDGE_APP_SECRET, and "
+ "LONGBRIDGE_ACCESS_TOKEN"
+ )
+
openapi = _require_longbridge()
try:
cfg = openapi.Config(
@@ -305,12 +325,10 @@ class LongbridgeLoader:
elif bars is not None:
all_bars.append(bars)
except Exception as exc:
- logger.warning(
- "LongPort history_candlesticks_by_date failed for %s "
- "%s..%s: %s",
- lp_symbol, w_start, w_end, exc,
- )
- continue
+ raise NoAvailableSourceError(
+ "incomplete Longbridge history for "
+ f"{lp_symbol}: window {w_start}..{w_end} failed: {exc}"
+ ) from exc
if not all_bars:
logger.warning(
diff --git a/agent/tests/test_longbridge_loader.py b/agent/tests/test_longbridge_loader.py
new file mode 100644
index 000000000..e60848712
--- /dev/null
+++ b/agent/tests/test_longbridge_loader.py
@@ -0,0 +1,190 @@
+"""Contract tests for the optional Longbridge historical-data loader."""
+
+from __future__ import annotations
+
+import datetime as dt
+from types import SimpleNamespace
+
+import pandas as pd
+import pytest
+
+from backtest.loaders import longbridge as loader_mod
+from backtest.loaders.base import NoAvailableSourceError
+
+
+def test_wide_date_range_never_truncates_silently() -> None:
+ start = dt.date(2000, 1, 1)
+ end = start + dt.timedelta(days=loader_mod._MAX_WINDOW_DAYS * loader_mod._MAX_WINDOWS)
+
+ with pytest.raises(NoAvailableSourceError, match="exceeds.*window limit"):
+ loader_mod._date_windows(start, end)
+
+
[email protected]("interval", ["2D", "4h", "garbage"])
+def test_unsupported_intervals_fail_instead_of_changing_fidelity(
+ interval: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake_openapi = SimpleNamespace(Period=SimpleNamespace(Day="day"))
+ monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)
+
+ with pytest.raises(NoAvailableSourceError, match="unsupported Longbridge interval"):
+ loader_mod._to_longport_period(interval)
+
+
+def test_normalize_frame_converts_intraday_timestamps_to_naive_utc() -> None:
+ bars = [
+ SimpleNamespace(
+ timestamp=pd.Timestamp("2026-07-14 09:30:00", tz="Asia/Hong_Kong"),
+ open=10,
+ high=11,
+ low=9,
+ close=10.5,
+ volume=100,
+ )
+ ]
+
+ frame = loader_mod._normalize_frame(bars)
+
+ assert frame.index.tz is None
+ assert frame.index[0] == pd.Timestamp("2026-07-14 01:30:00")
+
+
+def test_is_available_does_not_make_a_market_data_request(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("LONGBRIDGE_APP_KEY", "key")
+ monkeypatch.setenv("LONGBRIDGE_APP_SECRET", "secret")
+ monkeypatch.setenv("LONGBRIDGE_ACCESS_TOKEN", "token")
+ fake_openapi = SimpleNamespace()
+ monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)
+
+ assert loader_mod.LongbridgeLoader().is_available() is True
+
+
+def test_fetch_rejects_missing_credentials_before_sdk_initialization(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("LONGBRIDGE_APP_KEY", raising=False)
+ monkeypatch.delenv("LONGBRIDGE_APP_SECRET", raising=False)
+ monkeypatch.delenv("LONGBRIDGE_ACCESS_TOKEN", raising=False)
+ monkeypatch.setattr(
+ loader_mod,
+ "_require_longbridge",
+ lambda: (_ for _ in ()).throw(AssertionError("SDK must not initialize")),
+ )
+
+ with pytest.raises(NoAvailableSourceError, match="credentials are not configured"):
+ loader_mod.LongbridgeLoader().fetch(
+ ["AAPL"], "2026-01-01", "2026-01-02"
+ )
+
+
+def _configured_loader() -> loader_mod.LongbridgeLoader:
+ loader = loader_mod.LongbridgeLoader.__new__(loader_mod.LongbridgeLoader)
+ loader._app_key = "key"
+ loader._app_secret = "secret"
+ loader._access_token = "token"
+ return loader
+
+
+def test_fetch_combines_all_windows_and_caches_complete_frame(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[tuple[dt.date, dt.date]] = []
+ cached: list[pd.DataFrame] = []
+
+ class FakeQuoteContext:
+ def __init__(self, config: object) -> None:
+ assert config == ("key", "secret", "token")
+
+ def history_candlesticks_by_date(
+ self,
+ symbol: str,
+ period: str,
+ adjust_type: str,
+ *,
+ start: dt.date,
+ end: dt.date,
+ ) -> list[SimpleNamespace]:
+ assert symbol == "AAPL.US"
+ assert period == "day"
+ assert adjust_type == "none"
+ calls.append((start, end))
+ return [
+ SimpleNamespace(
+ timestamp=pd.Timestamp(start),
+ open=10,
+ high=11,
+ low=9,
+ close=10.5,
+ volume=100,
+ )
+ ]
+
+ fake_openapi = SimpleNamespace(
+ Config=lambda *args: args,
+ QuoteContext=FakeQuoteContext,
+ Period=SimpleNamespace(Day="day"),
+ AdjustType=SimpleNamespace(NoAdjust="none"),
+ )
+ monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)
+ monkeypatch.setattr(loader_mod, "loader_cache_get", lambda **kwargs: None)
+ monkeypatch.setattr(
+ loader_mod,
+ "loader_cache_put",
+ lambda **kwargs: cached.append(kwargs["frame"].copy()),
+ )
+
+ result = _configured_loader().fetch(
+ ["AAPL"], "2026-01-01", "2026-07-01", interval="1D"
+ )
+
+ assert calls == [
+ (dt.date(2026, 1, 1), dt.date(2026, 6, 29)),
+ (dt.date(2026, 6, 30), dt.date(2026, 7, 1)),
+ ]
+ assert list(result) == ["AAPL"]
+ assert len(result["AAPL"]) == 2
+ assert len(cached) == 1
+ pd.testing.assert_frame_equal(cached[0], result["AAPL"])
+
+
+def test_fetch_rejects_partial_history_when_a_window_fails(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class FakeQuoteContext:
+ def __init__(self, config: object) -> None:
+ pass
+
+ def history_candlesticks_by_date(self, *args: object, **kwargs: object):
+ if kwargs["start"] == dt.date(2026, 6, 30):
+ raise RuntimeError("quota exhausted")
+ return [
+ SimpleNamespace(
+ timestamp=pd.Timestamp(kwargs["start"]),
+ open=10,
+ high=11,
+ low=9,
+ close=10.5,
+ volume=100,
+ )
+ ]
+
+ fake_openapi = SimpleNamespace(
+ Config=lambda *args: args,
+ QuoteContext=FakeQuoteContext,
+ Period=SimpleNamespace(Day="day"),
+ AdjustType=SimpleNamespace(NoAdjust="none"),
+ )
+ monkeypatch.setattr(loader_mod, "_require_longbridge", lambda: fake_openapi)
+ monkeypatch.setattr(loader_mod, "loader_cache_get", lambda **kwargs: None)
+ monkeypatch.setattr(
+ loader_mod,
+ "loader_cache_put",
+ lambda **kwargs: (_ for _ in ()).throw(AssertionError("must not cache")),
+ )
+
+ with pytest.raises(NoAvailableSourceError, match="incomplete Longbridge history"):
+ _configured_loader().fetch(
+ ["AAPL"], "2026-01-01", "2026-07-01", interval="1D"
+ )