"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: add Futu data loader for HK and A-share equities (#47)
Hamza Mobeenbc62206ad66f
diff --git a/agent/.env.example b/agent/.env.exampleindex 477109941..16f9a8716 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -93,6 +93,10 @@ TUSHARE_TOKEN=your-tushare-token# Crypto: OKX public API (free, no config needed)# Crypto fallback exchange (default: binance). Change if OKX is blocked:# CCXT_EXCHANGE=binance+# HK / A-share equities via Futu OpenAPI (optional, requires FutuOpenD running locally)+# Download FutuOpenD: https://www.futunn.com/download/openAPI+# FUTU_HOST=127.0.0.1+# FUTU_PORT=11111# ============================================================================# API Server (optional)diff --git a/agent/backtest/loaders/futu.py b/agent/backtest/loaders/futu.pynew file mode 100644index 000000000..3449d43e4--- /dev/null+++ b/agent/backtest/loaders/futu.py@@ -0,0 +1,160 @@+"""Futu OpenAPI-backed loader for HK and China A-share OHLCV data."""++from __future__ import annotations++import os+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders.base import NoAvailableSourceError, validate_date_range+from backtest.loaders.registry import register++_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]++_INTERVAL_MAP: dict[str, str] = {+ "1D": "K_DAY",+ "1H": "K_60M",+ "4H": "K_240M",+ "1W": "K_WEEK",+ "1M": "K_MON",+}+++def _to_futu_symbol(code: str) -> str:+ """Convert project symbol to Futu OpenAPI format.++ Examples:+ 700.HK -> HK.00700+ 5.HK -> HK.00005+ 000001.SZ -> SZ.000001+ 600519.SH -> SH.600519+ """+ upper = code.strip().upper()+ if upper.endswith(".HK"):+ return f"HK.{upper[:-3].zfill(5)}"+ if upper.endswith(".SZ"):+ return f"SZ.{upper[:-3].zfill(6)}"+ if upper.endswith(".SH"):+ return f"SH.{upper[:-3].zfill(6)}"+ return upper+++def _to_futu_ktype(interval: str):+ """Map project interval string to a futu KLType enum value.++ Lazy-imports futu so the module can be imported without futu installed.+ Unknown intervals fall back to K_DAY.+ """+ from futu import KLType # noqa: PLC0415+ return getattr(KLType, _INTERVAL_MAP.get(interval.strip(), "K_DAY"))+++def _normalize_frame(df: pd.DataFrame) -> pd.DataFrame:+ """Normalise a Futu kline DataFrame to the standard OHLCV schema.++ Args:+ df: Raw DataFrame returned by ``request_history_kline()``.++ Returns:+ DataFrame with columns [open, high, low, close, volume] indexed+ by ``trade_date`` (timezone-naive DatetimeIndex), sorted ascending.+ """+ if df.empty:+ return pd.DataFrame(columns=_OHLCV_COLUMNS)++ result = df.copy()+ result.index = pd.to_datetime(result["time_key"])+ result.index.name = "trade_date"+ result = result[_OHLCV_COLUMNS].copy()+ result = result.apply(pd.to_numeric, errors="coerce")+ result["volume"] = result["volume"].fillna(0.0)+ result = result.dropna(subset=["open", "high", "low", "close"])+ return result.sort_index()+++@register+class FutuLoader:+ """Fetch HK and China A-share bars from Futu OpenAPI.++ Requires FutuOpenD running locally (https://www.futunn.com/download/openAPI)+ and the environment variables ``FUTU_HOST`` / ``FUTU_PORT`` to be set.+ """++ name = "futu"+ markets = {"hk_equity", "a_share"}+ requires_auth = True++ def __init__(self) -> None:+ self._host = os.environ.get("FUTU_HOST", "127.0.0.1")+ self._port = int(os.environ.get("FUTU_PORT", "11111"))++ def is_available(self) -> bool:+ """Return True if env vars are set and FutuOpenD is reachable."""+ if not os.environ.get("FUTU_HOST") or not os.environ.get("FUTU_PORT"):+ return False+ try:+ import futu # noqa: PLC0415+ ctx = futu.OpenQuoteContext(host=self._host, port=self._port)+ ctx.close()+ return True+ except Exception:+ return False++ def fetch(+ self,+ codes: List[str],+ start_date: str,+ end_date: str,+ *,+ interval: str = "1D",+ fields: Optional[List[str]] = None,+ ) -> Dict[str, pd.DataFrame]:+ """Fetch OHLCV history from Futu OpenAPI.++ Args:+ codes: Project symbols such as ``700.HK`` or ``000001.SZ``.+ start_date: Start date in ``YYYY-MM-DD`` format.+ end_date: End date in ``YYYY-MM-DD`` format.+ interval: Backtest interval — ``1D``, ``1H``, or ``4H``.+ fields: Ignored; included for interface compatibility.++ Returns:+ Mapping of input symbol to normalised OHLCV dataframe.++ Raises:+ NoAvailableSourceError: If FutuOpenD connection fails.+ """+ del fields+ if not codes:+ return {}+ validate_date_range(start_date, end_date)++ try:+ import futu # noqa: PLC0415+ ktype = _to_futu_ktype(interval)+ ctx = futu.OpenQuoteContext(host=self._host, port=self._port)+ except Exception as exc:+ raise NoAvailableSourceError(+ f"Cannot connect to FutuOpenD at {self._host}:{self._port}: {exc}"+ ) from exc++ results: Dict[str, pd.DataFrame] = {}+ try:+ for code in codes:+ futu_code = _to_futu_symbol(code)+ ret, data = ctx.request_history_kline(+ futu_code,+ start=start_date,+ end=end_date,+ ktype=ktype,+ max_count=10_000,+ )+ if ret != futu.RET_OK:+ print(f"[WARN] Futu returned error for {futu_code}: {data}")+ continue+ results[code] = _normalize_frame(data)+ finally:+ ctx.close()++ return resultsdiff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 7c4cab09d..973cca600 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -52,6 +52,7 @@ def _ensure_registered() -> None:"backtest.loaders.yfinance_loader","backtest.loaders.akshare_loader","backtest.loaders.ccxt_loader",+ "backtest.loaders.futu",]import importlibfor mod in _loader_modules:@@ -68,7 +69,7 @@ def _ensure_registered() -> None:FALLBACK_CHAINS: dict[str, list[str]] = {"a_share": ["tushare", "akshare"],"us_equity": ["yfinance", "akshare"],- "hk_equity": ["yfinance", "akshare"],+ "hk_equity": ["yfinance", "futu", "akshare"],"crypto": ["okx", "ccxt"],"futures": ["tushare", "akshare"],"fund": ["tushare", "akshare"],diff --git a/agent/tests/test_futu_loader.py b/agent/tests/test_futu_loader.pynew file mode 100644index 000000000..98d71668d--- /dev/null+++ b/agent/tests/test_futu_loader.py@@ -0,0 +1,219 @@+"""Tests for FutuLoader — all Futu API calls are mocked.++futu-api is not installed in CI, so we stub ``sys.modules['futu']`` before+importing the loader. Every external call goes through the stub.+"""++from __future__ import annotations++import sys+from unittest.mock import MagicMock++import pandas as pd+import pytest+++# ---------------------------------------------------------------------------+# Stub futu before importing loader+# ---------------------------------------------------------------------------++class _KLType:+ K_DAY = "K_DAY"+ K_60M = "K_60M"+ K_240M = "K_240M"+ K_WEEK = "K_WEEK"+ K_MON = "K_MON"+++_futu_stub = MagicMock()+_futu_stub.RET_OK = 0+_futu_stub.KLType = _KLType+sys.modules.setdefault("futu", _futu_stub)++from backtest.loaders.futu import FutuLoader, _normalize_frame, _to_futu_symbol, _to_futu_ktype # noqa: E402+from backtest.loaders.base import NoAvailableSourceError # noqa: E402+++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+[email protected](autouse=True)+def reset_futu_mock():+ """Ensure the futu stub is clean before and after every test."""+ _futu_stub.OpenQuoteContext.reset_mock()+ _futu_stub.OpenQuoteContext.side_effect = None+ yield+ _futu_stub.OpenQuoteContext.reset_mock()+ _futu_stub.OpenQuoteContext.side_effect = None+++def _make_kline_df(dates=None) -> pd.DataFrame:+ """Build a minimal Futu kline DataFrame mirroring request_history_kline output."""+ dates = dates or ["2024-01-02 00:00:00", "2024-01-03 00:00:00"]+ n = len(dates)+ return pd.DataFrame({+ "code": ["HK.00700"] * n,+ "time_key": dates,+ "open": [350.0] * n,+ "high": [360.0] * n,+ "low": [345.0] * n,+ "close": [355.0] * n,+ "volume": [1_000_000] * n,+ "turnover": [350_000_000.0] * n,+ })+++# ---------------------------------------------------------------------------+# Symbol mapping+# ---------------------------------------------------------------------------++class TestSymbolMapping:+ def test_hk_five_digit(self):+ assert _to_futu_symbol("700.HK") == "HK.00700"++ def test_hk_short_padded(self):+ assert _to_futu_symbol("5.HK") == "HK.00005"++ def test_sz_symbol(self):+ assert _to_futu_symbol("000001.SZ") == "SZ.000001"++ def test_sh_symbol(self):+ assert _to_futu_symbol("600519.SH") == "SH.600519"++ def test_case_insensitive(self):+ assert _to_futu_symbol("700.hk") == "HK.00700"+++# ---------------------------------------------------------------------------+# Interval mapping+# ---------------------------------------------------------------------------++class TestIntervalMapping:+ def test_daily(self):+ assert _to_futu_ktype("1D") == "K_DAY"++ def test_hourly(self):+ assert _to_futu_ktype("1H") == "K_60M"++ def test_four_hourly(self):+ assert _to_futu_ktype("4H") == "K_240M"++ def test_unknown_defaults_to_daily(self):+ assert _to_futu_ktype("999X") == "K_DAY"+++# ---------------------------------------------------------------------------+# _normalize_frame+# ---------------------------------------------------------------------------++class TestNormalizeFrame:+ def test_ohlcv_columns(self):+ result = _normalize_frame(_make_kline_df())+ assert list(result.columns) == ["open", "high", "low", "close", "volume"]++ def test_index_name(self):+ result = _normalize_frame(_make_kline_df())+ assert result.index.name == "trade_date"++ def test_sorted_ascending(self):+ df = _make_kline_df(dates=["2024-01-03 00:00:00", "2024-01-02 00:00:00"])+ result = _normalize_frame(df)+ assert result.index[0] < result.index[1]++ def test_empty_input(self):+ result = _normalize_frame(pd.DataFrame())+ assert result.empty+ assert list(result.columns) == ["open", "high", "low", "close", "volume"]++ def test_drops_nan_ohlc_rows(self):+ df = _make_kline_df()+ df.loc[0, "close"] = None+ result = _normalize_frame(df)+ assert len(result) == 1++ def test_fills_nan_volume_with_zero(self):+ df = _make_kline_df()+ df.loc[0, "volume"] = None+ result = _normalize_frame(df)+ assert result["volume"].iloc[0] == 0.0+++# ---------------------------------------------------------------------------+# is_available()+# ---------------------------------------------------------------------------++class TestIsAvailable:+ def test_false_when_host_missing(self, monkeypatch):+ monkeypatch.delenv("FUTU_HOST", raising=False)+ monkeypatch.setenv("FUTU_PORT", "11111")+ assert FutuLoader().is_available() is False++ def test_false_when_port_missing(self, monkeypatch):+ monkeypatch.setenv("FUTU_HOST", "127.0.0.1")+ monkeypatch.delenv("FUTU_PORT", raising=False)+ assert FutuLoader().is_available() is False++ def test_true_when_connection_succeeds(self, monkeypatch):+ monkeypatch.setenv("FUTU_HOST", "127.0.0.1")+ monkeypatch.setenv("FUTU_PORT", "11111")+ mock_ctx = MagicMock()+ _futu_stub.OpenQuoteContext.return_value = mock_ctx+ assert FutuLoader().is_available() is True+ mock_ctx.close.assert_called_once()++ def test_false_when_connection_raises(self, monkeypatch):+ monkeypatch.setenv("FUTU_HOST", "127.0.0.1")+ monkeypatch.setenv("FUTU_PORT", "11111")+ _futu_stub.OpenQuoteContext.side_effect = OSError("connection refused")+ assert FutuLoader().is_available() is False+++# ---------------------------------------------------------------------------+# fetch()+# ---------------------------------------------------------------------------++class TestFetch:+ @pytest.fixture()+ def loader(self, monkeypatch):+ monkeypatch.setenv("FUTU_HOST", "127.0.0.1")+ monkeypatch.setenv("FUTU_PORT", "11111")+ return FutuLoader()++ @pytest.fixture()+ def mock_ctx(self):+ ctx = MagicMock()+ _futu_stub.OpenQuoteContext.return_value = ctx+ return ctx++ def test_empty_codes_returns_empty(self, loader):+ assert loader.fetch([], "2024-01-01", "2024-01-31") == {}++ def test_returns_normalized_dataframe(self, loader, mock_ctx):+ mock_ctx.request_history_kline.return_value = (0, _make_kline_df())+ result = loader.fetch(["700.HK"], "2024-01-01", "2024-01-31")+ assert "700.HK" in result+ df = result["700.HK"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"++ def test_futu_symbol_converted_correctly(self, loader, mock_ctx):+ mock_ctx.request_history_kline.return_value = (0, _make_kline_df())+ loader.fetch(["700.HK"], "2024-01-01", "2024-01-31")+ args, _ = mock_ctx.request_history_kline.call_args+ assert args[0] == "HK.00700"++ def test_raises_on_connection_failure(self, loader):+ _futu_stub.OpenQuoteContext.side_effect = OSError("connection refused")+ with pytest.raises(NoAvailableSourceError):+ loader.fetch(["700.HK"], "2024-01-01", "2024-01-31")++ def test_skips_symbol_on_non_ret_ok(self, loader, mock_ctx):+ mock_ctx.request_history_kline.return_value = (1, "error message")+ result = loader.fetch(["700.HK"], "2024-01-01", "2024-01-31")+ assert "700.HK" not in result++ def test_context_always_closed(self, loader, mock_ctx):+ mock_ctx.request_history_kline.return_value = (0, _make_kline_df())+ loader.fetch(["700.HK"], "2024-01-01", "2024-01-31")+ mock_ctx.close.assert_called_once()