"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): block trades, margin and statements stop reading a rejected query as no data
Haozhe Wu0b0c195d99dc
diff --git a/agent/backtest/loaders/eastmoney_client.py b/agent/backtest/loaders/eastmoney_client.pyindex b84cf49f4..67093a131 100644--- a/agent/backtest/loaders/eastmoney_client.py+++ b/agent/backtest/loaders/eastmoney_client.py@@ -73,6 +73,37 @@ _JSONP_WRAPPER = re.compile()+def datacenter_rejection(payload: Any) -> str | None:+ """Return the datacenter's complaint when it rejected a report query.++ The datacenter answers HTTP 200 with ``success: false`` both for a query it+ rejects (a report or column that no longer exists, code 9501) and for a query+ with no rows (code 9201, ``返回数据为空``). Only the first is an error; read as+ an empty result it turns a stale query into "no data for this stock" (#1489,+ #1501, #1502). The empty answer is recognised only as that message with+ code 9201 (or no code); anything else is a rejection.++ Args:+ payload: Decoded datacenter JSON.++ Returns:+ ``"code=<code> message=<message>"`` for a rejection, ``None`` for an+ accepted query, including one with no rows.+ """+ if not isinstance(payload, dict) or payload.get("success") is not False:+ return None+ code = payload.get("code")+ message = payload.get("message")+ message = message.strip() if isinstance(message, str) else ""+ # Live empty answers are code 9201 with exactly this message; the same+ # message under a rejection code (9501) is still a rejection.+ if message == "返回数据为空" and code in (9201, None):+ return None+ if not message:+ message = "request rejected without a message"+ return f"code={code} message={message}" if code is not None else message++def _min_interval() -> float:"""Resolve the per-call minimum Eastmoney request spacing in seconds."""return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL)diff --git a/agent/src/tools/block_trades_tool.py b/agent/src/tools/block_trades_tool.pyindex c0d075a60..5cf615fd9 100644--- a/agent/src/tools/block_trades_tool.py+++ b/agent/src/tools/block_trades_tool.py@@ -20,7 +20,7 @@ import loggingfrom datetime import date, datetime, timedeltafrom typing import Any-from backtest.loaders.eastmoney_client import get_json, resolve_secid+from backtest.loaders.eastmoney_client import datacenter_rejection, get_json, resolve_secidfrom src.agent.tools import BaseToolfrom src.tools.trade_journal_parsers import _qualify_a_share@@ -262,6 +262,12 @@ class BlockTradesTool(BaseTool):ensure_ascii=False,)+ rejection = datacenter_rejection(payload)+ if rejection is not None:+ return json.dumps(+ {"ok": False, "error": f"eastmoney datacenter rejected the request: {rejection}"},+ ensure_ascii=False,+ )rows = _extract_rows(payload)records = [_normalize_record(row) for row in rows[:_MAX_RECORDS]]diff --git a/agent/src/tools/dragon_tiger_tool.py b/agent/src/tools/dragon_tiger_tool.pyindex 42db2cc90..7ae806ce4 100644--- a/agent/src/tools/dragon_tiger_tool.py+++ b/agent/src/tools/dragon_tiger_tool.py@@ -100,12 +100,9 @@ def _fetch_report()if not isinstance(payload, dict):return []- if payload.get("success") is False:- code = payload.get("code")- message = payload.get("message", "unknown provider error")- if code == 9201 or message == "返回数据为空":- return []- raise RuntimeError(f"Eastmoney rejected {report_name} ({code}): {message}")+ rejection = eastmoney_client.datacenter_rejection(payload)+ if rejection is not None:+ raise RuntimeError(f"Eastmoney rejected {report_name} ({rejection})")result = payload.get("result")if not isinstance(result, dict):return []diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pyindex 8aec0de21..53a87cb04 100644--- a/agent/src/tools/financial_statements_tool.py+++ b/agent/src/tools/financial_statements_tool.py@@ -30,7 +30,7 @@ from typing import Anyfrom backtest.loaders import sec_framesfrom backtest.loaders import yahoo_client-from backtest.loaders.eastmoney_client import get_json, resolve_secid+from backtest.loaders.eastmoney_client import datacenter_rejection, get_json, resolve_secidfrom backtest.loaders.sec_edgar_client import cik_for, get_company_factsfrom src.agent.tools import BaseToolfrom src.tools._result_paging import fit_records@@ -286,6 +286,10 @@ def _fetch_eastmoney_statement(logger.warning("eastmoney statement fetch failed for %s: %s", code, exc)return {"error": str(exc)}+ rejection = datacenter_rejection(payload)+ if rejection is not None:+ # A stale report or column reads as a rejection, not as no filings (#1502).+ return {"error": f"eastmoney rejected the request: {rejection}"}periods = _filter_by_period(_parse_eastmoney_periods(payload), period)return {"periods": _cap_periods(periods)}diff --git a/agent/src/tools/lockup_expiry_tool.py b/agent/src/tools/lockup_expiry_tool.pyindex 2d02631d2..9dc6c36da 100644--- a/agent/src/tools/lockup_expiry_tool.py+++ b/agent/src/tools/lockup_expiry_tool.py@@ -170,22 +170,6 @@ _UNITS = {"total_ratio": "fraction of total shares",}-_EMPTY_RESULT_MESSAGES = ("返回数据为空",)---def _upstream_rejection(payload: Any) -> str | None:- if not isinstance(payload, dict) or payload.get("success") is not False:- return None- message = payload.get("message")- if not isinstance(message, str) or not message.strip():- return "request rejected without a message"- message = message.strip()- code = payload.get("code")- if code == 9201 and message in _EMPTY_RESULT_MESSAGES:- return None- return f"code={code} message={message}" if code is not None else message--def _extract_rows(payload: Any) -> list[dict]:"""Pull the ``result.data`` list out of a datacenter payload.@@ -239,7 +223,7 @@ def _fetch_lockups(code: str | None, horizon_days: int) -> list[dict]:},)- rejection = _upstream_rejection(payload)+ rejection = eastmoney_client.datacenter_rejection(payload)if rejection is not None:raise ValueError(f"eastmoney datacenter rejected the request: {rejection}")diff --git a/agent/src/tools/margin_trading_tool.py b/agent/src/tools/margin_trading_tool.pyindex f806bf9a0..e5c12d93b 100644--- a/agent/src/tools/margin_trading_tool.py+++ b/agent/src/tools/margin_trading_tool.py@@ -214,14 +214,21 @@ class MarginTradingTool(BaseTool):ensure_ascii=False,)+ rejection = eastmoney_client.datacenter_rejection(payload)result = payload.get("result") if isinstance(payload, dict) else Nonedata = result.get("data") if isinstance(result, dict) else None- if not isinstance(data, list) or not data:+ if rejection is not None or not isinstance(data, list) or not data:+ # A rejected query is named as one, not read as "no rows" (#1502).+ eastmoney_said = (+ f"eastmoney rejected the request ({rejection})"+ if rejection is not None+ else "eastmoney returned no rows"+ )try:fallback_data = tushare_fallbacks.fetch_margin_trading(code, days=days)except Exception as fallback_exc: # noqa: BLE001 - preserve the original empty-data errorreturn _err(- f"No margin-trading data returned for {code}. "+ f"No margin-trading data returned for {code}: {eastmoney_said}. "f"Tushare fallback failed: {fallback_exc}")return json.dumps(@@ -229,7 +236,7 @@ class MarginTradingTool(BaseTool):"ok": True,"market": "a_share","source": "tushare",- "warnings": ["eastmoney returned no rows; used tushare fallback"],+ "warnings": [f"{eastmoney_said}; used tushare fallback"],"data": fallback_data,},ensure_ascii=False,diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.pyindex 4b7b61c44..30981dbf4 100644--- a/agent/src/tools/shareholder_count_tool.py+++ b/agent/src/tools/shareholder_count_tool.py@@ -17,7 +17,7 @@ from __future__ import annotationsimport jsonfrom typing import Any-from backtest.loaders.eastmoney_client import get_json, resolve_secid+from backtest.loaders.eastmoney_client import datacenter_rejection, get_json, resolve_secidfrom src.agent.tools import BaseTool# Eastmoney datacenter report endpoint + the two shareholder-number reports:@@ -43,10 +43,6 @@ _MAX_PERIODS = 24# A-share exchange suffixes this disclosure covers._A_SHARE_SUFFIXES = ("SH", "SZ", "BJ")-# The datacenter answers a filter that matches nothing with the same ``success:-# false`` shape it uses to reject a request, so this message means "no rows" and is-# not a complaint about the request itself.-_EMPTY_RESULT_MESSAGES = ("返回数据为空",)class ShareholderCountTool(BaseTool):@@ -132,7 +128,7 @@ class ShareholderCountTool(BaseTool):except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelopereturn _error(f"eastmoney datacenter request failed: {exc}")- rejection = _upstream_rejection(detail_payload)+ rejection = datacenter_rejection(detail_payload)if rejection is not None:return _error(f"eastmoney datacenter rejected the request: {rejection}")@@ -178,35 +174,6 @@ def _clamp_periods(value: Any) -> int:return max(1, min(n, _MAX_PERIODS))-def _upstream_rejection(payload: Any) -> str | None:- """Return the datacenter's own complaint when it rejected the request.-- The datacenter answers HTTP 200 with ``success: false``, ``result: null`` and a- ``message`` naming the offending parameter (typically a report column that no- longer exists). Without this check the payload is indistinguishable from a- symbol that carries no disclosure, so a changed report schema would reach the- caller as "no data for this stock" instead of "our query is stale".-- An empty result uses the same flags, so its message is passed through to the- caller's empty-disclosure path instead of being reported as a rejection.-- Args:- payload: Decoded datacenter JSON.-- Returns:- The upstream message, or ``None`` when the request was not rejected.- """- if not isinstance(payload, dict) or payload.get("success") is not False:- return None- message = payload.get("message")- if not (isinstance(message, str) and message.strip()):- return "request rejected without a message"- message = message.strip()- if message in _EMPTY_RESULT_MESSAGES:- return None- return message--def _parse_periods(payload: Any) -> list[dict]:"""Extract per-period shareholder records from a datacenter payload.@@ -305,7 +272,7 @@ def _fetch_latest_row(code: str) -> tuple[dict | None, str | None]:)except Exception as exc: # noqa: BLE001 - reported to the caller, never raisedreturn None, f"request failed: {exc}"- rejection = _upstream_rejection(payload)+ rejection = datacenter_rejection(payload)if rejection is not None:return None, f"rejected the request: {rejection}"periods = _parse_periods(payload)diff --git a/agent/tests/test_eastmoney_datacenter_rejection.py b/agent/tests/test_eastmoney_datacenter_rejection.pynew file mode 100644index 000000000..180091c86--- /dev/null+++ b/agent/tests/test_eastmoney_datacenter_rejection.py@@ -0,0 +1,99 @@+"""The datacenter's rejected-query and empty-result answers look alike (#1489, #1501, #1502).++Both are HTTP 200 with ``success: false``. A rejection (a retired report or+column, code 9501) read as an empty result tells the caller "this stock has no+data" when the query is stale. Every datacenter caller shares one rule, pinned+here from both sides, and the three tools that used to swallow a rejection are+checked against it.+"""++from __future__ import annotations++import json+from unittest.mock import patch++import pytest++from backtest.loaders import eastmoney_client+from backtest.loaders.eastmoney_client import datacenter_rejection+from src.tools import block_trades_tool+from src.tools.financial_statements_tool import FinancialStatementsTool+from src.tools.margin_trading_tool import MarginTradingTool++REJECTED = {"success": False, "code": 9501, "message": "RPT_OLD报表配置不存在", "result": None}+EMPTY = {"success": False, "code": 9201, "message": "返回数据为空", "result": None}+++ "payload",+ [+ {"success": True, "result": {"data": [{"a": 1}]}},+ EMPTY,+ {"success": False, "message": "返回数据为空", "result": None}, # no code at all+ {"result": {"data": []}}, # no success flag+ None,+ ],+)+def test_accepted_and_empty_answers_are_not_rejections(payload):+ assert datacenter_rejection(payload) is None+++ ("payload", "fragment"),+ [+ (REJECTED, "code=9501 message=RPT_OLD报表配置不存在"),+ ({"success": False, "code": 9501, "message": "返回数据为空"}, "code=9501"),+ ({"success": False, "code": 9201, "message": "COL返回字段不存在"}, "COL返回字段不存在"),+ ({"success": False, "code": 9501, "message": ""}, "request rejected without a message"),+ ({"success": False, "message": "参数错误"}, "参数错误"),+ ],+)+def test_rejections_are_named(payload, fragment):+ rejection = datacenter_rejection(payload)+ assert rejection is not None and fragment in rejection+++def test_block_trades_reports_a_rejection_instead_of_zero_deals():+ with patch.object(block_trades_tool, "get_json", return_value=REJECTED):+ out = json.loads(block_trades_tool.BlockTradesTool().execute(code="600519.SH"))+ assert out["ok"] is False+ assert "9501" in out["error"]+++def test_block_trades_still_reads_an_empty_window_as_zero_deals():+ with patch.object(block_trades_tool, "get_json", return_value=EMPTY):+ out = json.loads(block_trades_tool.BlockTradesTool().execute(code="600519.SH"))+ assert out["ok"] is True+ assert out["data"]["count"] == 0+++def test_margin_trading_names_the_rejection_when_it_falls_back():+ fallback = {"code": "600519", "ts_code": "600519.SH", "rows": [{"trade_date": "2024-01-03"}]}+ with patch.object(eastmoney_client, "get_json", return_value=REJECTED), patch(+ "src.tools.margin_trading_tool.tushare_fallbacks.fetch_margin_trading", return_value=fallback+ ):+ out = json.loads(MarginTradingTool().execute(code="600519.SH", days=5))+ assert out["source"] == "tushare"+ assert "rejected" in out["warnings"][0] and "9501" in out["warnings"][0]+ assert "no rows" not in out["warnings"][0]+++def test_margin_trading_error_names_the_rejection_when_the_fallback_fails():+ with patch.object(eastmoney_client, "get_json", return_value=REJECTED), patch(+ "src.tools.margin_trading_tool.tushare_fallbacks.fetch_margin_trading",+ side_effect=RuntimeError("no tushare token"),+ ):+ out = json.loads(MarginTradingTool().execute(code="600519.SH", days=5))+ assert out["ok"] is False+ assert "9501" in out["error"]+++def test_financial_statements_report_a_rejection_instead_of_no_periods():+ with patch("src.tools.financial_statements_tool.resolve_secid", return_value="1.600519"), patch(+ "src.tools.financial_statements_tool.get_json", return_value=REJECTED+ ):+ out = json.loads(+ FinancialStatementsTool().execute(code="600519.SH", statement="balance", period="annual")+ )+ assert "9501" in json.dumps(out, ensure_ascii=False)+ assert out.get("data", {}).get("600519.SH", {}).get("periods") in (None, [])