stock-analysis-plugin 0.1.15 → 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.
@@ -12,6 +12,9 @@ import time
12
12
  from datetime import datetime, timedelta
13
13
  from pathlib import Path
14
14
 
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+ from _subproc import run_tool # noqa: E402
17
+
15
18
  # Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
16
19
  # Bare 6-digit codes are always stocks; the prefix is the disambiguation escape
17
20
  # hatch for index codes (sh000001 = 上证指数, not 平安银行).
@@ -62,15 +65,6 @@ def normalize_stock_code(symbol: str) -> dict:
62
65
  return info
63
66
 
64
67
 
65
- def mark_st(info: dict, name: str) -> dict:
66
- """Mark ST status from stock name; adjusts limit_pct to 5%."""
67
- if name and "ST" in name.upper():
68
- info["is_st"] = True
69
- if info["board"] == "main":
70
- info["limit_pct"] = 0.05
71
- return info
72
-
73
-
74
68
  def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
75
69
  """Calculate limit-up or limit-down price with banker's rounding."""
76
70
  import numpy as np
@@ -80,11 +74,22 @@ def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> f
80
74
 
81
75
 
82
76
  # Chains that get sticky ordering: the CN free-source chains, where failures are
83
- # typically chronic (regional blocking). The yf chains (`kline:`/`quote:`) are
77
+ # typically chronic (regional blocking / rate-limiting — eastmoney is the primary
78
+ # leg of most of them). The yf chains (`kline:`/`quote:`) are
84
79
  # excluded on purpose — their failures are usually transient yfinance blips, and
85
80
  # stickiness would let one blip degrade HK/US quote richness (finnhub has no
86
81
  # name/market_cap/pe/pb) for the whole TTL.
87
- _STICKY_CHAINS = {"kline_a", "quote_a", "quote_a_etf", "snapshot_a", "sector_constituents", "sina"}
82
+ _STICKY_CHAINS = {
83
+ "kline_a",
84
+ "quote_a",
85
+ "quote_a_etf",
86
+ "snapshot_a",
87
+ "sector_constituents",
88
+ "sina",
89
+ "sector_rankings",
90
+ "dragon_tiger",
91
+ "hot_stocks",
92
+ }
88
93
 
89
94
 
90
95
  def _failover(sources: list, label: str):
@@ -267,21 +272,13 @@ def _gbk_var_payload(content: bytes) -> str:
267
272
  return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
268
273
 
269
274
 
270
- def _quote_tencent(symbol: str) -> dict:
271
- """Tencent quote via qt.gtimg.cn. GBK-encoded `v_sh600519="1~name~code~..."` fields.
272
-
273
- Units differ from akshare: turnover arrives in 万元 and market_cap in 亿元 —
274
- both are normalized to 元 to match the rest of the chain."""
275
- import requests
276
-
277
- resp = requests.get(f"https://qt.gtimg.cn/q={_cn_code(symbol)}", timeout=10)
278
- f = _gbk_var_payload(resp.content).split("~")
279
- if len(f) < 35 or not f[1]:
280
- raise ValueError(f"tencent returned no quote for {symbol}")
281
- 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
282
279
  turnover = _parse_float(f[37])
283
280
  market_cap = _parse_float(f[45])
284
- row = {
281
+ return {
285
282
  "symbol": symbol,
286
283
  "name": f[1],
287
284
  "price": _parse_float(f[3]),
@@ -297,8 +294,23 @@ def _quote_tencent(symbol: str) -> dict:
297
294
  "pe": _parse_float(f[39]),
298
295
  "pb": _parse_float(f[46]),
299
296
  "turnover_rate": _parse_float(f[38]),
297
+ "volume_ratio": _parse_float(f[49]),
300
298
  "amplitude": _parse_float(f[43]),
301
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)
302
314
  if normalize_stock_code(symbol)["is_etf"]:
303
315
  row["is_etf"] = True
304
316
  return _clean_row(row)
@@ -1115,12 +1127,48 @@ def quote_yf(symbol: str) -> dict:
1115
1127
  )
1116
1128
 
1117
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
+
1118
1161
  def cmd_quote(args):
1119
1162
  market = detect_market(args.symbol)
1120
1163
  try:
1121
- 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)
1122
1165
  except Exception as e:
1123
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
1124
1172
 
1125
1173
 
1126
1174
  # --------------- capital_flow ---------------
@@ -1226,31 +1274,10 @@ def cmd_capital_flow(args):
1226
1274
 
1227
1275
  def _news_search_intel_fallback(symbol: str) -> list:
1228
1276
  """Fallback: use search_intel to find news when primary sources fail."""
1229
- import subprocess
1230
- from pathlib import Path
1231
-
1232
- tools_dir = Path(__file__).parent
1233
- try:
1234
- result = subprocess.run(
1235
- [sys.executable, str(tools_dir / "search_intel.py"), "search", f"{symbol} 最新消息"],
1236
- capture_output=True,
1237
- text=True,
1238
- encoding="utf-8",
1239
- timeout=30,
1240
- )
1241
- except (subprocess.TimeoutExpired, OSError):
1242
- return []
1243
- if result.returncode != 0 or not result.stdout.strip():
1244
- return []
1245
- try:
1246
- data = json.loads(result.stdout.strip())
1247
- if isinstance(data, list):
1248
- return [
1249
- {"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]
1250
- ]
1251
- return []
1252
- except (json.JSONDecodeError, TypeError):
1253
- return []
1277
+ data = run_tool("search_intel.py", ["search", f"{symbol} 最新消息"], timeout=30)
1278
+ if isinstance(data, list):
1279
+ return [{"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]]
1280
+ return []
1254
1281
 
1255
1282
 
1256
1283
  def cmd_news(args):
@@ -1363,17 +1390,29 @@ def cmd_financials(args):
1363
1390
 
1364
1391
 
1365
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)
1366
1402
  try:
1367
1403
  return _failover(
1368
1404
  [
1369
1405
  ("akshare", _snapshot_akshare),
1370
1406
  ("efinance", _snapshot_efinance),
1371
1407
  ("sina", _snapshot_sina),
1408
+ ("tencent", _snapshot_tencent),
1372
1409
  ],
1373
1410
  label="snapshot_a",
1374
1411
  )
1375
- except Exception:
1376
- 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)
1377
1416
 
1378
1417
 
1379
1418
  def _snapshot_efinance() -> list:
@@ -1429,6 +1468,63 @@ def _snapshot_sina() -> list:
1429
1468
  return [_clean_row(r) for r in df[keep].to_dict("records")]
1430
1469
 
1431
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
+
1432
1528
  def _snapshot_akshare() -> list:
1433
1529
  import akshare as ak
1434
1530
 
@@ -1612,8 +1708,9 @@ def cmd_market_indices(args):
1612
1708
  # --------------- sector_rankings ---------------
1613
1709
 
1614
1710
 
1615
- def _sector_rankings_efinance(top: int, direction: str):
1616
- """Fallback: fetch sector rankings via efinance."""
1711
+ def _sector_rankings_efinance() -> list:
1712
+ """Fallback: fetch industry board rankings via efinance (raw rows; sorting and
1713
+ top/direction are applied uniformly by cmd_sector_rankings after the failover)."""
1617
1714
  import efinance as ef
1618
1715
  import pandas as pd
1619
1716
 
@@ -1632,67 +1729,141 @@ def _sector_rankings_efinance(top: int, direction: str):
1632
1729
  df = df[keep]
1633
1730
  if "change_pct" in df.columns:
1634
1731
  df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
1635
- if direction == "bottom":
1636
- df = df.sort_values("change_pct", ascending=True).head(top)
1637
- elif direction == "both":
1638
- top_df = df.sort_values("change_pct", ascending=False).head(top)
1639
- bottom_df = df.sort_values("change_pct", ascending=True).head(top)
1640
- return {
1641
- "top": [_clean_row(r) for r in top_df.to_dict("records")],
1642
- "bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
1643
- }
1644
- else:
1645
- df = df.sort_values("change_pct", ascending=False).head(top)
1646
1732
  return [_clean_row(r) for r in df.to_dict("records")]
1647
1733
 
1648
1734
 
1735
+ def _sourced(name: str, fn):
1736
+ """Failover leg wrapper: tag each returned row with the provider name, so the
1737
+ caller can tell which source won (_failover returns only the result)."""
1738
+
1739
+ def run():
1740
+ rows = fn()
1741
+ for r in rows:
1742
+ r["source"] = name
1743
+ return rows
1744
+
1745
+ return name, run
1746
+
1747
+
1748
+ def _sector_rankings_em(board_type: str) -> list:
1749
+ """Eastmoney board rankings (industry or concept) via akshare."""
1750
+ import akshare as ak
1751
+ import pandas as pd
1752
+
1753
+ fetch = ak.stock_board_industry_name_em if board_type == "industry" else ak.stock_board_concept_name_em
1754
+ df = _akshare_retry(fetch)
1755
+ if df is None or df.empty:
1756
+ raise ValueError("eastmoney sector data unavailable")
1757
+ col_map = {
1758
+ "板块名称": "name",
1759
+ "板块代码": "code",
1760
+ "最新价": "price",
1761
+ "涨跌幅": "change_pct",
1762
+ "成交量": "volume",
1763
+ "成交额": "turnover",
1764
+ "换手率": "turnover_rate",
1765
+ "总市值": "market_cap",
1766
+ "上涨家数": "up_count",
1767
+ "下跌家数": "down_count",
1768
+ "领涨股票": "leading_stock",
1769
+ # industry boards name the column 领涨涨跌幅, concept boards 领涨股票-涨跌幅
1770
+ "领涨涨跌幅": "leading_change_pct",
1771
+ "领涨股票-涨跌幅": "leading_change_pct",
1772
+ }
1773
+ df = df.rename(columns=col_map)
1774
+ keep = list(dict.fromkeys(c for c in col_map.values() if c in df.columns))
1775
+ df = df[keep]
1776
+ if "change_pct" in df.columns:
1777
+ df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
1778
+ return [_clean_row(r) for r in df.to_dict("records")]
1779
+
1780
+
1781
+ def _sector_rankings_ths() -> list:
1782
+ """THS industry board rankings via akshare stock_board_industry_summary_ths.
1783
+
1784
+ There is no THS *concept* rankings table in this akshare version:
1785
+ stock_board_concept_name_ths returns only name/code columns and
1786
+ stock_board_concept_summary_ths is a concept timeline (日期/驱动事件), so the
1787
+ concept chain falls back to sina instead."""
1788
+ import akshare as ak
1789
+
1790
+ df = _akshare_retry(ak.stock_board_industry_summary_ths)
1791
+ if df is None or df.empty:
1792
+ raise ValueError("ths sector data unavailable")
1793
+ col_map = {
1794
+ "板块": "name",
1795
+ "涨跌幅": "change_pct",
1796
+ "总成交量": "volume",
1797
+ "总成交额": "turnover",
1798
+ "净流入": "net_inflow",
1799
+ "上涨家数": "up_count",
1800
+ "下跌家数": "down_count",
1801
+ "领涨股": "leading_stock",
1802
+ "领涨股-最新价": "leading_price",
1803
+ "领涨股-涨跌幅": "leading_change_pct",
1804
+ }
1805
+ df = df.rename(columns=col_map)
1806
+ keep = [c for c in col_map.values() if c in df.columns]
1807
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1808
+
1809
+
1810
+ def _sector_rankings_sina(indicator: str) -> list:
1811
+ """Sina board rankings via akshare stock_sector_spot (概念/行业/...).
1812
+
1813
+ Sina has no 上涨家数/下跌家数 — only 公司家数 (stock_count); the leading stock
1814
+ rides along in the same row (股票名称/个股-涨跌幅/个股-当前价)."""
1815
+ import akshare as ak
1816
+
1817
+ df = _akshare_retry(ak.stock_sector_spot, indicator=indicator)
1818
+ if df is None or df.empty:
1819
+ raise ValueError(f"sina sector data unavailable (indicator={indicator})")
1820
+ col_map = {
1821
+ "板块": "name",
1822
+ "公司家数": "stock_count",
1823
+ "涨跌额": "change",
1824
+ "涨跌幅": "change_pct",
1825
+ "总成交量": "volume",
1826
+ "总成交额": "turnover",
1827
+ "股票名称": "leading_stock",
1828
+ "个股-涨跌幅": "leading_change_pct",
1829
+ "个股-当前价": "leading_price",
1830
+ }
1831
+ df = df.rename(columns=col_map)
1832
+ keep = [c for c in col_map.values() if c in df.columns]
1833
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1834
+
1835
+
1649
1836
  def cmd_sector_rankings(args):
1837
+ board_type = getattr(args, "board_type", "industry")
1838
+ direction = getattr(args, "direction", "top")
1839
+ sources = [_sourced("eastmoney", lambda: _sector_rankings_em(board_type))]
1840
+ if board_type == "industry":
1841
+ # efinance has no concept boards — it stays an industry-only leg
1842
+ sources.append(_sourced("ths", _sector_rankings_ths))
1843
+ sources.append(_sourced("efinance", _sector_rankings_efinance))
1844
+ else:
1845
+ sources.append(_sourced("sina", lambda: _sector_rankings_sina("概念")))
1650
1846
  try:
1651
- import akshare as ak
1652
- import pandas as pd
1847
+ rows = _failover(sources, label=f"sector_rankings:{board_type}")
1848
+ if not rows:
1849
+ raise ValueError(f"no {board_type} board rankings data")
1850
+ except Exception as e:
1851
+ return {"error": str(e)}
1852
+ for r in rows:
1853
+ r["board_type"] = board_type
1653
1854
 
1654
- df = _akshare_retry(ak.stock_board_industry_name_em)
1655
- if df is None or df.empty:
1656
- raise ValueError("akshare sector data unavailable")
1657
- col_map = {
1658
- "板块名称": "name",
1659
- "板块代码": "code",
1660
- "最新价": "price",
1661
- "涨跌幅": "change_pct",
1662
- "成交量": "volume",
1663
- "成交额": "turnover",
1664
- "换手率": "turnover_rate",
1665
- "总市值": "market_cap",
1666
- "上涨家数": "up_count",
1667
- "下跌家数": "down_count",
1668
- "领涨股票": "leading_stock",
1669
- "领涨涨跌幅": "leading_change_pct",
1855
+ def _pct(row, default):
1856
+ v = row.get("change_pct")
1857
+ return v if isinstance(v, (int, float)) else default
1858
+
1859
+ if direction == "bottom":
1860
+ return sorted(rows, key=lambda r: _pct(r, float("inf")))[: args.top]
1861
+ if direction == "both":
1862
+ return {
1863
+ "top": sorted(rows, key=lambda r: _pct(r, float("-inf")), reverse=True)[: args.top],
1864
+ "bottom": sorted(rows, key=lambda r: _pct(r, float("inf")))[: args.top],
1670
1865
  }
1671
- df = df.rename(columns=col_map)
1672
- keep = [c for c in col_map.values() if c in df.columns]
1673
- df = df[keep]
1674
- if "change_pct" in df.columns:
1675
- df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
1676
-
1677
- direction = getattr(args, "direction", "top")
1678
- if direction == "bottom":
1679
- df = df.sort_values("change_pct", ascending=True).head(args.top)
1680
- elif direction == "both":
1681
- top_df = df.sort_values("change_pct", ascending=False).head(args.top)
1682
- bottom_df = df.sort_values("change_pct", ascending=True).head(args.top)
1683
- return {
1684
- "top": [_clean_row(r) for r in top_df.to_dict("records")],
1685
- "bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
1686
- }
1687
- else:
1688
- df = df.head(args.top)
1689
- return [_clean_row(r) for r in df.to_dict("records")]
1690
- except Exception:
1691
- try:
1692
- direction = getattr(args, "direction", "top")
1693
- return _sector_rankings_efinance(args.top, direction)
1694
- except Exception as e2:
1695
- return {"error": str(e2)}
1866
+ return sorted(rows, key=lambda r: _pct(r, float("-inf")), reverse=True)[: args.top]
1696
1867
 
1697
1868
 
1698
1869
  # --------------- sector constituents / stock sectors (issue #18) ---------------
@@ -2259,6 +2430,291 @@ def cmd_fundamental_context(args):
2259
2430
  return {"error": str(e)}
2260
2431
 
2261
2432
 
2433
+ # --------------- short-term sentiment: limit_up_pool / dragon_tiger / hot_stocks (A-share only) ---------------
2434
+
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
+
2460
+ def cmd_limit_up_pool(args):
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}"
2480
+ try:
2481
+ import akshare as ak
2482
+
2483
+ df = _akshare_retry(ak.stock_zt_pool_em, date=date)
2484
+ if df is None or df.empty:
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
2496
+ col_map = {
2497
+ "代码": "code",
2498
+ "名称": "name",
2499
+ "涨跌幅": "change_pct",
2500
+ "最新价": "price",
2501
+ "成交额": "turnover",
2502
+ "流通市值": "float_market_cap",
2503
+ "总市值": "total_market_cap",
2504
+ "换手率": "turnover_rate",
2505
+ "封板资金": "seal_amount",
2506
+ "首次封板时间": "first_seal_time",
2507
+ "最后封板时间": "last_seal_time",
2508
+ "炸板次数": "break_count",
2509
+ "涨停统计": "limit_up_stat",
2510
+ "连板数": "consecutive_boards",
2511
+ "所属行业": "industry",
2512
+ }
2513
+ df = df.rename(columns=col_map)
2514
+ keep = [c for c in col_map.values() if c in df.columns]
2515
+ pool = [_clean_row(r) for r in df[keep].to_dict("records")]
2516
+ boards = [r["consecutive_boards"] for r in pool if isinstance(r.get("consecutive_boards"), (int, float))]
2517
+ result["count"] = len(pool)
2518
+ result["max_consecutive_boards"] = max(boards) if boards else 0
2519
+ result["pool"] = pool
2520
+ return result
2521
+ except Exception as e:
2522
+ return {"error": f"limit_up_pool date={requested}: {e}"}
2523
+
2524
+
2525
+ def _dragon_tiger_em(raw: str) -> list:
2526
+ """Eastmoney 龙虎榜 via akshare stock_lhb_detail_em."""
2527
+ import akshare as ak
2528
+ import pandas as pd
2529
+
2530
+ df = _akshare_retry(ak.stock_lhb_detail_em, start_date=raw, end_date=raw)
2531
+ if df is None or df.empty:
2532
+ return []
2533
+ col_map = {
2534
+ "代码": "code",
2535
+ "名称": "name",
2536
+ "上榜日": "list_date",
2537
+ "收盘价": "close",
2538
+ "涨跌幅": "change_pct",
2539
+ "龙虎榜净买额": "net_buy",
2540
+ "龙虎榜买入额": "buy_amount",
2541
+ "龙虎榜卖出额": "sell_amount",
2542
+ "龙虎榜成交额": "lhb_turnover",
2543
+ "上榜原因": "reason",
2544
+ "解读": "interpretation",
2545
+ }
2546
+ df = df.rename(columns=col_map)
2547
+ keep = [c for c in col_map.values() if c in df.columns]
2548
+ df = df[keep]
2549
+ if "net_buy" in df.columns:
2550
+ df["net_buy"] = pd.to_numeric(df["net_buy"], errors="coerce")
2551
+ return [_clean_row(r) for r in df.to_dict("records")]
2552
+
2553
+
2554
+ def _dragon_tiger_sina(raw: str) -> list:
2555
+ """Sina 龙虎榜每日详情 via akshare stock_lhb_detail_daily_sina.
2556
+
2557
+ Sina has no 涨跌幅/净买额/买入额/卖出额/上榜日/解读 — its 指标 column is the
2558
+ listing reason and list_date is filled from the query date. A stock listed for
2559
+ several reasons appears once per reason (sina's page layout)."""
2560
+ import akshare as ak
2561
+
2562
+ df = _akshare_retry(ak.stock_lhb_detail_daily_sina, date=raw)
2563
+ if df is None or df.empty:
2564
+ return []
2565
+ col_map = {
2566
+ "股票代码": "code",
2567
+ "股票名称": "name",
2568
+ "收盘价": "close",
2569
+ "指标": "reason",
2570
+ }
2571
+ df = df.rename(columns=col_map)
2572
+ keep = [c for c in col_map.values() if c in df.columns]
2573
+ rows = [_clean_row(r) for r in df[keep].to_dict("records")]
2574
+ date_iso = f"{raw[:4]}-{raw[4:6]}-{raw[6:8]}"
2575
+ for r in rows:
2576
+ r["list_date"] = date_iso
2577
+ return rows
2578
+
2579
+
2580
+ def cmd_dragon_tiger(args):
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")
2593
+ sources = [
2594
+ _sourced("eastmoney", lambda: _dragon_tiger_em(raw)),
2595
+ _sourced("sina", lambda: _dragon_tiger_sina(raw)),
2596
+ ]
2597
+ try:
2598
+ rows = _failover(sources, label=f"dragon_tiger:{raw}")
2599
+ except Exception as e:
2600
+ return {"error": str(e)}
2601
+ stale = req != data_day
2602
+ if not rows:
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
2614
+ source = rows[0]["source"]
2615
+ if args.symbol:
2616
+ m = re.fullmatch(r"(?:sh|sz|bj)(\d{6})", str(args.symbol), re.IGNORECASE)
2617
+ want = m.group(1) if m else str(args.symbol)
2618
+ rows = [r for r in rows if str(r.get("code")) == want]
2619
+ if any(isinstance(r.get("net_buy"), (int, float)) for r in rows):
2620
+ rows = sorted(
2621
+ rows,
2622
+ key=lambda r: abs(r["net_buy"]) if isinstance(r.get("net_buy"), (int, float)) else 0,
2623
+ reverse=True,
2624
+ )
2625
+ items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
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
2632
+
2633
+
2634
+ def _strip_exchange_prefix(row: dict) -> dict:
2635
+ """Bare the exchange prefix on row["code"] ("SZ000001" → "000001", original kept in
2636
+ code_full). Bare 6-digit codes pass through unchanged."""
2637
+ m = re.fullmatch(r"(sh|sz|bj)(\d{6})", str(row.get("code") or ""), re.IGNORECASE)
2638
+ if m:
2639
+ row["code_full"] = row["code"]
2640
+ row["code"] = m.group(2)
2641
+ return row
2642
+
2643
+
2644
+ def _hot_stocks_em() -> list:
2645
+ """Eastmoney 人气榜 via akshare stock_hot_rank_em."""
2646
+ import akshare as ak
2647
+
2648
+ df = _akshare_retry(ak.stock_hot_rank_em)
2649
+ if df is None or df.empty:
2650
+ return []
2651
+ col_map = {
2652
+ "当前排名": "rank",
2653
+ "代码": "code",
2654
+ "股票名称": "name",
2655
+ "最新价": "price",
2656
+ "涨跌幅": "change_pct",
2657
+ }
2658
+ df = df.rename(columns=col_map)
2659
+ keep = [c for c in col_map.values() if c in df.columns]
2660
+ return [_strip_exchange_prefix(_clean_row(r)) for r in df[keep].to_dict("records")]
2661
+
2662
+
2663
+ def _hot_stocks_xq() -> list:
2664
+ """Xueqiu follow ranking via akshare stock_hot_follow_xq. No 涨跌幅 column;
2665
+ rank is the row position. Codes arrive SH/SZ-prefixed like eastmoney's."""
2666
+ import akshare as ak
2667
+
2668
+ df = _akshare_retry(ak.stock_hot_follow_xq, symbol="最热门")
2669
+ if df is None or df.empty:
2670
+ return []
2671
+ col_map = {
2672
+ "股票代码": "code",
2673
+ "股票简称": "name",
2674
+ "最新价": "price",
2675
+ }
2676
+ df = df.rename(columns=col_map)
2677
+ keep = [c for c in col_map.values() if c in df.columns]
2678
+ return [{"rank": i, **_strip_exchange_prefix(_clean_row(r))} for i, r in enumerate(df[keep].to_dict("records"), 1)]
2679
+
2680
+
2681
+ def _hot_stocks_baidu() -> list:
2682
+ """Baidu 股市通热搜 via akshare stock_hot_search_baidu. No code/price columns —
2683
+ only the stock name — and 涨跌幅 strings carry a % suffix."""
2684
+ import akshare as ak
2685
+
2686
+ df = _akshare_retry(
2687
+ ak.stock_hot_search_baidu,
2688
+ symbol="A股",
2689
+ date=datetime.now().strftime("%Y%m%d"),
2690
+ time="今日",
2691
+ )
2692
+ if df is None or df.empty:
2693
+ return []
2694
+ rows = []
2695
+ for i, r in enumerate(df.to_dict("records"), 1):
2696
+ pct = str(r.get("涨跌幅") or "").replace("%", "")
2697
+ rows.append(_clean_row({"rank": i, "name": r.get("名称/代码"), "change_pct": _parse_float(pct)}))
2698
+ return rows
2699
+
2700
+
2701
+ def cmd_hot_stocks(args):
2702
+ """A-share popularity ranking (人气榜): eastmoney → xueqiu → baidu."""
2703
+ sources = [
2704
+ _sourced("eastmoney", _hot_stocks_em),
2705
+ _sourced("xueqiu", _hot_stocks_xq),
2706
+ _sourced("baidu", _hot_stocks_baidu),
2707
+ ]
2708
+ try:
2709
+ rows = _failover(sources, label="hot_stocks")
2710
+ except Exception as e:
2711
+ return {"error": str(e)}
2712
+ if not rows:
2713
+ return {"count": 0, "items": [], "note": "no hot-rank data available"}
2714
+ items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
2715
+ return {"count": len(items), "items": items, "source": rows[0]["source"]}
2716
+
2717
+
2262
2718
  # --------------- CLI ---------------
2263
2719
 
2264
2720
 
@@ -2298,6 +2754,7 @@ def main():
2298
2754
  p_sec = sub.add_parser("sector_rankings")
2299
2755
  p_sec.add_argument("--top", type=int, default=10)
2300
2756
  p_sec.add_argument("--direction", default="top", choices=["top", "bottom", "both"])
2757
+ p_sec.add_argument("--board-type", default="industry", choices=["industry", "concept"])
2301
2758
 
2302
2759
  p_cons = sub.add_parser("sector_constituents")
2303
2760
  p_cons.add_argument("sector")
@@ -2312,12 +2769,22 @@ def main():
2312
2769
  p_chip = sub.add_parser("chip_distribution")
2313
2770
  p_chip.add_argument("symbol")
2314
2771
 
2315
- p_stats = sub.add_parser("market_stats")
2316
- p_stats.add_argument("--market", default="A", choices=["A"])
2772
+ sub.add_parser("market_stats")
2317
2773
 
2318
2774
  p_fund = sub.add_parser("fundamental_context")
2319
2775
  p_fund.add_argument("symbol")
2320
2776
 
2777
+ p_zt = sub.add_parser("limit_up_pool")
2778
+ p_zt.add_argument("--date", default=None, help="Trading date in YYYYMMDD format (default: today)")
2779
+
2780
+ p_lhb = sub.add_parser("dragon_tiger")
2781
+ p_lhb.add_argument("--date", default=None, help="Trading date in YYYY-MM-DD format (default: today)")
2782
+ p_lhb.add_argument("--symbol", default=None, help="Filter to a single stock code")
2783
+ p_lhb.add_argument("--top", type=int, default=20)
2784
+
2785
+ p_hot = sub.add_parser("hot_stocks")
2786
+ p_hot.add_argument("--top", type=int, default=20)
2787
+
2321
2788
  args = parser.parse_args()
2322
2789
  if not args.command:
2323
2790
  parser.print_help()
@@ -2338,6 +2805,9 @@ def main():
2338
2805
  "chip_distribution": cmd_chip_distribution,
2339
2806
  "market_stats": cmd_market_stats,
2340
2807
  "fundamental_context": cmd_fundamental_context,
2808
+ "limit_up_pool": cmd_limit_up_pool,
2809
+ "dragon_tiger": cmd_dragon_tiger,
2810
+ "hot_stocks": cmd_hot_stocks,
2341
2811
  }
2342
2812
  # Provider libraries (baostock etc.) print prose to stdout on failure,
2343
2813
  # which would corrupt the JSON-only contract — divert that noise to stderr.