@weaxs/openclaw-stock-analysis 0.1.14 → 0.2.0
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 +1 -1
- package/dist/index.js +178 -44
- package/index.ts +189 -42
- package/openclaw.plugin.json +7 -0
- package/package.json +1 -1
- package/skills/bottom-volume/SKILL.md +1 -4
- package/skills/bottom-volume/scripts/gather.py +1 -1
- package/skills/box-oscillation/SKILL.md +1 -4
- package/skills/box-oscillation/scripts/gather.py +1 -1
- package/skills/bull-trend/SKILL.md +1 -4
- package/skills/bull-trend/scripts/gather.py +1 -1
- package/skills/chan-theory/SKILL.md +1 -4
- package/skills/chan-theory/scripts/gather.py +1 -1
- package/skills/dragon-head/SKILL.md +24 -28
- package/skills/dragon-head/scripts/gather.py +1 -1
- package/skills/emotion-cycle/SKILL.md +19 -33
- package/skills/emotion-cycle/scripts/gather.py +4 -3
- package/skills/event-driven/SKILL.md +42 -26
- package/skills/event-driven/scripts/gather.py +1 -1
- package/skills/expectation-repricing/SKILL.md +11 -6
- package/skills/expectation-repricing/scripts/gather.py +1 -1
- package/skills/growth-quality/SKILL.md +11 -6
- package/skills/growth-quality/scripts/gather.py +1 -1
- package/skills/hot-theme/SKILL.md +27 -23
- package/skills/hot-theme/scripts/gather.py +1 -1
- package/skills/ma-crossover/SKILL.md +1 -4
- package/skills/ma-crossover/scripts/gather.py +1 -1
- package/skills/market-review/SKILL.md +11 -8
- package/skills/market-review/scripts/gather.py +1 -1
- package/skills/one-yang-three-yin/SKILL.md +1 -4
- package/skills/one-yang-three-yin/scripts/gather.py +1 -1
- package/skills/shrink-pullback/SKILL.md +1 -4
- package/skills/shrink-pullback/scripts/gather.py +1 -1
- package/skills/stock-analysis/SKILL.md +18 -77
- package/skills/stock-analysis/references/short-term-trading.md +78 -0
- package/skills/stock-analysis/scripts/gather.py +1 -1
- package/skills/stock-screener/SKILL.md +7 -6
- package/skills/stock-screener/scripts/gather.py +1 -1
- package/skills/strategy-backtest/SKILL.md +24 -20
- package/skills/strategy-backtest/scripts/gather.py +1 -1
- package/skills/volume-breakout/SKILL.md +21 -23
- package/skills/volume-breakout/scripts/gather.py +1 -1
- package/skills/wave-theory/SKILL.md +1 -4
- package/skills/wave-theory/scripts/gather.py +1 -1
- package/skills/wisburg-research/SKILL.md +2 -2
- package/tools/alert_rules.py +5 -18
- package/tools/backtest.py +4 -4
- package/tools/capabilities.py +11 -4
- package/tools/diagnostics.py +13 -2
- package/tools/gather.py +12 -31
- package/tools/market_regime.py +4 -1
- package/tools/market_review.py +1 -1
- package/tools/name_resolver.py +4 -10
- package/tools/pattern.py +3 -24
- package/tools/report_renderer.py +1 -2
- package/tools/screener.py +2 -16
- package/tools/search_intel.py +1 -24
- package/tools/signal_tracker.py +275 -0
- package/tools/stock_data.py +704 -167
- package/tools/trading_calendar.py +92 -7
- package/tools/volume_analysis.py +3 -23
- package/tools/watchlist_context.py +1 -10
- package/scripts/sync-version.sh +0 -56
package/tools/stock_data.py
CHANGED
|
@@ -12,9 +12,19 @@ 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
|
+
|
|
18
|
+
# Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
|
|
19
|
+
# Bare 6-digit codes are always stocks; the prefix is the disambiguation escape
|
|
20
|
+
# hatch for index codes (sh000001 = 上证指数, not 平安银行).
|
|
21
|
+
_A_PREFIXED_RE = re.compile(r"(?:sh|sz|bj)\d{6}", re.IGNORECASE)
|
|
22
|
+
|
|
15
23
|
|
|
16
24
|
def detect_market(symbol: str) -> str:
|
|
17
25
|
s = symbol.upper()
|
|
26
|
+
if _A_PREFIXED_RE.fullmatch(symbol):
|
|
27
|
+
return "A"
|
|
18
28
|
if s.endswith(".HK"):
|
|
19
29
|
return "HK"
|
|
20
30
|
if s.endswith(".T"):
|
|
@@ -55,15 +65,6 @@ def normalize_stock_code(symbol: str) -> dict:
|
|
|
55
65
|
return info
|
|
56
66
|
|
|
57
67
|
|
|
58
|
-
def mark_st(info: dict, name: str) -> dict:
|
|
59
|
-
"""Mark ST status from stock name; adjusts limit_pct to 5%."""
|
|
60
|
-
if name and "ST" in name.upper():
|
|
61
|
-
info["is_st"] = True
|
|
62
|
-
if info["board"] == "main":
|
|
63
|
-
info["limit_pct"] = 0.05
|
|
64
|
-
return info
|
|
65
|
-
|
|
66
|
-
|
|
67
68
|
def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
|
|
68
69
|
"""Calculate limit-up or limit-down price with banker's rounding."""
|
|
69
70
|
import numpy as np
|
|
@@ -72,13 +73,46 @@ def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> f
|
|
|
72
73
|
return np.floor(pre_close * (1 + sign * ratio) * 100 + 0.5) / 100.0
|
|
73
74
|
|
|
74
75
|
|
|
76
|
+
# Chains that get sticky ordering: the CN free-source chains, where failures are
|
|
77
|
+
# typically chronic (regional blocking / rate-limiting — eastmoney is the primary
|
|
78
|
+
# leg of most of them). The yf chains (`kline:`/`quote:`) are
|
|
79
|
+
# excluded on purpose — their failures are usually transient yfinance blips, and
|
|
80
|
+
# stickiness would let one blip degrade HK/US quote richness (finnhub has no
|
|
81
|
+
# name/market_cap/pe/pb) for the whole TTL.
|
|
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
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
75
95
|
def _failover(sources: list, label: str):
|
|
76
|
-
"""Return first truthy result; else raise RuntimeError aggregating each source's error.
|
|
96
|
+
"""Return first truthy result; else raise RuntimeError aggregating each source's error.
|
|
97
|
+
|
|
98
|
+
Sticky ordering (issue #25): for chains in _STICKY_CHAINS (keyed by the label
|
|
99
|
+
before ":"), the last winning source is tried first next time; the rest keep
|
|
100
|
+
their declared order. Persisted via the sector disk cache below (tempdir, 24h
|
|
101
|
+
TTL), so it survives across the one-process-per-CLI-call host model; a stale
|
|
102
|
+
entry costs one failed attempt, then the new winner replaces it (self-healing).
|
|
103
|
+
"""
|
|
104
|
+
chain = label.split(":", 1)[0]
|
|
105
|
+
if chain in _STICKY_CHAINS:
|
|
106
|
+
sticky = _disk_cache_get(f"sticky-{chain}")
|
|
107
|
+
if sticky:
|
|
108
|
+
sources = sorted(sources, key=lambda s: s[0] != sticky)
|
|
77
109
|
errors = []
|
|
78
110
|
for name, fn in sources:
|
|
79
111
|
try:
|
|
80
112
|
result = fn()
|
|
81
113
|
if result:
|
|
114
|
+
if chain in _STICKY_CHAINS:
|
|
115
|
+
_disk_cache_set(f"sticky-{chain}", name)
|
|
82
116
|
return result
|
|
83
117
|
except Exception as e:
|
|
84
118
|
errors.append(f"{name}: {type(e).__name__}: {e}")
|
|
@@ -97,30 +131,9 @@ def _akshare_retry(fn, *args, retries=2, delay=1, **kwargs):
|
|
|
97
131
|
time.sleep(delay)
|
|
98
132
|
|
|
99
133
|
|
|
100
|
-
# Index codes collide with SZ stocks in the 000xxx range (000001 is both the
|
|
101
|
-
# SSE Composite and Ping An Bank), so indices need an explicit exchange mapping.
|
|
102
|
-
_BAOSTOCK_INDEX_CODES = {
|
|
103
|
-
"000001": "sh", # 上证综指
|
|
104
|
-
"000016": "sh", # 上证50
|
|
105
|
-
"000300": "sh", # 沪深300
|
|
106
|
-
"000688": "sh", # 科创50
|
|
107
|
-
"000852": "sh", # 中证1000
|
|
108
|
-
"000905": "sh", # 中证500
|
|
109
|
-
"399001": "sz", # 深证成指
|
|
110
|
-
"399005": "sz", # 中小100
|
|
111
|
-
"399006": "sz", # 创业板指
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
|
|
115
134
|
def _to_baostock_code(symbol: str) -> str:
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
return f"{index_exchange}.{symbol}"
|
|
119
|
-
if symbol.startswith(
|
|
120
|
-
("600", "601", "603", "605", "688", "689", "510", "512", "513", "515", "516", "518", "560", "588")
|
|
121
|
-
):
|
|
122
|
-
return f"sh.{symbol}"
|
|
123
|
-
return f"sz.{symbol}"
|
|
135
|
+
code = _cn_code(symbol)
|
|
136
|
+
return f"{code[:2]}.{code[2:]}"
|
|
124
137
|
|
|
125
138
|
|
|
126
139
|
def _kline_efinance(symbol: str, period: str, count: int) -> list:
|
|
@@ -229,6 +242,181 @@ def _quote_efinance(symbol: str) -> dict:
|
|
|
229
242
|
return _clean_row(result)
|
|
230
243
|
|
|
231
244
|
|
|
245
|
+
# --------------- tencent / sina (non-eastmoney A-share fallbacks, issue #25) ---------------
|
|
246
|
+
#
|
|
247
|
+
# akshare/efinance both resolve to eastmoney hosts, so an eastmoney-blocked network
|
|
248
|
+
# kills the whole A-share chain. Tencent (qt.gtimg.cn) and Sina (hq.sinajs.cn) are
|
|
249
|
+
# independent quote endpoints needing no credentials; both cover stocks, ETFs,
|
|
250
|
+
# indices and BSE codes.
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _cn_code(symbol: str) -> str:
|
|
254
|
+
"""Exchange-prefixed code shared by Tencent and Sina: 600519 → sh600519, BSE → bj920001."""
|
|
255
|
+
if _A_PREFIXED_RE.fullmatch(symbol):
|
|
256
|
+
return symbol.lower()
|
|
257
|
+
if symbol.startswith(("43", "81", "82", "83", "87", "88", "92")):
|
|
258
|
+
return f"bj{symbol}"
|
|
259
|
+
return f"sh{symbol}" if symbol.startswith(("5", "6", "9")) else f"sz{symbol}"
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _parse_float(value):
|
|
263
|
+
"""Provider string field → float; empty/garbage → None (never raises)."""
|
|
264
|
+
try:
|
|
265
|
+
return float(value)
|
|
266
|
+
except (TypeError, ValueError):
|
|
267
|
+
return None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _gbk_var_payload(content: bytes) -> str:
|
|
271
|
+
"""Extract the quoted payload from a GBK `v_sh600519="..."` / `var hq_str_...="..."` body."""
|
|
272
|
+
return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
|
|
273
|
+
|
|
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
|
|
287
|
+
turnover = _parse_float(f[37])
|
|
288
|
+
market_cap = _parse_float(f[45])
|
|
289
|
+
row = {
|
|
290
|
+
"symbol": symbol,
|
|
291
|
+
"name": f[1],
|
|
292
|
+
"price": _parse_float(f[3]),
|
|
293
|
+
"change": _parse_float(f[31]),
|
|
294
|
+
"change_pct": _parse_float(f[32]),
|
|
295
|
+
"volume": _parse_float(f[6]), # 手, same as akshare
|
|
296
|
+
"turnover": turnover * 1e4 if turnover is not None else None,
|
|
297
|
+
"high": _parse_float(f[33]),
|
|
298
|
+
"low": _parse_float(f[34]),
|
|
299
|
+
"open": _parse_float(f[5]),
|
|
300
|
+
"prev_close": _parse_float(f[4]),
|
|
301
|
+
"market_cap": market_cap * 1e8 if market_cap is not None else None,
|
|
302
|
+
"pe": _parse_float(f[39]),
|
|
303
|
+
"pb": _parse_float(f[46]),
|
|
304
|
+
"turnover_rate": _parse_float(f[38]),
|
|
305
|
+
"amplitude": _parse_float(f[43]),
|
|
306
|
+
}
|
|
307
|
+
if normalize_stock_code(symbol)["is_etf"]:
|
|
308
|
+
row["is_etf"] = True
|
|
309
|
+
return _clean_row(row)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _kline_tencent(symbol: str, period: str, count: int) -> list:
|
|
313
|
+
"""Tencent kline via web.ifzq.gtimg.cn. Rows are [date, open, close, high, low,
|
|
314
|
+
volume(手)] ascending; qfq-adjusted like akshare. When a symbol has no qfq series
|
|
315
|
+
(e.g. BSE codes) the endpoint returns the raw `day/week/month` key instead."""
|
|
316
|
+
import requests
|
|
317
|
+
|
|
318
|
+
p_map = {"daily": "day", "weekly": "week", "monthly": "month"}
|
|
319
|
+
p = p_map.get(period, "day")
|
|
320
|
+
code = _cn_code(symbol)
|
|
321
|
+
resp = requests.get(
|
|
322
|
+
"https://web.ifzq.gtimg.cn/appstock/app/fqkline/get",
|
|
323
|
+
params={"param": f"{code},{p},,,{count},qfq"},
|
|
324
|
+
timeout=10,
|
|
325
|
+
)
|
|
326
|
+
data = resp.json()
|
|
327
|
+
if data.get("code") != 0:
|
|
328
|
+
raise ValueError(f"tencent kline failed: {data.get('msg', '')}")
|
|
329
|
+
node = data.get("data", {}).get(code, {})
|
|
330
|
+
rows = node.get(f"qfq{p}") or node.get(p)
|
|
331
|
+
if not rows:
|
|
332
|
+
raise ValueError("tencent kline returned empty data")
|
|
333
|
+
return [
|
|
334
|
+
_clean_row(
|
|
335
|
+
{
|
|
336
|
+
"date": r[0],
|
|
337
|
+
"open": _parse_float(r[1]),
|
|
338
|
+
"high": _parse_float(r[3]),
|
|
339
|
+
"low": _parse_float(r[4]),
|
|
340
|
+
"close": _parse_float(r[2]),
|
|
341
|
+
"volume": _parse_float(r[5]),
|
|
342
|
+
}
|
|
343
|
+
)
|
|
344
|
+
for r in rows[-count:]
|
|
345
|
+
]
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _quote_sina(symbol: str) -> dict:
|
|
349
|
+
"""Sina quote via hq.sinajs.cn. Requires a finance.sina.com.cn Referer or the
|
|
350
|
+
endpoint answers 403. GBK-encoded CSV; volume arrives in 股 → normalized to 手."""
|
|
351
|
+
import requests
|
|
352
|
+
|
|
353
|
+
resp = requests.get(
|
|
354
|
+
f"https://hq.sinajs.cn/list={_cn_code(symbol)}",
|
|
355
|
+
headers={"Referer": "https://finance.sina.com.cn"},
|
|
356
|
+
timeout=10,
|
|
357
|
+
)
|
|
358
|
+
f = _gbk_var_payload(resp.content).split(",")
|
|
359
|
+
if len(f) < 10 or not f[0]:
|
|
360
|
+
raise ValueError(f"sina returned no quote for {symbol}")
|
|
361
|
+
price = _parse_float(f[3])
|
|
362
|
+
prev_close = _parse_float(f[2])
|
|
363
|
+
volume = _parse_float(f[8])
|
|
364
|
+
row = {
|
|
365
|
+
"symbol": symbol,
|
|
366
|
+
"name": f[0],
|
|
367
|
+
"price": price,
|
|
368
|
+
"change": (price - prev_close) if price is not None and prev_close else None,
|
|
369
|
+
"change_pct": ((price / prev_close) - 1) * 100 if price is not None and prev_close else None,
|
|
370
|
+
"volume": volume / 100 if volume is not None else None,
|
|
371
|
+
"turnover": _parse_float(f[9]), # already 元
|
|
372
|
+
"high": _parse_float(f[4]),
|
|
373
|
+
"low": _parse_float(f[5]),
|
|
374
|
+
"open": _parse_float(f[1]),
|
|
375
|
+
"prev_close": prev_close,
|
|
376
|
+
}
|
|
377
|
+
if normalize_stock_code(symbol)["is_etf"]:
|
|
378
|
+
row["is_etf"] = True
|
|
379
|
+
return _clean_row(row)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _kline_sina(symbol: str, period: str, count: int) -> list:
|
|
383
|
+
"""Sina daily kline via quotes.sina.cn (JSONP-wrapped; scale=240 = daily is the
|
|
384
|
+
only supported period). Unadjusted; volume arrives in 股 → normalized to 手."""
|
|
385
|
+
if period != "daily":
|
|
386
|
+
raise ValueError("sina kline supports daily period only")
|
|
387
|
+
import requests
|
|
388
|
+
|
|
389
|
+
resp = requests.get(
|
|
390
|
+
"https://quotes.sina.cn/cn/api/jsonp_v2.php/var%20_k=/CN_MarketDataService.getKLineData",
|
|
391
|
+
params={"symbol": _cn_code(symbol), "scale": "240", "ma": "no", "datalen": str(min(count, 1023))},
|
|
392
|
+
headers={"Referer": "https://finance.sina.com.cn"},
|
|
393
|
+
timeout=10,
|
|
394
|
+
)
|
|
395
|
+
text = resp.text
|
|
396
|
+
start, end = text.find("["), text.rfind("]")
|
|
397
|
+
if start < 0 or end <= start:
|
|
398
|
+
raise ValueError("sina kline returned unparseable data")
|
|
399
|
+
rows = json.loads(text[start : end + 1])
|
|
400
|
+
if not rows:
|
|
401
|
+
raise ValueError("sina kline returned empty data")
|
|
402
|
+
result = []
|
|
403
|
+
for r in rows[-count:]:
|
|
404
|
+
volume = _parse_float(r.get("volume"))
|
|
405
|
+
result.append(
|
|
406
|
+
_clean_row(
|
|
407
|
+
{
|
|
408
|
+
"date": r.get("day"),
|
|
409
|
+
"open": _parse_float(r.get("open")),
|
|
410
|
+
"high": _parse_float(r.get("high")),
|
|
411
|
+
"low": _parse_float(r.get("low")),
|
|
412
|
+
"close": _parse_float(r.get("close")),
|
|
413
|
+
"volume": volume / 100 if volume is not None else None,
|
|
414
|
+
}
|
|
415
|
+
)
|
|
416
|
+
)
|
|
417
|
+
return result
|
|
418
|
+
|
|
419
|
+
|
|
232
420
|
def _sanitize(obj):
|
|
233
421
|
"""Convert pandas types to JSON-serializable Python types."""
|
|
234
422
|
import numpy as np
|
|
@@ -255,17 +443,27 @@ def _clean_row(d: dict) -> dict:
|
|
|
255
443
|
|
|
256
444
|
|
|
257
445
|
def kline_a(symbol: str, period: str, count: int) -> list:
|
|
258
|
-
"""A-share kline with failover: akshare → tushare → efinance → pytdx → baostock.
|
|
259
|
-
|
|
260
|
-
|
|
446
|
+
"""A-share kline with failover: akshare → tushare → efinance → tencent → sina → pytdx → baostock.
|
|
447
|
+
|
|
448
|
+
Explicitly-prefixed symbols (sh000001, typically indices) skip the eastmoney
|
|
449
|
+
sources — they take bare 6-digit codes only and would fail slowly first."""
|
|
450
|
+
if _A_PREFIXED_RE.fullmatch(symbol):
|
|
451
|
+
sources = [
|
|
452
|
+
("tencent", lambda: _kline_tencent(symbol, period, count)),
|
|
453
|
+
("sina", lambda: _kline_sina(symbol, period, count)),
|
|
454
|
+
("baostock", lambda: _kline_baostock(symbol, period, count)),
|
|
455
|
+
]
|
|
456
|
+
else:
|
|
457
|
+
sources = [
|
|
261
458
|
("akshare", lambda: _kline_akshare(symbol, period, count)),
|
|
262
459
|
("tushare", lambda: _kline_tushare(symbol, period, count)),
|
|
263
460
|
("efinance", lambda: _kline_efinance(symbol, period, count)),
|
|
461
|
+
("tencent", lambda: _kline_tencent(symbol, period, count)),
|
|
462
|
+
("sina", lambda: _kline_sina(symbol, period, count)),
|
|
264
463
|
("pytdx", lambda: _kline_pytdx(symbol, period, count)),
|
|
265
464
|
("baostock", lambda: _kline_baostock(symbol, period, count)),
|
|
266
|
-
]
|
|
267
|
-
|
|
268
|
-
)
|
|
465
|
+
]
|
|
466
|
+
return _failover(sources, label=f"kline_a:{symbol}")
|
|
269
467
|
|
|
270
468
|
|
|
271
469
|
def _kline_akshare(symbol: str, period: str, count: int) -> list:
|
|
@@ -771,17 +969,29 @@ def cmd_kline(args):
|
|
|
771
969
|
|
|
772
970
|
|
|
773
971
|
def quote_a(symbol: str) -> dict:
|
|
774
|
-
"""A-share quote with failover: akshare → tushare → efinance → pytdx. ETFs try fund spot first.
|
|
972
|
+
"""A-share quote with failover: akshare → tushare → efinance → tencent → sina → pytdx. ETFs try fund spot first.
|
|
973
|
+
|
|
974
|
+
Explicitly-prefixed symbols (sh000001, typically indices) go straight to
|
|
975
|
+
tencent/sina — the eastmoney sources take bare 6-digit codes only, and pytdx
|
|
976
|
+
can't place prefixed codes either. ETF quotes use their own sticky chain key
|
|
977
|
+
(quote_a_etf) so a stock-side winner never demotes the fund-spot source."""
|
|
978
|
+
if _A_PREFIXED_RE.fullmatch(symbol):
|
|
979
|
+
sources = [("tencent", lambda: _quote_tencent(symbol)), ("sina", lambda: _quote_sina(symbol))]
|
|
980
|
+
return _failover(sources, label=f"quote_a:{symbol}")
|
|
981
|
+
is_etf = normalize_stock_code(symbol)["is_etf"]
|
|
775
982
|
sources = []
|
|
776
|
-
if
|
|
983
|
+
if is_etf:
|
|
777
984
|
sources.append(("akshare_etf", lambda: _quote_akshare_etf(symbol)))
|
|
778
985
|
sources += [
|
|
779
986
|
("akshare", lambda: _quote_akshare(symbol)),
|
|
780
987
|
("tushare", lambda: _quote_tushare(symbol)),
|
|
781
988
|
("efinance", lambda: _quote_efinance(symbol)),
|
|
989
|
+
("tencent", lambda: _quote_tencent(symbol)),
|
|
990
|
+
("sina", lambda: _quote_sina(symbol)),
|
|
782
991
|
("pytdx", lambda: _quote_pytdx(symbol)),
|
|
783
992
|
]
|
|
784
|
-
|
|
993
|
+
chain = "quote_a_etf" if is_etf else "quote_a"
|
|
994
|
+
return _failover(sources, label=f"{chain}:{symbol}")
|
|
785
995
|
|
|
786
996
|
|
|
787
997
|
def _quote_akshare_etf(symbol: str) -> dict:
|
|
@@ -1021,31 +1231,10 @@ def cmd_capital_flow(args):
|
|
|
1021
1231
|
|
|
1022
1232
|
def _news_search_intel_fallback(symbol: str) -> list:
|
|
1023
1233
|
"""Fallback: use search_intel to find news when primary sources fail."""
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
try:
|
|
1029
|
-
result = subprocess.run(
|
|
1030
|
-
[sys.executable, str(tools_dir / "search_intel.py"), "search", f"{symbol} 最新消息"],
|
|
1031
|
-
capture_output=True,
|
|
1032
|
-
text=True,
|
|
1033
|
-
encoding="utf-8",
|
|
1034
|
-
timeout=30,
|
|
1035
|
-
)
|
|
1036
|
-
except (subprocess.TimeoutExpired, OSError):
|
|
1037
|
-
return []
|
|
1038
|
-
if result.returncode != 0 or not result.stdout.strip():
|
|
1039
|
-
return []
|
|
1040
|
-
try:
|
|
1041
|
-
data = json.loads(result.stdout.strip())
|
|
1042
|
-
if isinstance(data, list):
|
|
1043
|
-
return [
|
|
1044
|
-
{"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]
|
|
1045
|
-
]
|
|
1046
|
-
return []
|
|
1047
|
-
except (json.JSONDecodeError, TypeError):
|
|
1048
|
-
return []
|
|
1234
|
+
data = run_tool("search_intel.py", ["search", f"{symbol} 最新消息"], timeout=30)
|
|
1235
|
+
if isinstance(data, list):
|
|
1236
|
+
return [{"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]]
|
|
1237
|
+
return []
|
|
1049
1238
|
|
|
1050
1239
|
|
|
1051
1240
|
def cmd_news(args):
|
|
@@ -1159,37 +1348,71 @@ def cmd_financials(args):
|
|
|
1159
1348
|
|
|
1160
1349
|
def snapshot_a() -> list:
|
|
1161
1350
|
try:
|
|
1162
|
-
return
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
raise ValueError("efinance snapshot empty")
|
|
1171
|
-
col_map = {
|
|
1172
|
-
"股票代码": "symbol",
|
|
1173
|
-
"股票名称": "name",
|
|
1174
|
-
"最新价": "price",
|
|
1175
|
-
"涨跌幅": "change_pct",
|
|
1176
|
-
"涨跌额": "change",
|
|
1177
|
-
"成交量": "volume",
|
|
1178
|
-
"成交额": "turnover",
|
|
1179
|
-
"市盈率": "pe",
|
|
1180
|
-
"换手率": "turnover_rate",
|
|
1181
|
-
"最高": "high",
|
|
1182
|
-
"最低": "low",
|
|
1183
|
-
"今开": "open",
|
|
1184
|
-
"昨收": "prev_close",
|
|
1185
|
-
}
|
|
1186
|
-
df = df.rename(columns=col_map)
|
|
1187
|
-
keep = [c for c in col_map.values() if c in df.columns]
|
|
1188
|
-
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1351
|
+
return _failover(
|
|
1352
|
+
[
|
|
1353
|
+
("akshare", _snapshot_akshare),
|
|
1354
|
+
("efinance", _snapshot_efinance),
|
|
1355
|
+
("sina", _snapshot_sina),
|
|
1356
|
+
],
|
|
1357
|
+
label="snapshot_a",
|
|
1358
|
+
)
|
|
1189
1359
|
except Exception:
|
|
1190
1360
|
return [{"error": "A-share snapshot unavailable from all sources"}]
|
|
1191
1361
|
|
|
1192
1362
|
|
|
1363
|
+
def _snapshot_efinance() -> list:
|
|
1364
|
+
import efinance as ef
|
|
1365
|
+
|
|
1366
|
+
df = ef.stock.get_realtime_quotes()
|
|
1367
|
+
if df is None or df.empty:
|
|
1368
|
+
raise ValueError("efinance snapshot empty")
|
|
1369
|
+
col_map = {
|
|
1370
|
+
"股票代码": "symbol",
|
|
1371
|
+
"股票名称": "name",
|
|
1372
|
+
"最新价": "price",
|
|
1373
|
+
"涨跌幅": "change_pct",
|
|
1374
|
+
"涨跌额": "change",
|
|
1375
|
+
"成交量": "volume",
|
|
1376
|
+
"成交额": "turnover",
|
|
1377
|
+
"市盈率": "pe",
|
|
1378
|
+
"换手率": "turnover_rate",
|
|
1379
|
+
"最高": "high",
|
|
1380
|
+
"最低": "low",
|
|
1381
|
+
"今开": "open",
|
|
1382
|
+
"昨收": "prev_close",
|
|
1383
|
+
}
|
|
1384
|
+
df = df.rename(columns=col_map)
|
|
1385
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1386
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1387
|
+
|
|
1388
|
+
|
|
1389
|
+
def _snapshot_sina() -> list:
|
|
1390
|
+
import akshare as ak
|
|
1391
|
+
import pandas as pd
|
|
1392
|
+
|
|
1393
|
+
df = _akshare_retry(ak.stock_zh_a_spot)
|
|
1394
|
+
if df is None or df.empty:
|
|
1395
|
+
raise ValueError("sina snapshot empty")
|
|
1396
|
+
df["代码"] = df["代码"].astype(str).str.replace(r"^(?:sh|sz|bj)", "", regex=True)
|
|
1397
|
+
df["成交量"] = pd.to_numeric(df["成交量"], errors="coerce") / 100
|
|
1398
|
+
col_map = {
|
|
1399
|
+
"代码": "symbol",
|
|
1400
|
+
"名称": "name",
|
|
1401
|
+
"最新价": "price",
|
|
1402
|
+
"涨跌额": "change",
|
|
1403
|
+
"涨跌幅": "change_pct",
|
|
1404
|
+
"成交量": "volume",
|
|
1405
|
+
"成交额": "turnover",
|
|
1406
|
+
"昨收": "prev_close",
|
|
1407
|
+
"今开": "open",
|
|
1408
|
+
"最高": "high",
|
|
1409
|
+
"最低": "low",
|
|
1410
|
+
}
|
|
1411
|
+
df = df.rename(columns=col_map)
|
|
1412
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1413
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1414
|
+
|
|
1415
|
+
|
|
1193
1416
|
def _snapshot_akshare() -> list:
|
|
1194
1417
|
import akshare as ak
|
|
1195
1418
|
|
|
@@ -1373,8 +1596,9 @@ def cmd_market_indices(args):
|
|
|
1373
1596
|
# --------------- sector_rankings ---------------
|
|
1374
1597
|
|
|
1375
1598
|
|
|
1376
|
-
def _sector_rankings_efinance(
|
|
1377
|
-
"""Fallback: fetch
|
|
1599
|
+
def _sector_rankings_efinance() -> list:
|
|
1600
|
+
"""Fallback: fetch industry board rankings via efinance (raw rows; sorting and
|
|
1601
|
+
top/direction are applied uniformly by cmd_sector_rankings after the failover)."""
|
|
1378
1602
|
import efinance as ef
|
|
1379
1603
|
import pandas as pd
|
|
1380
1604
|
|
|
@@ -1393,91 +1617,166 @@ def _sector_rankings_efinance(top: int, direction: str):
|
|
|
1393
1617
|
df = df[keep]
|
|
1394
1618
|
if "change_pct" in df.columns:
|
|
1395
1619
|
df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
|
|
1396
|
-
if direction == "bottom":
|
|
1397
|
-
df = df.sort_values("change_pct", ascending=True).head(top)
|
|
1398
|
-
elif direction == "both":
|
|
1399
|
-
top_df = df.sort_values("change_pct", ascending=False).head(top)
|
|
1400
|
-
bottom_df = df.sort_values("change_pct", ascending=True).head(top)
|
|
1401
|
-
return {
|
|
1402
|
-
"top": [_clean_row(r) for r in top_df.to_dict("records")],
|
|
1403
|
-
"bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
|
|
1404
|
-
}
|
|
1405
|
-
else:
|
|
1406
|
-
df = df.sort_values("change_pct", ascending=False).head(top)
|
|
1407
1620
|
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1408
1621
|
|
|
1409
1622
|
|
|
1623
|
+
def _sourced(name: str, fn):
|
|
1624
|
+
"""Failover leg wrapper: tag each returned row with the provider name, so the
|
|
1625
|
+
caller can tell which source won (_failover returns only the result)."""
|
|
1626
|
+
|
|
1627
|
+
def run():
|
|
1628
|
+
rows = fn()
|
|
1629
|
+
for r in rows:
|
|
1630
|
+
r["source"] = name
|
|
1631
|
+
return rows
|
|
1632
|
+
|
|
1633
|
+
return name, run
|
|
1634
|
+
|
|
1635
|
+
|
|
1636
|
+
def _sector_rankings_em(board_type: str) -> list:
|
|
1637
|
+
"""Eastmoney board rankings (industry or concept) via akshare."""
|
|
1638
|
+
import akshare as ak
|
|
1639
|
+
import pandas as pd
|
|
1640
|
+
|
|
1641
|
+
fetch = ak.stock_board_industry_name_em if board_type == "industry" else ak.stock_board_concept_name_em
|
|
1642
|
+
df = _akshare_retry(fetch)
|
|
1643
|
+
if df is None or df.empty:
|
|
1644
|
+
raise ValueError("eastmoney sector data unavailable")
|
|
1645
|
+
col_map = {
|
|
1646
|
+
"板块名称": "name",
|
|
1647
|
+
"板块代码": "code",
|
|
1648
|
+
"最新价": "price",
|
|
1649
|
+
"涨跌幅": "change_pct",
|
|
1650
|
+
"成交量": "volume",
|
|
1651
|
+
"成交额": "turnover",
|
|
1652
|
+
"换手率": "turnover_rate",
|
|
1653
|
+
"总市值": "market_cap",
|
|
1654
|
+
"上涨家数": "up_count",
|
|
1655
|
+
"下跌家数": "down_count",
|
|
1656
|
+
"领涨股票": "leading_stock",
|
|
1657
|
+
# industry boards name the column 领涨涨跌幅, concept boards 领涨股票-涨跌幅
|
|
1658
|
+
"领涨涨跌幅": "leading_change_pct",
|
|
1659
|
+
"领涨股票-涨跌幅": "leading_change_pct",
|
|
1660
|
+
}
|
|
1661
|
+
df = df.rename(columns=col_map)
|
|
1662
|
+
keep = list(dict.fromkeys(c for c in col_map.values() if c in df.columns))
|
|
1663
|
+
df = df[keep]
|
|
1664
|
+
if "change_pct" in df.columns:
|
|
1665
|
+
df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
|
|
1666
|
+
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1667
|
+
|
|
1668
|
+
|
|
1669
|
+
def _sector_rankings_ths() -> list:
|
|
1670
|
+
"""THS industry board rankings via akshare stock_board_industry_summary_ths.
|
|
1671
|
+
|
|
1672
|
+
There is no THS *concept* rankings table in this akshare version:
|
|
1673
|
+
stock_board_concept_name_ths returns only name/code columns and
|
|
1674
|
+
stock_board_concept_summary_ths is a concept timeline (日期/驱动事件), so the
|
|
1675
|
+
concept chain falls back to sina instead."""
|
|
1676
|
+
import akshare as ak
|
|
1677
|
+
|
|
1678
|
+
df = _akshare_retry(ak.stock_board_industry_summary_ths)
|
|
1679
|
+
if df is None or df.empty:
|
|
1680
|
+
raise ValueError("ths sector data unavailable")
|
|
1681
|
+
col_map = {
|
|
1682
|
+
"板块": "name",
|
|
1683
|
+
"涨跌幅": "change_pct",
|
|
1684
|
+
"总成交量": "volume",
|
|
1685
|
+
"总成交额": "turnover",
|
|
1686
|
+
"净流入": "net_inflow",
|
|
1687
|
+
"上涨家数": "up_count",
|
|
1688
|
+
"下跌家数": "down_count",
|
|
1689
|
+
"领涨股": "leading_stock",
|
|
1690
|
+
"领涨股-最新价": "leading_price",
|
|
1691
|
+
"领涨股-涨跌幅": "leading_change_pct",
|
|
1692
|
+
}
|
|
1693
|
+
df = df.rename(columns=col_map)
|
|
1694
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1695
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1696
|
+
|
|
1697
|
+
|
|
1698
|
+
def _sector_rankings_sina(indicator: str) -> list:
|
|
1699
|
+
"""Sina board rankings via akshare stock_sector_spot (概念/行业/...).
|
|
1700
|
+
|
|
1701
|
+
Sina has no 上涨家数/下跌家数 — only 公司家数 (stock_count); the leading stock
|
|
1702
|
+
rides along in the same row (股票名称/个股-涨跌幅/个股-当前价)."""
|
|
1703
|
+
import akshare as ak
|
|
1704
|
+
|
|
1705
|
+
df = _akshare_retry(ak.stock_sector_spot, indicator=indicator)
|
|
1706
|
+
if df is None or df.empty:
|
|
1707
|
+
raise ValueError(f"sina sector data unavailable (indicator={indicator})")
|
|
1708
|
+
col_map = {
|
|
1709
|
+
"板块": "name",
|
|
1710
|
+
"公司家数": "stock_count",
|
|
1711
|
+
"涨跌额": "change",
|
|
1712
|
+
"涨跌幅": "change_pct",
|
|
1713
|
+
"总成交量": "volume",
|
|
1714
|
+
"总成交额": "turnover",
|
|
1715
|
+
"股票名称": "leading_stock",
|
|
1716
|
+
"个股-涨跌幅": "leading_change_pct",
|
|
1717
|
+
"个股-当前价": "leading_price",
|
|
1718
|
+
}
|
|
1719
|
+
df = df.rename(columns=col_map)
|
|
1720
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1721
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1722
|
+
|
|
1723
|
+
|
|
1410
1724
|
def cmd_sector_rankings(args):
|
|
1725
|
+
board_type = getattr(args, "board_type", "industry")
|
|
1726
|
+
direction = getattr(args, "direction", "top")
|
|
1727
|
+
sources = [_sourced("eastmoney", lambda: _sector_rankings_em(board_type))]
|
|
1728
|
+
if board_type == "industry":
|
|
1729
|
+
# efinance has no concept boards — it stays an industry-only leg
|
|
1730
|
+
sources.append(_sourced("ths", _sector_rankings_ths))
|
|
1731
|
+
sources.append(_sourced("efinance", _sector_rankings_efinance))
|
|
1732
|
+
else:
|
|
1733
|
+
sources.append(_sourced("sina", lambda: _sector_rankings_sina("概念")))
|
|
1411
1734
|
try:
|
|
1412
|
-
|
|
1413
|
-
|
|
1735
|
+
rows = _failover(sources, label=f"sector_rankings:{board_type}")
|
|
1736
|
+
if not rows:
|
|
1737
|
+
raise ValueError(f"no {board_type} board rankings data")
|
|
1738
|
+
except Exception as e:
|
|
1739
|
+
return {"error": str(e)}
|
|
1740
|
+
for r in rows:
|
|
1741
|
+
r["board_type"] = board_type
|
|
1414
1742
|
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
"
|
|
1424
|
-
"
|
|
1425
|
-
"换手率": "turnover_rate",
|
|
1426
|
-
"总市值": "market_cap",
|
|
1427
|
-
"上涨家数": "up_count",
|
|
1428
|
-
"下跌家数": "down_count",
|
|
1429
|
-
"领涨股票": "leading_stock",
|
|
1430
|
-
"领涨涨跌幅": "leading_change_pct",
|
|
1743
|
+
def _pct(row, default):
|
|
1744
|
+
v = row.get("change_pct")
|
|
1745
|
+
return v if isinstance(v, (int, float)) else default
|
|
1746
|
+
|
|
1747
|
+
if direction == "bottom":
|
|
1748
|
+
return sorted(rows, key=lambda r: _pct(r, float("inf")))[: args.top]
|
|
1749
|
+
if direction == "both":
|
|
1750
|
+
return {
|
|
1751
|
+
"top": sorted(rows, key=lambda r: _pct(r, float("-inf")), reverse=True)[: args.top],
|
|
1752
|
+
"bottom": sorted(rows, key=lambda r: _pct(r, float("inf")))[: args.top],
|
|
1431
1753
|
}
|
|
1432
|
-
|
|
1433
|
-
keep = [c for c in col_map.values() if c in df.columns]
|
|
1434
|
-
df = df[keep]
|
|
1435
|
-
if "change_pct" in df.columns:
|
|
1436
|
-
df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
|
|
1437
|
-
|
|
1438
|
-
direction = getattr(args, "direction", "top")
|
|
1439
|
-
if direction == "bottom":
|
|
1440
|
-
df = df.sort_values("change_pct", ascending=True).head(args.top)
|
|
1441
|
-
elif direction == "both":
|
|
1442
|
-
top_df = df.sort_values("change_pct", ascending=False).head(args.top)
|
|
1443
|
-
bottom_df = df.sort_values("change_pct", ascending=True).head(args.top)
|
|
1444
|
-
return {
|
|
1445
|
-
"top": [_clean_row(r) for r in top_df.to_dict("records")],
|
|
1446
|
-
"bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
|
|
1447
|
-
}
|
|
1448
|
-
else:
|
|
1449
|
-
df = df.head(args.top)
|
|
1450
|
-
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1451
|
-
except Exception:
|
|
1452
|
-
try:
|
|
1453
|
-
direction = getattr(args, "direction", "top")
|
|
1454
|
-
return _sector_rankings_efinance(args.top, direction)
|
|
1455
|
-
except Exception as e2:
|
|
1456
|
-
return {"error": str(e2)}
|
|
1754
|
+
return sorted(rows, key=lambda r: _pct(r, float("-inf")), reverse=True)[: args.top]
|
|
1457
1755
|
|
|
1458
1756
|
|
|
1459
1757
|
# --------------- sector constituents / stock sectors (issue #18) ---------------
|
|
1460
1758
|
|
|
1461
|
-
#
|
|
1462
|
-
#
|
|
1463
|
-
|
|
1464
|
-
|
|
1759
|
+
# Disk cache lives in tempdir — cross-platform (Windows has no ~/.cache). Stores
|
|
1760
|
+
# sector constituents (24h TTL; membership changes slowly) and sticky failover
|
|
1761
|
+
# winners (keys prefixed `sticky-`, see _failover).
|
|
1762
|
+
_DATA_CACHE_DIR = Path(tempfile.gettempdir()) / "pi-stock-analysis"
|
|
1763
|
+
_DATA_CACHE_TTL = 24 * 3600
|
|
1465
1764
|
|
|
1466
1765
|
|
|
1467
|
-
def
|
|
1766
|
+
def _disk_cache_get(key: str):
|
|
1468
1767
|
try:
|
|
1469
|
-
path =
|
|
1470
|
-
if path.exists() and time.time() - path.stat().st_mtime <
|
|
1768
|
+
path = _DATA_CACHE_DIR / f"{key}.json"
|
|
1769
|
+
if path.exists() and time.time() - path.stat().st_mtime < _DATA_CACHE_TTL:
|
|
1471
1770
|
return json.loads(path.read_text(encoding="utf-8"))
|
|
1472
1771
|
except Exception:
|
|
1473
1772
|
pass
|
|
1474
1773
|
return None
|
|
1475
1774
|
|
|
1476
1775
|
|
|
1477
|
-
def
|
|
1776
|
+
def _disk_cache_set(key: str, data):
|
|
1478
1777
|
try:
|
|
1479
|
-
|
|
1480
|
-
(
|
|
1778
|
+
_DATA_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
1779
|
+
(_DATA_CACHE_DIR / f"{key}.json").write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
1481
1780
|
except Exception:
|
|
1482
1781
|
pass
|
|
1483
1782
|
|
|
@@ -1601,14 +1900,14 @@ def cmd_sector_constituents(args):
|
|
|
1601
1900
|
# Sector names are user input — hash them instead of sanitizing, so names that
|
|
1602
1901
|
# differ only in whitespace/punctuation (创新药 vs 创新 药) can't collide.
|
|
1603
1902
|
cache_key = hashlib.sha256(f"{sector}|{board_type}".encode()).hexdigest()[:16]
|
|
1604
|
-
cached =
|
|
1903
|
+
cached = _disk_cache_get(cache_key)
|
|
1605
1904
|
if cached is not None:
|
|
1606
1905
|
return cached
|
|
1607
1906
|
try:
|
|
1608
1907
|
result = sector_constituents_a(sector, board_type)
|
|
1609
1908
|
except Exception as e:
|
|
1610
1909
|
return {"error": str(e)}
|
|
1611
|
-
|
|
1910
|
+
_disk_cache_set(cache_key, result)
|
|
1612
1911
|
return result
|
|
1613
1912
|
|
|
1614
1913
|
|
|
@@ -1686,10 +1985,10 @@ def _stock_boards_from_cache(symbol: str) -> list:
|
|
|
1686
1985
|
live A-share sources are both eastmoney-flavored). Reads every unexpired
|
|
1687
1986
|
constituents payload in the cache dir and returns one entry per cached sector
|
|
1688
1987
|
containing the symbol. Cold cache → []; malformed cache files are skipped
|
|
1689
|
-
(
|
|
1988
|
+
(_disk_cache_get returns None on expiry, bad JSON, or read errors)."""
|
|
1690
1989
|
boards = []
|
|
1691
|
-
for path in
|
|
1692
|
-
data =
|
|
1990
|
+
for path in _DATA_CACHE_DIR.glob("*.json"):
|
|
1991
|
+
data = _disk_cache_get(path.stem)
|
|
1693
1992
|
if not isinstance(data, dict):
|
|
1694
1993
|
continue
|
|
1695
1994
|
sector = data.get("sector")
|
|
@@ -1944,6 +2243,8 @@ def cmd_market_stats(args):
|
|
|
1944
2243
|
data = snapshot_a()
|
|
1945
2244
|
if isinstance(data, dict) and "error" in data:
|
|
1946
2245
|
return data
|
|
2246
|
+
if isinstance(data, list) and len(data) == 1 and isinstance(data[0], dict) and "error" in data[0]:
|
|
2247
|
+
return data[0]
|
|
1947
2248
|
if not data:
|
|
1948
2249
|
return {"error": "No market data"}
|
|
1949
2250
|
return compute_market_stats(data)
|
|
@@ -2017,6 +2318,228 @@ def cmd_fundamental_context(args):
|
|
|
2017
2318
|
return {"error": str(e)}
|
|
2018
2319
|
|
|
2019
2320
|
|
|
2321
|
+
# --------------- short-term sentiment: limit_up_pool / dragon_tiger / hot_stocks (A-share only) ---------------
|
|
2322
|
+
|
|
2323
|
+
|
|
2324
|
+
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("-", "")
|
|
2327
|
+
try:
|
|
2328
|
+
import akshare as ak
|
|
2329
|
+
|
|
2330
|
+
df = _akshare_retry(ak.stock_zt_pool_em, date=date)
|
|
2331
|
+
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
|
+
}
|
|
2339
|
+
col_map = {
|
|
2340
|
+
"代码": "code",
|
|
2341
|
+
"名称": "name",
|
|
2342
|
+
"涨跌幅": "change_pct",
|
|
2343
|
+
"最新价": "price",
|
|
2344
|
+
"成交额": "turnover",
|
|
2345
|
+
"流通市值": "float_market_cap",
|
|
2346
|
+
"总市值": "total_market_cap",
|
|
2347
|
+
"换手率": "turnover_rate",
|
|
2348
|
+
"封板资金": "seal_amount",
|
|
2349
|
+
"首次封板时间": "first_seal_time",
|
|
2350
|
+
"最后封板时间": "last_seal_time",
|
|
2351
|
+
"炸板次数": "break_count",
|
|
2352
|
+
"涨停统计": "limit_up_stat",
|
|
2353
|
+
"连板数": "consecutive_boards",
|
|
2354
|
+
"所属行业": "industry",
|
|
2355
|
+
}
|
|
2356
|
+
df = df.rename(columns=col_map)
|
|
2357
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2358
|
+
pool = [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
2359
|
+
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
|
+
}
|
|
2366
|
+
except Exception as e:
|
|
2367
|
+
return {"error": str(e)}
|
|
2368
|
+
|
|
2369
|
+
|
|
2370
|
+
def _dragon_tiger_em(raw: str) -> list:
|
|
2371
|
+
"""Eastmoney 龙虎榜 via akshare stock_lhb_detail_em."""
|
|
2372
|
+
import akshare as ak
|
|
2373
|
+
import pandas as pd
|
|
2374
|
+
|
|
2375
|
+
df = _akshare_retry(ak.stock_lhb_detail_em, start_date=raw, end_date=raw)
|
|
2376
|
+
if df is None or df.empty:
|
|
2377
|
+
return []
|
|
2378
|
+
col_map = {
|
|
2379
|
+
"代码": "code",
|
|
2380
|
+
"名称": "name",
|
|
2381
|
+
"上榜日": "list_date",
|
|
2382
|
+
"收盘价": "close",
|
|
2383
|
+
"涨跌幅": "change_pct",
|
|
2384
|
+
"龙虎榜净买额": "net_buy",
|
|
2385
|
+
"龙虎榜买入额": "buy_amount",
|
|
2386
|
+
"龙虎榜卖出额": "sell_amount",
|
|
2387
|
+
"龙虎榜成交额": "lhb_turnover",
|
|
2388
|
+
"上榜原因": "reason",
|
|
2389
|
+
"解读": "interpretation",
|
|
2390
|
+
}
|
|
2391
|
+
df = df.rename(columns=col_map)
|
|
2392
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2393
|
+
df = df[keep]
|
|
2394
|
+
if "net_buy" in df.columns:
|
|
2395
|
+
df["net_buy"] = pd.to_numeric(df["net_buy"], errors="coerce")
|
|
2396
|
+
return [_clean_row(r) for r in df.to_dict("records")]
|
|
2397
|
+
|
|
2398
|
+
|
|
2399
|
+
def _dragon_tiger_sina(raw: str) -> list:
|
|
2400
|
+
"""Sina 龙虎榜每日详情 via akshare stock_lhb_detail_daily_sina.
|
|
2401
|
+
|
|
2402
|
+
Sina has no 涨跌幅/净买额/买入额/卖出额/上榜日/解读 — its 指标 column is the
|
|
2403
|
+
listing reason and list_date is filled from the query date. A stock listed for
|
|
2404
|
+
several reasons appears once per reason (sina's page layout)."""
|
|
2405
|
+
import akshare as ak
|
|
2406
|
+
|
|
2407
|
+
df = _akshare_retry(ak.stock_lhb_detail_daily_sina, date=raw)
|
|
2408
|
+
if df is None or df.empty:
|
|
2409
|
+
return []
|
|
2410
|
+
col_map = {
|
|
2411
|
+
"股票代码": "code",
|
|
2412
|
+
"股票名称": "name",
|
|
2413
|
+
"收盘价": "close",
|
|
2414
|
+
"指标": "reason",
|
|
2415
|
+
}
|
|
2416
|
+
df = df.rename(columns=col_map)
|
|
2417
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2418
|
+
rows = [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
2419
|
+
date_iso = f"{raw[:4]}-{raw[4:6]}-{raw[6:8]}"
|
|
2420
|
+
for r in rows:
|
|
2421
|
+
r["list_date"] = date_iso
|
|
2422
|
+
return rows
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
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
|
|
2429
|
+
sources = [
|
|
2430
|
+
_sourced("eastmoney", lambda: _dragon_tiger_em(raw)),
|
|
2431
|
+
_sourced("sina", lambda: _dragon_tiger_sina(raw)),
|
|
2432
|
+
]
|
|
2433
|
+
try:
|
|
2434
|
+
rows = _failover(sources, label=f"dragon_tiger:{raw}")
|
|
2435
|
+
except Exception as e:
|
|
2436
|
+
return {"error": str(e)}
|
|
2437
|
+
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
|
+
}
|
|
2444
|
+
source = rows[0]["source"]
|
|
2445
|
+
if args.symbol:
|
|
2446
|
+
m = re.fullmatch(r"(?:sh|sz|bj)(\d{6})", str(args.symbol), re.IGNORECASE)
|
|
2447
|
+
want = m.group(1) if m else str(args.symbol)
|
|
2448
|
+
rows = [r for r in rows if str(r.get("code")) == want]
|
|
2449
|
+
if any(isinstance(r.get("net_buy"), (int, float)) for r in rows):
|
|
2450
|
+
rows = sorted(
|
|
2451
|
+
rows,
|
|
2452
|
+
key=lambda r: abs(r["net_buy"]) if isinstance(r.get("net_buy"), (int, float)) else 0,
|
|
2453
|
+
reverse=True,
|
|
2454
|
+
)
|
|
2455
|
+
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}
|
|
2457
|
+
|
|
2458
|
+
|
|
2459
|
+
def _strip_exchange_prefix(row: dict) -> dict:
|
|
2460
|
+
"""Bare the exchange prefix on row["code"] ("SZ000001" → "000001", original kept in
|
|
2461
|
+
code_full). Bare 6-digit codes pass through unchanged."""
|
|
2462
|
+
m = re.fullmatch(r"(sh|sz|bj)(\d{6})", str(row.get("code") or ""), re.IGNORECASE)
|
|
2463
|
+
if m:
|
|
2464
|
+
row["code_full"] = row["code"]
|
|
2465
|
+
row["code"] = m.group(2)
|
|
2466
|
+
return row
|
|
2467
|
+
|
|
2468
|
+
|
|
2469
|
+
def _hot_stocks_em() -> list:
|
|
2470
|
+
"""Eastmoney 人气榜 via akshare stock_hot_rank_em."""
|
|
2471
|
+
import akshare as ak
|
|
2472
|
+
|
|
2473
|
+
df = _akshare_retry(ak.stock_hot_rank_em)
|
|
2474
|
+
if df is None or df.empty:
|
|
2475
|
+
return []
|
|
2476
|
+
col_map = {
|
|
2477
|
+
"当前排名": "rank",
|
|
2478
|
+
"代码": "code",
|
|
2479
|
+
"股票名称": "name",
|
|
2480
|
+
"最新价": "price",
|
|
2481
|
+
"涨跌幅": "change_pct",
|
|
2482
|
+
}
|
|
2483
|
+
df = df.rename(columns=col_map)
|
|
2484
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2485
|
+
return [_strip_exchange_prefix(_clean_row(r)) for r in df[keep].to_dict("records")]
|
|
2486
|
+
|
|
2487
|
+
|
|
2488
|
+
def _hot_stocks_xq() -> list:
|
|
2489
|
+
"""Xueqiu follow ranking via akshare stock_hot_follow_xq. No 涨跌幅 column;
|
|
2490
|
+
rank is the row position. Codes arrive SH/SZ-prefixed like eastmoney's."""
|
|
2491
|
+
import akshare as ak
|
|
2492
|
+
|
|
2493
|
+
df = _akshare_retry(ak.stock_hot_follow_xq, symbol="最热门")
|
|
2494
|
+
if df is None or df.empty:
|
|
2495
|
+
return []
|
|
2496
|
+
col_map = {
|
|
2497
|
+
"股票代码": "code",
|
|
2498
|
+
"股票简称": "name",
|
|
2499
|
+
"最新价": "price",
|
|
2500
|
+
}
|
|
2501
|
+
df = df.rename(columns=col_map)
|
|
2502
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2503
|
+
return [{"rank": i, **_strip_exchange_prefix(_clean_row(r))} for i, r in enumerate(df[keep].to_dict("records"), 1)]
|
|
2504
|
+
|
|
2505
|
+
|
|
2506
|
+
def _hot_stocks_baidu() -> list:
|
|
2507
|
+
"""Baidu 股市通热搜 via akshare stock_hot_search_baidu. No code/price columns —
|
|
2508
|
+
only the stock name — and 涨跌幅 strings carry a % suffix."""
|
|
2509
|
+
import akshare as ak
|
|
2510
|
+
|
|
2511
|
+
df = _akshare_retry(
|
|
2512
|
+
ak.stock_hot_search_baidu,
|
|
2513
|
+
symbol="A股",
|
|
2514
|
+
date=datetime.now().strftime("%Y%m%d"),
|
|
2515
|
+
time="今日",
|
|
2516
|
+
)
|
|
2517
|
+
if df is None or df.empty:
|
|
2518
|
+
return []
|
|
2519
|
+
rows = []
|
|
2520
|
+
for i, r in enumerate(df.to_dict("records"), 1):
|
|
2521
|
+
pct = str(r.get("涨跌幅") or "").replace("%", "")
|
|
2522
|
+
rows.append(_clean_row({"rank": i, "name": r.get("名称/代码"), "change_pct": _parse_float(pct)}))
|
|
2523
|
+
return rows
|
|
2524
|
+
|
|
2525
|
+
|
|
2526
|
+
def cmd_hot_stocks(args):
|
|
2527
|
+
"""A-share popularity ranking (人气榜): eastmoney → xueqiu → baidu."""
|
|
2528
|
+
sources = [
|
|
2529
|
+
_sourced("eastmoney", _hot_stocks_em),
|
|
2530
|
+
_sourced("xueqiu", _hot_stocks_xq),
|
|
2531
|
+
_sourced("baidu", _hot_stocks_baidu),
|
|
2532
|
+
]
|
|
2533
|
+
try:
|
|
2534
|
+
rows = _failover(sources, label="hot_stocks")
|
|
2535
|
+
except Exception as e:
|
|
2536
|
+
return {"error": str(e)}
|
|
2537
|
+
if not rows:
|
|
2538
|
+
return {"count": 0, "items": [], "note": "no hot-rank data available"}
|
|
2539
|
+
items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
|
|
2540
|
+
return {"count": len(items), "items": items, "source": rows[0]["source"]}
|
|
2541
|
+
|
|
2542
|
+
|
|
2020
2543
|
# --------------- CLI ---------------
|
|
2021
2544
|
|
|
2022
2545
|
|
|
@@ -2056,6 +2579,7 @@ def main():
|
|
|
2056
2579
|
p_sec = sub.add_parser("sector_rankings")
|
|
2057
2580
|
p_sec.add_argument("--top", type=int, default=10)
|
|
2058
2581
|
p_sec.add_argument("--direction", default="top", choices=["top", "bottom", "both"])
|
|
2582
|
+
p_sec.add_argument("--board-type", default="industry", choices=["industry", "concept"])
|
|
2059
2583
|
|
|
2060
2584
|
p_cons = sub.add_parser("sector_constituents")
|
|
2061
2585
|
p_cons.add_argument("sector")
|
|
@@ -2070,12 +2594,22 @@ def main():
|
|
|
2070
2594
|
p_chip = sub.add_parser("chip_distribution")
|
|
2071
2595
|
p_chip.add_argument("symbol")
|
|
2072
2596
|
|
|
2073
|
-
|
|
2074
|
-
p_stats.add_argument("--market", default="A", choices=["A"])
|
|
2597
|
+
sub.add_parser("market_stats")
|
|
2075
2598
|
|
|
2076
2599
|
p_fund = sub.add_parser("fundamental_context")
|
|
2077
2600
|
p_fund.add_argument("symbol")
|
|
2078
2601
|
|
|
2602
|
+
p_zt = sub.add_parser("limit_up_pool")
|
|
2603
|
+
p_zt.add_argument("--date", default=None, help="Trading date in YYYYMMDD format (default: today)")
|
|
2604
|
+
|
|
2605
|
+
p_lhb = sub.add_parser("dragon_tiger")
|
|
2606
|
+
p_lhb.add_argument("--date", default=None, help="Trading date in YYYY-MM-DD format (default: today)")
|
|
2607
|
+
p_lhb.add_argument("--symbol", default=None, help="Filter to a single stock code")
|
|
2608
|
+
p_lhb.add_argument("--top", type=int, default=20)
|
|
2609
|
+
|
|
2610
|
+
p_hot = sub.add_parser("hot_stocks")
|
|
2611
|
+
p_hot.add_argument("--top", type=int, default=20)
|
|
2612
|
+
|
|
2079
2613
|
args = parser.parse_args()
|
|
2080
2614
|
if not args.command:
|
|
2081
2615
|
parser.print_help()
|
|
@@ -2096,6 +2630,9 @@ def main():
|
|
|
2096
2630
|
"chip_distribution": cmd_chip_distribution,
|
|
2097
2631
|
"market_stats": cmd_market_stats,
|
|
2098
2632
|
"fundamental_context": cmd_fundamental_context,
|
|
2633
|
+
"limit_up_pool": cmd_limit_up_pool,
|
|
2634
|
+
"dragon_tiger": cmd_dragon_tiger,
|
|
2635
|
+
"hot_stocks": cmd_hot_stocks,
|
|
2099
2636
|
}
|
|
2100
2637
|
# Provider libraries (baostock etc.) print prose to stdout on failure,
|
|
2101
2638
|
# which would corrupt the JSON-only contract — divert that noise to stderr.
|