Skip to content

"Vibe-Trading: Your Personal Trading Agent"

Merge PR #2082: decode JSONP and recover fingerprint-filtered news

Haozhe Wu0ac28b3ccc3b
diff --cc CHANGELOG.md
index 98c0cd60f,34ce2f85b..0d831572f
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -7,20 -7,13 +7,27 @@@ This project adheres to [Semantic Versi
### Fixed
+- **Forex symbol detection** no longer depends on AKShare's module layout:
+ `akshare.forex` was deleted in 1.20.0 and the symbol map moved to
+ `akshare.fx.cons_forex`, so the single hard-coded import turned every FX pair
+ into an A-share lookup. Both layouts are now probed, and a wholly missing map
+ degrades to "not a forex pair" instead of silently matching nothing.
+- **Bare US ETF and fund symbols** such as `QQQ` and `SPY` now resolve to
+ `QQQ.US` / market `us` instead of a suffix-less `global` candidate. The fetch
+ layer already routed bare US tickers as US equities, so the resolver was the
+ only place that disagreed: the identity lock then rejected the follow-up call
+ ("consumer symbol/venue differs from the locked resolver identity"). ETFs and
+ mutual funds on non-US venues keep their native form (#2084).
+- **`etf_holdings` accepts the `.US` market suffix** on US symbols, so the
+ identity locked as `QQQ.US` still reaches the SEC series/class ticker `QQQ`
+ instead of being reported as an unknown share class.
+ - **JSONP-wrapped provider bodies** decode instead of raising: the throttled
+ JSON GET helper unwraps a `callback(...)` envelope when `response.json()`
+ cannot parse the body, so A-share news search keeps working when Eastmoney
+ switches to JSONP (#2081).
+ - **Degraded Eastmoney news indexes** now raise an actionable error instead of
+ reading as an empty article list: the Guba user index (`passportWeb`) can no
+ longer masquerade as "this stock has no news" (#2081).
- **Global futures routing and pricing**: digit-bearing contracts such as
`M2K=F` and `6EZ2026.CME`, including `local:` inputs, reach the global
futures engine with their full product code. OJ and ZR use quote-unit
diff --cc agent/backtest/loaders/_http.py
index 89fe6ab42,9443d629f..cab42439b
--- a/agent/backtest/loaders/_http.py
+++ b/agent/backtest/loaders/_http.py
@@@ -197,9 -243,15 +243,49 @@@ def throttled_get_json
timeout=timeout,
)
response.raise_for_status()
- return response.json()
+ try:
+ return response.json()
+ except ValueError:
+ decoded = decode_jsonp_body(response.text)
+ if decoded is None:
+ raise
+ return decoded
+
+
++def throttled_browser_get_json(
++ url: str, *, host_key: str, min_interval: float,
++ params: dict[str, Any] | None = None, timeout: float = 15.0,
++) -> Any:
++ """Retry a fingerprint-filtered public GET through the same host throttle.
++
++ Args:
++ url: Public provider endpoint.
++ host_key: Shared throttle bucket, also used by the plain client.
++ min_interval: Minimum spacing between requests to this provider.
++ params: Query parameters.
++ timeout: Bounded request timeout in seconds.
++
++ Returns:
++ Decoded JSON or JSONP payload.
++
++ Raises:
++ RuntimeError: Optional browser transport is unavailable.
++ ValueError: The response is not JSON or JSONP.
++ """
++ try:
++ from curl_cffi import requests as browser_requests
++ except ImportError as exc:
++ raise RuntimeError("Eastmoney filtered the client TLS fingerprint; install curl_cffi to enable the browser transport.") from exc
++ _THROTTLE.wait(host_key, min_interval)
++ with browser_requests.Session(impersonate="chrome") as session:
++ response = session.get(url, params=params, timeout=timeout)
++ response.raise_for_status()
++ decoded = decode_jsonp_body(response.text)
++ if decoded is None:
++ raise ValueError("Browser transport returned neither JSON nor JSONP")
++ return decoded
+
+
def throttled_post_json(
url: str,
*,
diff --cc agent/backtest/loaders/eastmoney_client.py
index 67093a131,d17d435f6..0816a08d8
--- a/agent/backtest/loaders/eastmoney_client.py
+++ b/agent/backtest/loaders/eastmoney_client.py
@@@ -20,12 -20,14 +20,15 @@@ Eastmoney addresses every instrument b
from __future__ import annotations
- import json
import logging
- import re
from typing import Any
- from backtest.loaders._http import resolve_min_interval, throttled_get_json
+ from backtest.loaders._http import (
+ decode_jsonp_body,
+ resolve_min_interval,
++ throttled_browser_get_json,
+ throttled_get_json,
+ )
logger = logging.getLogger(__name__)
@@@ -109,12 -102,12 +103,13 @@@ def _min_interval() -> float
return resolve_min_interval(_MIN_INTERVAL_ENV, _DEFAULT_MIN_INTERVAL)
--def get_json(url: str, *, params: dict[str, Any]) -> Any:
++def get_json(url: str, *, params: dict[str, Any], browser: bool = False) -> Any:
"""Issue a throttled Eastmoney GET and decode the body as JSON.
Args:
url: Fully-qualified Eastmoney endpoint URL.
params: Query parameters for the request.
++ browser: Use the optional Chrome TLS transport for a filtered retry.
Returns:
The decoded JSON payload (typically a ``dict``).
@@@ -125,7 -118,7 +120,8 @@@
requests.HTTPError: Non-2xx response status.
ValueError: Body is not valid JSON.
"""
-- return throttled_get_json(
++ getter = throttled_browser_get_json if browser else throttled_get_json
++ return getter(
url,
host_key=_HOST_KEY,
min_interval=_min_interval(),
diff --cc agent/src/tools/stock_news_tool.py
index 24efdcb35,c25471dbe..b3a8883fa
--- a/agent/src/tools/stock_news_tool.py
+++ b/agent/src/tools/stock_news_tool.py
@@@ -181,9 -182,9 +182,10 @@@ def _fetch_eastmoney_news(query: str, l
},
ensure_ascii=False,
)
++ params = {"cb": "", "param": param, "_": "0"}
payload = eastmoney_client.get_json(
_EM_NEWS_URL,
-- params={"cb": "", "param": param, "_": "0"},
++ params=params,
)
decoded = _decode_jsonp(payload)
if not isinstance(decoded, dict):
@@@ -193,6 -194,16 +195,23 @@@
return []
articles = result.get("cmsArticleWebOld")
if not isinstance(articles, list):
+ # Eastmoney swaps the CMS article index for its Guba user index
+ # ("passportWeb") when it distrusts the caller, so a degraded answer is
+ # shaped like a valid but empty one. Reading it as ``[]`` would turn a
+ # blocked upstream into a silent "no news for this stock" (#2081).
+ if result:
++ # Retry once with a browser TLS fingerprint, through the SAME
++ # provider throttle. A genuine empty CMS list never reaches here.
++ retry = eastmoney_client.get_json(_EM_NEWS_URL, params=params, browser=True)
++ retry = _decode_jsonp(retry)
++ result = retry.get("result", {}) if isinstance(retry, dict) else {}
++ if isinstance(result, dict) and isinstance(result.get("cmsArticleWebOld"), list):
++ return [_em_article(a) for a in result["cmsArticleWebOld"] if isinstance(a, dict)][:limit]
+ raise ValueError(
+ "eastmoney returned no cmsArticleWebOld section "
- f"(result keys: {sorted(result)}): the search index was degraded,"
- " most likely anti-bot filtering of this network"
++ f"(result keys: {sorted(result) if isinstance(result, dict) else []}):"
++ " the search index remained degraded after the browser TLS retry"
+ )
return []
return [_em_article(a) for a in articles if isinstance(a, dict)][:limit]
diff --cc agent/tests/test_http_jsonp_fallback.py
index 000000000,6f7b20e4b..7f9697e96
mode 000000,100644..100644
--- a/agent/tests/test_http_jsonp_fallback.py
+++ b/agent/tests/test_http_jsonp_fallback.py
@@@ -1,0 -1,67 +1,96 @@@
+ """Tests for the JSONP fallback in the throttled JSON GET helper.
+
+ Eastmoney's search endpoints answer with a ``callback(...)`` envelope instead of
+ a JSON body when they distrust the caller (see issue #2081), which
+ ``response.json()`` cannot parse. These tests pin the fallback at the HTTP
+ boundary so every caller of :func:`backtest.loaders._http.throttled_get_json`
+ benefits, and pin that a genuinely malformed body keeps raising.
+
+ No request leaves the process: :func:`backtest.loaders._http.throttled_get` is
+ mocked with a stand-in response object.
+ """
+
+ from __future__ import annotations
+
+ import json
+ from typing import Any
+ from unittest.mock import patch
+
+ import pytest
+
+ from backtest.loaders import _http
+
+
+ class _FakeResponse:
+ """Minimal stand-in for ``requests.Response`` at the HTTP boundary."""
+
+ def __init__(self, body: str) -> None:
+ self.text = body
+
+ def raise_for_status(self) -> None:
+ """No-op: these tests never model a non-2xx status."""
+
+ def json(self) -> Any:
+ """Mimic ``requests``: undecodable bodies raise ``ValueError``."""
+ return json.loads(self.text)
+
+
+ def _call(body: str) -> Any:
+ """Run ``throttled_get_json`` against a canned response body."""
+ with patch.object(_http, "throttled_get", return_value=_FakeResponse(body)):
+ return _http.throttled_get_json(
+ "https://search-api-web.eastmoney.com/search/jsonp",
+ host_key="eastmoney",
+ min_interval=0,
+ params={"cb": ""},
+ )
+
+
+ class TestJsonpFallback:
+ def test_jsonp_envelope_is_decoded(self) -> None:
+ body = 'jQuery3700123_456({"code": 0, "result": {"hitsTotal": 1}})'
+ assert _call(body) == {"code": 0, "result": {"hitsTotal": 1}}
+
+ def test_dotted_callback_identifier_is_decoded(self) -> None:
+ body = 'window.jQuery.cb({"code": 0});'
+ assert _call(body) == {"code": 0}
+
+ def test_plain_json_still_parses(self) -> None:
+ assert _call('{"code": 0, "result": {}}') == {"code": 0, "result": {}}
+
+ def test_plain_json_with_parens_in_values_is_not_mangled(self) -> None:
+ body = '{"title": "公司(600519)发布三季报(更新)"}'
+ assert _call(body) == {"title": "公司(600519)发布三季报(更新)"}
+
+ def test_unparseable_body_still_raises(self) -> None:
+ with pytest.raises(ValueError):
+ _call("<html>blocked</html>")
++
++
++def test_browser_transport_obeys_the_same_throttle_and_decodes_jsonp(monkeypatch):
++ from curl_cffi import requests
++
++ calls = []
++
++ class Session:
++ def __init__(self, **kwargs):
++ assert kwargs == {"impersonate": "chrome"}
++
++ def __enter__(self):
++ return self
++
++ def __exit__(self, *args):
++ pass
++
++ def get(self, url, **kwargs):
++ calls.append((url, kwargs))
++ return _FakeResponse('callback({"result":{"cmsArticleWebOld":[]}})')
++
++ monkeypatch.setattr(requests, "Session", Session)
++ waits = []
++ monkeypatch.setattr(_http._THROTTLE, "wait", lambda *args: waits.append(args))
++ assert _http.throttled_browser_get_json("https://example.invalid/news", host_key="eastmoney", min_interval=0.5) == {
++ "result": {"cmsArticleWebOld": []}
++ }
++ assert waits == [("eastmoney", 0.5)]
++ assert calls[0][1]["timeout"] == 15.0
diff --cc agent/tests/test_stock_news_tool.py
index 1e8a176b9,f5a11d3f8..95b8194e4
--- a/agent/tests/test_stock_news_tool.py
+++ b/agent/tests/test_stock_news_tool.py
@@@ -243,3 -243,36 +243,66 @@@ class TestExecuteError
assert out["ok"] is False
assert "yahoo 429" in out["error"]
assert "yahoo news fetch failed" in out["error"]
+
+
+ class TestEastmoneyDegradedIndex:
+ """A degraded Eastmoney answer must not read as "this stock has no news".
+
+ Eastmoney serves its Guba user index (``passportWeb``) instead of the CMS
+ article index when it distrusts the caller, and that degraded answer is
+ shaped like a valid but empty one (see issue #2081).
+ """
+
+ def test_degraded_user_index_raises_instead_of_empty(self) -> None:
+ payload = {"code": 0, "result": {"passportWeb": [], "userWeb": []}}
- with patch.object(eastmoney_client, "throttled_get_json", return_value=payload):
++ with patch.object(eastmoney_client, "throttled_get_json", return_value=payload), patch.object(
++ eastmoney_client, "throttled_browser_get_json", return_value=payload
++ ):
+ out = json.loads(StockNewsTool().execute(code="600519.SH"))
+
+ assert out["ok"] is False
+ assert "degraded" in out["error"]
+
+ def test_empty_cms_section_is_a_clean_empty_result(self) -> None:
+ payload = {"code": 0, "result": {"cmsArticleWebOld": []}}
+ with patch.object(eastmoney_client, "throttled_get_json", return_value=payload):
+ out = json.loads(StockNewsTool().execute(code="600519.SH"))
+
+ assert out["ok"] is True
+ assert out["data"]["articles"] == []
+
+ def test_jsonp_enveloped_body_is_parsed_into_articles(self) -> None:
+ body = "jQuery3700123_456(" + json.dumps(_em_news_payload(), ensure_ascii=False) + ")"
+ with patch.object(eastmoney_client, "throttled_get_json", return_value=body):
+ out = json.loads(StockNewsTool().execute(code="600519.SH"))
+
+ assert out["ok"] is True
+ assert len(out["data"]["articles"]) == 2
++
++ def test_filtered_plain_client_recovers_through_one_browser_retry(self) -> None:
++ filtered = {"result": {"passportWeb": []}}
++ with patch.object(eastmoney_client, "throttled_get_json", return_value=filtered), patch.object(
++ eastmoney_client, "throttled_browser_get_json", return_value=_em_news_payload()
++ ) as browser:
++ out = json.loads(StockNewsTool().execute(code="600519.SH"))
++ assert out["ok"] is True
++ assert len(out["data"]["articles"]) == 2
++ browser.assert_called_once()
++ assert browser.call_args.kwargs["host_key"] == eastmoney_client._HOST_KEY
++
++ def test_genuine_empty_news_does_not_invoke_browser_transport(self) -> None:
++ with patch.object(eastmoney_client, "throttled_get_json", return_value={"result": {"cmsArticleWebOld": []}}), patch.object(
++ eastmoney_client, "throttled_browser_get_json"
++ ) as browser:
++ out = json.loads(StockNewsTool().execute(code="600519.SH"))
++ assert out["ok"] is True
++ assert out["data"]["articles"] == []
++ browser.assert_not_called()
++
++ def test_unavailable_browser_retry_is_an_error_not_empty_news(self) -> None:
++ with patch.object(eastmoney_client, "throttled_get_json", return_value={"result": {"passportWeb": []}}), patch.object(
++ eastmoney_client, "throttled_browser_get_json", side_effect=RuntimeError("install curl_cffi")
++ ):
++ out = json.loads(StockNewsTool().execute(code="600519.SH"))
++ assert out["ok"] is False
++ assert "install curl_cffi" in out["error"]