stock-analysis-plugin 0.2.0 → 0.2.1

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.1",
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
 
@@ -2321,21 +2433,66 @@ def cmd_fundamental_context(args):
2321
2433
  # --------------- short-term sentiment: limit_up_pool / dragon_tiger / hot_stocks (A-share only) ---------------
2322
2434
 
2323
2435
 
2436
+ def _resolve_cn_data_date(raw: str) -> tuple[datetime, datetime]:
2437
+ """Resolve a requested date (YYYYMMDD) to the CN trading day its data belongs to.
2438
+
2439
+ eastmoney's zt-pool/LHB endpoints silently clamp any date later than the latest
2440
+ trading day to that day and answer EMPTY for past non-trading days, so the
2441
+ requested date never proves the data's date (issue #31). Returns
2442
+ (requested, data_date) as datetimes — data_date is the last trading day at or
2443
+ before min(requested, today): weekends, holidays and future dates all resolve
2444
+ backward. Raises ValueError on malformed input."""
2445
+ from trading_calendar import cn_trade_dates # flat sibling import
2446
+
2447
+ req = datetime.strptime(raw, "%Y%m%d")
2448
+ d = min(req, datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))
2449
+ trade_dates = cn_trade_dates(d.year)
2450
+ if d.month == 1: # the walk-back can cross into December of the previous year
2451
+ trade_dates |= cn_trade_dates(d.year - 1)
2452
+ for _ in range(20): # 春节/国庆 plus adjoining weekends fit well within 20 days
2453
+ # empty trade-date set (calendar fetch failed) → weekday-only approximation
2454
+ if d.weekday() < 5 and (not trade_dates or d.strftime("%Y-%m-%d") in trade_dates):
2455
+ break
2456
+ d -= timedelta(days=1)
2457
+ return req, d
2458
+
2459
+
2324
2460
  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("-", "")
2461
+ """A-share limit-up pool (涨停池) for one trading day via eastmoney.
2462
+
2463
+ The requested date is first resolved to the trading day the data belongs to
2464
+ (_resolve_cn_data_date); when they differ the payload carries requested_date
2465
+ and stale=True so a weekend/future request can't be misread as that day's pool.
2466
+ Known limitation: on a trading day before that day's pool is published, the
2467
+ request resolves to itself and no stale label is emitted (the zt-pool payload
2468
+ carries no date column to cross-check against)."""
2469
+ try:
2470
+ req, data_day = _resolve_cn_data_date((args.date or datetime.now().strftime("%Y%m%d")).replace("-", ""))
2471
+ except ValueError:
2472
+ return {"error": f"limit_up_pool: invalid --date {args.date!r} (want YYYYMMDD)"}
2473
+ date = data_day.strftime("%Y%m%d")
2474
+ requested = req.strftime("%Y%m%d")
2475
+ result = {"date": date}
2476
+ if req != data_day:
2477
+ result["requested_date"] = requested
2478
+ result["stale"] = True
2479
+ result["note"] = f"{requested} is not a trading day or has no data yet; showing the last trading day {date}"
2327
2480
  try:
2328
2481
  import akshare as ak
2329
2482
 
2330
2483
  df = _akshare_retry(ak.stock_zt_pool_em, date=date)
2331
2484
  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
- }
2485
+ result["count"] = 0
2486
+ result["max_consecutive_boards"] = 0
2487
+ result["pool"] = []
2488
+ if date != requested:
2489
+ result["note"] = (
2490
+ f"{requested} is not a trading day or has no data yet; "
2491
+ f"last trading day {date} has no limit-up pool data"
2492
+ )
2493
+ else:
2494
+ result["note"] = f"no limit-up pool data for {date}"
2495
+ return result
2339
2496
  col_map = {
2340
2497
  "代码": "code",
2341
2498
  "名称": "name",
@@ -2357,14 +2514,12 @@ def cmd_limit_up_pool(args):
2357
2514
  keep = [c for c in col_map.values() if c in df.columns]
2358
2515
  pool = [_clean_row(r) for r in df[keep].to_dict("records")]
2359
2516
  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
- }
2517
+ result["count"] = len(pool)
2518
+ result["max_consecutive_boards"] = max(boards) if boards else 0
2519
+ result["pool"] = pool
2520
+ return result
2366
2521
  except Exception as e:
2367
- return {"error": str(e)}
2522
+ return {"error": f"limit_up_pool date={requested}: {e}"}
2368
2523
 
2369
2524
 
2370
2525
  def _dragon_tiger_em(raw: str) -> list:
@@ -2423,9 +2578,18 @@ def _dragon_tiger_sina(raw: str) -> list:
2423
2578
 
2424
2579
 
2425
2580
  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
2581
+ """A-share dragon-tiger list (龙虎榜) for one trading day: eastmoney → sina.
2582
+
2583
+ Same date resolution as cmd_limit_up_pool (issue #31): a non-trading or future
2584
+ date is served the last trading day's list, labeled with requested_date and
2585
+ stale=True."""
2586
+ try:
2587
+ req, data_day = _resolve_cn_data_date((args.date or datetime.now().strftime("%Y-%m-%d")).replace("-", ""))
2588
+ except ValueError:
2589
+ return {"error": f"dragon_tiger: invalid --date {args.date!r} (want YYYY-MM-DD)"}
2590
+ raw = data_day.strftime("%Y%m%d")
2591
+ date = data_day.strftime("%Y-%m-%d")
2592
+ requested_iso = req.strftime("%Y-%m-%d")
2429
2593
  sources = [
2430
2594
  _sourced("eastmoney", lambda: _dragon_tiger_em(raw)),
2431
2595
  _sourced("sina", lambda: _dragon_tiger_sina(raw)),
@@ -2434,13 +2598,19 @@ def cmd_dragon_tiger(args):
2434
2598
  rows = _failover(sources, label=f"dragon_tiger:{raw}")
2435
2599
  except Exception as e:
2436
2600
  return {"error": str(e)}
2601
+ stale = req != data_day
2437
2602
  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
- }
2603
+ result = {"date": date, "count": 0, "items": []}
2604
+ if stale:
2605
+ result["requested_date"] = requested_iso
2606
+ result["stale"] = True
2607
+ result["note"] = (
2608
+ f"{requested_iso} is not a trading day or has no data yet; "
2609
+ f"last trading day {date} has no dragon-tiger data"
2610
+ )
2611
+ else:
2612
+ result["note"] = f"no dragon-tiger data for {date}"
2613
+ return result
2444
2614
  source = rows[0]["source"]
2445
2615
  if args.symbol:
2446
2616
  m = re.fullmatch(r"(?:sh|sz|bj)(\d{6})", str(args.symbol), re.IGNORECASE)
@@ -2453,7 +2623,12 @@ def cmd_dragon_tiger(args):
2453
2623
  reverse=True,
2454
2624
  )
2455
2625
  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}
2626
+ result = {"date": date, "count": len(items), "items": items, "source": source}
2627
+ if stale:
2628
+ result["requested_date"] = requested_iso
2629
+ result["stale"] = True
2630
+ result["note"] = f"{requested_iso} is not a trading day or has no data yet; showing the last trading day {date}"
2631
+ return result
2457
2632
 
2458
2633
 
2459
2634
  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 {