stock-analysis-plugin 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -236,7 +236,7 @@ Agent 会自动调用行情 → 技术面 → 基本面 → 资金面 → 消息
236
236
  | 工具 | 说明 |
237
237
  |------|------|
238
238
  | `get_kline` | K 线数据(OHLCV),支持日/周/月线 |
239
- | `get_quote` | 实时行情快照 |
239
+ | `get_quote` | 实时行情快照(非交易时段返回最近交易日收盘价并以 as_of/stale 标注) |
240
240
  | `get_capital_flow` | 资金流向(仅 A 股) |
241
241
  | `get_news` | 个股相关新闻 |
242
242
  | `get_financials` | 财务指标 |
@@ -247,8 +247,8 @@ Agent 会自动调用行情 → 技术面 → 基本面 → 资金面 → 消息
247
247
  | `get_sector_constituents` | 板块成分股查询(仅 A 股,板块名模糊匹配) |
248
248
  | `resolve_stock_sectors` | 个股所属板块查询(A 股行业+概念 / 港股 GICS) |
249
249
  | `get_market_stats` | 市场统计(涨跌家数、涨停等) |
250
- | `get_limit_up_pool` | 涨停池/涨停板复盘(连板数、封板资金、炸板次数等,仅 A 股) |
251
- | `get_dragon_tiger` | 龙虎榜(净买额/上榜原因/解读,仅 A 股) |
250
+ | `get_limit_up_pool` | 涨停池/涨停板复盘(连板数、封板资金、炸板次数等,仅 A 股;非交易日自动回退到最近交易日并以 requested_date/stale 标注) |
251
+ | `get_dragon_tiger` | 龙虎榜(净买额/上榜原因/解读,仅 A 股;非交易日自动回退到最近交易日并以 requested_date/stale 标注) |
252
252
  | `get_hot_stocks` | 全市场人气热搜榜(东财→雪球→百度,仅 A 股) |
253
253
  | `get_fundamental_context` | 基本面综合上下文 |
254
254
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stock-analysis-plugin",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Pi Agent extension for stock analysis, screening, and strategy backtesting across A/HK/US markets",
5
5
  "type": "module",
6
6
  "main": "./pi/index.ts",
package/pi/index.ts CHANGED
@@ -63,7 +63,7 @@ export default (pi: ExtensionAPI) => {
63
63
  pi.registerTool({
64
64
  name: "get_quote",
65
65
  description:
66
- "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A股、港股、美股、日股、韩股、台股",
66
+ "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A股、港股、美股、日股、韩股、台股;非交易时段返回最近交易日收盘价并以 as_of/stale 标注",
67
67
  parameters: {
68
68
  type: "object",
69
69
  properties: {
@@ -401,7 +401,7 @@ export default (pi: ExtensionAPI) => {
401
401
  properties: {
402
402
  date: {
403
403
  type: "string",
404
- description: "日期(YYYYMMDD),默认当日",
404
+ description: "日期(YYYYMMDD),默认当日;非交易日或未来日期自动回退到最近交易日(返回含 requested_date 与 stale 标注)",
405
405
  },
406
406
  },
407
407
  },
@@ -423,7 +423,7 @@ export default (pi: ExtensionAPI) => {
423
423
  properties: {
424
424
  date: {
425
425
  type: "string",
426
- description: "日期(YYYY-MM-DD),默认当日",
426
+ description: "日期(YYYY-MM-DD),默认当日;非交易日或未来日期自动回退到最近交易日(返回含 requested_date 与 stale 标注)",
427
427
  },
428
428
  symbol: {
429
429
  type: "string",
@@ -24,7 +24,7 @@ python3 scripts/gather.py <symbol>
24
24
  同时用 resolve_stock_sectors 确认个股所属板块,再用 get_sector_constituents 拉取同板块个股列表——后续「龙头 vs 跟风」的强弱对比都在这个板块池内进行。
25
25
  获取不到板块池或池内个股同期表现时,只评估候选股的强势特征,不给出“龙头/龙一”结论。
26
26
 
27
- 短线情绪与资金席位补充:`get_limit_up_pool`(涨停池的连板数、首末次封板时间、封板资金、炸板次数)用于确认板块内个股的高度与封板质量;`get_dragon_tiger`(龙虎榜)用于查看上榜个股的席位净买额与上榜原因。
27
+ 短线情绪与资金席位补充:`get_limit_up_pool`(涨停池的连板数、首末次封板时间、封板资金、炸板次数)用于确认板块内个股的高度与封板质量;`get_dragon_tiger`(龙虎榜)用于查看上榜个股的席位净买额与上榜原因。两者在非交易日或未来日期会自动回退到最近交易日的数据(返回含 `requested_date` 与 `stale: true` 标注),解读时以 `date` 字段的实际数据日期为准,不得把回退数据当成请求日当日数据。
28
28
 
29
29
  ### 2. 相对强弱验证
30
30
 
@@ -17,7 +17,7 @@ description: 市场情绪周期:用市场宽度、涨跌停、成交额和热
17
17
  python3 scripts/gather.py [A|HK|US]
18
18
  ```
19
19
 
20
- A 股情绪另有两个直接数据源:`get_limit_up_pool`(涨停池:连板梯队高度、炸板率、封板资金)与 `get_hot_stocks`(全市场人气热搜榜)。
20
+ A 股情绪另有两个直接数据源:`get_limit_up_pool`(涨停池:连板梯队高度、炸板率、封板资金)与 `get_hot_stocks`(全市场人气热搜榜)。`get_limit_up_pool` 在非交易日或未来日期会回退到最近交易日数据(返回含 `requested_date` 与 `stale: true`),情绪判断以其 `date` 字段的实际数据日期为准。
21
21
 
22
22
  ### 2. 情绪指标
23
23
 
package/tools/screener.py CHANGED
@@ -54,8 +54,9 @@ def _fetch_json(args: list[str], timeout: int = 30) -> dict | list | None:
54
54
 
55
55
 
56
56
  def fetch_snapshot(market: str) -> list:
57
- # a cold full-market snapshot can exceed 30s (CI runners) — allow longer
58
- return _fetch_json(["market_snapshot", "--market", market], timeout=120)
57
+ # a cold full-market snapshot can exceed 30s (CI runners) — allow longer; with
58
+ # all eastmoney/sina legs timing out, the tencent fallback leg needs ~2min more
59
+ return _fetch_json(["market_snapshot", "--market", market], timeout=240)
59
60
 
60
61
 
61
62
  def load_config(path: str) -> dict:
@@ -272,21 +272,13 @@ def _gbk_var_payload(content: bytes) -> str:
272
272
  return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
273
273
 
274
274
 
275
- def _quote_tencent(symbol: str) -> dict:
276
- """Tencent quote via qt.gtimg.cn. GBK-encoded `v_sh600519="1~name~code~..."` fields.
277
-
278
- Units differ from akshare: turnover arrives in 万元 and market_cap in 亿元 —
279
- both are normalized to 元 to match the rest of the chain."""
280
- import requests
281
-
282
- resp = requests.get(f"https://qt.gtimg.cn/q={_cn_code(symbol)}", timeout=10)
283
- f = _gbk_var_payload(resp.content).split("~")
284
- if len(f) < 35 or not f[1]:
285
- raise ValueError(f"tencent returned no quote for {symbol}")
286
- f += [""] * (47 - len(f)) # pad optional tail fields (pe/pb/market_cap…) on short payloads
275
+ def _tencent_payload_row(f: list, symbol: str) -> dict:
276
+ """Build the quote row from one Tencent `~`-separated payload (already split).
277
+ Shared by _quote_tencent (single) and _tencent_batch_quotes (snapshot leg)."""
278
+ f += [""] * (50 - len(f)) # pad optional tail fields (pe/pb/market_cap/volume_ratio…) on short payloads
287
279
  turnover = _parse_float(f[37])
288
280
  market_cap = _parse_float(f[45])
289
- row = {
281
+ return {
290
282
  "symbol": symbol,
291
283
  "name": f[1],
292
284
  "price": _parse_float(f[3]),
@@ -302,8 +294,23 @@ def _quote_tencent(symbol: str) -> dict:
302
294
  "pe": _parse_float(f[39]),
303
295
  "pb": _parse_float(f[46]),
304
296
  "turnover_rate": _parse_float(f[38]),
297
+ "volume_ratio": _parse_float(f[49]),
305
298
  "amplitude": _parse_float(f[43]),
306
299
  }
300
+
301
+
302
+ def _quote_tencent(symbol: str) -> dict:
303
+ """Tencent quote via qt.gtimg.cn. GBK-encoded `v_sh600519="1~name~code~..."` fields.
304
+
305
+ Units differ from akshare: turnover arrives in 万元 and market_cap in 亿元 —
306
+ both are normalized to 元 to match the rest of the chain."""
307
+ import requests
308
+
309
+ resp = requests.get(f"https://qt.gtimg.cn/q={_cn_code(symbol)}", timeout=10)
310
+ f = _gbk_var_payload(resp.content).split("~")
311
+ if len(f) < 35 or not f[1]:
312
+ raise ValueError(f"tencent returned no quote for {symbol}")
313
+ row = _tencent_payload_row(f, symbol)
307
314
  if normalize_stock_code(symbol)["is_etf"]:
308
315
  row["is_etf"] = True
309
316
  return _clean_row(row)
@@ -1120,12 +1127,48 @@ def quote_yf(symbol: str) -> dict:
1120
1127
  )
1121
1128
 
1122
1129
 
1130
+ def _quote_stale_marker(market: str):
1131
+ """Stale-data annotation for a quote fetched outside the market's live session.
1132
+
1133
+ Quotes carry no date of their own, so a weekend/holiday or pre-market call
1134
+ would otherwise present the last trading day's close as if it were live
1135
+ (issue #31 follow-up). Returns None — no annotation — during live sessions
1136
+ and post-market (today's close), or when the calendar is unavailable.
1137
+ pre_market covers the call-auction window (e.g. CN 09:15-09:29), where the
1138
+ quote is actually auction-indicative — an accepted approximation rather than
1139
+ hand-maintaining per-market auction start times."""
1140
+ from trading_calendar import market_phase, prev_trading_days
1141
+
1142
+ # detect_market labels A-shares "A"; the trading calendar calls the same market "CN"
1143
+ cal_market = "CN" if market == "A" else market
1144
+ try:
1145
+ info = market_phase(cal_market)
1146
+ if info.get("error") or info.get("phase") not in ("closed", "pre_market"):
1147
+ return None
1148
+ prev = prev_trading_days(cal_market, 1, from_date=info["date"])
1149
+ except Exception:
1150
+ return None # calendar unavailable — don't guess
1151
+ if not prev:
1152
+ return None
1153
+ as_of = prev[0]
1154
+ return {
1155
+ "as_of": as_of,
1156
+ "stale": True,
1157
+ "note": f"market is not in a live session; quote is the last completed trading day {as_of}'s close",
1158
+ }
1159
+
1160
+
1123
1161
  def cmd_quote(args):
1124
1162
  market = detect_market(args.symbol)
1125
1163
  try:
1126
- return quote_a(args.symbol) if market == "A" else quote_yf(args.symbol)
1164
+ result = quote_a(args.symbol) if market == "A" else quote_yf(args.symbol)
1127
1165
  except Exception as e:
1128
1166
  return {"error": str(e)}
1167
+ if isinstance(result, dict) and "error" not in result:
1168
+ marker = _quote_stale_marker(market)
1169
+ if marker:
1170
+ result.update(marker)
1171
+ return result
1129
1172
 
1130
1173
 
1131
1174
  # --------------- capital_flow ---------------
@@ -1347,17 +1390,29 @@ def cmd_financials(args):
1347
1390
 
1348
1391
 
1349
1392
  def snapshot_a() -> list:
1393
+ import socket
1394
+
1395
+ # akshare/efinance leave requests timeout-less — on a blackholed network a leg
1396
+ # hangs until the kernel TCP timeout (~2min), and the chain would overrun the
1397
+ # caller's subprocess budget before ever reaching the tencent leg. Bound each
1398
+ # blocking socket op for the chain's duration (explicit per-request timeouts,
1399
+ # like the tencent leg's, still win).
1400
+ old_timeout = socket.getdefaulttimeout()
1401
+ socket.setdefaulttimeout(25)
1350
1402
  try:
1351
1403
  return _failover(
1352
1404
  [
1353
1405
  ("akshare", _snapshot_akshare),
1354
1406
  ("efinance", _snapshot_efinance),
1355
1407
  ("sina", _snapshot_sina),
1408
+ ("tencent", _snapshot_tencent),
1356
1409
  ],
1357
1410
  label="snapshot_a",
1358
1411
  )
1359
- except Exception:
1360
- return [{"error": "A-share snapshot unavailable from all sources"}]
1412
+ except Exception as e:
1413
+ return [{"error": f"A-share snapshot unavailable from all sources: {e}"}]
1414
+ finally:
1415
+ socket.setdefaulttimeout(old_timeout)
1361
1416
 
1362
1417
 
1363
1418
  def _snapshot_efinance() -> list:
@@ -1413,6 +1468,63 @@ def _snapshot_sina() -> list:
1413
1468
  return [_clean_row(r) for r in df[keep].to_dict("records")]
1414
1469
 
1415
1470
 
1471
+ # qt.gtimg.cn accepts comma-joined multi-code batches; 60 keeps URLs well short
1472
+ _TENCENT_BATCH = 60
1473
+
1474
+
1475
+ def _tencent_batch_quotes(codes: list) -> list:
1476
+ """Batch quotes from qt.gtimg.cn for exchange-prefixed codes, a few requests in
1477
+ flight (this leg fires only when the eastmoney/sina legs are all dead, and ~15k
1478
+ enumerated codes serialized would take minutes). Unknown codes are simply absent
1479
+ from the response; delisted/suspended ones come back frozen with volume=0 and
1480
+ are dropped here."""
1481
+ import concurrent.futures
1482
+
1483
+ import requests
1484
+
1485
+ def fetch(batch):
1486
+ try:
1487
+ resp = requests.get(f"https://qt.gtimg.cn/q={','.join(batch)}", timeout=10)
1488
+ except Exception:
1489
+ return [] # a lost batch loses 60 codes — a partial snapshot still beats none
1490
+ rows = []
1491
+ for part in resp.content.decode("gbk", errors="replace").split(";"):
1492
+ vname, _, payload = part.strip().partition('="')
1493
+ f = payload.rstrip('"').split("~")
1494
+ if len(f) < 35 or not f[1]:
1495
+ continue
1496
+ if not _parse_float(f[6]): # volume 0/empty → frozen payload (delisted/suspended)
1497
+ continue
1498
+ prefixed = vname[2:] # strip the leading "v_"
1499
+ bare = prefixed[2:] if prefixed[:2] in ("sh", "sz", "bj") else prefixed
1500
+ rows.append(_clean_row(_tencent_payload_row(f, bare)))
1501
+ return rows
1502
+
1503
+ batches = [codes[i : i + _TENCENT_BATCH] for i in range(0, len(codes), _TENCENT_BATCH)]
1504
+ rows = []
1505
+ with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
1506
+ for batch_rows in pool.map(fetch, batches):
1507
+ rows.extend(batch_rows)
1508
+ return rows
1509
+
1510
+
1511
+ def _snapshot_tencent() -> list:
1512
+ """Tencent full-market snapshot — the plain-HTTPS last-resort leg for when the
1513
+ eastmoney/sina legs are all blocked (datacenter IPs, issue #25).
1514
+
1515
+ Codes are enumerated over the known SH (600-605, 688-689) and SZ (000-003,
1516
+ 300-302) ranges and validated by the batch quotes themselves — no list API is
1517
+ reliable from blocked networks (www.szse.cn resets datacenter connections,
1518
+ query.sse.com.cn flaps, akshare's wrapper has no timeout). BSE and suspended
1519
+ stocks stay uncovered by this leg."""
1520
+ codes = [f"sh{i:06d}" for lo, hi in ((600000, 605999), (688000, 689999)) for i in range(lo, hi + 1)]
1521
+ codes += [f"sz{i:06d}" for lo, hi in ((1, 3999), (300000, 302999)) for i in range(lo, hi + 1)]
1522
+ rows = _tencent_batch_quotes(codes)
1523
+ if not rows:
1524
+ raise ValueError("tencent snapshot returned empty data")
1525
+ return rows
1526
+
1527
+
1416
1528
  def _snapshot_akshare() -> list:
1417
1529
  import akshare as ak
1418
1530
 
@@ -1917,6 +2029,20 @@ def _board_entry(name, source: str, board_type: str) -> dict:
1917
2029
  return {"name": str(name), "source": source, "board_type": board_type}
1918
2030
 
1919
2031
 
2032
+ class _DataMiss(ValueError):
2033
+ """Per-symbol data miss: the provider answered but doesn't cover this code
2034
+ (empty DataFrame / no industry field for an ETF/BSE/uncovered symbol). Never an
2035
+ outage — resolve_stock_sectors' negative cache must not mark the leg down."""
2036
+
2037
+
2038
+ def _require_industry(value, source: str) -> str:
2039
+ """Unwrap a provider's industry field into a real name. pandas NaN is truthy —
2040
+ only a non-empty string counts; a missing one is a _DataMiss, not an outage."""
2041
+ if not (isinstance(value, str) and value):
2042
+ raise _DataMiss(f"{source} has no industry")
2043
+ return value
2044
+
2045
+
1920
2046
  def _stock_boards_em(symbol: str, info_map=None) -> list:
1921
2047
  """A-share industry board from eastmoney individual info. Pass an already-fetched
1922
2048
  info_map (item → value) to reuse it instead of hitting the network again."""
@@ -1925,12 +2051,9 @@ def _stock_boards_em(symbol: str, info_map=None) -> list:
1925
2051
 
1926
2052
  df = _akshare_retry(ak.stock_individual_info_em, symbol=symbol)
1927
2053
  if df is None or df.empty:
1928
- raise ValueError("eastmoney individual info unavailable")
2054
+ raise _DataMiss("eastmoney individual info unavailable")
1929
2055
  info_map = {row.iloc[0]: row.iloc[1] for _, row in df.iterrows()}
1930
- industry = info_map.get("行业")
1931
- # pandas NaN is truthy — only a real string counts as an industry name
1932
- if not (isinstance(industry, str) and industry):
1933
- raise ValueError("eastmoney individual info has no industry")
2056
+ industry = _require_industry(info_map.get("行业"), "eastmoney individual info")
1934
2057
  return [_board_entry(industry, "eastmoney", "industry")]
1935
2058
 
1936
2059
 
@@ -1940,7 +2063,7 @@ def _stock_boards_efinance(symbol: str) -> list:
1940
2063
 
1941
2064
  df = ef.stock.get_belong_board(symbol)
1942
2065
  if df is None or df.empty or "板块名称" not in df.columns:
1943
- raise ValueError("efinance belong-board unavailable")
2066
+ raise _DataMiss("efinance belong-board unavailable")
1944
2067
  # pandas NaN is truthy and str(nan) == "nan" — drop non-string names or they
1945
2068
  # would pollute the dedup in resolve_stock_sectors as a bogus "nan" board
1946
2069
  return [
@@ -1968,17 +2091,30 @@ def _stock_boards_xueqiu(symbol: str) -> list:
1968
2091
 
1969
2092
  df = _akshare_retry(ak.stock_individual_basic_info_xq, symbol=_xq_symbol(symbol), token=token)
1970
2093
  if df is None or df.empty:
1971
- raise ValueError("xueqiu basic info unavailable")
2094
+ raise _DataMiss("xueqiu basic info unavailable")
1972
2095
  info_map = {row.iloc[0]: row.iloc[1] for _, row in df.iterrows()}
1973
2096
  # affiliate_industry is a nested dict: {'ind_code': 'BK0025', 'ind_name': '汽车整车'}
1974
2097
  industry = info_map.get("affiliate_industry")
1975
- name = industry.get("ind_name") if isinstance(industry, dict) else None
1976
- # pandas NaN is truthy — only a real string counts as an industry name
1977
- if not (isinstance(name, str) and name):
1978
- raise ValueError("xueqiu basic info has no industry")
2098
+ name = _require_industry(industry.get("ind_name") if isinstance(industry, dict) else None, "xueqiu basic info")
1979
2099
  return [_board_entry(name, "xueqiu", "industry")]
1980
2100
 
1981
2101
 
2102
+ def _stock_boards_cninfo(symbol: str) -> list:
2103
+ """A-share industry from cninfo (官方披露站) via akshare stock_profile_cninfo —
2104
+ the token-free, non-eastmoney active leg (issue #35). Runs only as the
2105
+ last-resort fallback: its industry naming follows the CSRC classification
2106
+ (酒、饮料和精制茶制造业), not eastmoney board names (酿酒行业), so its entries
2107
+ don't resolve against eastmoney/sina board lists downstream."""
2108
+ import akshare as ak
2109
+
2110
+ bare = symbol[2:] if _A_PREFIXED_RE.fullmatch(symbol) else symbol
2111
+ df = _akshare_retry(ak.stock_profile_cninfo, symbol=bare)
2112
+ if df is None or df.empty or "所属行业" not in df.columns:
2113
+ raise _DataMiss("cninfo profile unavailable")
2114
+ industry = _require_industry(df.iloc[0].get("所属行业"), "cninfo profile")
2115
+ return [_board_entry(industry, "cninfo", "industry")]
2116
+
2117
+
1982
2118
  def _stock_boards_from_cache(symbol: str) -> list:
1983
2119
  """Reverse lookup against the get_sector_constituents disk cache — the honest
1984
2120
  fallback when eastmoney blocks the caller's IP and xueqiu has no token (the two
@@ -2025,10 +2161,34 @@ def _stock_sectors_hk(symbol: str) -> list:
2025
2161
  return sectors
2026
2162
 
2027
2163
 
2164
+ # A failed A-share resolve leg is skipped for this long on subsequent calls
2165
+ # (issue #35): the motivating failure mode — regional blocking of eastmoney — is
2166
+ # chronic, while a 1h TTL keeps a transient blip from degrading the merged result
2167
+ # for the whole day. An expired marker costs one retried attempt (self-healing).
2168
+ _RESOLVE_DOWN_TTL = 3600
2169
+
2170
+
2171
+ def _resolve_leg_down(name: str) -> bool:
2172
+ """True while leg `name`'s failure marker is fresh. The marker stores a plain
2173
+ timestamp — the effective TTL above is shorter than the 24h file lifetime that
2174
+ _disk_cache_get enforces on the shared cache dir."""
2175
+ ts = _disk_cache_get(f"resolve-down-{name}")
2176
+ return isinstance(ts, (int, float)) and time.time() - ts < _RESOLVE_DOWN_TTL
2177
+
2178
+
2028
2179
  def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
2029
- """Reverse map: stock → boards it belongs to (A/HK). A single source failing
2030
- is not fatal — the other source's boards are still returned. An already-fetched
2031
- eastmoney info_map is reused for the em source instead of re-fetching."""
2180
+ """Reverse map: stock → boards it belongs to (A/HK). Sources are merged (a single
2181
+ source failing is not fatal — the others' boards are still returned) rather than
2182
+ first-hit failover: each source covers a different flavor (industry vs concept).
2183
+ An already-fetched eastmoney info_map is reused for the em source instead of
2184
+ re-fetching; that leg then needs no network and bypasses the failure cache.
2185
+
2186
+ A-share legs are socket-timeout-bounded and negative-cached per leg (issue #35):
2187
+ on an eastmoney-blackholed host the first call pays each dead leg's bounded
2188
+ timeout once, later calls skip them until the marker expires. The cninfo leg
2189
+ runs only when every other active leg came up empty — its CSRC industry names
2190
+ don't resolve against eastmoney/sina board lists, so it is a fallback, not an
2191
+ always-on flavor."""
2032
2192
  market = detect_market(symbol)
2033
2193
  result = {"symbol": symbol, "market": market}
2034
2194
  if market == "A":
@@ -2044,11 +2204,47 @@ def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
2044
2204
  result["error"] = f"resolve_stock_sectors only supports A-share and HK stocks, got market {market}"
2045
2205
  return result
2046
2206
  sectors, errors = [], []
2047
- for name, fn in sources:
2207
+
2208
+ def run_legs(legs, negative_cache: bool):
2209
+ for name, fn in legs:
2210
+ # em with an info_map in hand is a pure dict lookup — never skip it, and
2211
+ # a lookup miss must not mark a network leg down
2212
+ offline_em = name == "eastmoney" and info_map is not None
2213
+ if negative_cache and not offline_em and _resolve_leg_down(name):
2214
+ errors.append(f"{name}: skipped (failed within {_RESOLVE_DOWN_TTL}s)")
2215
+ continue
2216
+ try:
2217
+ sectors.extend(fn() or [])
2218
+ if negative_cache and not offline_em:
2219
+ _disk_cache_set(f"resolve-down-{name}", 0) # success clears the marker
2220
+ except _DataMiss as e:
2221
+ # per-symbol miss (provider answered but doesn't cover this code) —
2222
+ # not an outage: never poison the leg for every other symbol
2223
+ errors.append(f"{name}: {type(e).__name__}: {e}")
2224
+ except Exception as e:
2225
+ errors.append(f"{name}: {type(e).__name__}: {e}")
2226
+ if negative_cache and not offline_em:
2227
+ _disk_cache_set(f"resolve-down-{name}", time.time())
2228
+
2229
+ if market == "A":
2230
+ # akshare/efinance leave requests timeout-less — on a blackholed network a leg
2231
+ # hangs until the kernel TCP timeout (snapshot_a has the same guard). Bound
2232
+ # each blocking socket op so every leg gets its turn within the caller's
2233
+ # subprocess budget.
2234
+ import socket
2235
+
2236
+ old_timeout = socket.getdefaulttimeout()
2237
+ socket.setdefaulttimeout(25)
2048
2238
  try:
2049
- sectors.extend(fn() or [])
2050
- except Exception as e:
2051
- errors.append(f"{name}: {type(e).__name__}: {e}")
2239
+ run_legs(sources, negative_cache=True)
2240
+ # cninfo last: the token-free non-eastmoney active fallback (issue #35),
2241
+ # tried only when everything above yielded nothing
2242
+ if not sectors:
2243
+ run_legs([("cninfo", lambda: _stock_boards_cninfo(symbol))], negative_cache=True)
2244
+ finally:
2245
+ socket.setdefaulttimeout(old_timeout)
2246
+ else:
2247
+ run_legs(sources, negative_cache=False)
2052
2248
  seen = set()
2053
2249
  deduped = []
2054
2250
  for s in sectors:
@@ -2060,7 +2256,7 @@ def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
2060
2256
  if market == "A":
2061
2257
  # em/efinance are both eastmoney-flavored and xueqiu is usually untokened,
2062
2258
  # so an all-empty A-share result almost always means eastmoney blocked us.
2063
- error += "; 东财不可用且缓存为空,可先跑 get_sector_constituents 预热或设置 XUEQIU_TOKEN"
2259
+ error += "; 东财/cninfo 均不可用且缓存为空,可先跑 get_sector_constituents 预热或设置 XUEQIU_TOKEN"
2064
2260
  result["error"] = error
2065
2261
  return result
2066
2262
  result["sectors"] = deduped
@@ -2321,21 +2517,66 @@ def cmd_fundamental_context(args):
2321
2517
  # --------------- short-term sentiment: limit_up_pool / dragon_tiger / hot_stocks (A-share only) ---------------
2322
2518
 
2323
2519
 
2520
+ def _resolve_cn_data_date(raw: str) -> tuple[datetime, datetime]:
2521
+ """Resolve a requested date (YYYYMMDD) to the CN trading day its data belongs to.
2522
+
2523
+ eastmoney's zt-pool/LHB endpoints silently clamp any date later than the latest
2524
+ trading day to that day and answer EMPTY for past non-trading days, so the
2525
+ requested date never proves the data's date (issue #31). Returns
2526
+ (requested, data_date) as datetimes — data_date is the last trading day at or
2527
+ before min(requested, today): weekends, holidays and future dates all resolve
2528
+ backward. Raises ValueError on malformed input."""
2529
+ from trading_calendar import cn_trade_dates # flat sibling import
2530
+
2531
+ req = datetime.strptime(raw, "%Y%m%d")
2532
+ d = min(req, datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))
2533
+ trade_dates = cn_trade_dates(d.year)
2534
+ if d.month == 1: # the walk-back can cross into December of the previous year
2535
+ trade_dates |= cn_trade_dates(d.year - 1)
2536
+ for _ in range(20): # 春节/国庆 plus adjoining weekends fit well within 20 days
2537
+ # empty trade-date set (calendar fetch failed) → weekday-only approximation
2538
+ if d.weekday() < 5 and (not trade_dates or d.strftime("%Y-%m-%d") in trade_dates):
2539
+ break
2540
+ d -= timedelta(days=1)
2541
+ return req, d
2542
+
2543
+
2324
2544
  def cmd_limit_up_pool(args):
2325
- """A-share limit-up pool (涨停池) for one trading day via eastmoney."""
2326
- date = (args.date or datetime.now().strftime("%Y%m%d")).replace("-", "")
2545
+ """A-share limit-up pool (涨停池) for one trading day via eastmoney.
2546
+
2547
+ The requested date is first resolved to the trading day the data belongs to
2548
+ (_resolve_cn_data_date); when they differ the payload carries requested_date
2549
+ and stale=True so a weekend/future request can't be misread as that day's pool.
2550
+ Known limitation: on a trading day before that day's pool is published, the
2551
+ request resolves to itself and no stale label is emitted (the zt-pool payload
2552
+ carries no date column to cross-check against)."""
2553
+ try:
2554
+ req, data_day = _resolve_cn_data_date((args.date or datetime.now().strftime("%Y%m%d")).replace("-", ""))
2555
+ except ValueError:
2556
+ return {"error": f"limit_up_pool: invalid --date {args.date!r} (want YYYYMMDD)"}
2557
+ date = data_day.strftime("%Y%m%d")
2558
+ requested = req.strftime("%Y%m%d")
2559
+ result = {"date": date}
2560
+ if req != data_day:
2561
+ result["requested_date"] = requested
2562
+ result["stale"] = True
2563
+ result["note"] = f"{requested} is not a trading day or has no data yet; showing the last trading day {date}"
2327
2564
  try:
2328
2565
  import akshare as ak
2329
2566
 
2330
2567
  df = _akshare_retry(ak.stock_zt_pool_em, date=date)
2331
2568
  if df is None or df.empty:
2332
- return {
2333
- "date": date,
2334
- "count": 0,
2335
- "max_consecutive_boards": 0,
2336
- "pool": [],
2337
- "note": "no limit-up pool data (non-trading day or no limit-ups)",
2338
- }
2569
+ result["count"] = 0
2570
+ result["max_consecutive_boards"] = 0
2571
+ result["pool"] = []
2572
+ if date != requested:
2573
+ result["note"] = (
2574
+ f"{requested} is not a trading day or has no data yet; "
2575
+ f"last trading day {date} has no limit-up pool data"
2576
+ )
2577
+ else:
2578
+ result["note"] = f"no limit-up pool data for {date}"
2579
+ return result
2339
2580
  col_map = {
2340
2581
  "代码": "code",
2341
2582
  "名称": "name",
@@ -2357,14 +2598,12 @@ def cmd_limit_up_pool(args):
2357
2598
  keep = [c for c in col_map.values() if c in df.columns]
2358
2599
  pool = [_clean_row(r) for r in df[keep].to_dict("records")]
2359
2600
  boards = [r["consecutive_boards"] for r in pool if isinstance(r.get("consecutive_boards"), (int, float))]
2360
- return {
2361
- "date": date,
2362
- "count": len(pool),
2363
- "max_consecutive_boards": max(boards) if boards else 0,
2364
- "pool": pool,
2365
- }
2601
+ result["count"] = len(pool)
2602
+ result["max_consecutive_boards"] = max(boards) if boards else 0
2603
+ result["pool"] = pool
2604
+ return result
2366
2605
  except Exception as e:
2367
- return {"error": str(e)}
2606
+ return {"error": f"limit_up_pool date={requested}: {e}"}
2368
2607
 
2369
2608
 
2370
2609
  def _dragon_tiger_em(raw: str) -> list:
@@ -2423,9 +2662,18 @@ def _dragon_tiger_sina(raw: str) -> list:
2423
2662
 
2424
2663
 
2425
2664
  def cmd_dragon_tiger(args):
2426
- """A-share dragon-tiger list (龙虎榜) for one trading day: eastmoney → sina."""
2427
- raw = (args.date or datetime.now().strftime("%Y-%m-%d")).replace("-", "")
2428
- date = f"{raw[:4]}-{raw[4:6]}-{raw[6:8]}" if len(raw) == 8 and raw.isdigit() else args.date
2665
+ """A-share dragon-tiger list (龙虎榜) for one trading day: eastmoney → sina.
2666
+
2667
+ Same date resolution as cmd_limit_up_pool (issue #31): a non-trading or future
2668
+ date is served the last trading day's list, labeled with requested_date and
2669
+ stale=True."""
2670
+ try:
2671
+ req, data_day = _resolve_cn_data_date((args.date or datetime.now().strftime("%Y-%m-%d")).replace("-", ""))
2672
+ except ValueError:
2673
+ return {"error": f"dragon_tiger: invalid --date {args.date!r} (want YYYY-MM-DD)"}
2674
+ raw = data_day.strftime("%Y%m%d")
2675
+ date = data_day.strftime("%Y-%m-%d")
2676
+ requested_iso = req.strftime("%Y-%m-%d")
2429
2677
  sources = [
2430
2678
  _sourced("eastmoney", lambda: _dragon_tiger_em(raw)),
2431
2679
  _sourced("sina", lambda: _dragon_tiger_sina(raw)),
@@ -2434,13 +2682,19 @@ def cmd_dragon_tiger(args):
2434
2682
  rows = _failover(sources, label=f"dragon_tiger:{raw}")
2435
2683
  except Exception as e:
2436
2684
  return {"error": str(e)}
2685
+ stale = req != data_day
2437
2686
  if not rows:
2438
- return {
2439
- "date": date,
2440
- "count": 0,
2441
- "items": [],
2442
- "note": "no dragon-tiger data (non-trading day or no listings)",
2443
- }
2687
+ result = {"date": date, "count": 0, "items": []}
2688
+ if stale:
2689
+ result["requested_date"] = requested_iso
2690
+ result["stale"] = True
2691
+ result["note"] = (
2692
+ f"{requested_iso} is not a trading day or has no data yet; "
2693
+ f"last trading day {date} has no dragon-tiger data"
2694
+ )
2695
+ else:
2696
+ result["note"] = f"no dragon-tiger data for {date}"
2697
+ return result
2444
2698
  source = rows[0]["source"]
2445
2699
  if args.symbol:
2446
2700
  m = re.fullmatch(r"(?:sh|sz|bj)(\d{6})", str(args.symbol), re.IGNORECASE)
@@ -2453,7 +2707,12 @@ def cmd_dragon_tiger(args):
2453
2707
  reverse=True,
2454
2708
  )
2455
2709
  items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
2456
- return {"date": date, "count": len(items), "items": items, "source": source}
2710
+ result = {"date": date, "count": len(items), "items": items, "source": source}
2711
+ if stale:
2712
+ result["requested_date"] = requested_iso
2713
+ result["stale"] = True
2714
+ result["note"] = f"{requested_iso} is not a trading day or has no data yet; showing the last trading day {date}"
2715
+ return result
2457
2716
 
2458
2717
 
2459
2718
  def _strip_exchange_prefix(row: dict) -> dict:
@@ -14,7 +14,21 @@ def _is_weekend(d: datetime) -> bool:
14
14
  return d.weekday() >= 5
15
15
 
16
16
 
17
- def _cn_holidays(year: int) -> set[str]:
17
+ # Process-local memo: one CLI call = one process, and the CN path
18
+ # (is_trading_day / the prev|next_trading_days walk-back) would otherwise
19
+ # re-fetch the sina calendar per step — up to ~5 fetches for one stale check.
20
+ _CN_TRADE_DATES: dict[int, set[str]] = {}
21
+
22
+
23
+ def cn_trade_dates(year: int) -> set[str]:
24
+ """CN trading dates (YYYY-MM-DD) for `year` from the sina trade-date history.
25
+
26
+ Empty set when the calendar can't be fetched (failures are not cached — the
27
+ next call retries); callers treat empty as "weekends are the only non-trading
28
+ days"."""
29
+ cached = _CN_TRADE_DATES.get(year)
30
+ if cached is not None:
31
+ return cached
18
32
  try:
19
33
  import akshare as ak
20
34
 
@@ -25,9 +39,11 @@ def _cn_holidays(year: int) -> set[str]:
25
39
  d = str(val)[:10]
26
40
  if d.startswith(str(year)):
27
41
  dates.add(d)
28
- return dates
29
42
  except Exception:
30
43
  return set()
44
+ if dates:
45
+ _CN_TRADE_DATES[year] = dates
46
+ return dates
31
47
 
32
48
 
33
49
  def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
@@ -52,7 +68,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
52
68
  return {"date": date_str, "market": market, "is_trading_day": False, "reason": "weekend"}
53
69
 
54
70
  if market == "CN":
55
- trading_dates = _cn_holidays(d.year)
71
+ trading_dates = cn_trade_dates(d.year)
56
72
  if trading_dates:
57
73
  is_td = date_str in trading_dates
58
74
  return {
@@ -80,7 +96,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
80
96
  }
81
97
  except Exception:
82
98
  pass
83
- trading_dates = _cn_holidays(d.year)
99
+ trading_dates = cn_trade_dates(d.year)
84
100
  if trading_dates:
85
101
  is_td = date_str in trading_dates
86
102
  return {