Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(tools): add tushare fallbacks for flow tools

asahikiko5fe512dcdfb3
diff --git a/agent/src/tools/dragon_tiger_tool.py b/agent/src/tools/dragon_tiger_tool.py
index 158d2d9e4..b84e625c5 100644
--- a/agent/src/tools/dragon_tiger_tool.py
+++ b/agent/src/tools/dragon_tiger_tool.py
@@ -20,6 +20,7 @@ from typing import Any
from backtest.loaders import eastmoney_client
from src.agent.tools import BaseTool
+from src.tools import tushare_fallbacks
logger = logging.getLogger(__name__)
@@ -208,7 +209,23 @@ class DragonTigerTool(BaseTool):
data = self._collect(trade_date, code)
except Exception as exc: # noqa: BLE001 - surface any fetch failure as an envelope
logger.warning("dragon-tiger fetch failed for %s/%s: %s", trade_date, code, exc)
- return self._error(f"eastmoney dragon-tiger fetch failed: {exc}")
+ try:
+ data = tushare_fallbacks.fetch_dragon_tiger(trade_date, code)
+ except Exception as fallback_exc: # noqa: BLE001 - return both provider failures
+ return self._error(
+ "eastmoney dragon-tiger fetch failed: "
+ f"{exc}; tushare fallback failed: {fallback_exc}"
+ )
+ return json.dumps(
+ {
+ "ok": True,
+ "market": "a_share",
+ "source": "tushare",
+ "warnings": [f"eastmoney failed ({exc}); used tushare fallback"],
+ "data": data,
+ },
+ ensure_ascii=False,
+ )
return json.dumps(
{"ok": True, "market": "a_share", "source": "eastmoney", "data": data},
diff --git a/agent/src/tools/fund_flow_tool.py b/agent/src/tools/fund_flow_tool.py
index 33ee19b0b..fb736f1eb 100644
--- a/agent/src/tools/fund_flow_tool.py
+++ b/agent/src/tools/fund_flow_tool.py
@@ -21,6 +21,7 @@ from typing import Any
from backtest.loaders.eastmoney_client import get_json, resolve_secid
from src.agent.tools import BaseTool
+from src.tools import tushare_fallbacks
logger = logging.getLogger(__name__)
@@ -98,6 +99,17 @@ def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]
"""
secid = resolve_secid(symbol)
if secid is None:
+ if period == "daily":
+ try:
+ fallback = tushare_fallbacks.fetch_fund_flow(symbol, days=days)
+ fallback["warning"] = "eastmoney symbol resolution failed; used tushare fallback"
+ return fallback
+ except Exception as exc: # noqa: BLE001 - fallback details belong in the symbol result
+ return {
+ "symbol": symbol,
+ "error": "unresolvable symbol",
+ "fallback_error": str(exc),
+ }
return {"symbol": symbol, "error": "unresolvable symbol"}
is_daily = period == "daily"
@@ -113,6 +125,17 @@ def _fetch_symbol_flow(symbol: str, *, period: str, days: int) -> dict[str, Any]
payload = get_json(url, params=params)
except Exception as exc: # noqa: BLE001 - one bad symbol must not kill the batch
logger.warning("fund flow fetch failed for %s: %s", symbol, exc)
+ if period == "daily":
+ try:
+ fallback = tushare_fallbacks.fetch_fund_flow(symbol, days=days)
+ fallback["warning"] = f"eastmoney failed ({exc}); used tushare fallback"
+ return fallback
+ except Exception as fallback_exc: # noqa: BLE001 - keep per-symbol isolation
+ return {
+ "symbol": symbol,
+ "error": str(exc),
+ "fallback_error": str(fallback_exc),
+ }
return {"symbol": symbol, "error": str(exc)}
data = payload.get("data") if isinstance(payload, dict) else None
@@ -220,6 +243,7 @@ class FundFlowTool(BaseTool):
"ok": True,
"market": "stock",
"source": "eastmoney",
+ "fallback_sources": ["tushare"],
"period": period,
"buckets": list(_BUCKETS),
"data": results,
diff --git a/agent/src/tools/margin_trading_tool.py b/agent/src/tools/margin_trading_tool.py
index 1c9ca798d..02c2ad534 100644
--- a/agent/src/tools/margin_trading_tool.py
+++ b/agent/src/tools/margin_trading_tool.py
@@ -20,6 +20,7 @@ from typing import Any
from backtest.loaders import eastmoney_client
from src.agent.tools import BaseTool
+from src.tools import tushare_fallbacks
logger = logging.getLogger(__name__)
@@ -196,12 +197,44 @@ class MarginTradingTool(BaseTool):
)
except Exception as exc: # noqa: BLE001 - surface any provider failure as envelope
logger.warning("eastmoney margin fetch failed for %s: %s", code, exc)
- return _err(f"Eastmoney margin request failed: {exc}")
+ try:
+ fallback_data = tushare_fallbacks.fetch_margin_trading(code, days=days)
+ except Exception as fallback_exc: # noqa: BLE001 - return both provider failures
+ return _err(
+ f"Eastmoney margin request failed: {exc}; "
+ f"tushare fallback failed: {fallback_exc}"
+ )
+ return json.dumps(
+ {
+ "ok": True,
+ "market": "a_share",
+ "source": "tushare",
+ "warnings": [f"eastmoney failed ({exc}); used tushare fallback"],
+ "data": fallback_data,
+ },
+ ensure_ascii=False,
+ )
result = payload.get("result") if isinstance(payload, dict) else None
data = result.get("data") if isinstance(result, dict) else None
if not isinstance(data, list) or not data:
- return _err(f"No margin-trading data returned for {code}.")
+ try:
+ fallback_data = tushare_fallbacks.fetch_margin_trading(code, days=days)
+ except Exception as fallback_exc: # noqa: BLE001 - preserve the original empty-data error
+ return _err(
+ f"No margin-trading data returned for {code}. "
+ f"Tushare fallback failed: {fallback_exc}"
+ )
+ return json.dumps(
+ {
+ "ok": True,
+ "market": "a_share",
+ "source": "tushare",
+ "warnings": ["eastmoney returned no rows; used tushare fallback"],
+ "data": fallback_data,
+ },
+ ensure_ascii=False,
+ )
rows = [_normalize_row(item) for item in data if isinstance(item, dict)]
rows = rows[:days]
diff --git a/agent/src/tools/northbound_tool.py b/agent/src/tools/northbound_tool.py
index f1f6dba87..50ddf681c 100644
--- a/agent/src/tools/northbound_tool.py
+++ b/agent/src/tools/northbound_tool.py
@@ -20,6 +20,7 @@ from typing import Any
from backtest.loaders.eastmoney_client import get_json
from src.agent.tools import BaseTool
+from src.tools import tushare_fallbacks
logger = logging.getLogger(__name__)
@@ -230,7 +231,31 @@ class NorthboundFlowTool(BaseTool):
)
except Exception as exc: # noqa: BLE001 - surface as error envelope
logger.warning("northbound flow fetch failed: %s", exc)
- return json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)
+ try:
+ fallback_data = tushare_fallbacks.fetch_northbound_flow(
+ lookback_days=lookback_days
+ )
+ except Exception as fallback_exc: # noqa: BLE001 - return both provider failures
+ return json.dumps(
+ {
+ "ok": False,
+ "error": f"{exc}; tushare fallback failed: {fallback_exc}",
+ },
+ ensure_ascii=False,
+ )
+ return json.dumps(
+ {
+ "ok": True,
+ "market": "China A",
+ "source": "tushare",
+ "warnings": [
+ "eastmoney failed "
+ f"({exc}); used tushare fallback with latest daily data"
+ ],
+ "data": fallback_data,
+ },
+ ensure_ascii=False,
+ )
realtime = _parse_realtime(realtime_payload)
history = _parse_history(history_payload, lookback_days)
diff --git a/agent/src/tools/tushare_fallbacks.py b/agent/src/tools/tushare_fallbacks.py
new file mode 100644
index 000000000..48c09960a
--- /dev/null
+++ b/agent/src/tools/tushare_fallbacks.py
@@ -0,0 +1,231 @@
+"""Optional Tushare fallback adapters for China-market flow tools.
+
+The public Eastmoney endpoints are free and remain the primary source for these
+tools. When they are unavailable, a configured Tushare token can recover the
+same research workflow through a separate provider with a compatible envelope.
+"""
+
+from __future__ import annotations
+
+from datetime import date, timedelta
+from typing import Any
+
+from src.config.accessor import get_env_config
+
+_TUSHARE_TOKEN_PLACEHOLDERS = {"", "your-tushare-token"}
+
+
+class TushareFallbackUnavailable(RuntimeError):
+ """Raised when the optional Tushare fallback cannot be used."""
+
+
+def _pro_api() -> Any:
+ token = get_env_config().data.tushare_token.strip()
+ if token in _TUSHARE_TOKEN_PLACEHOLDERS:
+ raise TushareFallbackUnavailable("TUSHARE_TOKEN is not configured")
+ try:
+ import tushare as ts
+ except Exception as exc: # noqa: BLE001 - import errors vary by install
+ raise TushareFallbackUnavailable(f"tushare import failed: {exc}") from exc
+ return ts.pro_api(token)
+
+
+def _records(frame: Any) -> list[dict[str, Any]]:
+ if frame is None:
+ return []
+ if bool(getattr(frame, "empty", False)):
+ return []
+ if hasattr(frame, "to_dict"):
+ rows = frame.to_dict("records")
+ return [row for row in rows if isinstance(row, dict)]
+ if isinstance(frame, list):
+ return [row for row in frame if isinstance(row, dict)]
+ return []
+
+
+def _compact_date(value: str) -> str:
+ digits = str(value).strip().replace("-", "")
+ if len(digits) != 8 or not digits.isdigit():
+ raise TushareFallbackUnavailable(f"invalid date for tushare fallback: {value!r}")
+ return digits
+
+
+def _dashed_date(value: Any) -> str | None:
+ if value is None:
+ return None
+ digits = str(value).strip().replace("-", "")
+ if len(digits) == 8 and digits.isdigit():
+ return f"{digits[:4]}-{digits[4:6]}-{digits[6:]}"
+ return str(value)[:10] if value else None
+
+
+def _date_window(days: int) -> tuple[str, str]:
+ end = date.today()
+ # Market holidays/weekends mean calendar days need slack to recover the
+ # requested number of trading rows.
+ start = end - timedelta(days=max(days * 3, 10))
+ return start.strftime("%Y%m%d"), end.strftime("%Y%m%d")
+
+
+def _to_float(value: Any) -> float | None:
+ if value in (None, "", "-"):
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _net_amount(row: dict[str, Any], buy_key: str, sell_key: str) -> float | None:
+ buy = _to_float(row.get(buy_key))
+ sell = _to_float(row.get(sell_key))
+ if buy is None and sell is None:
+ return None
+ # Tushare moneyflow amount fields are in 10k CNY; the Eastmoney tool emits
+ # CNY, so convert to keep the existing bucket units.
+ return ((buy or 0.0) - (sell or 0.0)) * 10_000
+
+
+def _ts_code(code: str) -> str:
+ token = code.strip().upper()
+ if "." in token:
+ bare, suffix = token.split(".", 1)
+ if suffix in {"SH", "SZ", "BJ"} and len(bare) == 6 and bare.isdigit():
+ return f"{bare}.{suffix}"
+ raise TushareFallbackUnavailable(f"unsupported Tushare symbol: {code}")
+ for prefix in ("SH", "SZ", "BJ"):
+ if token.startswith(prefix):
+ token = token[len(prefix) :]
+ break
+ if len(token) != 6 or not token.isdigit():
+ raise TushareFallbackUnavailable(f"unsupported Tushare symbol: {code}")
+ if token.startswith(("5", "6", "9")):
+ suffix = "SH"
+ elif token.startswith(("0", "2", "3")):
+ suffix = "SZ"
+ elif token.startswith(("4", "8")):
+ suffix = "BJ"
+ else:
+ raise TushareFallbackUnavailable(f"unsupported Tushare symbol: {code}")
+ return f"{token}.{suffix}"
+
+
+def fetch_fund_flow(symbol: str, *, days: int) -> dict[str, Any]:
+ ts_code = _ts_code(symbol)
+ start_date, end_date = _date_window(days)
+ rows = _records(
+ _pro_api().moneyflow(ts_code=ts_code, start_date=start_date, end_date=end_date)
+ )
+ parsed: list[dict[str, Any]] = []
+ for row in rows:
+ parsed.append(
+ {
+ "timestamp": _dashed_date(row.get("trade_date")),
+ "main": (_to_float(row.get("net_mf_amount")) or 0.0) * 10_000,
+ "small": _net_amount(row, "buy_sm_amount", "sell_sm_amount"),
+ "medium": _net_amount(row, "buy_md_amount", "sell_md_amount"),
+ "large": _net_amount(row, "buy_lg_amount", "sell_lg_amount"),
+ "super_large": _net_amount(row, "buy_elg_amount", "sell_elg_amount"),
+ }
+ )
+ parsed.sort(key=lambda item: item.get("timestamp") or "")
+ parsed = parsed[-days:]
+ return {"symbol": symbol, "ts_code": ts_code, "source": "tushare", "rows": parsed}
+
+
+def fetch_dragon_tiger(trade_date: str, code: str | None) -> dict[str, Any]:
+ compact = _compact_date(trade_date)
+ ts_code = _ts_code(code) if code else None
+ pro = _pro_api()
+ kwargs: dict[str, str] = {"trade_date": compact}
+ if ts_code:
+ kwargs["ts_code"] = ts_code
+ appearances_raw = _records(pro.top_list(**kwargs))
+ appearances = [
+ {
+ "code": str(row.get("ts_code", "")).split(".", 1)[0] or None,
+ "name": row.get("name"),
+ "close": row.get("close"),
+ "change_pct": row.get("pct_change"),
+ "net_buy": row.get("net_amount"),
+ "buy_amount": row.get("l_buy"),
+ "sell_amount": row.get("l_sell"),
+ "turnover": row.get("amount"),
+ "reason": row.get("reason"),
+ }
+ for row in appearances_raw
+ ]
+
+ data: dict[str, Any] = {
+ "date": _dashed_date(compact),
+ "count": len(appearances_raw),
+ "appearances": appearances,
+ }
+ if ts_code:
+ seats_raw = _records(pro.top_inst(trade_date=compact, ts_code=ts_code))
+ data["code"] = ts_code.split(".", 1)[0]
+ data["seats"] = [
+ {
+ "seat": row.get("exalter"),
+ "side": row.get("side"),
+ "buy": row.get("buy"),
+ "sell": row.get("sell"),
+ "net": row.get("net_buy"),
+ "rank": None,
+ }
+ for row in seats_raw
+ ]
+ return data
+
+
+def fetch_northbound_flow(*, lookback_days: int) -> dict[str, Any]:
+ start_date, end_date = _date_window(lookback_days)
+ rows = _records(_pro_api().moneyflow_hsgt(start_date=start_date, end_date=end_date))
+ history: list[dict[str, Any]] = []
+ for row in rows:
+ shanghai = _to_float(row.get("hgt"))
+ shenzhen = _to_float(row.get("sgt"))
+ total = _to_float(row.get("north_money"))
+ history.append(
+ {
+ "trade_date": _dashed_date(row.get("trade_date")),
+ "shanghai_connect": shanghai * 100 if shanghai is not None else None,
+ "shenzhen_connect": shenzhen * 100 if shenzhen is not None else None,
+ "total": total * 100 if total is not None else None,
+ }
+ )
+ history.sort(key=lambda item: item.get("trade_date") or "")
+ history = history[-lookback_days:]
+ latest = history[-1] if history else {}
+ return {
+ "unit": "10k CNY",
+ "lookback_days": lookback_days,
+ "realtime": {
+ "shanghai_connect": latest.get("shanghai_connect"),
+ "shenzhen_connect": latest.get("shenzhen_connect"),
+ "total": latest.get("total"),
+ },
+ "history": history,
+ }
+
+
+def fetch_margin_trading(code: str, *, days: int) -> dict[str, Any]:
+ ts_code = _ts_code(code)
+ start_date, end_date = _date_window(days)
+ rows = _records(
+ _pro_api().margin_detail(ts_code=ts_code, start_date=start_date, end_date=end_date)
+ )
+ normalized = [
+ {
+ "trade_date": _dashed_date(row.get("trade_date")),
+ "financing_balance": _to_float(row.get("rzye")),
+ "financing_buy": _to_float(row.get("rzmre")),
+ "financing_repay": _to_float(row.get("rzche")),
+ "short_balance": _to_float(row.get("rqye")),
+ "short_volume": _to_float(row.get("rqyl")),
+ "margin_total_balance": _to_float(row.get("rzrqye")),
+ }
+ for row in rows
+ ]
+ normalized.sort(key=lambda item: item.get("trade_date") or "", reverse=True)
+ return {"code": ts_code.split(".", 1)[0], "ts_code": ts_code, "rows": normalized[:days]}
diff --git a/agent/tests/test_dragon_tiger_tool.py b/agent/tests/test_dragon_tiger_tool.py
index d849f7aac..c5c836247 100644
--- a/agent/tests/test_dragon_tiger_tool.py
+++ b/agent/tests/test_dragon_tiger_tool.py
@@ -146,8 +146,34 @@ class TestExecuteError:
eastmoney_client,
"throttled_get_json",
side_effect=RuntimeError("eastmoney banned"),
+ ), patch(
+ "src.tools.dragon_tiger_tool.tushare_fallbacks.fetch_dragon_tiger",
+ side_effect=RuntimeError("no fallback"),
):
out = json.loads(tool.execute(date="2024-01-02"))
assert out["ok"] is False
assert "eastmoney banned" in out["error"]
+
+ def test_http_failure_uses_tushare_fallback_when_available(self) -> None:
+ fallback = {
+ "date": "2024-01-02",
+ "count": 1,
+ "appearances": [{"code": "600519", "net_buy": 1.0}],
+ }
+ tool = DragonTigerTool()
+ with patch.object(
+ eastmoney_client,
+ "throttled_get_json",
+ side_effect=RuntimeError("eastmoney banned"),
+ ), patch(
+ "src.tools.dragon_tiger_tool.tushare_fallbacks.fetch_dragon_tiger",
+ return_value=fallback,
+ ) as fallback_fetch:
+ out = json.loads(tool.execute(date="2024-01-02", code="600519.SH"))
+
+ fallback_fetch.assert_called_once_with("2024-01-02", "600519")
+ assert out["ok"] is True
+ assert out["source"] == "tushare"
+ assert out["data"]["appearances"][0]["code"] == "600519"
+ assert "used tushare fallback" in out["warnings"][0]
diff --git a/agent/tests/test_fund_flow_tool.py b/agent/tests/test_fund_flow_tool.py
index bc7f14844..5d992ed32 100644
--- a/agent/tests/test_fund_flow_tool.py
+++ b/agent/tests/test_fund_flow_tool.py
@@ -103,6 +103,9 @@ class TestPerSymbolIsolation:
"src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"
), patch(
"src.tools.fund_flow_tool.get_json", side_effect=RuntimeError("HTTP 429")
+ ), patch(
+ "src.tools.fund_flow_tool.tushare_fallbacks.fetch_fund_flow",
+ side_effect=RuntimeError("no fallback"),
):
text = FundFlowTool().execute(codes=["600519.SH"])
@@ -110,6 +113,30 @@ class TestPerSymbolIsolation:
assert payload["ok"] is True
assert "429" in payload["data"]["600519.SH"]["error"]
+ def test_http_failure_uses_tushare_fallback_when_available(self):
+ fallback = {
+ "symbol": "600519.SH",
+ "ts_code": "600519.SH",
+ "source": "tushare",
+ "rows": [{"timestamp": "2024-01-03", "main": 100.0}],
+ }
+ with patch(
+ "src.tools.fund_flow_tool.resolve_secid", return_value="1.600519"
+ ), patch(
+ "src.tools.fund_flow_tool.get_json", side_effect=RuntimeError("HTTP 429")
+ ), patch(
+ "src.tools.fund_flow_tool.tushare_fallbacks.fetch_fund_flow",
+ return_value=fallback,
+ ) as fallback_fetch:
+ text = FundFlowTool().execute(codes=["600519.SH"], period="daily", days=5)
+
+ fallback_fetch.assert_called_once_with("600519.SH", days=5)
+ payload = json.loads(text)
+ result = payload["data"]["600519.SH"]
+ assert result["source"] == "tushare"
+ assert result["rows"][0]["timestamp"] == "2024-01-03"
+ assert "used tushare fallback" in result["warning"]
+
def test_malformed_row_skipped(self):
bad = {"data": {"klines": ["garbage", "2024-01-03,-50.0,20.0,-5.0,-30.0,-20.0"]}}
with patch(
diff --git a/agent/tests/test_margin_trading_tool.py b/agent/tests/test_margin_trading_tool.py
index 1d329d63b..8af25e62a 100644
--- a/agent/tests/test_margin_trading_tool.py
+++ b/agent/tests/test_margin_trading_tool.py
@@ -103,6 +103,9 @@ class TestErrors:
tool = MarginTradingTool()
with patch.object(
eastmoney_client, "get_json", side_effect=RuntimeError("eastmoney boom")
+ ), patch(
+ "src.tools.margin_trading_tool.tushare_fallbacks.fetch_margin_trading",
+ side_effect=RuntimeError("no fallback"),
):
out = tool.execute(code="600519.SH", days=5)
@@ -110,10 +113,35 @@ class TestErrors:
assert payload["ok"] is False
assert "eastmoney boom" in payload["error"]
+ def test_provider_failure_uses_tushare_fallback_when_available(self) -> None:
+ fallback = {
+ "code": "600519",
+ "ts_code": "600519.SH",
+ "rows": [{"trade_date": "2024-01-03", "financing_balance": 1.0}],
+ }
+ tool = MarginTradingTool()
+ with patch.object(
+ eastmoney_client, "get_json", side_effect=RuntimeError("eastmoney boom")
+ ), patch(
+ "src.tools.margin_trading_tool.tushare_fallbacks.fetch_margin_trading",
+ return_value=fallback,
+ ) as fallback_fetch:
+ out = tool.execute(code="600519.SH", days=5)
+
+ fallback_fetch.assert_called_once_with("600519", days=5)
+ payload = json.loads(out)
+ assert payload["ok"] is True
+ assert payload["source"] == "tushare"
+ assert payload["data"]["ts_code"] == "600519.SH"
+ assert "used tushare fallback" in payload["warnings"][0]
+
def test_empty_data_becomes_error_envelope(self) -> None:
tool = MarginTradingTool()
with patch.object(
eastmoney_client, "get_json", return_value={"result": {"data": []}}
+ ), patch(
+ "src.tools.margin_trading_tool.tushare_fallbacks.fetch_margin_trading",
+ side_effect=RuntimeError("no fallback"),
):
out = tool.execute(code="600519.SH")
diff --git a/agent/tests/test_northbound_tool.py b/agent/tests/test_northbound_tool.py
index a48b189b3..fd038cfe3 100644
--- a/agent/tests/test_northbound_tool.py
+++ b/agent/tests/test_northbound_tool.py
@@ -9,8 +9,6 @@ from __future__ import annotations
import json
from unittest.mock import patch
-import pytest
-
from src.tools import northbound_tool as nb
@@ -92,12 +90,37 @@ class TestSuccessEnvelope:
class TestErrorEnvelope:
def test_http_failure_returns_error_envelope(self):
- with patch.object(nb, "get_json", side_effect=RuntimeError("HTTP 429")):
+ with patch.object(nb, "get_json", side_effect=RuntimeError("HTTP 429")), patch.object(
+ nb.tushare_fallbacks,
+ "fetch_northbound_flow",
+ side_effect=RuntimeError("no fallback"),
+ ):
text = nb.NorthboundFlowTool().execute(lookback_days=5)
payload = json.loads(text)
assert payload["ok"] is False
assert "429" in payload["error"]
+ def test_http_failure_uses_tushare_fallback_when_available(self):
+ fallback = {
+ "unit": "10k CNY",
+ "lookback_days": 5,
+ "realtime": {"total": 100.0},
+ "history": [{"trade_date": "2024-01-03", "total": 100.0}],
+ }
+ with patch.object(nb, "get_json", side_effect=RuntimeError("HTTP 429")), patch.object(
+ nb.tushare_fallbacks,
+ "fetch_northbound_flow",
+ return_value=fallback,
+ ) as fallback_fetch:
+ text = nb.NorthboundFlowTool().execute(lookback_days=5)
+
+ fallback_fetch.assert_called_once_with(lookback_days=5)
+ payload = json.loads(text)
+ assert payload["ok"] is True
+ assert payload["source"] == "tushare"
+ assert payload["data"]["history"][0]["trade_date"] == "2024-01-03"
+ assert "used tushare fallback" in payload["warnings"][0]
+
def test_missing_data_block_yields_empty_history_and_null_realtime(self):
with patch.object(nb, "get_json", return_value={"data": None}):
text = nb.NorthboundFlowTool().execute(lookback_days=5)
diff --git a/agent/tests/test_tushare_fallbacks.py b/agent/tests/test_tushare_fallbacks.py
new file mode 100644
index 000000000..d180f1c55
--- /dev/null
+++ b/agent/tests/test_tushare_fallbacks.py
@@ -0,0 +1,109 @@
+"""Unit tests for optional Tushare fallback adapters.
+
+The Tushare client is replaced by small in-memory fakes, so these tests never
+touch the network or require a real token.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from src.tools import tushare_fallbacks as tf
+
+
+def test_fund_flow_maps_moneyflow_buckets_to_existing_schema() -> None:
+ pro = SimpleNamespace(
+ moneyflow=lambda **_: [
+ {
+ "trade_date": "20240103",
+ "net_mf_amount": 12.5,
+ "buy_sm_amount": 3.0,
+ "sell_sm_amount": 1.0,
+ "buy_md_amount": 5.0,
+ "sell_md_amount": 8.0,
+ "buy_lg_amount": 20.0,
+ "sell_lg_amount": 7.0,
+ "buy_elg_amount": 30.0,
+ "sell_elg_amount": 10.0,
+ }
+ ]
+ )
+ with patch.object(tf, "_pro_api", return_value=pro), patch.object(
+ tf, "_date_window", return_value=("20240101", "20240103")
+ ):
+ result = tf.fetch_fund_flow("600519.SH", days=5)
+
+ row = result["rows"][0]
+ assert result["source"] == "tushare"
+ assert row["timestamp"] == "2024-01-03"
+ assert row["main"] == 125000.0
+ assert row["small"] == 20000.0
+ assert row["medium"] == -30000.0
+ assert row["large"] == 130000.0
+ assert row["super_large"] == 200000.0
+
+
+def test_dragon_tiger_maps_top_list_and_top_inst() -> None:
+ pro = SimpleNamespace(
+ top_list=lambda **_: [
+ {
+ "ts_code": "600519.SH",
+ "name": "Kweichow Moutai",
+ "close": 1700.0,
+ "pct_change": 5.2,
+ "net_amount": 1.2e8,
+ "l_buy": 3.0e8,
+ "l_sell": 1.8e8,
+ "amount": 9.0e8,
+ "reason": "daily move",
+ }
+ ],
+ top_inst=lambda **_: [
+ {"exalter": "Institution", "side": "0", "buy": 2.0e8, "sell": 0.0, "net_buy": 2.0e8}
+ ],
+ )
+ with patch.object(tf, "_pro_api", return_value=pro):
+ data = tf.fetch_dragon_tiger("2024-01-02", "600519")
+
+ assert data["date"] == "2024-01-02"
+ assert data["appearances"][0]["code"] == "600519"
+ assert data["appearances"][0]["net_buy"] == 1.2e8
+ assert data["seats"][0]["seat"] == "Institution"
+ assert data["seats"][0]["net"] == 2.0e8
+
+
+def test_northbound_converts_tushare_million_yuan_to_10k_cny() -> None:
+ pro = SimpleNamespace(
+ moneyflow_hsgt=lambda **_: [
+ {"trade_date": "20240102", "hgt": 12.0, "sgt": -2.0, "north_money": 10.0},
+ {"trade_date": "20240103", "hgt": 3.5, "sgt": 1.0, "north_money": 4.5},
+ ]
+ )
+ with patch.object(tf, "_pro_api", return_value=pro), patch.object(
+ tf, "_date_window", return_value=("20240101", "20240103")
+ ):
+ data = tf.fetch_northbound_flow(lookback_days=2)
+
+ assert data["unit"] == "10k CNY"
+ assert data["history"][0]["shanghai_connect"] == 1200.0
+ assert data["history"][0]["total"] == 1000.0
+ assert data["realtime"]["total"] == 450.0
+
+
+def test_margin_trading_maps_and_sorts_most_recent_first() -> None:
+ pro = SimpleNamespace(
+ margin_detail=lambda **_: [
+ {"trade_date": "20240102", "rzye": 1.0, "rzmre": 2.0, "rzche": 3.0, "rqye": 4.0, "rqyl": 5.0, "rzrqye": 6.0},
+ {"trade_date": "20240103", "rzye": 7.0, "rzmre": 8.0, "rzche": 9.0, "rqye": 10.0, "rqyl": 11.0, "rzrqye": 12.0},
+ ]
+ )
+ with patch.object(tf, "_pro_api", return_value=pro), patch.object(
+ tf, "_date_window", return_value=("20240101", "20240103")
+ ):
+ data = tf.fetch_margin_trading("600519.SH", days=5)
+
+ assert data["ts_code"] == "600519.SH"
+ assert data["rows"][0]["trade_date"] == "2024-01-03"
+ assert data["rows"][0]["financing_balance"] == 7.0
+ assert data["rows"][1]["margin_total_balance"] == 6.0