"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): shareholder-count history says when the latest join fails (#1518)
Haozhe Wu9162dc6addf7
diff --git a/agent/src/tools/shareholder_count_tool.py b/agent/src/tools/shareholder_count_tool.pyindex 7eeea788b..4b7b61c44 100644--- a/agent/src/tools/shareholder_count_tool.py+++ b/agent/src/tools/shareholder_count_tool.py@@ -122,7 +122,9 @@ class ShareholderCountTool(BaseTool):"sortColumns": "END_DATE","sortTypes": "-1","pageNumber": "1",- "pageSize": str(limit),+ # One row past the limit: the oldest returned period's+ # prev_period_end comes from the row after it.+ "pageSize": str(limit + 1),"source": "WEB","client": "WEB",},@@ -135,29 +137,34 @@ class ShareholderCountTool(BaseTool):return _error(f"eastmoney datacenter rejected the request: {rejection}")periods = _parse_periods(detail_payload)+ warnings: list[str] = []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)+ latest, problem = _fetch_latest_row(code)+ if problem is not None:+ warnings.append(+ f"average holding and market cap unavailable: latest-only report {problem}"+ )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)+ latest, problem = _fetch_latest_row(code)+ if problem is not None:+ return _error(f"eastmoney latest-only report {problem}")if latest is None:return _error(f"no shareholder-count disclosure found for '{code}'")periods = [latest]+ data: dict[str, Any] = {"code": code, "periods": periods[:limit]}+ if warnings:+ data["warnings"] = warningsreturn json.dumps(- {- "ok": True,- "market": "CN",- "source": "eastmoney",- "data": {"code": code, "periods": periods[:limit]},- },+ {"ok": True, "market": "CN", "source": "eastmoney", "data": data},ensure_ascii=False,)@@ -269,13 +276,17 @@ def _normalize_row(row: Any) -> dict | None:}-def _fetch_latest_row(code: str) -> dict | None:- """Fetch the latest-only report's single row for ``code``, or ``None``.+def _fetch_latest_row(code: str) -> tuple[dict | None, str | None]:+ """Fetch the latest-only report's single row for ``code``.Used for the average-holding / market-cap columns the detail report doesnot 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.+ rows for the symbol. A failure is returned, not raised, so the caller can+ keep the history it has and say what is missing.++ Returns:+ ``(row, None)`` on success, ``(None, None)`` when the report has no+ row, or ``(None, problem)`` when the request failed or was rejected."""try:payload = get_json(@@ -292,12 +303,13 @@ def _fetch_latest_row(code: str) -> dict | None:"client": "WEB",},)- except Exception: # noqa: BLE001 - best-effort enrichment, never fatal- return None- if _upstream_rejection(payload) is not None:- return None+ except Exception as exc: # noqa: BLE001 - reported to the caller, never raised+ return None, f"request failed: {exc}"+ rejection = _upstream_rejection(payload)+ if rejection is not None:+ return None, f"rejected the request: {rejection}"periods = _parse_periods(payload)- return periods[0] if periods else None+ return (periods[0] if periods else None), Nonedef _clean_date(value: Any) -> str | None:diff --git a/agent/tests/test_shareholder_count_tool.py b/agent/tests/test_shareholder_count_tool.pyindex f59919383..1c5e375f4 100644--- a/agent/tests/test_shareholder_count_tool.py+++ b/agent/tests/test_shareholder_count_tool.py@@ -111,10 +111,12 @@ def test_max_periods_caps_returned_rows():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)+ # used to return exactly one row whatever was asked (#1503) — plus one row,+ # so the oldest returned period still knows its previous period_, kwargs = mock_get.call_args_list[0]assert kwargs["params"]["reportName"] == sct._DETAIL_REPORT- assert kwargs["params"]["pageSize"] == "1"+ assert kwargs["params"]["pageSize"] == "2"+ assert payload["data"]["periods"][0]["prev_period_end"] == "2023-12-31"def test_latest_only_fallback_when_detail_report_is_empty():@@ -149,6 +151,40 @@ def test_latest_join_failure_keeps_the_history():assert payload["ok"] is Trueassert len(payload["data"]["periods"]) == 3assert payload["data"]["periods"][0]["avg_hold_shares"] is None+ # ...but it says why the average fields are empty+ assert any("HTTP 502" in w for w in payload["data"]["warnings"])+++def test_latest_join_rejection_is_a_warning_not_silence():+ """A retired latest-only column (the #1489 failure) must not read as null data."""+ def latest_rejected(url, params=None, **kwargs):+ if (params or {}).get("reportName") == sct._DETAIL_REPORT:+ return _DETAIL_PAYLOAD+ return {"success": False, "result": None, "code": 9501, "message": "AVG_HOLD_AMT返回字段不存在"}++ with patch.object(sct, "get_json", side_effect=latest_rejected):+ payload = json.loads(ShareholderCountTool().execute(code="600519.SH"))+ assert payload["ok"] is True+ assert any("AVG_HOLD_AMT" in w for w in payload["data"]["warnings"])+++def test_latest_only_fallback_rejection_is_an_error_not_no_disclosure():+ def both(url, params=None, **kwargs):+ if (params or {}).get("reportName") == sct._DETAIL_REPORT:+ return {"result": {"data": []}}+ return {"success": False, "result": None, "code": 9501, "message": "AVG_HOLD_AMT返回字段不存在"}++ with patch.object(sct, "get_json", side_effect=both):+ payload = json.loads(ShareholderCountTool().execute(code="600519.SH"))+ assert payload["ok"] is False+ assert "AVG_HOLD_AMT" in payload["error"]+ assert "no shareholder-count disclosure" not in payload["error"]+++def test_a_clean_join_carries_no_warnings():+ with patch.object(sct, "get_json", side_effect=_route_by_report):+ payload = json.loads(ShareholderCountTool().execute(code="600519.SH"))+ assert "warnings" not in payload["data"]def test_non_a_share_returns_error_envelope():