Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): expose loader-backed market data tool (#199)

Chengcheng Ding7436986246a5
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index ff62c6085..b1663a45d 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -32,9 +32,7 @@ from __future__ import annotations
import json
import logging
-import math
import os
-import re
import sys
from pathlib import Path
from typing import Any
@@ -45,6 +43,13 @@ if str(AGENT_DIR) not in sys.path:
sys.path.insert(0, str(AGENT_DIR))
from fastmcp import Context, FastMCP
+from src.market_data import (
+ DEFAULT_MAX_ROWS,
+ cap_rows,
+ detect_source,
+ fetch_market_data_json,
+ get_loader,
+)
mcp = FastMCP("Vibe-Trading")
@@ -994,29 +999,13 @@ async def run_swarm(
# Market data tool
# ---------------------------------------------------------------------------
-DEFAULT_MAX_ROWS = 250
-
-_SOURCE_PATTERNS = [
- (re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tushare"),
- (re.compile(r"^[A-Z]+\.US$", re.I), "yfinance"),
- (re.compile(r"^\d{3,5}\.HK$", re.I), "yfinance"),
- (re.compile(r"^[A-Z]+-USDT$", re.I), "okx"),
- (re.compile(r"^[A-Z]+/USDT$", re.I), "ccxt"),
-]
-
-
def _detect_source(code: str) -> str:
- for pattern, source in _SOURCE_PATTERNS:
- if pattern.match(code):
- return source
- return "tushare"
+ return detect_source(code)
def _get_loader(source: str):
"""Get loader class via registry with fallback support."""
- from backtest.loaders.registry import get_loader_cls_with_fallback
-
- return get_loader_cls_with_fallback(source)
+ return get_loader(source)
def _cap_rows(records: list, max_rows: int) -> list | dict[str, object]:
@@ -1030,23 +1019,7 @@ def _cap_rows(records: list, max_rows: int) -> list | dict[str, object]:
cap are returned unchanged (plain list) — small queries are
byte-identical.
"""
- n = len(records)
- if max_rows < 0:
- max_rows = DEFAULT_MAX_ROWS # negative invalid -> enforce cap, never unbounded
- if max_rows == 0 or n <= max_rows:
- return records
- step = math.ceil(n / max_rows)
- sampled = records[::step]
- if sampled[-1] is not records[-1]:
- sampled = sampled + [records[-1]]
- return {
- "rows": n,
- "returned": len(sampled),
- "truncated": True,
- "policy": f"every-{step}th-row (even stride; last bar pinned)",
- "hint": "narrow the date range, coarsen interval, or set max_rows=0 for all rows",
- "data": sampled,
- }
+ return cap_rows(records, max_rows)
@mcp.tool
@@ -1080,47 +1053,15 @@ def get_market_data(
plus truncation metadata. Set max_rows=0 for all rows
(unbounded, legacy behavior).
"""
- results = {}
-
- if source == "auto":
- groups: dict[str, list[str]] = {}
- for code in codes:
- src = _detect_source(code)
- groups.setdefault(src, []).append(code)
- else:
- groups = {source: list(codes)}
-
- for src, src_codes in groups.items():
- loader_cls = _get_loader(src)
- loader = loader_cls()
- try:
- data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)
- except Exception:
- # A loader blow-up for one group must not lose already-resolved
- # symbols or surface as an opaque MCP error; those codes fall
- # through to _unresolved below (P05).
- logger.exception("market-data loader %r failed for %s; codes fall through to _unresolved", src, src_codes)
- data_map = {}
- for symbol, df in data_map.items():
- records = df.reset_index().to_dict(orient="records")
- for r in records:
- for k, v in r.items():
- if hasattr(v, "isoformat"):
- r[k] = v.isoformat()
- elif hasattr(v, "item"):
- r[k] = v.item()
- results[symbol] = _cap_rows(records, max_rows)
-
- # P05: a typo / wrong-suffix / delisted / no-data symbol used to vanish
- # silently (the dict only held winners), indistinguishable from "no data".
- # Surface every requested code that produced nothing under a reserved key.
- # Additive: omitted entirely when all codes resolved, so the happy-path
- # payload is byte-identical to before.
- unresolved = [c for c in codes if c not in results]
- if unresolved:
- results["_unresolved"] = unresolved
-
- return json.dumps(results, ensure_ascii=False, indent=2)
+ return fetch_market_data_json(
+ codes=codes,
+ start_date=start_date,
+ end_date=end_date,
+ source=source,
+ interval=interval,
+ max_rows=max_rows,
+ loader_resolver=_get_loader,
+ )
# ---------------------------------------------------------------------------
diff --git a/agent/src/market_data.py b/agent/src/market_data.py
new file mode 100644
index 000000000..ecfd42e02
--- /dev/null
+++ b/agent/src/market_data.py
@@ -0,0 +1,120 @@
+"""Shared market data helpers for MCP and local agent tools."""
+
+from __future__ import annotations
+
+import json
+import logging
+import math
+import re
+from collections.abc import Callable
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_MAX_ROWS = 250
+
+_SOURCE_PATTERNS = [
+ (re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tushare"),
+ (re.compile(r"^[A-Z]+\.US$", re.I), "yfinance"),
+ (re.compile(r"^\d{3,5}\.HK$", re.I), "yfinance"),
+ (re.compile(r"^[A-Z]+-USDT$", re.I), "okx"),
+ (re.compile(r"^[A-Z]+/USDT$", re.I), "ccxt"),
+]
+
+
+def detect_source(code: str) -> str:
+ """Infer the best loader source for a normalized symbol."""
+ for pattern, source in _SOURCE_PATTERNS:
+ if pattern.match(code):
+ return source
+ return "tushare"
+
+
+def get_loader(source: str):
+ """Get loader class via registry with fallback support."""
+ from backtest.loaders.registry import get_loader_cls_with_fallback
+
+ return get_loader_cls_with_fallback(source)
+
+
+def cap_rows(records: list, max_rows: int) -> list | dict[str, object]:
+ """Bound a per-symbol row list to keep tool payloads within budget."""
+ n = len(records)
+ if max_rows < 0:
+ max_rows = DEFAULT_MAX_ROWS
+ if max_rows == 0 or n <= max_rows:
+ return records
+ step = math.ceil(n / max_rows)
+ sampled = records[::step]
+ if sampled[-1] is not records[-1]:
+ sampled = sampled + [records[-1]]
+ return {
+ "rows": n,
+ "returned": len(sampled),
+ "truncated": True,
+ "policy": f"every-{step}th-row (even stride; last bar pinned)",
+ "hint": "narrow the date range, coarsen interval, or set max_rows=0 for all rows",
+ "data": sampled,
+ }
+
+
+def _json_safe(value: Any) -> Any:
+ if hasattr(value, "isoformat"):
+ return value.isoformat()
+ if hasattr(value, "item"):
+ value = value.item()
+ if isinstance(value, float) and not math.isfinite(value):
+ return None
+ return value
+
+
+def fetch_market_data(
+ *,
+ codes: list[str],
+ start_date: str,
+ end_date: str,
+ source: str = "auto",
+ interval: str = "1D",
+ max_rows: int = DEFAULT_MAX_ROWS,
+ loader_resolver: Callable[[str], type] = get_loader,
+) -> dict[str, Any]:
+ """Fetch normalized OHLCV data through the repository loader layer."""
+ results: dict[str, Any] = {}
+
+ if source == "auto":
+ groups: dict[str, list[str]] = {}
+ for code in codes:
+ src = detect_source(code)
+ groups.setdefault(src, []).append(code)
+ else:
+ groups = {source: list(codes)}
+
+ for src, src_codes in groups.items():
+ loader_cls = loader_resolver(src)
+ loader = loader_cls()
+ try:
+ data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)
+ except Exception:
+ logger.exception(
+ "market-data loader %r failed for %s; codes fall through to _unresolved",
+ src,
+ src_codes,
+ )
+ data_map = {}
+ for symbol, df in data_map.items():
+ records = df.reset_index().to_dict(orient="records")
+ for row in records:
+ for key, value in row.items():
+ row[key] = _json_safe(value)
+ results[symbol] = cap_rows(records, max_rows)
+
+ unresolved = [code for code in codes if code not in results]
+ if unresolved:
+ results["_unresolved"] = unresolved
+
+ return results
+
+
+def fetch_market_data_json(**kwargs: Any) -> str:
+ """Fetch market data and return strict JSON."""
+ return json.dumps(fetch_market_data(**kwargs), ensure_ascii=False, indent=2, allow_nan=False)
diff --git a/agent/src/skills/yfinance/SKILL.md b/agent/src/skills/yfinance/SKILL.md
index feacc0602..5e5e1827a 100644
--- a/agent/src/skills/yfinance/SKILL.md
+++ b/agent/src/skills/yfinance/SKILL.md
@@ -11,22 +11,32 @@ yfinance is an open-source Python wrapper for Yahoo Finance, providing global ma
The project has a built-in yfinance DataLoader (`backtest/loaders/yfinance_loader.py`). When backtesting, set `source: "yfinance"` or `source: "auto"` to invoke it automatically.
+For OHLCV bars in agent/swarm work, prefer the `get_market_data` tool when it is available. It routes through the project loader layer, normalizes symbols, removes malformed OHLC rows, and returns strict JSON. Use direct `yfinance` calls mainly for data outside OHLCV coverage such as company info, financial statements, options, holders, and insider transactions.
+
## Quick Start
-```bash
-pip install yfinance pandas
+Preferred OHLCV tool call:
+
+```json
+{
+ "codes": ["AAPL.US", "700.HK"],
+ "start_date": "2025-01-01",
+ "end_date": "2026-01-01",
+ "source": "yfinance",
+ "interval": "1D"
+}
```
+If you must write a Python script for OHLCV, use the DataLoader instead of raw `yf.download`:
+
```python
-import yfinance as yf
+from backtest.loaders.registry import get_loader_cls_with_fallback
-# Apple daily bars for the past year
-df = yf.download("AAPL", start="2025-01-01", end="2026-01-01", progress=False)
-print(df.head())
+loader = get_loader_cls_with_fallback("yfinance")()
+data = loader.fetch(["AAPL.US", "700.HK"], "2025-01-01", "2026-01-01", interval="1D")
-# Tencent (HK-listed)
-df = yf.download("0700.HK", start="2025-01-01", end="2026-01-01", progress=False)
-print(df.head())
+for symbol, df in data.items():
+ print(symbol, df.tail())
```
## Ticker Format Conversion
@@ -49,19 +59,31 @@ The project uses a unified ticker format. The DataLoader automatically converts
### 1. Historical OHLCV
+Prefer `get_market_data` for OHLCV whenever the tool is available:
+
+```json
+{
+ "codes": ["AAPL.US", "MSFT.US", "GOOGL.US"],
+ "start_date": "2025-01-01",
+ "end_date": "2026-01-01",
+ "source": "yfinance",
+ "interval": "1D",
+ "max_rows": 250
+}
+```
+
+For script-based OHLCV analysis, use the loader:
+
```python
-import yfinance as yf
-import pandas as pd
+from backtest.loaders.registry import get_loader_cls_with_fallback
-# Single stock
-df = yf.download("AAPL", start="2025-01-01", end="2026-01-01", progress=False)
+loader = get_loader_cls_with_fallback("yfinance")()
-# Batch download
-df = yf.download(["AAPL", "MSFT", "GOOGL"], start="2025-01-01", end="2026-01-01", progress=False)
+# Single stock
+single = loader.fetch(["AAPL.US"], "2025-01-01", "2026-01-01", interval="1D")
# Specific interval
-df = yf.download("AAPL", start="2026-03-01", end="2026-03-30",
- interval="1h", progress=False) # 1m/5m/15m/30m/1h/1d/1wk/1mo
+hourly = loader.fetch(["AAPL.US"], "2026-03-01", "2026-03-30", interval="1H")
```
**Supported intervals:**
diff --git a/agent/src/swarm/presets/equity_research_team.yaml b/agent/src/swarm/presets/equity_research_team.yaml
index 5a51a53e2..77892248b 100644
--- a/agent/src/swarm/presets/equity_research_team.yaml
+++ b/agent/src/swarm/presets/equity_research_team.yaml
@@ -22,7 +22,7 @@ agents:
5. **Conclusion for {market}** — Summarize the bullish / bearish / neutral rationale
Use load_skill to access data query methods; prioritize using tools to obtain the latest data to support the analysis.
- tools: [bash, read_file, write_file, load_skill, read_url]
+ tools: [bash, read_file, write_file, load_skill, get_market_data, read_url]
skills: [tushare, okx-market, yfinance, web-reader, global-macro]
max_iterations: 50
timeout_seconds: 1800
@@ -47,7 +47,7 @@ agents:
5. **Recommended Sectors and Rationale** — Explicitly recommend 2–3 sectors with suggested allocation weights
Use the factor_analysis tool for factor-based analysis to support judgments.
- tools: [bash, read_file, write_file, load_skill, factor_analysis]
+ tools: [bash, read_file, write_file, load_skill, get_market_data, factor_analysis]
skills: [tushare, yfinance, fundamental-filter, multi-factor, us-etf-flow, sector-rotation]
max_iterations: 50
timeout_seconds: 1800
@@ -73,7 +73,7 @@ agents:
Always use load_skill("strategy-generate") for strategy writing standards.
Use the backtest tool to validate the historical performance of stock selection logic.
- tools: [bash, read_file, write_file, load_skill, backtest, factor_analysis]
+ tools: [bash, read_file, write_file, load_skill, get_market_data, backtest, factor_analysis]
skills: [tushare, yfinance, strategy-generate, technical-basic, multi-factor, earnings-revision]
max_iterations: 50
timeout_seconds: 1800
diff --git a/agent/src/swarm/presets/investment_committee.yaml b/agent/src/swarm/presets/investment_committee.yaml
index 96e82bca4..b4ffa4fd3 100644
--- a/agent/src/swarm/presets/investment_committee.yaml
+++ b/agent/src/swarm/presets/investment_committee.yaml
@@ -44,7 +44,7 @@ agents:
7. **Main risk to the bull case** — Honestly list 2–3 scenarios that would invalidate the bull thesis
Use factor_analysis for quant support; use load_skill for frameworks.
- tools: [bash, read_file, write_file, load_skill, factor_analysis]
+ tools: [bash, read_file, write_file, load_skill, get_market_data, factor_analysis]
skills: [technical-basic, fundamental-filter, yfinance, earnings-revision, sentiment-analysis]
max_iterations: 50
timeout_seconds: 1800
@@ -97,7 +97,7 @@ agents:
7. **What would disprove the bear case** — Signals that would invalidate the bear thesis (i.e., bull-side rebuttal points)
Use factor_analysis for risk-factor views; use load_skill for risk frameworks.
- tools: [bash, read_file, write_file, load_skill, factor_analysis]
+ tools: [bash, read_file, write_file, load_skill, get_market_data, factor_analysis]
skills: [technical-basic, fundamental-filter, yfinance, risk-analysis, volatility]
max_iterations: 50
timeout_seconds: 1800
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 880d85eb3..f6a4341a2 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -202,6 +202,17 @@ def build_worker_prompt(
# instruction to prefer these prices over training data.
prompt_parts.append(grounding_block)
+ if "get_market_data" in (agent_spec.tools or []):
+ prompt_parts.append(
+ "## Market Data Tool Policy\n\n"
+ "For OHLCV price bars, recent closes, volume, technical indicators, "
+ "or return calculations, call `get_market_data` before writing raw "
+ "provider scripts. It uses the repository loader layer, normalizes "
+ "symbols, drops malformed OHLC rows, and returns strict JSON. Use "
+ "raw yfinance scripts only for fields outside OHLCV coverage, such "
+ "as fundamentals, holders, options, or corporate metadata."
+ )
+
# Universal anti-fabrication rule. The grounding_block carries a similar
# instruction but only renders when user_vars supplies explicit symbols.
# Free-form prompts ("look at A-share short-term sentiment") otherwise
diff --git a/agent/src/tools/market_data_tool.py b/agent/src/tools/market_data_tool.py
new file mode 100644
index 000000000..27a5fe0dc
--- /dev/null
+++ b/agent/src/tools/market_data_tool.py
@@ -0,0 +1,63 @@
+"""Local market data tool backed by the shared loader layer."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from src.agent.tools import BaseTool
+from src.market_data import DEFAULT_MAX_ROWS, fetch_market_data_json
+
+
+class MarketDataTool(BaseTool):
+ """Fetch normalized OHLCV data through repository loaders."""
+
+ name = "get_market_data"
+ description = (
+ "Fetch normalized OHLCV market data through the repository loader layer. "
+ "Use this for stock, ETF, index, or crypto price bars before writing raw "
+ "yfinance/OKX/Tushare scripts."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "codes": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": 'Symbols such as ["AAPL.US"], ["700.HK"], ["BTC-USDT"].',
+ },
+ "start_date": {
+ "type": "string",
+ "description": "Start date in YYYY-MM-DD format.",
+ },
+ "end_date": {
+ "type": "string",
+ "description": "End date in YYYY-MM-DD format.",
+ },
+ "source": {
+ "type": "string",
+ "description": "Data source: auto, yfinance, okx, tushare, akshare, or ccxt.",
+ "default": "auto",
+ },
+ "interval": {
+ "type": "string",
+ "description": "Bar size, e.g. 1D, 1H, 4H, 30m.",
+ "default": "1D",
+ },
+ "max_rows": {
+ "type": "integer",
+ "description": "Per-symbol row cap. Use 0 only when the full series is required.",
+ "default": DEFAULT_MAX_ROWS,
+ },
+ },
+ "required": ["codes", "start_date", "end_date"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ return fetch_market_data_json(
+ codes=kwargs["codes"],
+ start_date=kwargs["start_date"],
+ end_date=kwargs["end_date"],
+ source=kwargs.get("source", "auto"),
+ interval=kwargs.get("interval", "1D"),
+ max_rows=kwargs.get("max_rows", DEFAULT_MAX_ROWS),
+ )
diff --git a/agent/tests/test_market_data_tool.py b/agent/tests/test_market_data_tool.py
new file mode 100644
index 000000000..448c2eca8
--- /dev/null
+++ b/agent/tests/test_market_data_tool.py
@@ -0,0 +1,62 @@
+from __future__ import annotations
+
+import json
+
+import pandas as pd
+
+from src.market_data import fetch_market_data_json
+from src.swarm.models import SwarmAgentSpec
+from src.swarm.worker import build_worker_prompt
+from src.tools import build_swarm_registry
+
+
+def test_market_data_json_is_strict_when_loader_returns_nan():
+ idx = pd.date_range("2026-01-01", periods=1, freq="D")
+ df = pd.DataFrame(
+ {
+ "open": [1.0],
+ "high": [float("nan")],
+ "low": [0.9],
+ "close": [1.1],
+ "volume": [100],
+ },
+ index=idx,
+ )
+ df.index.name = "trade_date"
+
+ class _Loader:
+ def fetch(self, codes, start, end, interval="1D"):
+ return {"X.US": df}
+
+ text = fetch_market_data_json(
+ codes=["X.US"],
+ start_date="2026-01-01",
+ end_date="2026-01-02",
+ source="yfinance",
+ loader_resolver=lambda source: _Loader,
+ )
+
+ assert "NaN" not in text
+ payload = json.loads(text)
+ assert payload["X.US"][0]["high"] is None
+
+
+def test_swarm_registry_can_expose_local_get_market_data_tool():
+ registry = build_swarm_registry(["get_market_data"])
+
+ assert "get_market_data" in registry.tool_names
+
+
+def test_worker_prompt_prioritizes_get_market_data_for_ohlcv():
+ spec = SwarmAgentSpec(
+ id="analyst",
+ role="Analyst",
+ system_prompt="Analyze prices.",
+ tools=["load_skill", "get_market_data", "write_file"],
+ skills=["yfinance"],
+ )
+
+ prompt = build_worker_prompt(spec, {}, " - yfinance: market data")
+
+ assert "Market Data Tool Policy" in prompt
+ assert "call `get_market_data` before writing raw provider scripts" in prompt