Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(data): gildata (Hundsun Juyuan) A-share OHLCV loader via the raw-api MCP endpoint

sambazhu64ebb7cf5c5a
diff --git a/agent/.env.example b/agent/.env.example
index a23f22bbe..bcf59e4c3 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -182,11 +182,11 @@ TUSHARE_TOKEN=your-tushare-token
# chain (same sources, new order); invalid values are ignored with a warning.
# Also editable in the Web UI: Settings -> Data Source Priority. Example —
# put the paid Tushare feed first for A-shares (default order is
-# tencent,mootdx,eastmoney,baostock,akshare,tushare,local):
-# MARKET_DATA_ORDER_A_SHARE=tushare,tencent,mootdx,eastmoney,baostock,akshare,local
+# tencent,mootdx,eastmoney,baostock,akshare,tushare,gildata,local):
+# MARKET_DATA_ORDER_A_SHARE=tushare,tencent,mootdx,eastmoney,baostock,akshare,gildata,local
# Caliber caveat: sources differ in adjustment basis (e.g. yahoo/yfinance serve
-# raw OHLC while tencent/eastmoney/tushare/baostock serve adjusted prices), so
-# a reordered chain can change backtest numbers.
+# raw OHLC while tencent/eastmoney/tushare/baostock/gildata serve adjusted
+# prices), so a reordered chain can change backtest numbers.
# HK/US equities: yfinance (free, no config needed)
# Crypto: OKX public API (free, no config needed)
# Crypto fallback exchange (default: binance). Change if OKX is blocked:
@@ -211,6 +211,8 @@ TUSHARE_TOKEN=your-tushare-token
# ALPHAVANTAGE_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)
# TIINGO_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)
# FMP_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)
+# GILDATA_TOKEN=xxx # optional Gildata (恒生聚源) A-share OHLCV fallback provider — commercial token via [email protected]; joins the a_share chain's tail when set (selectable get_market_data source)
+# GILDATA_BASE_URL=xxx # optional endpoint override (defaults to the vendor's raw-api MCP endpoint)
# TICKERALL_API_KEY=xxx # optional hosted MetaTrader 5 forex/metals feed — EXPLICIT source="tickerall" only, never an automatic fallback (no local terminal; https://tickerall.com)
# TICKERALL_ACCOUNT_ID=xxx # required alongside the key: history is served per connected broker account (read-only)
# TICKERALL_BASE_URL=xxx # optional endpoint override (defaults to the public API)
diff --git a/agent/backtest/loaders/_http.py b/agent/backtest/loaders/_http.py
index 0b701c992..89fe6ab42 100644
--- a/agent/backtest/loaders/_http.py
+++ b/agent/backtest/loaders/_http.py
@@ -198,3 +198,32 @@ def throttled_get_json(
)
response.raise_for_status()
return response.json()
+
+
+def throttled_post_json(
+ url: str,
+ *,
+ host_key: str,
+ min_interval: float,
+ json_body: Any,
+ params: dict[str, Any] | None = None,
+ headers: dict[str, str] | None = None,
+ timeout: float = 15.0,
+) -> Any:
+ """Throttled POST of a JSON body that decodes the response as JSON.
+
+ POST twin of :func:`throttled_get_json` for JSON-RPC style providers
+ (e.g. MCP-over-HTTP endpoints): same throttle/session bucketing, plus
+ ``raise_for_status()`` and ``.json()``. A non-2xx status or undecodable
+ body raises for the caller's retry policy to classify.
+ """
+ merged_headers = {"User-Agent": DEFAULT_USER_AGENT}
+ if headers:
+ merged_headers.update(headers)
+ _THROTTLE.wait(host_key, min_interval)
+ session = _session_for(host_key)
+ response = session.post(
+ url, json=json_body, params=params, headers=merged_headers, timeout=timeout
+ )
+ response.raise_for_status()
+ return response.json()
diff --git a/agent/backtest/loaders/gildata_loader.py b/agent/backtest/loaders/gildata_loader.py
new file mode 100644
index 000000000..89e267704
--- /dev/null
+++ b/agent/backtest/loaders/gildata_loader.py
@@ -0,0 +1,356 @@
+"""Gildata (恒生聚源) loader: token-gated A-share OHLCV via the raw-api MCP endpoint.
+
+Gildata serves its market data over MCP streamable-HTTP: every tool call is one
+JSON-RPC POST to a single endpoint whose token rides the URL query string::
+
+ POST https://api.gildata.com/mcp-servers/aidata-assistant-srv-rawapi
+ ?token=<GILDATA_TOKEN>&format=json
+ {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": "StockDailyQuote", "arguments": {...}}}
+
+The ``format=json`` parameter makes the tool answer with structured JSON
+instead of markdown. The JSON-RPC ``result.content[0].text`` field carries an
+inner envelope ``{"code": 0, "results": [{"api_name", "columns", "rows"}]}``;
+a non-zero inner ``code`` (e.g. 1001 on a bad token) is an error, while an
+*unresolvable symbol silently yields ``rows: []``* — the loader must treat
+that as "no data" so the fallback chain keeps walking, not as a hard failure.
+
+This loader uses the ``StockDailyQuote`` tool (A-share daily bars):
+
+* ``stockObject`` accepts project-style ``600519.SH`` codes directly (no
+ internal-code recall needed for A-shares, unlike the HK/US/index tools);
+* ``restorationStatus=1`` selects 前复权 (forward, split-AND-dividend
+ adjusted) — the same caliber tushare serves via ``adj_factor``;
+* one call covers the full requested window (verified against a 6.7-year
+ range) and up to 50 symbols; this loader still fetches per symbol so each
+ frame flows through the per-symbol loader cache;
+* ``turnovervolume`` is reported in 万股 (10k shares) and is converted to
+ plain shares here — ``volume_units`` therefore declares ``"shares"``.
+
+Auth: set ``GILDATA_TOKEN`` in the environment (apply via the vendor's sales
+channel, [email protected]). ``GILDATA_BASE_URL`` can override the endpoint.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, Dict, List, Optional
+
+import pandas as pd
+
+from backtest.loaders._http import resolve_min_interval, throttled_post_json
+from backtest.loaders.base import cached_loader_fetch, validate_date_range
+from backtest.loaders.registry import register
+
+logger = logging.getLogger(__name__)
+
+_TOKEN_ENV = "GILDATA_TOKEN"
+_BASE_URL_ENV = "GILDATA_BASE_URL"
+_DEFAULT_BASE_URL = "https://api.gildata.com/mcp-servers/aidata-assistant-srv-rawapi"
+
+# Tokens that must not count as "configured" (mirrors tushare's placeholder set).
+GILDATA_TOKEN_PLACEHOLDERS = {"", "your-gildata-token"}
+
+# Shared throttle/session bucket for every Gildata request in this process.
+_HOST_KEY = "gildata"
+_MIN_INTERVAL_ENV = "VIBE_TRADING_GILDATA_MIN_INTERVAL"
+_DEFAULT_MIN_INTERVAL_S = 0.3
+_TIMEOUT_S = 30.0
+
+# The MCP tool this loader routes to (A-share daily bars, 前复权).
+_DAILY_QUOTE_TOOL = "StockDailyQuote"
+_RESTORATION_QFQ = "1" # 1-前复权 / 2-后复权 / 3-不复权
+
+# Emitted columns, in this order, all float.
+_OHLCV_FIELDS = ("open", "high", "low", "close", "volume")
+
+# 万股 (10k shares) -> shares.
+_VOLUME_UNIT_MULTIPLIER = 10_000.0
+
+
+def _token() -> str:
+ """Return the configured Gildata token, stripped (``""`` if unset)."""
+ from src.config.accessor import get_env_config
+
+ return get_env_config().data.gildata_token.strip()
+
+
+def _base_url() -> str:
+ """Return the raw-api endpoint URL (env-overridable)."""
+ from src.config.accessor import get_env_config
+
+ return get_env_config().data.gildata_base_url.strip() or _DEFAULT_BASE_URL
+
+
+def _min_interval() -> float:
+ """Resolve the per-call minimum spacing, honoring the env override."""
+ return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL_S)
+
+
+def _gildata_symbol(code: str) -> Optional[str]:
+ """Translate a project symbol into Gildata's A-share convention.
+
+ Gildata A-share tools accept ``代码.交易所后缀`` with the SH/SZ/BJ
+ suffixes. The project already uses that shape, so suffixed codes pass
+ through (with ``.SS`` normalized to ``.SH`` like everywhere else). A bare
+ 6-digit code gets its exchange inferred from the leading digit. Anything
+ that is not recognizably an A-share symbol returns ``None`` so the caller
+ can drop it and let the fallback chain serve it from another source.
+
+ Args:
+ code: Project symbol, e.g. ``600519.SH``, ``000001``, ``00700.HK``.
+
+ Returns:
+ The Gildata symbol, or ``None`` for non-A-share inputs.
+ """
+ upper = code.strip().upper()
+ if not upper:
+ return None
+ if upper.endswith(".SS"):
+ upper = upper[: -len(".SS")] + ".SH"
+ if upper.endswith((".SH", ".SZ", ".BJ")):
+ digits = upper.split(".")[0]
+ return upper if len(digits) == 6 and digits.isdigit() else None
+ if len(upper) == 6 and upper.isdigit():
+ # Bare codes: 5/6/9 -> SH, 0/3 -> SZ, 4/8 -> BJ (BSE/NEEQ ranges).
+ if upper[0] in "569":
+ return upper + ".SH"
+ if upper[0] in "03":
+ return upper + ".SZ"
+ if upper[0] in "48":
+ return upper + ".BJ"
+ return None
+ return None
+
+
+def _call_tool(tool: str, arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Invoke one MCP tool and return its ``rows``.
+
+ Args:
+ tool: Tool name, e.g. ``"StockDailyQuote"``.
+ arguments: Structured tool arguments.
+
+ Returns:
+ The ``rows`` list of the first result entry (empty when the vendor
+ reports no data for the request).
+
+ Raises:
+ RuntimeError: If the token is missing, or the vendor answers with a
+ non-zero business code (bad token, quota, bad request).
+ requests.RequestException: Propagated from the HTTP layer.
+ ValueError: If the response shape cannot be unwrapped.
+ """
+ token = _token()
+ if not token:
+ raise RuntimeError(f"{_TOKEN_ENV} is not set")
+
+ base = _base_url()
+ url = f"{base}{'&' if '?' in base else '?'}token={token}&format=json"
+ payload = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {"name": tool, "arguments": arguments},
+ }
+ outer = throttled_post_json(
+ url,
+ host_key=_HOST_KEY,
+ min_interval=_min_interval(),
+ json_body=payload,
+ timeout=_TIMEOUT_S,
+ )
+
+ # Without a valid token the endpoint answers HTTP 200 with a plain error
+ # object (no JSON-RPC result envelope) — surface its message.
+ result = outer.get("result") if isinstance(outer, dict) else None
+ if result is None:
+ message = outer.get("message") if isinstance(outer, dict) else None
+ raise RuntimeError(f"gildata MCP call failed: {message or outer!r}")
+
+ content = result.get("content") or []
+ if not content or not isinstance(content[0], dict):
+ raise ValueError(f"gildata MCP response has no content: {outer!r}")
+ text = content[0].get("text")
+ if not isinstance(text, str):
+ raise ValueError(f"gildata MCP content is not text: {content[0]!r}")
+
+ inner = json.loads(text)
+ if not isinstance(inner, dict) or inner.get("code") not in (0, "0"):
+ raise RuntimeError(
+ f"gildata tool {tool} returned error: {str(inner)[:200]}"
+ )
+ results = inner.get("results") or []
+ if not results:
+ return []
+ rows = results[0].get("rows")
+ return rows if isinstance(rows, list) else []
+
+
+def _parse_daily_rows(rows: List[Dict[str, Any]]) -> Optional[pd.DataFrame]:
+ """Convert ``StockDailyQuote`` rows into an ascending OHLCV frame.
+
+ Field names come from the tool's own ``columns`` map (``tradingday``,
+ ``openprice``/``highprice``/``lowprice``/``closeprice``,
+ ``turnovervolume`` in 万股). The ``avgprice``/``prevcloseprice`` fields
+ are deliberately ignored: on adjusted series they stay on a different
+ adjustment basis than OHLC (measured on 600519: qfq close 1491 vs
+ avgprice 1666), so mixing them in would corrupt prices.
+
+ Args:
+ rows: Raw row dicts from :func:`_call_tool`.
+
+ Returns:
+ DataFrame indexed by ``trade_date`` with float ``open/high/low/close/
+ volume`` columns (volume converted to shares), or ``None`` when no
+ usable rows are present.
+ """
+ # Date key differs across the vendor's quote tools (tradingday/enddate);
+ # accept both so a tool swap never silently empties the frame.
+ def _date(row: Dict[str, Any]) -> Any:
+ return row.get("tradingday") or row.get("enddate")
+
+ records = [
+ {
+ "trade_date": _date(row),
+ "open": row.get("openprice"),
+ "high": row.get("highprice"),
+ "low": row.get("lowprice"),
+ "close": row.get("closeprice"),
+ "volume": row.get("turnovervolume"),
+ }
+ for row in rows
+ if isinstance(row, dict)
+ ]
+ records = [record for record in records if record["trade_date"]]
+ if not records:
+ return None
+
+ df = pd.DataFrame(records)
+ df["trade_date"] = pd.to_datetime(df["trade_date"])
+ for field in _OHLCV_FIELDS:
+ # Cast to float (not just to_numeric) so the float-OHLCV contract
+ # holds even when the vendor sends integers or numeric strings.
+ df[field] = pd.to_numeric(df[field], errors="coerce").astype(float)
+ # 万股 -> shares; suspended days may arrive without a volume reading.
+ df["volume"] = (df["volume"] * _VOLUME_UNIT_MULTIPLIER).fillna(0.0)
+
+ df = df.set_index("trade_date").sort_index()
+ df = df[list(_OHLCV_FIELDS)].dropna(subset=["open", "high", "low", "close"])
+ if df.empty:
+ return None
+ return df
+
+
+@register
+class DataLoader:
+ """Gildata A-share OHLCV loader (token-gated, MCP-over-HTTP)."""
+
+ name = "gildata"
+ markets = {"a_share"}
+ requires_auth = True
+ # turnovervolume is converted from 万股 to shares before serving.
+ volume_units = {"a_share": "shares"}
+
+ def __init__(self) -> None:
+ pass
+
+ def is_available(self) -> bool:
+ """Available when ``GILDATA_TOKEN`` is set to a non-placeholder value."""
+ return _token() not in GILDATA_TOKEN_PLACEHOLDERS
+
+ 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 daily OHLCV bars from Gildata, one symbol at a time.
+
+ Non-A-share symbols are dropped (the fallback chain serves them from
+ another source), and a single failing symbol is logged and skipped so
+ it never aborts the rest of the batch.
+
+ Args:
+ codes: Project symbols (e.g. ``["600519.SH", "000001.SZ"]``).
+ start_date: Inclusive start date, ``YYYY-MM-DD``.
+ end_date: Inclusive end date, ``YYYY-MM-DD``.
+ interval: Bar size; only ``"1D"`` is supported (others skipped).
+ fields: Ignored — Gildata returns a fixed OHLCV schema.
+
+ Returns:
+ Mapping ``{symbol: DataFrame(trade_date, open, high, low, close,
+ volume)}`` for every A-share symbol that returned non-empty data.
+
+ Raises:
+ ValueError: If ``start_date`` > ``end_date`` (via
+ :func:`validate_date_range`).
+ """
+ validate_date_range(start_date, end_date)
+
+ if str(interval).strip().lower() not in {"1d", "d", "day", "daily"}:
+ logger.warning("gildata only supports 1D bars; got interval=%r", interval)
+ return {}
+
+ if not self.is_available():
+ logger.warning("gildata fetch skipped: %s not set", _TOKEN_ENV)
+ return {}
+
+ result: Dict[str, pd.DataFrame] = {}
+ for code in codes:
+ symbol = _gildata_symbol(code)
+ if symbol is None:
+ logger.debug("gildata skipping non-A-share symbol %r", code)
+ continue
+ try:
+ df = cached_loader_fetch(
+ source=self.name,
+ symbol=code,
+ timeframe=interval,
+ start_date=start_date,
+ end_date=end_date,
+ fields=None,
+ fetch=lambda symbol=symbol: self._fetch_one(
+ symbol, start_date, end_date
+ ),
+ )
+ if df is not None and not df.empty:
+ result[code] = df
+ except Exception as exc:
+ logger.warning("gildata failed for %s: %s", code, exc)
+ return result
+
+ def _fetch_one(
+ self,
+ symbol: str,
+ start_date: str,
+ end_date: str,
+ ) -> Optional[pd.DataFrame]:
+ """Fetch and parse one symbol's daily bars; ``None`` on no data.
+
+ Args:
+ symbol: Normalized Gildata symbol (e.g. ``600519.SH``).
+ start_date: Inclusive start date, ``YYYY-MM-DD``.
+ end_date: Inclusive end date, ``YYYY-MM-DD``.
+
+ Returns:
+ An ascending OHLCV DataFrame indexed by ``trade_date``, or ``None``
+ when Gildata reports no bars for the symbol/window.
+
+ Raises:
+ RuntimeError: If the token is missing or the vendor errors.
+ requests.RequestException: Propagated from the HTTP layer.
+ """
+ rows = _call_tool(
+ _DAILY_QUOTE_TOOL,
+ {
+ "stockObject": [symbol],
+ "beginDate": start_date,
+ "endDate": end_date,
+ "restorationStatus": _RESTORATION_QFQ,
+ },
+ )
+ return _parse_daily_rows(rows)
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index 7f32d63d5..272323f1a 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -53,6 +53,7 @@ VALID_SOURCES: set[str] = {
"alphavantage",
"tiingo",
"fmp",
+ "gildata",
"qveris", # QVERIS-INTEGRATION
"india_broker",
"pykrx",
@@ -114,6 +115,7 @@ def _ensure_registered() -> None:
"backtest.loaders.alphavantage_loader",
"backtest.loaders.tiingo_loader",
"backtest.loaders.fmp_loader",
+ "backtest.loaders.gildata_loader",
"backtest.loaders.qveris_loader", # QVERIS-INTEGRATION
"backtest.loaders.india_broker_loader",
"backtest.loaders.pykrx_loader",
@@ -171,6 +173,9 @@ FALLBACK_CHAINS: dict[str, list[str]] = {
"baostock",
"akshare",
"tushare",
+ # Key-gated commercial vendor (恒生聚源): trails the free sources so
+ # paid quota is only spent when the public endpoints cannot serve.
+ "gildata",
"local",
],
"us_equity": [
@@ -251,6 +256,7 @@ PRICE_CALIBER_BY_SOURCE: dict[str, str] = {
"tushare": "split_dividend", # adj_factor applied via cn_adjust (A-share/fund)
"tiingo": "split_dividend", # prefers adjOpen/High/Low/Close, else adjClose/close
"fmp": "split_dividend", # Stable historical-price-eod/full, scaled by adjClose/close
+ "gildata": "split_dividend", # StockDailyQuote restorationStatus=1 (前复权), measured vs live payload
# Split-adjusted only.
"pykrx": "split", # get_market_ohlcv_by_date(adjusted=True), Naver-backed
# Unadjusted.
diff --git a/agent/backtest/metrics.py b/agent/backtest/metrics.py
index f38386b5b..e84ebf11b 100644
--- a/agent/backtest/metrics.py
+++ b/agent/backtest/metrics.py
@@ -33,6 +33,7 @@ _TRADING_DAYS = {
"nobitex": 365, "wallex": 365,
# A-share equity
"baostock": 252, "tencent": 252, "eastmoney": 252, "sina": 252,
+ "gildata": 252,
# US / international equity
"yahoo": 252, "finnhub": 252, "alphavantage": 252, "tiingo": 252,
"fmp": 252, "stooq": 252, "longbridge": 252,
@@ -59,7 +60,7 @@ _BARS_PER_DAY = {
"tiingo": 390, "fmp": 390, "stooq": 390, "longbridge": 390,
"local": 390, "qveris": 390,
# A-share equity (4.0h session)
- "tushare": 240, "akshare": 240, "baostock": 240, "tencent": 240,
+ "tushare": 240, "gildata": 240, "akshare": 240, "baostock": 240, "tencent": 240,
"eastmoney": 240, "sina": 240, "mootdx": 240, "futu": 240,
# crypto (24h)
"okx": 1440, "ccxt": 1440, "binance": 1440,
@@ -74,7 +75,7 @@ _BARS_PER_DAY = {
"5m": {"yfinance": 78, "yahoo": 78, "finnhub": 78, "alphavantage": 78,
"tiingo": 78, "fmp": 78, "stooq": 78, "longbridge": 78,
"local": 78, "qveris": 78,
- "tushare": 48, "akshare": 48, "baostock": 48, "tencent": 48,
+ "tushare": 48, "gildata": 48, "akshare": 48, "baostock": 48, "tencent": 48,
"eastmoney": 48, "sina": 48, "mootdx": 48, "futu": 48,
"okx": 288, "ccxt": 288, "binance": 288,
"nobitex": 288, "wallex": 288,
@@ -85,7 +86,7 @@ _BARS_PER_DAY = {
"15m": {"yfinance": 26, "yahoo": 26, "finnhub": 26, "alphavantage": 26,
"tiingo": 26, "fmp": 26, "stooq": 26, "longbridge": 26,
"local": 26, "qveris": 26,
- "tushare": 16, "akshare": 16, "baostock": 16, "tencent": 16,
+ "tushare": 16, "gildata": 16, "akshare": 16, "baostock": 16, "tencent": 16,
"eastmoney": 16, "sina": 16, "mootdx": 16, "futu": 16,
"okx": 96, "ccxt": 96, "binance": 96,
"nobitex": 96, "wallex": 96,
@@ -96,7 +97,7 @@ _BARS_PER_DAY = {
"30m": {"yfinance": 13, "yahoo": 13, "finnhub": 13, "alphavantage": 13,
"tiingo": 13, "fmp": 13, "stooq": 13, "longbridge": 13,
"local": 13, "qveris": 13,
- "tushare": 8, "akshare": 8, "baostock": 8, "tencent": 8,
+ "tushare": 8, "gildata": 8, "akshare": 8, "baostock": 8, "tencent": 8,
"eastmoney": 8, "sina": 8, "mootdx": 8, "futu": 8,
"okx": 48, "ccxt": 48, "binance": 48,
"nobitex": 48, "wallex": 48,
@@ -107,7 +108,7 @@ _BARS_PER_DAY = {
"1H": {"yfinance": 7, "yahoo": 7, "finnhub": 7, "alphavantage": 7,
"tiingo": 7, "fmp": 7, "stooq": 7, "longbridge": 7,
"local": 7, "qveris": 7,
- "tushare": 4, "akshare": 4, "baostock": 4, "tencent": 4,
+ "tushare": 4, "gildata": 4, "akshare": 4, "baostock": 4, "tencent": 4,
"eastmoney": 4, "sina": 4, "mootdx": 4, "futu": 4,
"okx": 24, "ccxt": 24, "binance": 24,
"nobitex": 24, "wallex": 24,
@@ -118,7 +119,7 @@ _BARS_PER_DAY = {
"4H": {"yfinance": 2, "yahoo": 2, "finnhub": 2, "alphavantage": 2,
"tiingo": 2, "fmp": 2, "stooq": 2, "longbridge": 2,
"local": 2, "qveris": 2,
- "tushare": 1, "akshare": 1, "baostock": 1, "tencent": 1,
+ "tushare": 1, "gildata": 1, "akshare": 1, "baostock": 1, "tencent": 1,
"eastmoney": 1, "sina": 1, "mootdx": 1, "futu": 1,
"okx": 6, "ccxt": 6, "binance": 6,
"nobitex": 6, "wallex": 6,
@@ -129,7 +130,7 @@ _BARS_PER_DAY = {
"1D": {"yfinance": 1, "yahoo": 1, "finnhub": 1, "alphavantage": 1,
"tiingo": 1, "fmp": 1, "stooq": 1, "longbridge": 1,
"local": 1, "qveris": 1,
- "tushare": 1, "akshare": 1, "baostock": 1, "tencent": 1,
+ "tushare": 1, "gildata": 1, "akshare": 1, "baostock": 1, "tencent": 1,
"eastmoney": 1, "sina": 1, "mootdx": 1, "futu": 1,
"okx": 1, "ccxt": 1, "binance": 1,
"nobitex": 1, "wallex": 1,
diff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.py
index 2541b4aed..26b77d35f 100644
--- a/agent/src/config/env_schema.py
+++ b/agent/src/config/env_schema.py
@@ -188,6 +188,11 @@ class DataConfig(_EnvBase):
alphavantage_api_key: str = Field(alias="ALPHAVANTAGE_API_KEY", default="")
tiingo_api_key: str = Field(alias="TIINGO_API_KEY", default="")
fmp_api_key: str = Field(alias="FMP_API_KEY", default="")
+ gildata_token: str = Field(alias="GILDATA_TOKEN", default="")
+ gildata_base_url: str = Field(
+ alias="GILDATA_BASE_URL",
+ default="https://api.gildata.com/mcp-servers/aidata-assistant-srv-rawapi",
+ )
fred_api_key: str = Field(alias="FRED_API_KEY", default="")
vibe_trading_iwencai_key: str = Field(alias="VIBE_TRADING_IWENCAI_KEY", default="")
vibe_trading_sec_ua: str = Field(alias="VIBE_TRADING_SEC_UA", default="")
diff --git a/agent/tests/test_env_schema.py b/agent/tests/test_env_schema.py
index dee8deac3..2b594eac6 100644
--- a/agent/tests/test_env_schema.py
+++ b/agent/tests/test_env_schema.py
@@ -115,6 +115,8 @@ class TestEnvConfigDefaults:
assert c.data.alphavantage_api_key == ""
assert c.data.tiingo_api_key == ""
assert c.data.fmp_api_key == ""
+ assert c.data.gildata_token == ""
+ assert c.data.gildata_base_url.endswith("aidata-assistant-srv-rawapi")
assert c.data.fred_api_key == ""
assert c.data.vibe_trading_iwencai_key == ""
assert c.data.vibe_trading_sec_ua == ""
diff --git a/agent/tests/test_gildata_loader.py b/agent/tests/test_gildata_loader.py
new file mode 100644
index 000000000..4241875e9
--- /dev/null
+++ b/agent/tests/test_gildata_loader.py
@@ -0,0 +1,266 @@
+"""Tests for gildata_loader: auth gating, symbol mapping, parsing, batch resilience.
+
+All HTTP is mocked at :func:`backtest.loaders._http.throttled_post_json` (imported
+into the loader module), so no test touches a live Gildata endpoint.
+"""
+
+import json
+from unittest.mock import patch
+
+import pandas as pd
+import pytest
+
+from backtest.loaders import gildata_loader as gl
+from backtest.loaders.gildata_loader import (
+ DataLoader,
+ _gildata_symbol,
+ _parse_daily_rows,
+)
+
+# Two raw StockDailyQuote rows exactly as the vendor sends them: descending
+# dates, turnovervolume in 万股, and avgprice on a different (unadjusted)
+# basis than the qfq OHLC — the parser must ignore it.
+_MAOTAI_ROWS = [
+ {
+ "tradingday": "2024-01-04",
+ "openprice": 1509.71, "highprice": 1525.45, "lowprice": 1501.33,
+ "closeprice": 1511.55, "avgprice": 1666.34,
+ "turnovervolume": 202.43, "turnovervalue": 337315.56,
+ },
+ {
+ "tradingday": "2024-01-03",
+ "openprice": 1491.24, "highprice": 1501.52, "lowprice": 1485.84,
+ "closeprice": 1491.23, "avgprice": 1642.56,
+ "turnovervolume": 244.12, "turnovervalue": 400982.65,
+ },
+]
+
+
+def _envelope(rows, *, inner_code=0):
+ """Build the full MCP JSON-RPC response around a StockDailyQuote result."""
+ inner = {"code": inner_code, "results": [{"api_name": "股票日行情", "columns": {}, "rows": rows}]}
+ return {"jsonrpc": "2.0", "id": 1, "result": {"content": [{"type": "text", "text": json.dumps(inner)}]}}
+
+
+class TestRegistration:
+ """Loader self-registers with the expected metadata."""
+
+ def test_registered_in_registry(self):
+ from backtest.loaders import registry
+
+ registry._ensure_registered()
+ assert registry.LOADER_REGISTRY.get("gildata") is DataLoader
+
+ def test_metadata(self):
+ assert DataLoader.name == "gildata"
+ assert DataLoader.markets == {"a_share"}
+ assert DataLoader.requires_auth is True
+ assert DataLoader.volume_units == {"a_share": "shares"}
+
+
+class TestIsAvailable:
+ """Availability is gated purely on GILDATA_TOKEN presence."""
+
+ def test_available_with_token(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ assert DataLoader().is_available() is True
+
+ def test_unavailable_without_token(self, monkeypatch):
+ monkeypatch.delenv("GILDATA_TOKEN", raising=False)
+ assert DataLoader().is_available() is False
+
+ def test_unavailable_with_blank_token(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", " ")
+ assert DataLoader().is_available() is False
+
+ def test_unavailable_with_placeholder_token(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "your-gildata-token")
+ assert DataLoader().is_available() is False
+
+
+class TestSymbolMapping:
+ """Project symbols map onto Gildata's 代码.后缀 convention."""
+
+ def test_suffixed_passthrough(self):
+ assert _gildata_symbol("600519.SH") == "600519.SH"
+ assert _gildata_symbol("000001.SZ") == "000001.SZ"
+ assert _gildata_symbol("831010.BJ") == "831010.BJ"
+
+ def test_ss_normalized_to_sh(self):
+ assert _gildata_symbol("600519.SS") == "600519.SH"
+
+ def test_lowercase_uppered(self):
+ assert _gildata_symbol("600519.sh") == "600519.SH"
+
+ def test_bare_code_exchange_inferred(self):
+ assert _gildata_symbol("600519") == "600519.SH"
+ assert _gildata_symbol("000001") == "000001.SZ"
+ assert _gildata_symbol("300750") == "300750.SZ"
+ assert _gildata_symbol("831010") == "831010.BJ"
+
+ def test_non_a_share_returns_none(self):
+ assert _gildata_symbol("00700.HK") is None
+ assert _gildata_symbol("AAPL.US") is None
+ assert _gildata_symbol("BTC-USDT") is None
+ assert _gildata_symbol("") is None
+ assert _gildata_symbol("12345") is None
+
+
+class TestParseDailyRows:
+ """Pure parsing of vendor rows needs no network."""
+
+ def test_sorts_ascending_and_typed(self):
+ df = _parse_daily_rows(_MAOTAI_ROWS)
+ assert list(df.index) == [pd.Timestamp("2024-01-03"), pd.Timestamp("2024-01-04")]
+ assert list(df.columns) == ["open", "high", "low", "close", "volume"]
+ assert df.index.name == "trade_date"
+ for col in df.columns:
+ assert df[col].dtype == float
+
+ def test_volume_converted_from_wan_shares_to_shares(self):
+ df = _parse_daily_rows(_MAOTAI_ROWS)
+ # 244.12 万股 on 2024-01-03 -> 2_441_200 shares.
+ assert df["volume"].iloc[0] == pytest.approx(2_441_200.0)
+
+ def test_avgprice_ignored(self):
+ df = _parse_daily_rows(_MAOTAI_ROWS)
+ # avgprice (1666) is on a different adjustment basis and must never
+ # leak into any served column.
+ assert df["close"].max() < 1600.0
+
+ def test_enddate_key_accepted(self):
+ rows = [
+ {"enddate": "2024-01-03", "openprice": 1.0, "highprice": 2.0,
+ "lowprice": 0.5, "closeprice": 1.5, "turnovervolume": 100.0},
+ ]
+ df = _parse_daily_rows(rows)
+ assert df is not None and len(df) == 1
+
+ def test_integer_fields_cast_to_float(self):
+ rows = [
+ {"tradingday": "2024-01-03", "openprice": 1, "highprice": 2,
+ "lowprice": 0, "closeprice": 1, "turnovervolume": 100},
+ ]
+ df = _parse_daily_rows(rows)
+ for col in df.columns:
+ assert df[col].dtype == float
+
+ def test_missing_volume_becomes_zero(self):
+ rows = [
+ {"tradingday": "2024-01-03", "openprice": 1.0, "highprice": 2.0,
+ "lowprice": 0.5, "closeprice": 1.5},
+ ]
+ df = _parse_daily_rows(rows)
+ assert df["volume"].iloc[0] == 0.0
+
+ def test_empty_rows_returns_none(self):
+ assert _parse_daily_rows([]) is None
+
+ def test_rows_with_incomplete_ohlc_dropped(self):
+ rows = [
+ {"tradingday": "2024-01-03", "openprice": None, "highprice": 2.0,
+ "lowprice": 0.5, "closeprice": 1.5, "turnovervolume": 100.0},
+ ]
+ assert _parse_daily_rows(rows) is None
+
+
+class TestFetch:
+ """End-to-end fetch with the HTTP layer mocked."""
+
+ def test_fetch_one_symbol(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with patch.object(gl, "throttled_post_json", return_value=_envelope(_MAOTAI_ROWS)) as mock_post:
+ out = DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-31")
+ assert set(out) == {"600519.SH"}
+ assert len(out["600519.SH"]) == 2
+ # Token and structured-JSON flag ride the URL query string.
+ url = mock_post.call_args[0][0]
+ assert "token=secret" in url
+ assert "format=json" in url
+ # The JSON-RPC body routes to StockDailyQuote with qfq adjustment.
+ body = mock_post.call_args.kwargs["json_body"]
+ assert body["method"] == "tools/call"
+ params = body["params"]
+ assert params["name"] == "StockDailyQuote"
+ assert params["arguments"] == {
+ "stockObject": ["600519.SH"],
+ "beginDate": "2024-01-01",
+ "endDate": "2024-01-31",
+ "restorationStatus": "1",
+ }
+
+ def test_ss_suffix_normalized_on_wire(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with patch.object(gl, "throttled_post_json", return_value=_envelope(_MAOTAI_ROWS)) as mock_post:
+ DataLoader().fetch(["600519.SS"], "2024-01-01", "2024-01-31")
+ args = mock_post.call_args.kwargs["json_body"]["params"]["arguments"]
+ assert args["stockObject"] == ["600519.SH"]
+
+ def test_non_a_share_symbols_skipped(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with patch.object(gl, "throttled_post_json") as mock_post:
+ out = DataLoader().fetch(["AAPL.US", "00700.HK"], "2024-01-01", "2024-01-31")
+ assert out == {}
+ mock_post.assert_not_called()
+
+ def test_one_failing_symbol_does_not_abort_batch(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+
+ def _side(url, **kwargs):
+ symbol = kwargs["json_body"]["params"]["arguments"]["stockObject"][0]
+ if symbol == "BAD.SZ":
+ raise RuntimeError("boom")
+ return _envelope(_MAOTAI_ROWS)
+
+ with patch.object(gl, "throttled_post_json", side_effect=_side):
+ out = DataLoader().fetch(["BAD.SZ", "600519.SH"], "2024-01-01", "2024-01-31")
+ assert set(out) == {"600519.SH"}
+
+ def test_empty_result_symbol_omitted(self, monkeypatch):
+ # An unresolvable symbol answers rows: [] (never an error) and must
+ # drop out so the fallback chain can serve it from another source.
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with patch.object(gl, "throttled_post_json", return_value=_envelope([])):
+ out = DataLoader().fetch(["ZZZZ99.SZ"], "2024-01-01", "2024-01-31")
+ assert out == {}
+
+ def test_vendor_error_code_raises_for_that_symbol(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with patch.object(gl, "throttled_post_json", return_value=_envelope([], inner_code=1001)):
+ out = DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-31")
+ # The symbol fails (logged) but fetch itself must not raise.
+ assert out == {}
+
+ def test_auth_error_shape_raises_for_that_symbol(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "bad-token")
+ body = {"success": False, "code": 1001, "message": "认证凭证缺失或有误", "data": None}
+ with patch.object(gl, "throttled_post_json", return_value=body):
+ out = DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-31")
+ assert out == {}
+
+ def test_non_daily_interval_returns_empty(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with patch.object(gl, "throttled_post_json") as mock_post:
+ out = DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-31", interval="5m")
+ assert out == {}
+ mock_post.assert_not_called()
+
+ def test_invalid_date_range_raises(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ with pytest.raises(ValueError):
+ DataLoader().fetch(["600519.SH"], "2024-02-01", "2024-01-01")
+
+ def test_missing_token_at_fetch_time_skips_symbol(self, monkeypatch):
+ monkeypatch.delenv("GILDATA_TOKEN", raising=False)
+ with patch.object(gl, "throttled_post_json") as mock_post:
+ out = DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-31")
+ assert out == {}
+ mock_post.assert_not_called()
+
+ def test_base_url_override_applied(self, monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "secret")
+ monkeypatch.setenv("GILDATA_BASE_URL", "https://proxy.example/mcp")
+ with patch.object(gl, "throttled_post_json", return_value=_envelope(_MAOTAI_ROWS)) as mock_post:
+ DataLoader().fetch(["600519.SH"], "2024-01-01", "2024-01-31")
+ url = mock_post.call_args[0][0]
+ assert url.startswith("https://proxy.example/mcp?")
diff --git a/agent/tests/test_price_caliber.py b/agent/tests/test_price_caliber.py
index 090ab5d18..6c4d75dfd 100644
--- a/agent/tests/test_price_caliber.py
+++ b/agent/tests/test_price_caliber.py
@@ -45,6 +45,7 @@ def _df() -> pd.DataFrame:
("pykrx", "split"),
("tiingo", "split_dividend"),
("fmp", "split_dividend"),
+ ("gildata", "split_dividend"),
("sina", "raw"),
("alphavantage", "raw"),
("longbridge", "raw"),
@@ -277,3 +278,26 @@ def test_tiingo_loader_serves_the_caliber_the_table_claims() -> None:
assert df["close"].iloc[0] == pytest.approx(50.0)
assert df["open"].iloc[0] == pytest.approx(50.0)
assert df["volume"].iloc[0] == pytest.approx(1000.0)
+
+
+def test_gildata_loader_serves_the_caliber_the_table_claims() -> None:
+ from backtest.loaders.gildata_loader import _RESTORATION_QFQ, _parse_daily_rows
+
+ assert price_caliber("gildata", "a_share") == "split_dividend"
+ # The caliber is pinned by the request parameter, not by any local
+ # scaling: restorationStatus=1 asks the vendor for 前复权 bars, and the
+ # parser must pass that OHLC through untouched (volume keeps its own
+ # unit conversion).
+ assert _RESTORATION_QFQ == "1"
+ df = _parse_daily_rows(
+ [
+ {
+ "tradingday": "2024-01-03",
+ "openprice": 1.0, "highprice": 2.0, "lowprice": 0.5,
+ "closeprice": 1.5, "turnovervolume": 100.0,
+ }
+ ]
+ )
+ assert df is not None
+ assert df["close"].iloc[0] == pytest.approx(1.5)
+ assert df["open"].iloc[0] == pytest.approx(1.0)
diff --git a/agent/tests/test_registry.py b/agent/tests/test_registry.py
index e5579180d..1b5e8efb6 100644
--- a/agent/tests/test_registry.py
+++ b/agent/tests/test_registry.py
@@ -242,6 +242,7 @@ class TestFallbackChains:
"baostock",
"akshare",
"tushare",
+ "gildata",
"local",
]
assert FALLBACK_CHAINS["us_equity"] == [