Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(futu): use the requested minute interval

xkam7ar0fecf31d739a
diff --git a/agent/backtest/loaders/futu.py b/agent/backtest/loaders/futu.py
index 107d7adc8..853eeec6d 100644
--- a/agent/backtest/loaders/futu.py
+++ b/agent/backtest/loaders/futu.py
@@ -20,6 +20,10 @@ logger = logging.getLogger(__name__)
_OHLCV_COLUMNS = ["open", "high", "low", "close", "volume"]
_INTERVAL_MAP: dict[str, str] = {
+ "1m": "K_1M",
+ "5m": "K_5M",
+ "15m": "K_15M",
+ "30m": "K_30M",
"1D": "K_DAY",
"1H": "K_60M",
"4H": "K_240M",
@@ -51,10 +55,24 @@ 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.
+ Unsupported intervals fail explicitly so requested bar fidelity is never
+ changed silently.
"""
from futu import KLType # noqa: PLC0415
- return getattr(KLType, _INTERVAL_MAP.get(interval.strip(), "K_DAY"))
+
+ token = interval.strip()
+ attr = _INTERVAL_MAP.get(token)
+ if attr is None:
+ raise NoAvailableSourceError(
+ f"unsupported Futu interval: {interval!r}; "
+ f"supported intervals: {sorted(_INTERVAL_MAP)}"
+ )
+ try:
+ return getattr(KLType, attr)
+ except AttributeError as exc:
+ raise NoAvailableSourceError(
+ f"installed Futu SDK does not expose KLType.{attr}"
+ ) from exc
def _normalize_frame(df: pd.DataFrame) -> pd.DataFrame:
@@ -129,7 +147,7 @@ class FutuLoader:
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``.
+ interval: Backtest interval supported by :data:`_INTERVAL_MAP`.
fields: Ignored; included for interface compatibility.
Returns:
@@ -142,6 +160,11 @@ class FutuLoader:
if not codes:
return {}
validate_date_range(start_date, end_date)
+ if interval.strip() not in _INTERVAL_MAP:
+ raise NoAvailableSourceError(
+ f"unsupported Futu interval: {interval!r}; "
+ f"supported intervals: {sorted(_INTERVAL_MAP)}"
+ )
results: Dict[str, pd.DataFrame] = {}
@@ -168,6 +191,7 @@ class FutuLoader:
try:
import futu # noqa: PLC0415
+
ktype = _to_futu_ktype(interval)
ctx = futu.OpenQuoteContext(host=self._host, port=self._port)
except Exception as exc:
diff --git a/agent/tests/test_futu_loader.py b/agent/tests/test_futu_loader.py
index 483e024c2..a5d682a6e 100644
--- a/agent/tests/test_futu_loader.py
+++ b/agent/tests/test_futu_loader.py
@@ -17,7 +17,12 @@ import pytest
# Stub futu before importing loader
# ---------------------------------------------------------------------------
+
class _KLType:
+ K_1M = "K_1M"
+ K_5M = "K_5M"
+ K_15M = "K_15M"
+ K_30M = "K_30M"
K_DAY = "K_DAY"
K_60M = "K_60M"
K_240M = "K_240M"
@@ -30,14 +35,19 @@ _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.futu import ( # noqa: E402
+ FutuLoader,
+ _normalize_frame,
+ _to_futu_symbol,
+ _to_futu_ktype,
+)
from backtest.loaders.base import NoAvailableSourceError # noqa: E402
-
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
+
@pytest.fixture(autouse=True)
def reset_futu_mock():
"""Ensure the futu stub is clean before and after every test."""
@@ -89,24 +99,35 @@ class TestSymbolMapping:
# 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"
+class TestIntervalMapping:
+ @pytest.mark.parametrize(
+ ("interval", "expected"),
+ [
+ ("1m", "K_1M"),
+ ("5m", "K_5M"),
+ ("15m", "K_15M"),
+ ("30m", "K_30M"),
+ ("1H", "K_60M"),
+ ("4H", "K_240M"),
+ ("1D", "K_DAY"),
+ ("1W", "K_WEEK"),
+ ("1M", "K_MON"),
+ ],
+ )
+ def test_supported_intervals(self, interval, expected):
+ assert _to_futu_ktype(interval) == expected
+
+ def test_unknown_fails_closed(self):
+ with pytest.raises(NoAvailableSourceError, match="unsupported Futu interval"):
+ _to_futu_ktype("999X")
# ---------------------------------------------------------------------------
# _normalize_frame
# ---------------------------------------------------------------------------
+
class TestNormalizeFrame:
def test_ohlcv_columns(self):
result = _normalize_frame(_make_kline_df())
@@ -233,3 +254,8 @@ class TestFetch:
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()
+
+ def test_fetch_unknown_interval_fails_before_opening_context(self, loader):
+ with pytest.raises(NoAvailableSourceError, match="unsupported Futu interval"):
+ loader.fetch(["700.HK"], "2024-01-01", "2024-01-31", interval="2m")
+ _futu_stub.OpenQuoteContext.assert_not_called()