"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): serve shareholder-count history from the per-period report
Yufeng He634a86bda164
diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex eaee3d302..48ad8178a 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -2010,11 +2010,13 @@ def get_block_trades(code: str, days: int = 30) -> str:@mcp.tooldef get_shareholder_count(code: str, max_periods: int = 24) -> str:- """Fetch mainland A-share quarterly shareholder count (股东户数) (Eastmoney).+ """Fetch mainland A-share shareholder count history (股东户数) (Eastmoney).- Returns holder count per report period, quarter-over-quarter change- (absolute and percent), and average holding (shares and market value) per- account. Markets: China A-shares only (.SH/.SZ/.BJ).+ Returns holder count per disclosed period, the change against the previous+ disclosed period (absolute and percent; each row states its own+ prev_period_end since intervals vary), and average holding (shares and+ market value) per account on the newest row. Markets: China A-shares only+ (.SH/.SZ/.BJ).Args:code: A-share symbol in <code>.<exchange> form (SH/SZ/BJ).diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.pyindex 7ff4f86d2..7eeea788b 100644--- a/agent/src/tools/shareholder_count_tool.py+++ b/agent/src/tools/shareholder_count_tool.py@@ -1,11 +1,12 @@-"""Read-only tool: A-share quarterly shareholder count via Eastmoney datacenter.+"""Read-only tool: A-share shareholder count history via Eastmoney datacenter.-Eastmoney's datacenter report API publishes the periodic "股东户数" (number of-registered shareholders) disclosure for mainland A-shares: the holder count per-report period, the quarter-over-quarter change, and the average holding value-per account. This tool wraps that report behind the project's BaseTool contract-and the frozen, IP-throttled Eastmoney client so the agent never hits the host-un-throttled and never re-implements provider plumbing.+Eastmoney's datacenter report API publishes the "股东户数" (number of+registered shareholders) disclosure for mainland A-shares. The history comes+from the per-period detail report: one row per disclosure, each with the change+against the previous disclosed period (the interval varies — quarterly reports,+plus intra-quarter ad-hoc disclosures — and each row states its own+``prev_period_end``). Average holding value per account exists only on the+latest-only report, so it is joined onto the newest row when the two agree.Only mainland A-shares (``.SH`` / ``.SZ`` / ``.BJ``) carry this disclosure;other markets return an error envelope.@@ -19,17 +20,20 @@ from typing import Anyfrom backtest.loaders.eastmoney_client import get_json, resolve_secidfrom src.agent.tools import BaseTool-# Eastmoney datacenter report endpoint + the shareholder-number report id.+# Eastmoney datacenter report endpoint + the two shareholder-number reports:+# the per-period detail report (one row per disclosure, what max_periods pages+# over) and the latest-only report (one row per symbol, the only carrier of the+# average-holding and market-cap columns)._DATACENTER_URL = "https://datacenter-web.eastmoney.com/api/data/v1/get"-_REPORT_NAME = "RPT_HOLDERNUMLATEST"+_DETAIL_REPORT = "RPT_HOLDERNUM_DET"+_LATEST_REPORT = "RPT_HOLDERNUMLATEST"-# Report columns we surface, mapped to the API's field names.-#+_DETAIL_COLUMNS = "SECUCODE,END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,HOLDER_NUM_RATIO"# 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,"+_LATEST_COLUMNS = (+ "SECUCODE,SECURITY_CODE,END_DATE,PRE_END_DATE,HOLDER_NUM,HOLDER_NUM_CHANGE,""HOLDER_NUM_RATIO,AVG_MARKET_CAP,AVG_HOLD_NUM,TOTAL_MARKET_CAP")@@ -46,14 +50,16 @@ _EMPTY_RESULT_MESSAGES = ("返回数据为空",)class ShareholderCountTool(BaseTool):- """Fetch A-share quarterly shareholder counts with QoQ change and avg holding."""+ """Fetch A-share shareholder count history with per-period change and avg holding."""name = "get_shareholder_count"description = (- "Fetch mainland A-share quarterly shareholder count (股东户数) from the "- "Eastmoney datacenter: holder count per report period, quarter-over-quarter "- "change (absolute and percent), and average holding (shares and market value) "- "per account. Markets: China A-shares only (.SH / .SZ / .BJ). "+ "Fetch mainland A-share shareholder count history (股东户数) from the "+ "Eastmoney datacenter: holder count per disclosed period, the change "+ "against the previous disclosed period (absolute and percent; the "+ "interval varies and each row states its own prev_period_end), and "+ "average holding (shares and market value) per account on the newest "+ "row. Markets: China A-shares only (.SH / .SZ / .BJ). "'Example: {"code": "600519.SH"}.')parameters = {@@ -107,11 +113,11 @@ class ShareholderCountTool(BaseTool):limit = _clamp_periods(kwargs.get("max_periods", _MAX_PERIODS))try:- payload = get_json(+ detail_payload = get_json(_DATACENTER_URL,params={- "reportName": _REPORT_NAME,- "columns": _COLUMNS,+ "reportName": _DETAIL_REPORT,+ "columns": _DETAIL_COLUMNS,"filter": f'(SECUCODE="{code}")',"sortColumns": "END_DATE","sortTypes": "-1",@@ -124,13 +130,26 @@ 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)+ rejection = _upstream_rejection(detail_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}'")+ periods = _parse_periods(detail_payload)+ if periods:+ # The per-period report has no average-holding or market-cap+ # columns; the latest-only report carries them, so join its row+ # onto the newest period when the two agree on the end date.+ latest = _fetch_latest_row(code)+ if latest is not None and periods[0]["end_date"] == latest["end_date"]:+ for key in ("avg_hold_shares", "avg_hold_amount", "total_market_cap"):+ periods[0][key] = latest.get(key)+ else:+ # Some symbols only surface on the latest-only report; answer the+ # single latest period rather than nothing.+ latest = _fetch_latest_row(code)+ if latest is None:+ return _error(f"no shareholder-count disclosure found for '{code}'")+ periods = [latest]return json.dumps({@@ -205,6 +224,17 @@ def _parse_periods(payload: Any) -> list[dict]:record = _normalize_row(row)if record is not None:periods.append(record)+ # Each row's change columns are measured against the previous disclosed+ # period; state that interval per row instead of calling it+ # quarter-over-quarter (#1503 measured PRE_END_DATE drifting to nine+ # months or nine years on the latest-only report).+ for i, record in enumerate(periods):+ # the detail report carries no PRE_END_DATE; the latest-only fallback+ # row already carries its own, so only fill the gap+ if record.get("prev_period_end") is None:+ record["prev_period_end"] = (+ periods[i + 1]["end_date"] if i + 1 < len(periods) else None+ )return periods@@ -235,9 +265,41 @@ def _normalize_row(row: Any) -> dict | None:"avg_hold_shares": _to_number(row.get("AVG_HOLD_NUM")),"avg_hold_amount": _to_number(row.get("AVG_MARKET_CAP")),"total_market_cap": _to_number(row.get("TOTAL_MARKET_CAP")),+ "prev_period_end": _clean_date(row.get("PRE_END_DATE")),}+def _fetch_latest_row(code: str) -> dict | None:+ """Fetch the latest-only report's single row for ``code``, or ``None``.++ Used for the average-holding / market-cap columns the detail report does+ not carry, and as the single-period answer when the detail report has no+ rows for the symbol. Its own failures never fail the call: the caller+ already has (or lacks) the history either way.+ """+ try:+ payload = get_json(+ _DATACENTER_URL,+ params={+ "reportName": _LATEST_REPORT,+ "columns": _LATEST_COLUMNS,+ "filter": f'(SECUCODE="{code}")',+ "sortColumns": "END_DATE",+ "sortTypes": "-1",+ "pageNumber": "1",+ "pageSize": "1",+ "source": "WEB",+ "client": "WEB",+ },+ )+ except Exception: # noqa: BLE001 - best-effort enrichment, never fatal+ return None+ if _upstream_rejection(payload) is not None:+ return None+ periods = _parse_periods(payload)+ return periods[0] if periods else None++def _clean_date(value: Any) -> str | None:"""Trim a datacenter timestamp to its ``YYYY-MM-DD`` date, or ``None``."""if not isinstance(value, str) or not value.strip():diff --git a/agent/tests/test_shareholder_count_tool.py b/agent/tests/test_shareholder_count_tool.pyindex 31f948875..f59919383 100644--- a/agent/tests/test_shareholder_count_tool.py+++ b/agent/tests/test_shareholder_count_tool.py@@ -12,7 +12,9 @@ from unittest.mock import patchfrom src.tools import shareholder_count_tool as sctfrom src.tools.shareholder_count_tool import ShareholderCountTool-_SAMPLE_PAYLOAD = {+# The per-period detail report: one row per disclosure, no avg/market-cap+# columns (it never carries them).+_DETAIL_PAYLOAD = {"result": {"data": [{@@ -21,9 +23,6 @@ _SAMPLE_PAYLOAD = {"HOLDER_NUM": 188000,"HOLDER_NUM_CHANGE": -2000,"HOLDER_NUM_RATIO": -1.05,- "AVG_HOLD_NUM": 6680.0,- "AVG_MARKET_CAP": 12345678.0,- "TOTAL_MARKET_CAP": 2.1e12,},{"SECUCODE": "600519.SH",@@ -31,17 +30,48 @@ _SAMPLE_PAYLOAD = {"HOLDER_NUM": 190000,"HOLDER_NUM_CHANGE": 1500,"HOLDER_NUM_RATIO": 0.80,- "AVG_HOLD_NUM": 6610.0,- "AVG_MARKET_CAP": 12000000.0,- "TOTAL_MARKET_CAP": 2.0e12,+ },+ {+ "SECUCODE": "600519.SH",+ "END_DATE": "2023-09-30 00:00:00",+ "HOLDER_NUM": 188500,+ "HOLDER_NUM_CHANGE": 500,+ "HOLDER_NUM_RATIO": 0.27,},]}}+# The latest-only report: one row, the only carrier of avg holding/market cap.+_LATEST_PAYLOAD = {+ "result": {+ "data": [+ {+ "SECUCODE": "600519.SH",+ "END_DATE": "2024-03-31 00:00:00",+ "PRE_END_DATE": "2023-12-31 00:00:00",+ "HOLDER_NUM": 188000,+ "HOLDER_NUM_CHANGE": -2000,+ "HOLDER_NUM_RATIO": -1.05,+ "AVG_HOLD_NUM": 6680.0,+ "AVG_MARKET_CAP": 12345678.0,+ "TOTAL_MARKET_CAP": 2.1e12,+ },+ ]+ }+}+++def _route_by_report(url, params=None, **kwargs):+ """Serve the detail or latest payload by the request's reportName."""+ report = (params or {}).get("reportName")+ if report == sct._DETAIL_REPORT:+ return _DETAIL_PAYLOAD+ return _LATEST_PAYLOAD+def test_success_envelope_parses_periods_newest_first():- with patch.object(sct, "get_json", return_value=_SAMPLE_PAYLOAD) as mock_get:+ with patch.object(sct, "get_json", side_effect=_route_by_report) as mock_get:out = ShareholderCountTool().execute(code="600519.SH")payload = json.loads(out)@@ -51,16 +81,22 @@ def test_success_envelope_parses_periods_newest_first():assert payload["data"]["code"] == "600519.SH"periods = payload["data"]["periods"]- assert len(periods) == 2+ assert len(periods) == 3assert periods[0] == {"end_date": "2024-03-31","holder_count": 188000.0,"holder_count_change": -2000.0,"holder_count_change_pct": -1.05,+ # the latest-only report's avg/market-cap fields join onto the newest row"avg_hold_shares": 6680.0,"avg_hold_amount": 12345678.0,"total_market_cap": 2.1e12,+ "prev_period_end": "2023-12-31",}+ # older rows carry no avg fields, and each states its own interval+ assert periods[1]["avg_hold_shares"] is None+ assert periods[1]["prev_period_end"] == "2023-09-30"+ assert periods[2]["prev_period_end"] is None# SECUCODE filter flows through to the datacenter request._, kwargs = mock_get.call_args@@ -70,10 +106,49 @@ def test_success_envelope_parses_periods_newest_first():def test_max_periods_caps_returned_rows():- with patch.object(sct, "get_json", return_value=_SAMPLE_PAYLOAD):+ with patch.object(sct, "get_json", side_effect=_route_by_report) as mock_get:out = ShareholderCountTool().execute(code="600519.SH", max_periods=1)payload = json.loads(out)assert len(payload["data"]["periods"]) == 1+ # the cap flows to the detail report's pageSize — the latest-only report+ # used to return exactly one row whatever was asked (#1503)+ _, kwargs = mock_get.call_args_list[0]+ assert kwargs["params"]["reportName"] == sct._DETAIL_REPORT+ assert kwargs["params"]["pageSize"] == "1"+++def test_latest_only_fallback_when_detail_report_is_empty():+ """A symbol absent from the per-period report still answers its latest row."""+ def detail_empty(url, params=None, **kwargs):+ if (params or {}).get("reportName") == sct._DETAIL_REPORT:+ return {"result": {"data": []}}+ return _LATEST_PAYLOAD++ with patch.object(sct, "get_json", side_effect=detail_empty):+ out = ShareholderCountTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is True+ periods = payload["data"]["periods"]+ assert len(periods) == 1+ assert periods[0]["end_date"] == "2024-03-31"+ assert periods[0]["avg_hold_shares"] == 6680.0+ # the latest report's own PRE_END_DATE states the interval for a single row+ assert periods[0]["prev_period_end"] == "2023-12-31"+++def test_latest_join_failure_keeps_the_history():+ """The avg-field enrichment is best-effort: history survives it failing."""+ def latest_down(url, params=None, **kwargs):+ if (params or {}).get("reportName") == sct._DETAIL_REPORT:+ return _DETAIL_PAYLOAD+ raise RuntimeError("HTTP 502")++ with patch.object(sct, "get_json", side_effect=latest_down):+ out = ShareholderCountTool().execute(code="600519.SH")+ payload = json.loads(out)+ assert payload["ok"] is True+ assert len(payload["data"]["periods"]) == 3+ assert payload["data"]["periods"][0]["avg_hold_shares"] is Nonedef test_non_a_share_returns_error_envelope():