"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): get_shareholder_count called a report column that no longer exists
cgycorey2cdf78befe63
diff --git "a/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md" "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md"index 0415b32e6..465024963 100644--- "a/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md"+++ "b/agent/src/skills/eastmoney/references/\345\217\202\350\200\203\346\225\260\346\215\256/\350\202\241\344\270\234\346\210\267\346\225\260.md"@@ -27,7 +27,7 @@ max_periods | int | N | 返回最近报告期数上限(1–24,默认 24)名称 | 取值 | 描述---- | ---- | ----reportName | `RPT_HOLDERNUMLATEST` | 报表名-columns | `SECUCODE,SECURITY_CODE,END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,HOLDER_NUM_RATIO,AVG_HOLD_AMT,AVG_HOLD_NUM,TOTAL_MARKET_CAP` | 请求列+columns | `SECUCODE,SECURITY_CODE,END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,HOLDER_NUM_RATIO,AVG_MARKET_CAP,AVG_HOLD_NUM,TOTAL_MARKET_CAP` | 请求列filter | `(SECUCODE="<code>")` | 个股过滤sortColumns / sortTypes | `END_DATE` / `-1` | 按报告期降序pageNumber / pageSize | `1` / `<max_periods>` | 分页@@ -44,7 +44,7 @@ HOLDER_NUM | holder_count | float | 股东户数HOLDER_NUM_CHANGE | holder_count_change | float | 户数环比变动(绝对)HOLDER_NUM_RATIO | holder_count_change_pct | float | 户数环比变动(%)AVG_HOLD_NUM | avg_hold_shares | float | 户均持股(股)-AVG_HOLD_AMT | avg_hold_amount | float | 户均持股市值+AVG_MARKET_CAP | avg_hold_amount | float | 户均持股市值TOTAL_MARKET_CAP | total_market_cap | float | 总市值end_date 与 holder_count 同时缺失的行被丢弃。信封:`{"ok": true, "market": "CN", "source": "eastmoney", "data": {"code", "periods": [...]}}`(最新在前)。diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.pyindex 9dfb78466..7ff4f86d2 100644--- a/agent/src/tools/shareholder_count_tool.py+++ b/agent/src/tools/shareholder_count_tool.py@@ -24,9 +24,13 @@ _DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"_REPORT_NAME = "RPT_HOLDERNUMLATEST"# Report columns we surface, mapped to the API's field names.+#+# Per-account market value is ``AVG_MARKET_CAP``; the older ``AVG_HOLD_AMT`` name+# no longer exists upstream, and asking for it makes the datacenter reject the+# whole request (HTTP 200, ``success: false``, ``result: null``)._COLUMNS = ("SECUCODE,SECURITY_CODE,END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,"- "HOLDER_NUM_RATIO,AVG_HOLD_AMT,AVG_HOLD_NUM,TOTAL_MARKET_CAP"+ "HOLDER_NUM_RATIO,AVG_MARKET_CAP,AVG_HOLD_NUM,TOTAL_MARKET_CAP")# Hard cap on returned periods so a long history cannot bloat the payload.@@ -35,6 +39,11 @@ _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):"""Fetch A-share quarterly shareholder counts with QoQ change and avg holding."""@@ -115,6 +124,10 @@ 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(payload)+ if rejection is not None:+ return _error(f"eastmoney datacenter rejected the request: {rejection}")+periods = _parse_periods(payload)if not periods:return _error(f"no shareholder-count disclosure found for '{code}'")@@ -139,6 +152,35 @@ 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.@@ -191,7 +233,7 @@ def _normalize_row(row: Any) -> dict | None:"holder_count_change": _to_number(row.get("HOLDER_NUM_CHANGE")),"holder_count_change_pct": _to_number(row.get("HOLDER_NUM_RATIO")),"avg_hold_shares": _to_number(row.get("AVG_HOLD_NUM")),- "avg_hold_amount": _to_number(row.get("AVG_HOLD_AMT")),+ "avg_hold_amount": _to_number(row.get("AVG_MARKET_CAP")),"total_market_cap": _to_number(row.get("TOTAL_MARKET_CAP")),}diff --git a/agent/tests/test_shareholder_count_tool.py b/agent/tests/test_shareholder_count_tool.pyindex 99a152b53..31f948875 100644--- a/agent/tests/test_shareholder_count_tool.py+++ b/agent/tests/test_shareholder_count_tool.py@@ -22,7 +22,7 @@ _SAMPLE_PAYLOAD = {"HOLDER_NUM_CHANGE": -2000,"HOLDER_NUM_RATIO": -1.05,"AVG_HOLD_NUM": 6680.0,- "AVG_HOLD_AMT": 12345678.0,+ "AVG_MARKET_CAP": 12345678.0,"TOTAL_MARKET_CAP": 2.1e12,},{@@ -32,7 +32,7 @@ _SAMPLE_PAYLOAD = {"HOLDER_NUM_CHANGE": 1500,"HOLDER_NUM_RATIO": 0.80,"AVG_HOLD_NUM": 6610.0,- "AVG_HOLD_AMT": 12000000.0,+ "AVG_MARKET_CAP": 12000000.0,"TOTAL_MARKET_CAP": 2.0e12,},]@@ -65,6 +65,8 @@ def test_success_envelope_parses_periods_newest_first():# SECUCODE filter flows through to the datacenter request._, kwargs = mock_get.call_argsassert kwargs["params"]["filter"] == '(SECUCODE="600519.SH")'+ # The retired AVG_HOLD_AMT spelling makes the datacenter reject the request.+ assert "AVG_MARKET_CAP" in kwargs["params"]["columns"]def test_max_periods_caps_returned_rows():@@ -96,6 +98,43 @@ def test_empty_disclosure_returns_error_envelope():assert "no shareholder-count" in payload["error"]+def test_upstream_rejection_is_surfaced_not_reported_as_missing_data():+ """A stale request must not be reported as a symbol without a disclosure.++ The datacenter answers HTTP 200 with ``success: false`` and a message naming an+ unknown column when the requested column list drifts; the envelope has to carry+ that message rather than the empty-disclosure error.+ """+ drift = {+ "success": False,+ "message": "AVG_HOLD_AMT参数不存在",+ "result": None,+ }+ with patch.object(sct, "get_json", return_value=drift):+ out = ShareholderCountTool().execute(code="600519.SH")++ payload = json.loads(out)+ assert payload["ok"] is False+ assert "AVG_HOLD_AMT参数不存在" in payload["error"]+ assert "no shareholder-count" not in payload["error"]+++def test_empty_result_message_is_reported_as_no_disclosure():+ """The datacenter's no-rows answer is not a rejection of the request.++ An empty match arrives with the same ``success: false`` flags as a schema+ complaint, so it has to stay on the empty-disclosure path.+ """+ empty = {"success": False, "message": "返回数据为空", "result": None}+ with patch.object(sct, "get_json", return_value=empty):+ out = ShareholderCountTool().execute(code="999999.SH")++ payload = json.loads(out)+ assert payload["ok"] is False+ assert "no shareholder-count" in payload["error"]+ assert "rejected" not in payload["error"]++def test_request_failure_is_caught_as_error_envelope():with patch.object(sct, "get_json", side_effect=RuntimeError("HTTP 429")):out = ShareholderCountTool().execute(code="600519.SH")