"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(loaders): add mootdx A-share OHLCV loader
Haozhe Wue4e2a9d9c2a8
diff --git a/README.md b/README.mdindex da751ce9a..f424bd4ae 100644--- a/README.md+++ b/README.md@@ -234,7 +234,7 @@ Detailed inventories are folded below to keep the main README scannable. Open th| Category | Skills | Examples ||----------|--------|----------|-| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |+| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -896,7 +896,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 6 sources: tushare, okx, yfinance, akshare, ccxt, futu+│ ├── loaders/ # 7 sources: tushare, okx, yfinance, akshare, mootdx, ccxt, futu│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_ar.md b/README_ar.mdindex 2ebe04342..cece1266a 100644--- a/README_ar.md+++ b/README_ar.md@@ -235,7 +235,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| الفئة | المهارات | أمثلة ||----------|--------|----------|-| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |+| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -809,7 +809,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 6 sources: tushare, okx, yfinance, akshare, ccxt, futu+│ ├── loaders/ # 7 sources: tushare, okx, yfinance, akshare, mootdx, ccxt, futu│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_ja.md b/README_ja.mdindex 25a841d9c..b28e4d315 100644--- a/README_ja.md+++ b/README_ja.md@@ -235,7 +235,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| Category | Skills | Examples ||----------|--------|----------|-| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |+| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -806,7 +806,7 @@ Vibe-Trading/│ ││ └── backtest/ # バックテストエンジン│ ├── engines/ # 7 エンジン + クロスマーケット composite engine + options_portfolio-│ ├── loaders/ # 6 ソース: tushare、okx、yfinance、akshare、ccxt、futu+│ ├── loaders/ # 7 ソース: tushare、okx、yfinance、akshare、mootdx、ccxt、futu│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + 自動フォールバックチェーン│ └── optimizers/ # MVO、equal vol、max div、risk paritydiff --git a/README_ko.md b/README_ko.mdindex 63c80ab4b..2555e86c5 100644--- a/README_ko.md+++ b/README_ko.md@@ -235,7 +235,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| 카테고리 | 스킬 | 예시 ||----------|------|------|-| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |+| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -809,7 +809,7 @@ Vibe-Trading/│ ││ └── backtest/ # Backtest engines│ ├── engines/ # 7 engines + composite cross-market engine + options_portfolio-│ ├── loaders/ # 6 sources: tushare, okx, yfinance, akshare, ccxt, futu+│ ├── loaders/ # 7 sources: tushare, okx, yfinance, akshare, mootdx, ccxt, futu│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + auto-fallback chains│ └── optimizers/ # MVO, equal vol, max div, risk paritydiff --git a/README_zh.md b/README_zh.mdindex fdebade76..7578fba68 100644--- a/README_zh.md+++ b/README_zh.md@@ -234,7 +234,7 @@ vibe-trading run -p "Analyze my trading behavior, extract my shadow strategy, an| 类别 | Skills | 示例 ||------|--------|------|-| Data Source | 6 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `ccxt` |+| Data Source | 7 | `data-routing`, `tushare`, `yfinance`, `okx-market`, `akshare`, `mootdx`, `ccxt` || Strategy | 17 | `strategy-generate`, `cross-market-strategy`, `technical-basic`, `candlestick`, `ichimoku`, `elliott-wave`, `smc`, `multi-factor`, `ml-strategy` || Analysis | 17 | `factor-research`, `macro-analysis`, `global-macro`, `valuation-model`, `earnings-forecast`, `credit-analysis`, `dividend-analysis` || Asset Class | 9 | `options-strategy`, `options-advanced`, `convertible-bond`, `etf-analysis`, `asset-allocation`, `sector-rotation` |@@ -805,7 +805,7 @@ Vibe-Trading/│ ││ └── backtest/ # 回测引擎│ ├── engines/ # 7 个引擎 + 跨市场 composite 引擎 + options_portfolio-│ ├── loaders/ # 6 个数据源:tushare、okx、yfinance、akshare、ccxt、futu+│ ├── loaders/ # 7 个数据源:tushare、okx、yfinance、akshare、mootdx、ccxt、futu│ │ ├── base.py # DataLoader Protocol│ │ └── registry.py # Registry + 自动 fallback 链路│ └── optimizers/ # MVO、equal vol、max div、risk paritydiff --git a/agent/SKILL.md b/agent/SKILL.mdindex 274cc553f..e41415ece 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,7 +1,7 @@---name: vibe-tradingversion: 0.1.8-description: Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 75 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 6 data sources (tushare, yfinance, okx, akshare, ccxt, futu).+description: Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 75 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).dependencies:python: ">=3.11"pip:@@ -73,7 +73,7 @@ Feed a CSV broker export (同花顺 / 东财 / 富途 / generic), and the agent5. `scan_shadow_signals` — list today's symbols that match your shadow's entry cadence (research only).### Backtesting-Create and run quantitative strategies across 7 engines (ChinaA, GlobalEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 6 data sources:+Create and run quantitative strategies across 7 engines (ChinaA, GlobalEquity, Crypto, ChinaFutures, GlobalFutures, Forex + options) with 7 data sources:- **HK/US equities** via yfinance (free, no API key)- **Cryptocurrency** via OKX or CCXT/100+ exchanges (free, no API key)- **China A-shares** via Tushare (token) or AKShare (free fallback)diff --git a/agent/backtest/loaders/mootdx_loader.py b/agent/backtest/loaders/mootdx_loader.pynew file mode 100644index 000000000..0c7a7b36f--- /dev/null+++ b/agent/backtest/loaders/mootdx_loader.py@@ -0,0 +1,243 @@+"""Mootdx loader: A-share OHLCV via TCP-direct 通达信 servers (no IP ban).++Mootdx (https://github.com/mootdx/mootdx) talks the native 通达信 binary+protocol over TCP and is not subject to the HTTP scraping rate limits that+periodically break the akshare → East Money path. Public market data only,+no token required, no per-IP throttling.++Scope: A-share OHLCV only (沪/深/京 auto-detected from symbol). Mootdx's+extended-market endpoint (futures/options) is upstream-broken as of+v0.11.7 — falls through to tushare/akshare for those markets.+"""++from __future__ import annotations++import logging+from typing import Dict, List, Optional++import pandas as pd++from backtest.loaders.base import validate_date_range+from backtest.loaders.registry import register++logger = logging.getLogger(__name__)++# Mootdx frequency codes (see mootdx.consts).+_INTRADAY_FREQ: dict[str, int] = {+ "1m": 8,+ "5m": 0,+ "15m": 1,+ "30m": 2,+ "1H": 3,+}+_DAILY_FREQ: dict[str, int] = {+ "1D": 4,+ "1W": 5,+ "1M": 6,+}++# bars() returns one page of N rows ending at the latest bar. Pages older+# than this need to be requested with ``start=offset_into_history``. We cap+# pagination at MAX_PAGES so a wildly out-of-range request can't grind for+# minutes against the TDX server.+_BARS_PAGE = 800+_MAX_PAGES = 25 # 25 × 800 = 20 000 bars (~10y daily, ~5y 1H, ~3mo 1m)+++def _is_a_share(code: str) -> bool:+ """Accept either explicit `.SH/.SZ/.BJ` suffix or bare 6-digit ticker."""+ upper = code.upper()+ if upper.endswith((".SH", ".SZ", ".BJ")):+ return True+ return len(code) == 6 and code.isdigit()+++def _is_bj(code: str) -> bool:+ """Detect 北交所 symbols. Mootdx std factory does not serve BJ data+ (get_k_data raises KeyError, bars() returns empty), so the loader logs+ a warning and skips these instead of silently returning nothing."""+ upper = code.upper()+ if upper.endswith(".BJ"):+ return True+ # 4xxxxx / 8xxxxx are BJ prefixes (bare 6-digit form).+ return len(code) == 6 and code.isdigit() and code[0] in ("4", "8")+++@register+class DataLoader:+ """Mootdx-backed A-share OHLCV loader (TCP-direct, no auth)."""++ name = "mootdx"+ markets = {"a_share"}+ requires_auth = False++ def __init__(self) -> None:+ self._client = None++ def is_available(self) -> bool:+ """Available if mootdx is installed."""+ try:+ import mootdx # noqa: F401+ return True+ except ImportError:+ return False++ def _get_client(self):+ if self._client is None:+ from mootdx.quotes import Quotes+ self._client = Quotes.factory(market="std")+ return self._client++ 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 A-share OHLCV via mootdx.++ Args:+ codes: Symbol list. `.SH/.SZ/.BJ` suffix or bare 6-digit+ tickers; non-A-share symbols are silently skipped.+ start_date: YYYY-MM-DD.+ end_date: YYYY-MM-DD.+ interval: One of ``1m / 5m / 15m / 30m / 1H / 1D / 1W / 1M``.+ fields: Ignored.++ Returns:+ Mapping symbol -> OHLCV DataFrame.++ Raises:+ ValueError: If ``interval`` is not in the supported set.+ """+ validate_date_range(start_date, end_date)+ if interval not in _DAILY_FREQ and interval not in _INTRADAY_FREQ:+ raise ValueError(+ f"Unsupported interval for mootdx: {interval!r}. "+ f"Supported: {sorted(_DAILY_FREQ) + sorted(_INTRADAY_FREQ)}"+ )++ result: Dict[str, pd.DataFrame] = {}+ for code in codes:+ if not _is_a_share(code):+ logger.debug("mootdx: skipping non-A-share symbol %s", code)+ continue+ if _is_bj(code):+ logger.warning(+ "mootdx: 北交所 (%s) not supported upstream; use akshare/tushare",+ code,+ )+ continue+ try:+ df = self._fetch_one(code, start_date, end_date, interval)+ if df is not None and not df.empty:+ result[code] = df+ except Exception as exc:+ logger.warning("mootdx failed for %s: %s", code, exc)+ return result++ def _fetch_one(+ self, code: str, start_date: str, end_date: str, interval: str,+ ) -> Optional[pd.DataFrame]:+ symbol = code.split(".")[0]+ client = self._get_client()++ # Daily has a native date-range API; intraday and weekly/monthly+ # only expose offset-from-latest, so we page back through history+ # until the first row of the page is older than start_date.+ if interval == "1D":+ df = client.get_k_data(code=symbol, start_date=start_date, end_date=end_date)+ return self._normalize_daily(df)++ freq = _DAILY_FREQ.get(interval) or _INTRADAY_FREQ[interval]+ return self._fetch_bars_paginated(client, symbol, freq, start_date, end_date)++ @staticmethod+ def _fetch_bars_paginated(+ client, symbol: str, freq: int, start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ """Walk backward through ``bars()`` pages until the requested+ window is covered, then clip and concatenate.++ Mootdx ``bars()`` returns the latest ``_BARS_PAGE`` rows by default;+ ``start=N`` skips the newest N rows. We page until the oldest row+ in a page is at or before ``start_date``, or until ``_MAX_PAGES``+ is exhausted (very old or thinly-traded symbols).+ """+ start_ts = pd.Timestamp(start_date)+ chunks: list[pd.DataFrame] = []+ for page in range(_MAX_PAGES):+ df = client.bars(+ symbol=symbol,+ frequency=freq,+ start=page * _BARS_PAGE,+ offset=_BARS_PAGE,+ )+ if df is None or df.empty:+ break+ chunks.append(df)+ first_dt = pd.to_datetime(df["datetime"].iloc[0])+ if first_dt <= start_ts:+ break+ else:+ logger.warning(+ "mootdx: %s %s pagination hit cap (%d pages) without reaching %s",+ symbol, freq, _MAX_PAGES, start_date,+ )+ if not chunks:+ return None+ combined = pd.concat(chunks, ignore_index=False)+ return DataLoader._normalize_bars(combined, start_date, end_date)++ @staticmethod+ def _normalize_daily(df: Optional[pd.DataFrame]) -> Optional[pd.DataFrame]:+ """Normalize `get_k_data()` output to the OHLCV contract.++ get_k_data returns columns ``[open, close, high, low, vol, amount,+ date, code]`` with ``date`` as the index name.+ """+ if df is None or df.empty:+ return None+ out = df.rename(columns={"vol": "volume"}).copy()+ out.index = pd.to_datetime(out.index)+ out.index.name = "trade_date"+ for col in ("open", "high", "low", "close", "volume"):+ out[col] = pd.to_numeric(out[col], errors="coerce")+ out = out[["open", "high", "low", "close", "volume"]].dropna(+ subset=["open", "high", "low", "close"]+ )+ return out.sort_index() if not out.empty else None++ @staticmethod+ def _normalize_bars(+ df: Optional[pd.DataFrame], start_date: str, end_date: str,+ ) -> Optional[pd.DataFrame]:+ """Normalize `bars()` output and clip to the requested window.++ bars() returns ``[open, close, high, low, vol, amount, year, month,+ day, hour, minute, datetime, volume]`` with a datetime index.+ ``volume`` (lowercase, last column) is the canonical share count;+ ``vol`` is a historical alias kept by mootdx for compatibility.+ """+ if df is None or df.empty:+ return None+ out = df.copy()+ if "datetime" in out.columns:+ out["trade_date"] = pd.to_datetime(out["datetime"])+ out = out.set_index("trade_date")+ else:+ out.index = pd.to_datetime(out.index)+ out.index.name = "trade_date"+ out = out.sort_index()+ for col in ("open", "high", "low", "close", "volume"):+ out[col] = pd.to_numeric(out[col], errors="coerce")+ out = out[["open", "high", "low", "close", "volume"]].dropna(+ subset=["open", "high", "low", "close"]+ )+ # Inclusive end-of-day so a `2025-02-01` window keeps the 15:00 bar.+ end_ts = pd.Timestamp(end_date) + pd.Timedelta(days=1) - pd.Timedelta(seconds=1)+ out = out.loc[pd.Timestamp(start_date):end_ts]+ return out if not out.empty else Nonediff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.pyindex 4ba7d6dd7..be29a4460 100644--- a/agent/backtest/loaders/registry.py+++ b/agent/backtest/loaders/registry.py@@ -51,6 +51,7 @@ def _ensure_registered() -> None:"backtest.loaders.okx","backtest.loaders.yfinance_loader","backtest.loaders.akshare_loader",+ "backtest.loaders.mootdx_loader","backtest.loaders.ccxt_loader","backtest.loaders.futu",]@@ -67,7 +68,7 @@ def _ensure_registered() -> None:# ---------------------------------------------------------------------------FALLBACK_CHAINS: dict[str, list[str]] = {- "a_share": ["tushare", "akshare"],+ "a_share": ["tushare", "mootdx", "akshare"],"us_equity": ["yfinance", "akshare"],"hk_equity": ["yfinance", "futu", "akshare"],"crypto": ["okx", "ccxt"],diff --git a/agent/src/skills/mootdx/SKILL.md b/agent/src/skills/mootdx/SKILL.mdnew file mode 100644index 000000000..7f246e3a4--- /dev/null+++ b/agent/src/skills/mootdx/SKILL.md@@ -0,0 +1,94 @@+---+name: mootdx+category: data-source+description: Mootdx A-share market data via TCP-direct 通达信 servers. Free, no API key, no IP rate limits. Use as the stable A-share OHLCV fallback when akshare's East Money scrape is throttled.+---++## Overview++Mootdx talks the native 通达信 (TDX) binary protocol over TCP, bypassing the HTTP scrapers that periodically fail under load (akshare → East Money is the canonical example). Public market data only — no token, no per-IP throttling, no captcha.++- GitHub: https://github.com/mootdx/mootdx+- Install: `pip install mootdx && pip install 'httpx>=0.28.1'`++> Mootdx pins `httpx<0.26` in `setup.py`, but only uses basic `httpx.Client/get` APIs that are forward-compatible. The second `pip install` restores the modern httpx that the rest of Vibe-Trading (MCP server, fastmcp) needs.++## Quick Start++```python+from mootdx.quotes import Quotes++client = Quotes.factory(market="std") # std = 沪/深/京; ext = 期货/期权 (upstream-broken)++# Daily OHLCV with a date range (preferred API).+df = client.get_k_data(code="000001", start_date="2025-01-01", end_date="2025-02-01")++# Intraday — offset-from-latest only, no native date range.+df_15m = client.bars(symbol="600519", frequency=1, offset=800)+```++## Frequency Codes++`bars(frequency=N)` uses integer codes from `mootdx.consts`:++| Code | Bar |+|------|-----|+| 8 | 1m |+| 0 | 5m |+| 1 | 15m |+| 2 | 30m |+| 3 | 1H |+| 4 | 1D |+| 5 | 1W |+| 6 | 1M |++`get_k_data()` is **daily only** but accepts `start_date / end_date`. For intraday, `bars()` returns the latest N rows — the built-in loader over-fetches `offset=800` then clips to the requested window.++## Key Methods++| Method | Use | Returns |+|--------|-----|---------|+| `get_k_data(code, start_date, end_date)` | Daily OHLCV with date range | `[open, close, high, low, vol, amount, date, code]` |+| `bars(symbol, frequency, offset=800)` | Intraday / weekly / monthly | `[open, close, high, low, vol, amount, datetime, volume, ...]` |+| `minute(symbol)` | Current trading day 1m bars | Same schema as `bars()` |+| `quotes(symbol)` | Real-time L1 snapshot | `{price, bid, ask, volume, ...}` |+| `stocks(market)` | List all tickers on an exchange | DataFrame of `code/name` |+| `F10(symbol)` / `finance(symbol)` | Fundamentals snapshot | Heterogeneous dict |++## Symbol Format++- Pure 6-digit: `"000001"`, `"600519"`, `"835174"` — mootdx auto-detects exchange from prefix:+ - `60x / 68x` → SH+ - `00x / 30x / 002 / 003` → SZ+ - `4x / 8x` → BJ+- The built-in loader also accepts `"000001.SZ"`, `"600519.SH"`, `"835174.BJ"` and strips the suffix.++## Column Names++`get_k_data()` returns lowercase English: `open / close / high / low / vol / amount / date / code`. The built-in loader renames `vol` → `volume` to match the project's OHLCV contract.++`bars()` returns the same OHLC columns plus a duplicate `volume` (alongside the legacy `vol`), a `datetime` string column, and decomposed `year / month / day / hour / minute` columns.++## Built-in Loader++`backtest/loaders/mootdx_loader.py` is registered as the `mootdx` source. Fallback chain for `a_share` is `[tushare, mootdx, akshare]` — tushare wins when a token is present; mootdx wins when no token but TCP egress works; akshare is the broadest fallback.++```python+from backtest.runner import run+result = run(strategy=..., source="mootdx") # explicit override+```++## Known Limitations++| Limitation | Workaround |+|------------|------------|+| 北交所 (BJ): `get_k_data` raises `KeyError`, `bars()` returns empty (upstream missing data) | Loader logs a warning and skips BJ symbols — use akshare or tushare |+| Extended market (futures/options) returns empty as of v0.11.7 (upstream issue) | Use tushare/akshare for futures |+| Each `bars()` page is 800 rows; loader paginates back up to 25 pages (≈10y daily / ≈5y 1H / ≈3mo 1m) | For longer 1m history use tushare minute bars |+| Server selection has cold-start latency (first call picks the fastest server) | First call may be ~2s slower |+| Returns data in 前复权 by default — no API parameter for 不复权 | Use tushare/akshare if raw prices are required |++## Reference Docs++- Mootdx 文档: https://www.mootdx.com/+- 通达信协议参考: https://github.com/rainx/pytdxdiff --git a/agent/tests/test_mootdx_loader.py b/agent/tests/test_mootdx_loader.pynew file mode 100644index 000000000..2d5c0f42c--- /dev/null+++ b/agent/tests/test_mootdx_loader.py@@ -0,0 +1,209 @@+"""Tests for the mootdx A-share OHLCV loader."""++from __future__ import annotations++from types import SimpleNamespace++import pandas as pd+import pytest++from backtest.loaders.mootdx_loader import DataLoader, _is_a_share, _is_bj+++# ---------------------------------------------------------------------------+# Symbol detection+# ---------------------------------------------------------------------------+++ "code, expected",+ [+ ("000001.SZ", True),+ ("600519.SH", True),+ ("835174.BJ", True),+ ("000001", True),+ ("600519", True),+ ("AAPL.US", False),+ ("00700.HK", False),+ ("BTC-USDT", False),+ ("12345", False), # 5-digit+ ("000001A", False), # contains letter+ ],+)+def test_is_a_share(code: str, expected: bool) -> None:+ assert _is_a_share(code) is expected+++# ---------------------------------------------------------------------------+# Fake mootdx client (no network, no TCP)+# ---------------------------------------------------------------------------+++class _FakeStdQuotes:+ """Drop-in for ``mootdx.quotes.StdQuotes`` covering the two methods we call."""++ def __init__(self) -> None:+ self.calls: list[tuple] = []++ def get_k_data(self, code: str, start_date: str, end_date: str):+ self.calls.append(("get_k_data", code, start_date, end_date))+ idx = pd.DatetimeIndex(["2025-01-02", "2025-01-03", "2025-01-06"], name="date")+ return pd.DataFrame(+ {+ "open": [11.73, 11.44, 11.38],+ "close": [11.43, 11.38, 11.44],+ "high": [11.77, 11.54, 11.48],+ "low": [11.40, 11.32, 11.31],+ "vol": [1_000_000, 800_000, 950_000],+ "amount": [1.1e7, 9.1e6, 1.08e7],+ "date": ["2025-01-02", "2025-01-03", "2025-01-06"],+ "code": [code, code, code],+ },+ index=idx,+ )++ def bars(self, symbol: str, frequency: int, start: int = 0, offset: int = 800):+ self.calls.append(("bars", symbol, frequency, start, offset))+ # First page (start=0): four 15-min bars on 2025-01-02. Subsequent+ # pages return empty so the paginator stops promptly.+ if start > 0:+ return pd.DataFrame(columns=["open", "close", "high", "low", "vol",+ "amount", "datetime", "volume"])+ timestamps = pd.date_range("2025-01-02 09:30", periods=4, freq="15min")+ return pd.DataFrame(+ {+ "open": [11.73, 11.74, 11.75, 11.76],+ "close": [11.74, 11.75, 11.76, 11.77],+ "high": [11.78, 11.79, 11.80, 11.81],+ "low": [11.70, 11.71, 11.72, 11.73],+ "vol": [100, 200, 300, 400],+ "amount": [1100, 2200, 3300, 4400],+ "datetime": [t.strftime("%Y-%m-%d %H:%M") for t in timestamps],+ "volume": [100, 200, 300, 400],+ },+ index=pd.DatetimeIndex(timestamps, name="datetime"),+ )+++def fake_client(monkeypatch: pytest.MonkeyPatch) -> _FakeStdQuotes:+ """Install a fake StdQuotes so DataLoader doesn't hit the TDX network."""+ fake = _FakeStdQuotes()+ fake_module = SimpleNamespace(Quotes=SimpleNamespace(factory=lambda market: fake))+ import sys+ monkeypatch.setitem(sys.modules, "mootdx", SimpleNamespace())+ monkeypatch.setitem(sys.modules, "mootdx.quotes", fake_module)+ return fake+++# ---------------------------------------------------------------------------+# Loader behavior+# ---------------------------------------------------------------------------+++def test_fetch_daily_uses_get_k_data(fake_client: _FakeStdQuotes) -> None:+ loader = DataLoader()+ out = loader.fetch(["000001.SZ"], "2025-01-01", "2025-01-10", interval="1D")++ assert "000001.SZ" in out+ df = out["000001.SZ"]+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]+ assert df.index.name == "trade_date"+ assert len(df) == 3+ # Symbol stripping: SDK called with bare 6-digit code.+ assert any(call[0] == "get_k_data" and call[1] == "000001" for call in fake_client.calls)+++def test_fetch_intraday_uses_bars_and_clips_window(+ fake_client: _FakeStdQuotes,+) -> None:+ loader = DataLoader()+ out = loader.fetch(["600519"], "2025-01-02", "2025-01-02", interval="15m")++ assert "600519" in out+ df = out["600519"]+ assert len(df) == 4 # all four 15-min bars on 2025-01-02 are in window+ # frequency=1 corresponds to KLINE_15MIN in mootdx.consts.+ assert any(call[0] == "bars" and call[2] == 1 for call in fake_client.calls)+ # Paginator stopped after the first non-empty page returned older bars.+ assert sum(1 for c in fake_client.calls if c[0] == "bars") >= 1+++def test_fetch_intraday_empty_window_returns_no_entry(+ fake_client: _FakeStdQuotes,+) -> None:+ loader = DataLoader()+ out = loader.fetch(["600519"], "2030-01-01", "2030-01-02", interval="5m")+ assert out == {}+++def test_fetch_skips_non_a_share_symbols(fake_client: _FakeStdQuotes) -> None:+ loader = DataLoader()+ out = loader.fetch(["AAPL.US", "00700.HK", "BTC-USDT"], "2025-01-01", "2025-01-10")+ assert out == {}+ assert fake_client.calls == []+++def test_fetch_skips_bj_symbols_with_warning(+ fake_client: _FakeStdQuotes, caplog: pytest.LogCaptureFixture,+) -> None:+ """Mootdx upstream has no BJ data; loader must skip + warn, not crash."""+ import logging+ caplog.set_level(logging.WARNING)+ loader = DataLoader()+ out = loader.fetch(["835174.BJ", "832000", "000001.SZ"], "2025-01-01", "2025-01-10")+ assert "835174.BJ" not in out+ assert "832000" not in out+ assert "000001.SZ" in out+ assert fake_client.calls and fake_client.calls[0][1] == "000001"+ warnings = [r for r in caplog.records if "北交所" in r.message]+ assert len(warnings) == 2+++ "code, expected",+ [("835174.BJ", True), ("832000", True), ("488888", True),+ ("000001.SZ", False), ("600519", False), ("300750", False)],+)+def test_is_bj(code: str, expected: bool) -> None:+ assert _is_bj(code) is expected+++def test_fetch_rejects_unknown_interval(fake_client: _FakeStdQuotes) -> None:+ loader = DataLoader()+ with pytest.raises(ValueError, match="Unsupported interval"):+ loader.fetch(["000001.SZ"], "2025-01-01", "2025-01-10", interval="3D")+++def test_is_available_false_when_mootdx_missing(monkeypatch: pytest.MonkeyPatch) -> None:+ import builtins+ real_import = builtins.__import__++ def blocking_import(name, *args, **kwargs):+ if name == "mootdx" or name.startswith("mootdx."):+ raise ImportError("mootdx not installed")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", blocking_import)+ assert DataLoader().is_available() is False+++def test_is_available_true_when_mootdx_present(fake_client: _FakeStdQuotes) -> None:+ assert DataLoader().is_available() is True+++# ---------------------------------------------------------------------------+# Registry integration+# ---------------------------------------------------------------------------+++def test_registry_lists_mootdx_in_a_share_chain() -> None:+ from backtest.loaders.registry import FALLBACK_CHAINS, _ensure_registered, LOADER_REGISTRY++ _ensure_registered()+ assert "mootdx" in LOADER_REGISTRY+ chain = FALLBACK_CHAINS["a_share"]+ assert "mootdx" in chain+ # Order: tushare (auth) > mootdx (TCP, no auth) > akshare (HTTP scrape).+ assert chain.index("mootdx") < chain.index("akshare")+ assert chain.index("tushare") < chain.index("mootdx")