"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(gildata): add stock screening with cross-period indicators
tangwj46958bffb1b2eb5b6
diff --git a/agent/.env.example b/agent/.env.exampleindex bb973f6cb..819b369cd 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -234,7 +234,7 @@ TUSHARE_TOKEN=your-tushare-token# TIINGO_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)# FMP_API_KEY=xxx # optional US-equity OHLCV fallback provider (selectable get_market_data source)# GILDATA_TOKEN=xxx # optional Gildata (恒生聚源) provider — commercial token via [email protected]; joins the a_share/hk_equity chain tails for OHLCV (selectable get_market_data source) and powers the get_fund_nav OTC-fund NAV tool-# Also enables gildata_fin_query for combined financial, operating and market-data questions.+# Also enables gildata_fin_query for mixed data queries and gildata_stock_selection for screening with cross-period indicators.# GILDATA_BASE_URL=xxx # optional endpoint override (defaults to the vendor's raw-api MCP endpoint)# GILDATA_SRV_TOOL_URL=xxx # optional override of the vendor's 标准版 NL research endpoint (powers get_cn_macro_series / get_cn_announcements / search_broker_reports)# TICKERALL_API_KEY=xxx # optional hosted MetaTrader 5 forex/metals feed — EXPLICIT source="tickerall" only, never an automatic fallback (no local terminal; https://tickerall.com)diff --git a/agent/src/skills/data-routing/SKILL.md b/agent/src/skills/data-routing/SKILL.mdindex 92890ae6e..8b2aacd60 100644--- a/agent/src/skills/data-routing/SKILL.md+++ b/agent/src/skills/data-routing/SKILL.md@@ -74,6 +74,7 @@ is required only where listed (no key listed = free / no auth).| CN announcements (公告检索) | `get_cn_announcements` | A-share / HK / fund | `GILDATA_TOKEN` || Broker research (券商研报) | `search_broker_reports` | A-share / HK | `GILDATA_TOKEN` || Mixed financial/operating and market-data queries for one known security | `gildata_fin_query` | Vendor-supported securities | `GILDATA_TOKEN` |+| Stock screening / Top-N ranking with cross-period indicators in one query | `gildata_stock_selection` | Vendor-supported stocks | `GILDATA_TOKEN` || iWenCai NL search (问财) | `iwencai_search` | A-share | `VIBE_TRADING_IWENCAI_KEY` |Notes:diff --git a/agent/src/tools/gildata_fin_query_tool.py b/agent/src/tools/gildata_fin_query_tool.pyindex b9a531ce0..c41f93580 100644--- a/agent/src/tools/gildata_fin_query_tool.py+++ b/agent/src/tools/gildata_fin_query_tool.py@@ -65,7 +65,7 @@ def _normalize_table(table: dict[str, Any], table_index: int) -> dict[str, Any]:label = columns.get(field, "")target = renames.get(field, field)leaf = None- if re.search(r"代码|内码", label):+ if re.search(r"代码|内码|编码", label) or field.casefold() == "innercode":converted[target] = str(value) if value is not None else Nonecontinuenumber = _numeric(value)diff --git a/agent/src/tools/gildata_research_tools.py b/agent/src/tools/gildata_research_tools.pyindex d7e41109b..8152543ff 100644--- a/agent/src/tools/gildata_research_tools.py+++ b/agent/src/tools/gildata_research_tools.py@@ -13,10 +13,8 @@ picked for value the project does not already cover:search over the Juyuan report library (deeper metadata than the existingeastmoney-backed ``get_research_reports``; both coexist).-Deliberately NOT wrapped (overlap with existing tools): news-(``get_stock_news``/``web_search``), screening (``screen_market`` /-``iwencai_search``), fund/manager selection, the generic ``FinQuery`` and the-``FinDataFallbackQuery`` catch-all.+Separate modules wrap FinQuery and SmartStockSelection. Existing news and+screening sources remain available alongside them.The agent authors the natural-language ``query``; the server routes it. Therouted ``api_names`` are echoed in every envelope so a mis-routed question isdiff --git a/agent/src/tools/gildata_srv.py b/agent/src/tools/gildata_srv.pyindex e945019c8..6f077d9c2 100644--- a/agent/src/tools/gildata_srv.py+++ b/agent/src/tools/gildata_srv.py@@ -40,13 +40,15 @@ def _url() -> str:return f"{base}{'&' if '?' in base else '?'}format=json"-def call_srv_tool_results(name: str, query: str, *, timeout: float = _TIMEOUT_S) -> list[dict[str, Any]]:+def call_srv_tool_results(name: str, query: str, *, timeout: float = _TIMEOUT_S,+ topk: int | None = None) -> list[dict[str, Any]]:"""Invoke one srv-tool query, preserving each result table and its metadata.Args:name: Tool name, e.g. ``"MacroIndustryData"``.query: Natural-language question (authored by the agent).timeout: Per-request socket timeout; NL research calls are slow.+ topk: Optional vendor-side screening result count.Returns:The vendor's result tables, without flattening their columns or rows.@@ -70,6 +72,8 @@ def call_srv_tool_results(name: str, query: str, *, timeout: float = _TIMEOUT_S)"method": "tools/call","params": {"name": name, "arguments": {"query": query}},}+ if topk is not None:+ payload["params"]["arguments"]["topk"] = topkouter = throttled_post_json(url,host_key=_HOST_KEY,diff --git a/agent/src/tools/gildata_stock_selection_tool.py b/agent/src/tools/gildata_stock_selection_tool.pynew file mode 100644index 000000000..d197d89d1--- /dev/null+++ b/agent/src/tools/gildata_stock_selection_tool.py@@ -0,0 +1,60 @@+"""Optional Gildata screening with cross-period metrics in the same request."""+from __future__ import annotations++import json+from typing import Any++from src.agent.tools import BaseTool+from src.config.accessor import get_env_config+from src.tools.gildata_fin_query_tool import _normalize_table+from src.tools.gildata_srv import call_srv_tool_results+++class GildataStockSelectionTool(BaseTool):+ """Screen and enrich vendor-selected stocks without client-side query splitting."""++ name = "gildata_stock_selection"+ description = (+ "Gildata/聚源 stock screening and Top-N ranking within a stock universe. "+ "A single natural-language query can select stocks and return additional "+ "financial, valuation or market indicators across multiple report periods. "+ "Example: 沪深300权重最高的10只成分股及2023、2024年全年营业收入. "+ "Use gildata_fin_query for attribute/history queries without screening. "+ "Requires GILDATA_TOKEN; read-only."+ )+ parameters = {+ "type": "object",+ "properties": {+ "query": {"type": "string", "description": "Full question including universe, selection/ranking criteria and requested indicators and periods."},+ "topk": {"type": "integer", "description": "Optional result count; positive integer, or -1 only when all results are explicitly requested."},+ },+ "required": ["query"],+ }+ repeatable = True++ @classmethod+ def check_available(cls) -> bool:+ return get_env_config().data.gildata_token.strip() not in {"", "your-gildata-token"}++ def execute(self, **kwargs: Any) -> str:+ if not self.check_available():+ return json.dumps({"ok": False, "error_type": "not_configured", "error": "GILDATA_TOKEN is not configured"})+ query, topk = kwargs.get("query"), kwargs.get("topk")+ if not isinstance(query, str) or not 1 <= len(query.strip()) <= 4000:+ return json.dumps({"ok": False, "error_type": "invalid_query", "error": "query must contain 1 to 4000 characters"})+ if topk is not None and (type(topk) is not int or topk == 0 or topk < -1):+ return json.dumps({"ok": False, "error_type": "invalid_topk", "error": "topk must be a positive integer or -1"})+ try:+ results = call_srv_tool_results("SmartStockSelection", query.strip(), **({"topk": topk} if topk is not None else {}))+ except Exception:+ return json.dumps({"ok": False, "source": "gildata", "error_type": "service_error",+ "error": "Stock selection request failed. Check service access and query scope."})+ try:+ tables = [_normalize_table(table, index) for index, table in enumerate(results)]+ return json.dumps({"ok": True, "source": "gildata", "vendor_tool": "SmartStockSelection",+ "query": query.strip(), "data": {"tables": tables},+ "has_data": any(table["rows"] for table in tables)},+ ensure_ascii=False, allow_nan=False, indent=2)+ except (ValueError, TypeError, OverflowError):+ return json.dumps({"ok": False, "source": "gildata", "error_type": "unsupported_data",+ "error": "Unsupported stock selection data; no alternate source was called."})diff --git a/agent/tests/test_gildata_stock_selection.py b/agent/tests/test_gildata_stock_selection.pynew file mode 100644index 000000000..eec8e35db--- /dev/null+++ b/agent/tests/test_gildata_stock_selection.py@@ -0,0 +1,113 @@+"""Screening preserves vendor ranking, periods and existing grounding contracts."""+import copy+import json+from unittest.mock import Mock, patch++import pytest++from src.agent.grounding import GroundingLedger+from src.tools import gildata_stock_selection_tool as ss+from src.tools import gildata_srv+++def vendor(monkeypatch):+ monkeypatch.setenv("GILDATA_TOKEN", "test-token")+ call = Mock(return_value=[{+ "api_name": "智能选股",+ "columns": {"secucode": "证券代码", "secuabbr": "证券简称", "id": "证券编码",+ "rev_a": "营业收入(亿元)<[报告期]:2022-12-31><[单位]:亿元>",+ "rev_b": "营业收入(万元)<[报告期]:2025-12-31><[单位]:万元>",+ "weight": "指数成分股权重(%)<[截止日期]:NewestTradingDay()>"},+ "rows": [{"secucode": "600000.SH", "secuabbr": "甲", "id": "000001", "innercode": 77,+ "rev_a": 12.34, "rev_b": 567.89, "weight": 3.4},+ {"secucode": "000001.SZ", "secuabbr": "乙", "id": "000002", "innercode": 88,+ "rev_a": None, "rev_b": 432.1, "weight": 2.3}],+ }])+ monkeypatch.setattr(ss, "call_srv_tool_results", call)+ return call+++def execute(**kwargs):+ return json.loads(ss.GildataStockSelectionTool().execute(**{"query": "完整筛选问题", **kwargs}))++[email protected]("token", ["", " ", "your-gildata-token"])+def test_unconfigured_not_available_or_called(vendor, monkeypatch, token):+ monkeypatch.setenv("GILDATA_TOKEN", token)+ assert not ss.GildataStockSelectionTool.check_available()+ assert execute()["error_type"] == "not_configured"+ vendor.assert_not_called()++[email protected]("query", [None, " ", 123, "x" * 4001])+def test_invalid_query_not_sent(vendor, query):+ assert execute(query=query)["error_type"] == "invalid_query"+ vendor.assert_not_called()++[email protected]("topk", [0, -2, True, "10", 2.5])+def test_invalid_topk_not_sent(vendor, topk):+ assert execute(topk=topk)["error_type"] == "invalid_topk"+ vendor.assert_not_called()++[email protected]("topk", [None, 7, -1])+def test_one_unsplit_question_and_optional_vendor_topk(vendor, topk):+ q = " 指数权重最高的股票及两个报告期的营收 "+ assert execute(query=q, topk=topk)["ok"]+ vendor.assert_called_once_with("SmartStockSelection", q.strip(), **({"topk": topk} if topk is not None else {}))+++def test_periods_order_nulls_and_identifiers_preserved(vendor):+ original = copy.deepcopy(vendor.return_value)+ table = execute()["data"]["tables"][0]+ assert table["columns"] == original[0]["columns"]+ assert [r["secucode"] for r in table["rows"]] == ["600000.SH", "000001.SZ"]+ row = table["rows"][0]+ assert row["rev_a"]["amount"] == 1234000000+ assert row["rev_b"]["display"] == "567.89万元"+ assert row["weight"]["percent"] == 3.4+ assert row["id"] == "000001" and row["innercode"] == "77"+ assert table["rows"][1]["rev_a"] is None+ assert vendor.return_value == original+++def test_real_ledger_checks_each_period_and_stock_path(vendor, tmp_path):+ ledger = GroundingLedger(run_dir=tmp_path, user_message="筛选股票及历史营业收入")+ ledger.ingest_tool_result(tool_name="gildata_stock_selection", arguments={"query": "完整筛选问题"},+ result=json.dumps(execute()), call_id="screen1", success=True)+ def check(field):+ return ledger.validate_final_answer(+ "营业收入12.34亿元。\n```figures\n"+ f"12.34亿元 | observed | 营业收入 | screen1::data.tables[0].rows[0].{field}.amount\n```")+ assert check("rev_a").valid+ assert not check("rev_b").valid+ assert not any(r.field.endswith((".innercode", ".id")) for r in ledger._evidence)+++def test_errors_empty_and_unsupported_responses(vendor):+ vendor.side_effect = RuntimeError("secret-token")+ result = execute()+ assert result["error_type"] == "service_error" and "secret-token" not in json.dumps(result)+ vendor.side_effect = None+ vendor.return_value = []+ assert execute()["has_data"] is False+ vendor.return_value = [{"api_name": "智能选股", "table_markdown": "unstructured"}]+ assert execute()["error_type"] == "unsupported_data"+++def test_transport_includes_topk_only_when_supplied(vendor):+ raw = {"result": {"content": [{"type": "text", "text": json.dumps({"code": 0, "results": vendor.return_value})}]}}+ with patch.object(gildata_srv, "throttled_post_json", return_value=raw) as post:+ for kwargs in [{}, {"topk": 7}, {"topk": -1}]:+ gildata_srv.call_srv_tool_results("SmartStockSelection", "完整筛选问题", **kwargs)+ assert post.call_args.kwargs["json_body"]["params"]["arguments"] == {"query": "完整筛选问题", **kwargs}+++def test_discovered_alongside_iwencai(monkeypatch):+ from src import tools+ from src.tools.iwencai_tool import IWenCaiSearchTool+ monkeypatch.setattr(tools, "_SUBCLASSES_CACHE", None)+ classes = tools._discover_subclasses()+ assert ss.GildataStockSelectionTool in classes and IWenCaiSearchTool in classes