Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(gildata): add optional stock candidates to symbol search

tangwj46958a04fe0e103bc
diff --git a/agent/backtest/loaders/gildata_loader.py b/agent/backtest/loaders/gildata_loader.py
index 5651326e0..4f33442fc 100644
--- a/agent/backtest/loaders/gildata_loader.py
+++ b/agent/backtest/loaders/gildata_loader.py
@@ -152,17 +152,16 @@ def _gildata_symbol(code: str) -> Optional[str]:
return None
-def _call_tool(tool: str, arguments: Dict[str, Any]) -> Any:
- """Invoke one MCP tool and return its first result entry.
+def _call_tool_results(tool: str, arguments: Dict[str, Any]) -> list[dict[str, Any]]:
+ """Invoke one MCP tool and retain every result entry.
Args:
tool: Tool name, e.g. ``"StockDailyQuote"``.
arguments: Structured tool arguments.
Returns:
- The first ``results`` entry dict (``{"api_name", "columns", "rows",
- ...}``) — quote tools carry ``rows`` there, the recall meta-tool
- carries ``candidates``. Empty dict when the vendor reports no results.
+ All ``results`` entries. Quote tools carry ``rows``; the recall
+ meta-tool carries ``candidates``. Empty list for no results.
Raises:
RuntimeError: If the token is missing, or the vendor answers with a
@@ -199,7 +198,12 @@ def _call_tool(tool: str, arguments: Dict[str, Any]) -> Any:
timeout=_TIMEOUT_S,
)
- results = _response_results(outer)
+ return _response_results(outer)
+
+
+def _call_tool(tool: str, arguments: Dict[str, Any]) -> Any:
+ """Preserve the single-resource contract of existing quote callers."""
+ results = _call_tool_results(tool, arguments)
if len(results) > 1:
raise ValueError("gildata raw-api returned multiple results for one resource; refusing a partial series")
return results[0] if results else {}
diff --git a/agent/src/tools/gildata_identity.py b/agent/src/tools/gildata_identity.py
new file mode 100644
index 000000000..433af094b
--- /dev/null
+++ b/agent/src/tools/gildata_identity.py
@@ -0,0 +1,40 @@
+"""Optional Gildata stock candidates for the existing symbol resolver."""
+import re
+
+from backtest.loaders.gildata_loader import _call_tool_results
+from src.config.accessor import get_env_config
+
+
+def search_candidates(query: str, limit: int) -> tuple[list[dict], str | None]:
+ if get_env_config().data.gildata_token.strip() in {"", "your-gildata-token"}:
+ return [], None
+ domains = {"StockDailyQuote": "a", "HKStockDailyQuotes": "hk", "USStockDailyQuotes": "us"}
+ keyword = query[:-3] if query.upper().endswith(".US") else query
+ try:
+ results = _call_tool_results("ParamCandidateRecall", {"recall_list": [
+ {"api_name": api, "param_name": "stockObject", "keyword": keyword, "top_k": limit}
+ for api in domains
+ ]})
+ candidates = []
+ for result in results:
+ market = domains.get(result.get("api_name"))
+ for row in result.get("candidates", []):
+ ref = str(row.get("ref_code") or "").upper()
+ if market == "a" and re.fullmatch(r"\d{6}\.(?:SH|SZ|BJ)", ref):
+ symbol = ref
+ elif market == "hk" and re.fullmatch(r"\d{3,5}\.HK", ref):
+ symbol = ref.split(".")[0].zfill(5) + ".HK"
+ elif market == "us" and re.fullmatch(r"[A-Z][A-Z0-9.\-]*\.[A-Z]+", ref):
+ symbol = ref.rsplit(".", 1)[0] + ".US"
+ else:
+ continue
+ candidates.append({"symbol": symbol, "name": row.get("caption"), "market": market,
+ "type": "equity", "source": "gildata",
+ "vendor_code": row.get("code"), "vendor_ref_code": ref})
+ # Exact matches take precedence over fuzzy recall, retaining every venue.
+ exact = [c for c in candidates if query.casefold() in {
+ str(c["name"]).casefold(), c["symbol"].casefold(), c["symbol"].split(".")[0].casefold()}]
+ return (exact or candidates), "ok"
+ except Exception:
+ # Do not expose authenticated URLs, response bodies or credentials.
+ return [], "gildata recall failed; check service access and quota"
diff --git a/agent/src/tools/symbol_search_tool.py b/agent/src/tools/symbol_search_tool.py
index ff3d99708..a2270736a 100644
--- a/agent/src/tools/symbol_search_tool.py
+++ b/agent/src/tools/symbol_search_tool.py
@@ -364,6 +364,16 @@ class SymbolSearchTool(BaseTool):
== query.strip().upper()
]
+ if (crypto_pair is None and _metal_or_fx_legs(query) is None
+ and not query.strip().upper().endswith("=F")
+ and not query.startswith("^") and not _is_canadian_symbol(query)):
+ from src.tools.gildata_identity import search_candidates
+
+ gildata_hits, gildata_status = search_candidates(query, limit)
+ if gildata_status is not None:
+ sources["gildata"] = gildata_status
+ candidates.extend(gildata_hits)
+
# Canada fail-fast: a Canadian ticker must resolve to the Canadian venue
# only. Yahoo also returns the US OTC alias of the same company (e.g.
# ``BYN.V`` -> ``BYAGF.US``), which would make the grounding ledger see
diff --git a/agent/tests/test_gildata_identity.py b/agent/tests/test_gildata_identity.py
new file mode 100644
index 000000000..6f170ad97
--- /dev/null
+++ b/agent/tests/test_gildata_identity.py
@@ -0,0 +1,86 @@
+"""Optional recall must preserve resolver identity and other sources."""
+import json
+from unittest.mock import Mock
+
+import pytest
+
+from src.agent.grounding import GroundingLedger
+from src.tools import gildata_identity as gi
+from src.tools import symbol_search_tool as ss
+
+
+def recall(monkeypatch):
+ monkeypatch.setenv("GILDATA_TOKEN", "test-token")
+ fn = Mock(return_value=[
+ {"api_name": "StockDailyQuote", "candidates": [
+ {"caption": "测试公司", "ref_code": "600000.SH", "code": "internal"},
+ {"caption": "其他公司", "ref_code": "600001.SH"},
+ {"caption": "未上市", "ref_code": "X12345.SH"}]},
+ {"api_name": "HKStockDailyQuotes", "candidates": [
+ {"caption": "测试公司", "ref_code": "700.HK", "code": "hk-internal"}]},
+ ])
+ monkeypatch.setattr(gi, "_call_tool_results", fn)
+ monkeypatch.setattr(ss, "_search_selected_connector", lambda *a: ([], None, None))
+ monkeypatch.setattr(ss, "_search_eastmoney", lambda *a: ([], "ok"))
+ monkeypatch.setattr(ss, "_search_yahoo", lambda *a: ([], "unavailable"))
+ monkeypatch.setattr(ss, "_enrich_us_cik", lambda x: (x, ss._NO_US))
+ return fn
+
+
[email protected]("token", ["", "your-gildata-token"])
+def test_no_token_does_not_change_sources(recall, monkeypatch, token):
+ monkeypatch.setenv("GILDATA_TOKEN", token)
+ out = json.loads(ss.SymbolSearchTool().execute(query="测试公司"))
+ assert "gildata" not in out["data"]["sources"]
+ recall.assert_not_called()
+
+
+def test_all_exact_venues_survive_and_remain_ambiguous(recall, tmp_path):
+ raw = ss.SymbolSearchTool().execute(query="测试公司")
+ data = json.loads(raw)["data"]
+ assert [c["symbol"] for c in data["candidates"]] == ["600000.SH", "00700.HK"]
+ assert data["candidates"][0]["vendor_code"] == "internal"
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="测试公司")
+ ledger.ingest_tool_result(tool_name="search_symbol", arguments={"query": "测试公司"},
+ call_id="search1", result=raw, success=True)
+ assert ledger.identity_status == "ambiguous"
+
+
+def test_unique_name_locks_with_original_gate(recall, tmp_path):
+ recall.return_value = recall.return_value[:1]
+ raw = ss.SymbolSearchTool().execute(query="测试公司")
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="测试公司")
+ ledger.ingest_tool_result(tool_name="search_symbol", arguments={"query": "测试公司"},
+ call_id="search1", result=raw, success=True)
+ assert ledger.identity_status == "locked"
+ assert ledger.authorized_symbols == {"600000.SH"}
+
+
+def test_failure_keeps_original_source_candidates(recall, monkeypatch):
+ recall.side_effect = RuntimeError("secret-token")
+ monkeypatch.setattr(ss, "_search_eastmoney", lambda *a: ([
+ {"symbol": "600001.SH", "name": "其他公司", "source": "eastmoney"}], "ok"))
+ raw = ss.SymbolSearchTool().execute(query="其他公司")
+ out = json.loads(raw)["data"]
+ assert out["candidates"][0]["symbol"] == "600001.SH"
+ assert out["sources"]["eastmoney"] == "ok"
+ assert "failed" in out["sources"]["gildata"] and "secret-token" not in raw
+
+
+def test_deduplicates_without_replacing_public_provider(recall, monkeypatch):
+ monkeypatch.setattr(ss, "_search_eastmoney", lambda *a: ([
+ {"symbol": "600000.SH", "name": "测试公司", "source": "eastmoney"}], "ok"))
+ out = json.loads(ss.SymbolSearchTool().execute(query="测试公司"))["data"]
+ hits = [c for c in out["candidates"] if c["symbol"] == "600000.SH"]
+ assert len(hits) == 1 and hits[0]["source"] == "eastmoney"
+ assert "gildata" in hits[0]["also_from"]
+
+
+def test_us_vendor_suffix_is_not_project_suffix(recall):
+ recall.return_value = [{"api_name": "USStockDailyQuotes", "candidates": [
+ {"caption": "Apple", "ref_code": "AAPL.N", "code": "us-internal"}]}]
+ hits, status = gi.search_candidates("AAPL.US", 5)
+ assert status == "ok" and hits[0]["symbol"] == "AAPL.US"
+ assert hits[0]["vendor_ref_code"] == "AAPL.N"
+ assert recall.call_args.args[1]["recall_list"][0]["keyword"] == "AAPL"