@weaxs/openclaw-stock-analysis 0.1.13 → 0.1.15

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.
Files changed (52) hide show
  1. package/dist/index.js +25 -25
  2. package/index.ts +25 -25
  3. package/package.json +1 -1
  4. package/skills/bottom-volume/SKILL.md +1 -4
  5. package/skills/bottom-volume/scripts/gather.py +1 -1
  6. package/skills/box-oscillation/SKILL.md +1 -4
  7. package/skills/box-oscillation/scripts/gather.py +1 -1
  8. package/skills/bull-trend/SKILL.md +1 -4
  9. package/skills/bull-trend/scripts/gather.py +1 -1
  10. package/skills/chan-theory/SKILL.md +1 -4
  11. package/skills/chan-theory/scripts/gather.py +1 -1
  12. package/skills/dragon-head/SKILL.md +22 -28
  13. package/skills/dragon-head/scripts/gather.py +1 -1
  14. package/skills/emotion-cycle/SKILL.md +17 -33
  15. package/skills/emotion-cycle/scripts/gather.py +4 -3
  16. package/skills/event-driven/SKILL.md +42 -26
  17. package/skills/event-driven/scripts/gather.py +1 -1
  18. package/skills/expectation-repricing/SKILL.md +11 -6
  19. package/skills/expectation-repricing/scripts/gather.py +1 -1
  20. package/skills/growth-quality/SKILL.md +11 -6
  21. package/skills/growth-quality/scripts/gather.py +1 -1
  22. package/skills/hot-theme/SKILL.md +25 -22
  23. package/skills/hot-theme/scripts/gather.py +1 -1
  24. package/skills/ma-crossover/SKILL.md +1 -4
  25. package/skills/ma-crossover/scripts/gather.py +1 -1
  26. package/skills/market-review/SKILL.md +11 -8
  27. package/skills/market-review/scripts/gather.py +1 -1
  28. package/skills/one-yang-three-yin/SKILL.md +1 -4
  29. package/skills/one-yang-three-yin/scripts/gather.py +1 -1
  30. package/skills/shrink-pullback/SKILL.md +1 -4
  31. package/skills/shrink-pullback/scripts/gather.py +1 -1
  32. package/skills/stock-analysis/SKILL.md +12 -79
  33. package/skills/stock-analysis/references/short-term-trading.md +78 -0
  34. package/skills/stock-analysis/scripts/gather.py +1 -1
  35. package/skills/stock-screener/SKILL.md +7 -6
  36. package/skills/stock-screener/scripts/gather.py +1 -1
  37. package/skills/strategy-backtest/SKILL.md +24 -20
  38. package/skills/strategy-backtest/scripts/gather.py +1 -1
  39. package/skills/volume-breakout/SKILL.md +21 -23
  40. package/skills/volume-breakout/scripts/gather.py +1 -1
  41. package/skills/wave-theory/SKILL.md +1 -4
  42. package/skills/wave-theory/scripts/gather.py +1 -1
  43. package/skills/wisburg-research/SKILL.md +2 -2
  44. package/tools/_subproc.py +18 -5
  45. package/tools/alert_rules.py +1 -20
  46. package/tools/capabilities.py +3 -4
  47. package/tools/diagnostics.py +13 -2
  48. package/tools/gather.py +7 -21
  49. package/tools/market_regime.py +4 -1
  50. package/tools/position_context.py +1 -19
  51. package/tools/stock_data.py +317 -75
  52. package/tools/watchlist_context.py +1 -19
package/tools/gather.py CHANGED
@@ -3,33 +3,19 @@
3
3
 
4
4
  import argparse
5
5
  import json
6
- import subprocess
7
6
  import sys
8
7
  from concurrent.futures import ThreadPoolExecutor, as_completed
9
8
  from pathlib import Path
10
9
 
11
- TOOLS_DIR = Path(__file__).resolve().parent
10
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
11
+ from _subproc import run_tool # noqa: E402
12
12
 
13
13
 
14
- def _find_python() -> str:
15
- venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
16
- if venv.exists():
17
- return str(venv)
18
- return sys.executable
19
-
20
-
21
- def _run(script: str, args: list[str], timeout: int = 60) -> str | None:
22
- python = _find_python()
23
- cmd = [python, str(TOOLS_DIR / script)] + args
24
- try:
25
- r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=timeout)
26
- if r.returncode == 0 and r.stdout.strip():
27
- return r.stdout.strip()
28
- except subprocess.TimeoutExpired:
29
- pass
30
- except Exception:
31
- pass
32
- return None
14
+ # gather fans out the heavier CLIs, so the default timeout stays 60s; JSON parsing
15
+ # is _parse_json's job, so raw stdout is wanted here. A def wrapper (not
16
+ # functools.partial) keeps timeout passable both positionally and by keyword.
17
+ def _run(script, args, timeout=60):
18
+ return run_tool(script, args, timeout=timeout, parse_json=False)
33
19
 
34
20
 
35
21
  def _parse_json(raw: str | None):
@@ -38,7 +38,10 @@ SKILL_RECOMMEND = {
38
38
 
39
39
  def _get_index_kline(market: str) -> list:
40
40
  code, _ = INDEX_MAP[market]
41
- data = _run_tool("stock_data.py", ["kline", code, "--period", "daily", "--count", "80"])
41
+ # A 股指数走显式交易所前缀(sh000001),避免与深市个股 000001(平安银行)撞代码
42
+ data = _run_tool(
43
+ "stock_data.py", ["kline", f"sh{code}" if market == "A" else code, "--period", "daily", "--count", "80"]
44
+ )
42
45
  if isinstance(data, list) and len(data) > 0:
43
46
  return data
44
47
  return []
@@ -6,32 +6,14 @@ Not a portfolio system. Stateless: user passes cost/quantity/stops each call.
6
6
 
7
7
  import argparse
8
8
  import json
9
- import subprocess
10
9
  import sys
11
10
  from datetime import datetime, timezone
12
11
  from pathlib import Path
13
12
 
14
13
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+ from _subproc import run_tool as _run_json # noqa: E402
15
15
  from stock_data import detect_market # noqa: E402
16
16
 
17
- TOOLS_DIR = Path(__file__).resolve().parent
18
-
19
-
20
- def _find_python() -> str:
21
- venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
22
- return str(venv) if venv.exists() else sys.executable
23
-
24
-
25
- def _run_json(script: str, args: list[str], timeout: int = 30):
26
- cmd = [_find_python(), str(TOOLS_DIR / script)] + args
27
- try:
28
- r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=timeout)
29
- if r.returncode == 0 and r.stdout.strip():
30
- return json.loads(r.stdout)
31
- except Exception:
32
- pass
33
- return None
34
-
35
17
 
36
18
  def _risk_level(distance_to_stop_pct: float, pnl_pct: float, trend: str) -> str:
37
19
  # ponytail: simple 3-bucket heuristic, upgrade to volatility-adjusted if needed
@@ -12,9 +12,16 @@ import time
12
12
  from datetime import datetime, timedelta
13
13
  from pathlib import Path
14
14
 
15
+ # Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
16
+ # Bare 6-digit codes are always stocks; the prefix is the disambiguation escape
17
+ # hatch for index codes (sh000001 = 上证指数, not 平安银行).
18
+ _A_PREFIXED_RE = re.compile(r"(?:sh|sz|bj)\d{6}", re.IGNORECASE)
19
+
15
20
 
16
21
  def detect_market(symbol: str) -> str:
17
22
  s = symbol.upper()
23
+ if _A_PREFIXED_RE.fullmatch(symbol):
24
+ return "A"
18
25
  if s.endswith(".HK"):
19
26
  return "HK"
20
27
  if s.endswith(".T"):
@@ -72,13 +79,35 @@ def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> f
72
79
  return np.floor(pre_close * (1 + sign * ratio) * 100 + 0.5) / 100.0
73
80
 
74
81
 
82
+ # Chains that get sticky ordering: the CN free-source chains, where failures are
83
+ # typically chronic (regional blocking). The yf chains (`kline:`/`quote:`) are
84
+ # excluded on purpose — their failures are usually transient yfinance blips, and
85
+ # stickiness would let one blip degrade HK/US quote richness (finnhub has no
86
+ # name/market_cap/pe/pb) for the whole TTL.
87
+ _STICKY_CHAINS = {"kline_a", "quote_a", "quote_a_etf", "snapshot_a", "sector_constituents", "sina"}
88
+
89
+
75
90
  def _failover(sources: list, label: str):
76
- """Return first truthy result; else raise RuntimeError aggregating each source's error."""
91
+ """Return first truthy result; else raise RuntimeError aggregating each source's error.
92
+
93
+ Sticky ordering (issue #25): for chains in _STICKY_CHAINS (keyed by the label
94
+ before ":"), the last winning source is tried first next time; the rest keep
95
+ their declared order. Persisted via the sector disk cache below (tempdir, 24h
96
+ TTL), so it survives across the one-process-per-CLI-call host model; a stale
97
+ entry costs one failed attempt, then the new winner replaces it (self-healing).
98
+ """
99
+ chain = label.split(":", 1)[0]
100
+ if chain in _STICKY_CHAINS:
101
+ sticky = _disk_cache_get(f"sticky-{chain}")
102
+ if sticky:
103
+ sources = sorted(sources, key=lambda s: s[0] != sticky)
77
104
  errors = []
78
105
  for name, fn in sources:
79
106
  try:
80
107
  result = fn()
81
108
  if result:
109
+ if chain in _STICKY_CHAINS:
110
+ _disk_cache_set(f"sticky-{chain}", name)
82
111
  return result
83
112
  except Exception as e:
84
113
  errors.append(f"{name}: {type(e).__name__}: {e}")
@@ -97,30 +126,9 @@ def _akshare_retry(fn, *args, retries=2, delay=1, **kwargs):
97
126
  time.sleep(delay)
98
127
 
99
128
 
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
129
  def _to_baostock_code(symbol: str) -> str:
116
- index_exchange = _BAOSTOCK_INDEX_CODES.get(symbol)
117
- if index_exchange:
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}"
130
+ code = _cn_code(symbol)
131
+ return f"{code[:2]}.{code[2:]}"
124
132
 
125
133
 
126
134
  def _kline_efinance(symbol: str, period: str, count: int) -> list:
@@ -229,6 +237,181 @@ def _quote_efinance(symbol: str) -> dict:
229
237
  return _clean_row(result)
230
238
 
231
239
 
240
+ # --------------- tencent / sina (non-eastmoney A-share fallbacks, issue #25) ---------------
241
+ #
242
+ # akshare/efinance both resolve to eastmoney hosts, so an eastmoney-blocked network
243
+ # kills the whole A-share chain. Tencent (qt.gtimg.cn) and Sina (hq.sinajs.cn) are
244
+ # independent quote endpoints needing no credentials; both cover stocks, ETFs,
245
+ # indices and BSE codes.
246
+
247
+
248
+ def _cn_code(symbol: str) -> str:
249
+ """Exchange-prefixed code shared by Tencent and Sina: 600519 → sh600519, BSE → bj920001."""
250
+ if _A_PREFIXED_RE.fullmatch(symbol):
251
+ return symbol.lower()
252
+ if symbol.startswith(("43", "81", "82", "83", "87", "88", "92")):
253
+ return f"bj{symbol}"
254
+ return f"sh{symbol}" if symbol.startswith(("5", "6", "9")) else f"sz{symbol}"
255
+
256
+
257
+ def _parse_float(value):
258
+ """Provider string field → float; empty/garbage → None (never raises)."""
259
+ try:
260
+ return float(value)
261
+ except (TypeError, ValueError):
262
+ return None
263
+
264
+
265
+ def _gbk_var_payload(content: bytes) -> str:
266
+ """Extract the quoted payload from a GBK `v_sh600519="..."` / `var hq_str_...="..."` body."""
267
+ return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
268
+
269
+
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
282
+ turnover = _parse_float(f[37])
283
+ market_cap = _parse_float(f[45])
284
+ row = {
285
+ "symbol": symbol,
286
+ "name": f[1],
287
+ "price": _parse_float(f[3]),
288
+ "change": _parse_float(f[31]),
289
+ "change_pct": _parse_float(f[32]),
290
+ "volume": _parse_float(f[6]), # 手, same as akshare
291
+ "turnover": turnover * 1e4 if turnover is not None else None,
292
+ "high": _parse_float(f[33]),
293
+ "low": _parse_float(f[34]),
294
+ "open": _parse_float(f[5]),
295
+ "prev_close": _parse_float(f[4]),
296
+ "market_cap": market_cap * 1e8 if market_cap is not None else None,
297
+ "pe": _parse_float(f[39]),
298
+ "pb": _parse_float(f[46]),
299
+ "turnover_rate": _parse_float(f[38]),
300
+ "amplitude": _parse_float(f[43]),
301
+ }
302
+ if normalize_stock_code(symbol)["is_etf"]:
303
+ row["is_etf"] = True
304
+ return _clean_row(row)
305
+
306
+
307
+ def _kline_tencent(symbol: str, period: str, count: int) -> list:
308
+ """Tencent kline via web.ifzq.gtimg.cn. Rows are [date, open, close, high, low,
309
+ volume(手)] ascending; qfq-adjusted like akshare. When a symbol has no qfq series
310
+ (e.g. BSE codes) the endpoint returns the raw `day/week/month` key instead."""
311
+ import requests
312
+
313
+ p_map = {"daily": "day", "weekly": "week", "monthly": "month"}
314
+ p = p_map.get(period, "day")
315
+ code = _cn_code(symbol)
316
+ resp = requests.get(
317
+ "https://web.ifzq.gtimg.cn/appstock/app/fqkline/get",
318
+ params={"param": f"{code},{p},,,{count},qfq"},
319
+ timeout=10,
320
+ )
321
+ data = resp.json()
322
+ if data.get("code") != 0:
323
+ raise ValueError(f"tencent kline failed: {data.get('msg', '')}")
324
+ node = data.get("data", {}).get(code, {})
325
+ rows = node.get(f"qfq{p}") or node.get(p)
326
+ if not rows:
327
+ raise ValueError("tencent kline returned empty data")
328
+ return [
329
+ _clean_row(
330
+ {
331
+ "date": r[0],
332
+ "open": _parse_float(r[1]),
333
+ "high": _parse_float(r[3]),
334
+ "low": _parse_float(r[4]),
335
+ "close": _parse_float(r[2]),
336
+ "volume": _parse_float(r[5]),
337
+ }
338
+ )
339
+ for r in rows[-count:]
340
+ ]
341
+
342
+
343
+ def _quote_sina(symbol: str) -> dict:
344
+ """Sina quote via hq.sinajs.cn. Requires a finance.sina.com.cn Referer or the
345
+ endpoint answers 403. GBK-encoded CSV; volume arrives in 股 → normalized to 手."""
346
+ import requests
347
+
348
+ resp = requests.get(
349
+ f"https://hq.sinajs.cn/list={_cn_code(symbol)}",
350
+ headers={"Referer": "https://finance.sina.com.cn"},
351
+ timeout=10,
352
+ )
353
+ f = _gbk_var_payload(resp.content).split(",")
354
+ if len(f) < 10 or not f[0]:
355
+ raise ValueError(f"sina returned no quote for {symbol}")
356
+ price = _parse_float(f[3])
357
+ prev_close = _parse_float(f[2])
358
+ volume = _parse_float(f[8])
359
+ row = {
360
+ "symbol": symbol,
361
+ "name": f[0],
362
+ "price": price,
363
+ "change": (price - prev_close) if price is not None and prev_close else None,
364
+ "change_pct": ((price / prev_close) - 1) * 100 if price is not None and prev_close else None,
365
+ "volume": volume / 100 if volume is not None else None,
366
+ "turnover": _parse_float(f[9]), # already 元
367
+ "high": _parse_float(f[4]),
368
+ "low": _parse_float(f[5]),
369
+ "open": _parse_float(f[1]),
370
+ "prev_close": prev_close,
371
+ }
372
+ if normalize_stock_code(symbol)["is_etf"]:
373
+ row["is_etf"] = True
374
+ return _clean_row(row)
375
+
376
+
377
+ def _kline_sina(symbol: str, period: str, count: int) -> list:
378
+ """Sina daily kline via quotes.sina.cn (JSONP-wrapped; scale=240 = daily is the
379
+ only supported period). Unadjusted; volume arrives in 股 → normalized to 手."""
380
+ if period != "daily":
381
+ raise ValueError("sina kline supports daily period only")
382
+ import requests
383
+
384
+ resp = requests.get(
385
+ "https://quotes.sina.cn/cn/api/jsonp_v2.php/var%20_k=/CN_MarketDataService.getKLineData",
386
+ params={"symbol": _cn_code(symbol), "scale": "240", "ma": "no", "datalen": str(min(count, 1023))},
387
+ headers={"Referer": "https://finance.sina.com.cn"},
388
+ timeout=10,
389
+ )
390
+ text = resp.text
391
+ start, end = text.find("["), text.rfind("]")
392
+ if start < 0 or end <= start:
393
+ raise ValueError("sina kline returned unparseable data")
394
+ rows = json.loads(text[start : end + 1])
395
+ if not rows:
396
+ raise ValueError("sina kline returned empty data")
397
+ result = []
398
+ for r in rows[-count:]:
399
+ volume = _parse_float(r.get("volume"))
400
+ result.append(
401
+ _clean_row(
402
+ {
403
+ "date": r.get("day"),
404
+ "open": _parse_float(r.get("open")),
405
+ "high": _parse_float(r.get("high")),
406
+ "low": _parse_float(r.get("low")),
407
+ "close": _parse_float(r.get("close")),
408
+ "volume": volume / 100 if volume is not None else None,
409
+ }
410
+ )
411
+ )
412
+ return result
413
+
414
+
232
415
  def _sanitize(obj):
233
416
  """Convert pandas types to JSON-serializable Python types."""
234
417
  import numpy as np
@@ -255,17 +438,27 @@ def _clean_row(d: dict) -> dict:
255
438
 
256
439
 
257
440
  def kline_a(symbol: str, period: str, count: int) -> list:
258
- """A-share kline with failover: akshare → tushare → efinance → pytdx → baostock."""
259
- return _failover(
260
- [
441
+ """A-share kline with failover: akshare → tushare → efinance → tencent → sina → pytdx → baostock.
442
+
443
+ Explicitly-prefixed symbols (sh000001, typically indices) skip the eastmoney
444
+ sources — they take bare 6-digit codes only and would fail slowly first."""
445
+ if _A_PREFIXED_RE.fullmatch(symbol):
446
+ sources = [
447
+ ("tencent", lambda: _kline_tencent(symbol, period, count)),
448
+ ("sina", lambda: _kline_sina(symbol, period, count)),
449
+ ("baostock", lambda: _kline_baostock(symbol, period, count)),
450
+ ]
451
+ else:
452
+ sources = [
261
453
  ("akshare", lambda: _kline_akshare(symbol, period, count)),
262
454
  ("tushare", lambda: _kline_tushare(symbol, period, count)),
263
455
  ("efinance", lambda: _kline_efinance(symbol, period, count)),
456
+ ("tencent", lambda: _kline_tencent(symbol, period, count)),
457
+ ("sina", lambda: _kline_sina(symbol, period, count)),
264
458
  ("pytdx", lambda: _kline_pytdx(symbol, period, count)),
265
459
  ("baostock", lambda: _kline_baostock(symbol, period, count)),
266
- ],
267
- label=f"kline_a:{symbol}",
268
- )
460
+ ]
461
+ return _failover(sources, label=f"kline_a:{symbol}")
269
462
 
270
463
 
271
464
  def _kline_akshare(symbol: str, period: str, count: int) -> list:
@@ -771,17 +964,29 @@ def cmd_kline(args):
771
964
 
772
965
 
773
966
  def quote_a(symbol: str) -> dict:
774
- """A-share quote with failover: akshare → tushare → efinance → pytdx. ETFs try fund spot first."""
967
+ """A-share quote with failover: akshare → tushare → efinance → tencent → sina → pytdx. ETFs try fund spot first.
968
+
969
+ Explicitly-prefixed symbols (sh000001, typically indices) go straight to
970
+ tencent/sina — the eastmoney sources take bare 6-digit codes only, and pytdx
971
+ can't place prefixed codes either. ETF quotes use their own sticky chain key
972
+ (quote_a_etf) so a stock-side winner never demotes the fund-spot source."""
973
+ if _A_PREFIXED_RE.fullmatch(symbol):
974
+ sources = [("tencent", lambda: _quote_tencent(symbol)), ("sina", lambda: _quote_sina(symbol))]
975
+ return _failover(sources, label=f"quote_a:{symbol}")
976
+ is_etf = normalize_stock_code(symbol)["is_etf"]
775
977
  sources = []
776
- if normalize_stock_code(symbol)["is_etf"]:
978
+ if is_etf:
777
979
  sources.append(("akshare_etf", lambda: _quote_akshare_etf(symbol)))
778
980
  sources += [
779
981
  ("akshare", lambda: _quote_akshare(symbol)),
780
982
  ("tushare", lambda: _quote_tushare(symbol)),
781
983
  ("efinance", lambda: _quote_efinance(symbol)),
984
+ ("tencent", lambda: _quote_tencent(symbol)),
985
+ ("sina", lambda: _quote_sina(symbol)),
782
986
  ("pytdx", lambda: _quote_pytdx(symbol)),
783
987
  ]
784
- return _failover(sources, label=f"quote_a:{symbol}")
988
+ chain = "quote_a_etf" if is_etf else "quote_a"
989
+ return _failover(sources, label=f"{chain}:{symbol}")
785
990
 
786
991
 
787
992
  def _quote_akshare_etf(symbol: str) -> dict:
@@ -1159,37 +1364,71 @@ def cmd_financials(args):
1159
1364
 
1160
1365
  def snapshot_a() -> list:
1161
1366
  try:
1162
- return _snapshot_akshare()
1163
- except Exception:
1164
- pass
1165
- try:
1166
- import efinance as ef
1167
-
1168
- df = ef.stock.get_realtime_quotes()
1169
- if df is None or df.empty:
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")]
1367
+ return _failover(
1368
+ [
1369
+ ("akshare", _snapshot_akshare),
1370
+ ("efinance", _snapshot_efinance),
1371
+ ("sina", _snapshot_sina),
1372
+ ],
1373
+ label="snapshot_a",
1374
+ )
1189
1375
  except Exception:
1190
1376
  return [{"error": "A-share snapshot unavailable from all sources"}]
1191
1377
 
1192
1378
 
1379
+ def _snapshot_efinance() -> list:
1380
+ import efinance as ef
1381
+
1382
+ df = ef.stock.get_realtime_quotes()
1383
+ if df is None or df.empty:
1384
+ raise ValueError("efinance snapshot empty")
1385
+ col_map = {
1386
+ "股票代码": "symbol",
1387
+ "股票名称": "name",
1388
+ "最新价": "price",
1389
+ "涨跌幅": "change_pct",
1390
+ "涨跌额": "change",
1391
+ "成交量": "volume",
1392
+ "成交额": "turnover",
1393
+ "市盈率": "pe",
1394
+ "换手率": "turnover_rate",
1395
+ "最高": "high",
1396
+ "最低": "low",
1397
+ "今开": "open",
1398
+ "昨收": "prev_close",
1399
+ }
1400
+ df = df.rename(columns=col_map)
1401
+ keep = [c for c in col_map.values() if c in df.columns]
1402
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1403
+
1404
+
1405
+ def _snapshot_sina() -> list:
1406
+ import akshare as ak
1407
+ import pandas as pd
1408
+
1409
+ df = _akshare_retry(ak.stock_zh_a_spot)
1410
+ if df is None or df.empty:
1411
+ raise ValueError("sina snapshot empty")
1412
+ df["代码"] = df["代码"].astype(str).str.replace(r"^(?:sh|sz|bj)", "", regex=True)
1413
+ df["成交量"] = pd.to_numeric(df["成交量"], errors="coerce") / 100
1414
+ col_map = {
1415
+ "代码": "symbol",
1416
+ "名称": "name",
1417
+ "最新价": "price",
1418
+ "涨跌额": "change",
1419
+ "涨跌幅": "change_pct",
1420
+ "成交量": "volume",
1421
+ "成交额": "turnover",
1422
+ "昨收": "prev_close",
1423
+ "今开": "open",
1424
+ "最高": "high",
1425
+ "最低": "low",
1426
+ }
1427
+ df = df.rename(columns=col_map)
1428
+ keep = [c for c in col_map.values() if c in df.columns]
1429
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1430
+
1431
+
1193
1432
  def _snapshot_akshare() -> list:
1194
1433
  import akshare as ak
1195
1434
 
@@ -1458,26 +1697,27 @@ def cmd_sector_rankings(args):
1458
1697
 
1459
1698
  # --------------- sector constituents / stock sectors (issue #18) ---------------
1460
1699
 
1461
- # No repo-wide disk-cache convention exists yet; tempdir keeps this cross-platform
1462
- # (Windows has no ~/.cache). Sector membership changes slowly — 24h TTL.
1463
- _SECTOR_CACHE_DIR = Path(tempfile.gettempdir()) / "pi-stock-analysis"
1464
- _SECTOR_CACHE_TTL = 24 * 3600
1700
+ # Disk cache lives in tempdir — cross-platform (Windows has no ~/.cache). Stores
1701
+ # sector constituents (24h TTL; membership changes slowly) and sticky failover
1702
+ # winners (keys prefixed `sticky-`, see _failover).
1703
+ _DATA_CACHE_DIR = Path(tempfile.gettempdir()) / "pi-stock-analysis"
1704
+ _DATA_CACHE_TTL = 24 * 3600
1465
1705
 
1466
1706
 
1467
- def _sector_cache_get(key: str):
1707
+ def _disk_cache_get(key: str):
1468
1708
  try:
1469
- path = _SECTOR_CACHE_DIR / f"{key}.json"
1470
- if path.exists() and time.time() - path.stat().st_mtime < _SECTOR_CACHE_TTL:
1709
+ path = _DATA_CACHE_DIR / f"{key}.json"
1710
+ if path.exists() and time.time() - path.stat().st_mtime < _DATA_CACHE_TTL:
1471
1711
  return json.loads(path.read_text(encoding="utf-8"))
1472
1712
  except Exception:
1473
1713
  pass
1474
1714
  return None
1475
1715
 
1476
1716
 
1477
- def _sector_cache_set(key: str, data):
1717
+ def _disk_cache_set(key: str, data):
1478
1718
  try:
1479
- _SECTOR_CACHE_DIR.mkdir(parents=True, exist_ok=True)
1480
- (_SECTOR_CACHE_DIR / f"{key}.json").write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
1719
+ _DATA_CACHE_DIR.mkdir(parents=True, exist_ok=True)
1720
+ (_DATA_CACHE_DIR / f"{key}.json").write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
1481
1721
  except Exception:
1482
1722
  pass
1483
1723
 
@@ -1601,14 +1841,14 @@ def cmd_sector_constituents(args):
1601
1841
  # Sector names are user input — hash them instead of sanitizing, so names that
1602
1842
  # differ only in whitespace/punctuation (创新药 vs 创新 药) can't collide.
1603
1843
  cache_key = hashlib.sha256(f"{sector}|{board_type}".encode()).hexdigest()[:16]
1604
- cached = _sector_cache_get(cache_key)
1844
+ cached = _disk_cache_get(cache_key)
1605
1845
  if cached is not None:
1606
1846
  return cached
1607
1847
  try:
1608
1848
  result = sector_constituents_a(sector, board_type)
1609
1849
  except Exception as e:
1610
1850
  return {"error": str(e)}
1611
- _sector_cache_set(cache_key, result)
1851
+ _disk_cache_set(cache_key, result)
1612
1852
  return result
1613
1853
 
1614
1854
 
@@ -1686,10 +1926,10 @@ def _stock_boards_from_cache(symbol: str) -> list:
1686
1926
  live A-share sources are both eastmoney-flavored). Reads every unexpired
1687
1927
  constituents payload in the cache dir and returns one entry per cached sector
1688
1928
  containing the symbol. Cold cache → []; malformed cache files are skipped
1689
- (_sector_cache_get returns None on expiry, bad JSON, or read errors)."""
1929
+ (_disk_cache_get returns None on expiry, bad JSON, or read errors)."""
1690
1930
  boards = []
1691
- for path in _SECTOR_CACHE_DIR.glob("*.json"):
1692
- data = _sector_cache_get(path.stem)
1931
+ for path in _DATA_CACHE_DIR.glob("*.json"):
1932
+ data = _disk_cache_get(path.stem)
1693
1933
  if not isinstance(data, dict):
1694
1934
  continue
1695
1935
  sector = data.get("sector")
@@ -1944,6 +2184,8 @@ def cmd_market_stats(args):
1944
2184
  data = snapshot_a()
1945
2185
  if isinstance(data, dict) and "error" in data:
1946
2186
  return data
2187
+ if isinstance(data, list) and len(data) == 1 and isinstance(data[0], dict) and "error" in data[0]:
2188
+ return data[0]
1947
2189
  if not data:
1948
2190
  return {"error": "No market data"}
1949
2191
  return compute_market_stats(data)
@@ -7,34 +7,16 @@ so the host agent can decide what to do next (write daily briefing, dig deeper,
7
7
 
8
8
  import argparse
9
9
  import json
10
- import subprocess
11
10
  import sys
12
11
  from concurrent.futures import ThreadPoolExecutor, as_completed
13
12
  from datetime import datetime, timezone
14
13
  from pathlib import Path
15
14
 
16
15
  sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+ from _subproc import run_tool as _run_json # noqa: E402
17
17
  from stock_data import detect_market # noqa: E402
18
18
  from watchlist import analyze_watchlist # noqa: E402
19
19
 
20
- TOOLS_DIR = Path(__file__).resolve().parent
21
-
22
-
23
- def _find_python() -> str:
24
- venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
25
- return str(venv) if venv.exists() else sys.executable
26
-
27
-
28
- def _run_json(script: str, args: list[str], timeout: int = 30):
29
- cmd = [_find_python(), str(TOOLS_DIR / script)] + args
30
- try:
31
- r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=timeout)
32
- if r.returncode == 0 and r.stdout.strip():
33
- return json.loads(r.stdout)
34
- except Exception:
35
- pass
36
- return None
37
-
38
20
 
39
21
  def _trend_label(overall: str) -> str:
40
22
  return {