@weaxs/openclaw-stock-analysis 0.1.3

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 (71) hide show
  1. package/README.md +70 -0
  2. package/index.ts +761 -0
  3. package/openclaw.plugin.json +47 -0
  4. package/package.json +46 -0
  5. package/schemas/report_schema.json +131 -0
  6. package/scripts/setup-python.mjs +52 -0
  7. package/skills/bottom-volume/SKILL.md +63 -0
  8. package/skills/bottom-volume/scripts/gather.py +15 -0
  9. package/skills/box-oscillation/SKILL.md +72 -0
  10. package/skills/box-oscillation/scripts/gather.py +15 -0
  11. package/skills/bull-trend/SKILL.md +60 -0
  12. package/skills/bull-trend/scripts/gather.py +15 -0
  13. package/skills/chan-theory/SKILL.md +71 -0
  14. package/skills/chan-theory/scripts/gather.py +15 -0
  15. package/skills/dragon-head/SKILL.md +69 -0
  16. package/skills/dragon-head/scripts/gather.py +15 -0
  17. package/skills/emotion-cycle/SKILL.md +65 -0
  18. package/skills/emotion-cycle/scripts/gather.py +15 -0
  19. package/skills/event-driven/SKILL.md +73 -0
  20. package/skills/event-driven/scripts/gather.py +15 -0
  21. package/skills/expectation-repricing/SKILL.md +72 -0
  22. package/skills/expectation-repricing/scripts/gather.py +15 -0
  23. package/skills/growth-quality/SKILL.md +74 -0
  24. package/skills/growth-quality/scripts/gather.py +15 -0
  25. package/skills/hot-theme/SKILL.md +74 -0
  26. package/skills/hot-theme/scripts/gather.py +15 -0
  27. package/skills/ma-crossover/SKILL.md +63 -0
  28. package/skills/ma-crossover/scripts/gather.py +15 -0
  29. package/skills/market-review/SKILL.md +70 -0
  30. package/skills/market-review/scripts/gather.py +16 -0
  31. package/skills/one-yang-three-yin/SKILL.md +74 -0
  32. package/skills/one-yang-three-yin/scripts/gather.py +15 -0
  33. package/skills/shrink-pullback/SKILL.md +59 -0
  34. package/skills/shrink-pullback/scripts/gather.py +15 -0
  35. package/skills/stock-analysis/SKILL.md +134 -0
  36. package/skills/stock-analysis/scripts/gather.py +15 -0
  37. package/skills/stock-screener/SKILL.md +68 -0
  38. package/skills/stock-screener/scripts/gather.py +15 -0
  39. package/skills/strategy-backtest/SKILL.md +129 -0
  40. package/skills/strategy-backtest/scripts/gather.py +16 -0
  41. package/skills/volume-breakout/SKILL.md +58 -0
  42. package/skills/volume-breakout/scripts/gather.py +15 -0
  43. package/skills/wave-theory/SKILL.md +67 -0
  44. package/skills/wave-theory/scripts/gather.py +15 -0
  45. package/skills/wisburg-research/SKILL.md +119 -0
  46. package/strategies/examples/bottom_volume.yaml +47 -0
  47. package/strategies/examples/box_oscillation.yaml +41 -0
  48. package/strategies/examples/bull_trend.yaml +42 -0
  49. package/strategies/examples/dragon_head.yaml +45 -0
  50. package/strategies/examples/emotion_cycle.yaml +43 -0
  51. package/strategies/examples/ma_crossover.yaml +34 -0
  52. package/strategies/examples/rsi_oversold.yaml +35 -0
  53. package/strategies/examples/shrink_pullback.yaml +45 -0
  54. package/strategies/examples/volume_breakout.yaml +42 -0
  55. package/tools/__init__.py +0 -0
  56. package/tools/anomaly_detect.py +570 -0
  57. package/tools/backtest.py +643 -0
  58. package/tools/gather.py +152 -0
  59. package/tools/market_regime.py +247 -0
  60. package/tools/market_review.py +150 -0
  61. package/tools/name_resolver.py +131 -0
  62. package/tools/pattern.py +509 -0
  63. package/tools/requirements.txt +13 -0
  64. package/tools/risk_screening.py +318 -0
  65. package/tools/screener.py +213 -0
  66. package/tools/search_intel.py +455 -0
  67. package/tools/stock_data.py +1649 -0
  68. package/tools/technical.py +636 -0
  69. package/tools/trading_calendar.py +198 -0
  70. package/tools/volume_analysis.py +172 -0
  71. package/tools/watchlist.py +61 -0
@@ -0,0 +1,1649 @@
1
+ #!/usr/bin/env python3
2
+ """Stock market data fetcher for A-shares (akshare), HK and US (yfinance)."""
3
+
4
+ import argparse
5
+ import contextlib
6
+ import json
7
+ import re
8
+ import sys
9
+ import time
10
+ from datetime import datetime, timedelta
11
+
12
+
13
+ def detect_market(symbol: str) -> str:
14
+ if symbol.upper().endswith(".HK"):
15
+ return "HK"
16
+ if re.match(r"^\d{6}$", symbol):
17
+ return "A"
18
+ return "US"
19
+
20
+
21
+ def normalize_stock_code(symbol: str) -> dict:
22
+ """Classify A-share stock code into board/type with limit-up/down ratio."""
23
+ info = {"market": detect_market(symbol), "board": "main", "is_st": False, "is_etf": False, "limit_pct": 0.10}
24
+ if info["market"] != "A":
25
+ info["limit_pct"] = None
26
+ return info
27
+
28
+ prefix2 = symbol[:2]
29
+ prefix3 = symbol[:3]
30
+
31
+ if prefix3 == "688":
32
+ info["board"] = "STAR"
33
+ info["limit_pct"] = 0.20
34
+ elif prefix2 == "30":
35
+ info["board"] = "ChiNext"
36
+ info["limit_pct"] = 0.20
37
+ elif prefix2 in ("92", "43", "81", "82", "83", "87", "88"):
38
+ info["board"] = "BSE"
39
+ info["limit_pct"] = 0.30
40
+ elif prefix2 in ("51", "52", "56", "58", "15", "16", "18"):
41
+ info["is_etf"] = True
42
+ info["board"] = "ETF"
43
+ info["limit_pct"] = None
44
+
45
+ return info
46
+
47
+
48
+ def mark_st(info: dict, name: str) -> dict:
49
+ """Mark ST status from stock name; adjusts limit_pct to 5%."""
50
+ if name and "ST" in name.upper():
51
+ info["is_st"] = True
52
+ if info["board"] == "main":
53
+ info["limit_pct"] = 0.05
54
+ return info
55
+
56
+
57
+ def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
58
+ """Calculate limit-up or limit-down price with banker's rounding."""
59
+ import numpy as np
60
+
61
+ sign = 1 if direction == "up" else -1
62
+ return np.floor(pre_close * (1 + sign * ratio) * 100 + 0.5) / 100.0
63
+
64
+
65
+ def _failover(sources: list, label: str = ""):
66
+ """Try each (name, fn) in order; return first success or raise last error."""
67
+ last_err = None
68
+ for _name, fn in sources:
69
+ try:
70
+ result = fn()
71
+ if result:
72
+ return result
73
+ except Exception as e:
74
+ last_err = e
75
+ if last_err:
76
+ raise last_err
77
+ return None
78
+
79
+
80
+ def _akshare_retry(fn, *args, retries=2, delay=1):
81
+ for attempt in range(retries + 1):
82
+ try:
83
+ return fn(*args)
84
+ except Exception:
85
+ if attempt == retries:
86
+ raise
87
+ time.sleep(delay)
88
+
89
+
90
+ def _to_baostock_code(symbol: str) -> str:
91
+ if symbol.startswith(
92
+ ("600", "601", "603", "605", "688", "689", "510", "512", "513", "515", "516", "518", "560", "588")
93
+ ):
94
+ return f"sh.{symbol}"
95
+ return f"sz.{symbol}"
96
+
97
+
98
+ def _kline_efinance(symbol: str, period: str, count: int) -> list:
99
+ import efinance as ef
100
+
101
+ freq_map = {"daily": 101, "weekly": 102, "monthly": 103}
102
+ df = ef.stock.get_quote_history(symbol, klt=freq_map.get(period, 101))
103
+ if df is None or df.empty:
104
+ raise ValueError("efinance returned empty data")
105
+ col_map = {
106
+ "日期": "date",
107
+ "开盘": "open",
108
+ "收盘": "close",
109
+ "最高": "high",
110
+ "最低": "low",
111
+ "成交量": "volume",
112
+ "成交额": "turnover",
113
+ "振幅": "amplitude",
114
+ "涨跌幅": "change_pct",
115
+ "换手率": "turnover_rate",
116
+ }
117
+ df = df.rename(columns=col_map)
118
+ for c in ["open", "high", "low", "close", "volume"]:
119
+ if c in df.columns:
120
+ df[c] = __import__("pandas").to_numeric(df[c], errors="coerce")
121
+ keep = [
122
+ c
123
+ for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct", "turnover_rate"]
124
+ if c in df.columns
125
+ ]
126
+ df = df[keep].tail(count)
127
+ return [_clean_row(r) for r in df.to_dict("records")]
128
+
129
+
130
+ def _kline_baostock(symbol: str, period: str, count: int) -> list:
131
+ import baostock as bs
132
+ import pandas as pd
133
+
134
+ freq_map = {"daily": "d", "weekly": "w", "monthly": "m"}
135
+ end = datetime.now()
136
+ start = end - timedelta(days=count * 7 if period == "weekly" else count * 31 if period == "monthly" else count * 2)
137
+ bs.login()
138
+ try:
139
+ rs = bs.query_history_k_data_plus(
140
+ _to_baostock_code(symbol),
141
+ "date,open,high,low,close,volume,amount,pctChg",
142
+ start_date=start.strftime("%Y-%m-%d"),
143
+ end_date=end.strftime("%Y-%m-%d"),
144
+ frequency=freq_map.get(period, "d"),
145
+ adjustflag="2",
146
+ )
147
+ rows = []
148
+ while (rs.error_code == "0") and rs.next():
149
+ rows.append(rs.get_row_data())
150
+ df = pd.DataFrame(rows, columns=rs.fields)
151
+ finally:
152
+ bs.logout()
153
+ if df.empty:
154
+ raise ValueError("baostock returned empty data")
155
+ col_map = {"amount": "turnover", "pctChg": "change_pct"}
156
+ df = df.rename(columns=col_map)
157
+ for c in ["open", "high", "low", "close", "volume"]:
158
+ if c in df.columns:
159
+ df[c] = pd.to_numeric(df[c], errors="coerce")
160
+ keep = [c for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct"] if c in df.columns]
161
+ df = df[keep].tail(count)
162
+ return [_clean_row(r) for r in df.to_dict("records")]
163
+
164
+
165
+ def _quote_efinance(symbol: str) -> dict:
166
+ import efinance as ef
167
+
168
+ df = ef.stock.get_realtime_quotes([symbol])
169
+ if df is None or df.empty:
170
+ raise ValueError("efinance quote returned empty")
171
+ r = df.iloc[0]
172
+ col_map = {
173
+ "股票代码": "symbol",
174
+ "股票名称": "name",
175
+ "最新价": "price",
176
+ "涨跌额": "change",
177
+ "涨跌幅": "change_pct",
178
+ "成交量": "volume",
179
+ "成交额": "turnover",
180
+ "最高": "high",
181
+ "最低": "low",
182
+ "今开": "open",
183
+ "昨收": "prev_close",
184
+ "总市值": "market_cap",
185
+ "市盈率": "pe",
186
+ "换手率": "turnover_rate",
187
+ }
188
+ result = {}
189
+ for cn_key, en_key in col_map.items():
190
+ val = r.get(cn_key)
191
+ if val is not None and val != "":
192
+ with contextlib.suppress(ValueError, TypeError):
193
+ val = float(val) if en_key not in ("symbol", "name") else val
194
+ result[en_key] = val
195
+ return _clean_row(result)
196
+
197
+
198
+ def _sanitize(obj):
199
+ """Convert pandas types to JSON-serializable Python types."""
200
+ import numpy as np
201
+ import pandas as pd
202
+
203
+ if isinstance(obj, (pd.Timestamp, datetime)):
204
+ return obj.strftime("%Y-%m-%d")
205
+ if isinstance(obj, (np.integer,)):
206
+ return int(obj)
207
+ if isinstance(obj, (np.floating,)):
208
+ return None if np.isnan(obj) else round(float(obj), 4)
209
+ if isinstance(obj, (np.bool_,)):
210
+ return bool(obj)
211
+ if isinstance(obj, float):
212
+ return None if obj != obj else round(obj, 4)
213
+ return obj
214
+
215
+
216
+ def _clean_row(d: dict) -> dict:
217
+ return {k: _sanitize(v) for k, v in d.items()}
218
+
219
+
220
+ # --------------- kline ---------------
221
+
222
+
223
+ def kline_a(symbol: str, period: str, count: int) -> list:
224
+ """A-share kline with failover: akshare → tushare → efinance → pytdx → baostock."""
225
+ return _failover(
226
+ [
227
+ ("akshare", lambda: _kline_akshare(symbol, period, count)),
228
+ ("tushare", lambda: _kline_tushare(symbol, period, count)),
229
+ ("efinance", lambda: _kline_efinance(symbol, period, count)),
230
+ ("pytdx", lambda: _kline_pytdx(symbol, period, count)),
231
+ ("baostock", lambda: _kline_baostock(symbol, period, count)),
232
+ ],
233
+ label=f"kline_a:{symbol}",
234
+ )
235
+
236
+
237
+ def _kline_akshare(symbol: str, period: str, count: int) -> list:
238
+ import akshare as ak
239
+
240
+ period_map = {"daily": "daily", "weekly": "weekly", "monthly": "monthly"}
241
+ end = datetime.now()
242
+ start = end - timedelta(days=count * 7 if period == "weekly" else count * 31 if period == "monthly" else count * 2)
243
+
244
+ df = _akshare_retry(
245
+ ak.stock_zh_a_hist,
246
+ symbol=symbol,
247
+ period=period_map.get(period, "daily"),
248
+ start_date=start.strftime("%Y%m%d"),
249
+ end_date=end.strftime("%Y%m%d"),
250
+ adjust="qfq",
251
+ )
252
+ col_map = {
253
+ "日期": "date",
254
+ "开盘": "open",
255
+ "收盘": "close",
256
+ "最高": "high",
257
+ "最低": "low",
258
+ "成交量": "volume",
259
+ "成交额": "turnover",
260
+ "振幅": "amplitude",
261
+ "涨跌幅": "change_pct",
262
+ "涨跌额": "change",
263
+ "换手率": "turnover_rate",
264
+ }
265
+ df = df.rename(columns=col_map)
266
+ keep = [
267
+ c
268
+ for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct", "turnover_rate"]
269
+ if c in df.columns
270
+ ]
271
+ df = df[keep].tail(count)
272
+ return [_clean_row(r) for r in df.to_dict("records")]
273
+
274
+
275
+ def _kline_tushare(symbol: str, period: str, count: int) -> list:
276
+ """Tushare kline via HTTP API. Requires TUSHARE_TOKEN."""
277
+ import os
278
+
279
+ import pandas as pd
280
+ import requests
281
+
282
+ token = os.environ.get("TUSHARE_TOKEN")
283
+ if not token:
284
+ raise ValueError("TUSHARE_TOKEN not set")
285
+
286
+ api_name_map = {"daily": "daily", "weekly": "weekly", "monthly": "monthly"}
287
+ end = datetime.now()
288
+ start = end - timedelta(days=count * 7 if period == "weekly" else count * 31 if period == "monthly" else count * 2)
289
+
290
+ ts_code = f"{symbol}.SH" if symbol.startswith(("6", "9", "5")) else f"{symbol}.SZ"
291
+
292
+ resp = requests.post(
293
+ "http://api.tushare.pro",
294
+ json={
295
+ "api_name": api_name_map.get(period, "daily"),
296
+ "token": token,
297
+ "params": {
298
+ "ts_code": ts_code,
299
+ "start_date": start.strftime("%Y%m%d"),
300
+ "end_date": end.strftime("%Y%m%d"),
301
+ },
302
+ "fields": "trade_date,open,high,low,close,vol,amount,pct_chg",
303
+ },
304
+ timeout=15,
305
+ )
306
+ data = resp.json()
307
+ if data.get("code") != 0 or not data.get("data", {}).get("items"):
308
+ raise ValueError(f"tushare returned no data: {data.get('msg', '')}")
309
+
310
+ df = pd.DataFrame(data["data"]["items"], columns=data["data"]["fields"])
311
+ col_map = {"trade_date": "date", "vol": "volume", "amount": "turnover", "pct_chg": "change_pct"}
312
+ df = df.rename(columns=col_map)
313
+ df = df.sort_values("date")
314
+ for c in ["open", "high", "low", "close", "volume"]:
315
+ if c in df.columns:
316
+ df[c] = pd.to_numeric(df[c], errors="coerce")
317
+ keep = [c for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct"] if c in df.columns]
318
+ df = df[keep].tail(count)
319
+ return [_clean_row(r) for r in df.to_dict("records")]
320
+
321
+
322
+ def _quote_tushare(symbol: str) -> dict:
323
+ """Tushare realtime quote via HTTP API."""
324
+ import os
325
+
326
+ import requests
327
+
328
+ token = os.environ.get("TUSHARE_TOKEN")
329
+ if not token:
330
+ raise ValueError("TUSHARE_TOKEN not set")
331
+
332
+ ts_code = f"{symbol}.SH" if symbol.startswith(("6", "9", "5")) else f"{symbol}.SZ"
333
+
334
+ resp = requests.post(
335
+ "http://api.tushare.pro",
336
+ json={
337
+ "api_name": "realtime_quote",
338
+ "token": token,
339
+ "params": {"ts_code": ts_code},
340
+ },
341
+ timeout=15,
342
+ )
343
+ data = resp.json()
344
+ if data.get("code") != 0 or not data.get("data", {}).get("items"):
345
+ raise ValueError(f"tushare quote failed: {data.get('msg', '')}")
346
+
347
+ row = dict(zip(data["data"]["fields"], data["data"]["items"][0]))
348
+ return _clean_row(
349
+ {
350
+ "symbol": symbol,
351
+ "name": row.get("name"),
352
+ "price": row.get("price"),
353
+ "change": row.get("change"),
354
+ "change_pct": row.get("pct_chg"),
355
+ "volume": row.get("vol"),
356
+ "turnover": row.get("amount"),
357
+ "high": row.get("high"),
358
+ "low": row.get("low"),
359
+ "open": row.get("open"),
360
+ "prev_close": row.get("pre_close"),
361
+ }
362
+ )
363
+
364
+
365
+ def _kline_pytdx(symbol: str, period: str, count: int) -> list:
366
+ """pytdx kline from TDX market servers. No credentials needed."""
367
+ from pytdx.hq import TdxHq_API
368
+
369
+ market = 1 if symbol.startswith(("6", "9", "5")) else 0
370
+ freq_map = {"daily": 9, "weekly": 5, "monthly": 6}
371
+
372
+ api = TdxHq_API()
373
+ with api.connect("119.147.212.81", 7709):
374
+ data = api.get_security_bars(freq_map.get(period, 9), market, symbol, 0, count)
375
+
376
+ if not data:
377
+ raise ValueError("pytdx returned empty data")
378
+
379
+ rows = []
380
+ for bar in data:
381
+ rows.append(
382
+ _clean_row(
383
+ {
384
+ "date": bar["datetime"][:10],
385
+ "open": bar["open"],
386
+ "high": bar["high"],
387
+ "low": bar["low"],
388
+ "close": bar["close"],
389
+ "volume": bar["vol"],
390
+ "turnover": bar.get("amount"),
391
+ }
392
+ )
393
+ )
394
+ return rows[-count:]
395
+
396
+
397
+ def _quote_pytdx(symbol: str) -> dict:
398
+ """pytdx realtime quote from TDX market servers."""
399
+ from pytdx.hq import TdxHq_API
400
+
401
+ market = 1 if symbol.startswith(("6", "9", "5")) else 0
402
+
403
+ api = TdxHq_API()
404
+ with api.connect("119.147.212.81", 7709):
405
+ data = api.get_security_quotes([(market, symbol)])
406
+
407
+ if not data:
408
+ raise ValueError("pytdx quote returned empty")
409
+
410
+ q = data[0]
411
+ prev_close = q.get("last_close")
412
+ price = q.get("price")
413
+ return _clean_row(
414
+ {
415
+ "symbol": symbol,
416
+ "name": q.get("name", ""),
417
+ "price": price,
418
+ "change": (price - prev_close) if price and prev_close else None,
419
+ "change_pct": ((price / prev_close) - 1) * 100 if price and prev_close else None,
420
+ "volume": q.get("vol"),
421
+ "high": q.get("high"),
422
+ "low": q.get("low"),
423
+ "open": q.get("open"),
424
+ "prev_close": prev_close,
425
+ }
426
+ )
427
+
428
+
429
+ def _kline_yfinance(symbol: str, period: str, count: int) -> list:
430
+ import yfinance as yf
431
+
432
+ period_map = {"daily": "1d", "weekly": "1wk", "monthly": "1mo"}
433
+ days = count * 2 if period == "daily" else count * 10 if period == "weekly" else count * 35
434
+ start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
435
+
436
+ df = yf.download(symbol, start=start, interval=period_map.get(period, "1d"), progress=False, auto_adjust=True)
437
+ if df.empty:
438
+ raise ValueError(f"yfinance returned empty data for {symbol}")
439
+ df = df.reset_index()
440
+ if isinstance(df.columns, __import__("pandas").MultiIndex):
441
+ df.columns = [c[0] if isinstance(c, tuple) else c for c in df.columns]
442
+ col_map = {
443
+ "Date": "date",
444
+ "Datetime": "date",
445
+ "Open": "open",
446
+ "High": "high",
447
+ "Low": "low",
448
+ "Close": "close",
449
+ "Volume": "volume",
450
+ }
451
+ df = df.rename(columns=col_map)
452
+ keep = [c for c in ["date", "open", "high", "low", "close", "volume"] if c in df.columns]
453
+ df = df[keep].tail(count)
454
+ return [_clean_row(r) for r in df.to_dict("records")]
455
+
456
+
457
+ def _kline_finnhub(symbol: str, period: str, count: int) -> list:
458
+ import os
459
+
460
+ api_key = os.environ.get("FINNHUB_API_KEY")
461
+ if not api_key:
462
+ raise ValueError("FINNHUB_API_KEY not set")
463
+ import finnhub
464
+
465
+ client = finnhub.Client(api_key=api_key)
466
+ resolution_map = {"daily": "D", "weekly": "W", "monthly": "M"}
467
+ resolution = resolution_map.get(period, "D")
468
+ days = count * 2 if period == "daily" else count * 10 if period == "weekly" else count * 35
469
+ end = int(datetime.now().timestamp())
470
+ start = int((datetime.now() - timedelta(days=days)).timestamp())
471
+ candles = client.stock_candles(symbol.replace(".HK", ""), resolution, start, end)
472
+ if candles.get("s") != "ok" or not candles.get("c"):
473
+ raise ValueError(f"finnhub returned no data for {symbol}")
474
+ rows = []
475
+ for i in range(len(candles["c"])):
476
+ rows.append(
477
+ _clean_row(
478
+ {
479
+ "date": datetime.fromtimestamp(candles["t"][i]).strftime("%Y-%m-%d"),
480
+ "open": candles["o"][i],
481
+ "high": candles["h"][i],
482
+ "low": candles["l"][i],
483
+ "close": candles["c"][i],
484
+ "volume": candles["v"][i],
485
+ }
486
+ )
487
+ )
488
+ return rows[-count:]
489
+
490
+
491
+ def _kline_longbridge(symbol: str, period: str, count: int) -> list:
492
+ """Longbridge kline via longport SDK. Requires LONGBRIDGE_* env vars."""
493
+ import os
494
+
495
+ app_key = os.environ.get("LONGBRIDGE_APP_KEY")
496
+ app_secret = os.environ.get("LONGBRIDGE_APP_SECRET")
497
+ access_token = os.environ.get("LONGBRIDGE_ACCESS_TOKEN")
498
+ if not all([app_key, app_secret, access_token]):
499
+ raise ValueError("LONGBRIDGE credentials not set (APP_KEY/APP_SECRET/ACCESS_TOKEN)")
500
+
501
+ from longport.openapi import AdjustType, Config, Period, QuoteContext
502
+
503
+ config = Config(app_key=app_key, app_secret=app_secret, access_token=access_token)
504
+ ctx = QuoteContext(config)
505
+
506
+ period_map = {"daily": Period.Day, "weekly": Period.Week, "monthly": Period.Month}
507
+
508
+ candlesticks = ctx.candlesticks(symbol, period_map.get(period, Period.Day), count, AdjustType.ForwardAdj)
509
+ if not candlesticks:
510
+ raise ValueError(f"longbridge returned no kline for {symbol}")
511
+
512
+ rows = []
513
+ for c in candlesticks:
514
+ rows.append(
515
+ _clean_row(
516
+ {
517
+ "date": str(c.timestamp)[:10],
518
+ "open": float(c.open),
519
+ "high": float(c.high),
520
+ "low": float(c.low),
521
+ "close": float(c.close),
522
+ "volume": int(c.volume),
523
+ "turnover": float(c.turnover) if c.turnover else None,
524
+ }
525
+ )
526
+ )
527
+ return rows[-count:]
528
+
529
+
530
+ def _quote_longbridge(symbol: str) -> dict:
531
+ """Longbridge realtime quote."""
532
+ import os
533
+
534
+ app_key = os.environ.get("LONGBRIDGE_APP_KEY")
535
+ app_secret = os.environ.get("LONGBRIDGE_APP_SECRET")
536
+ access_token = os.environ.get("LONGBRIDGE_ACCESS_TOKEN")
537
+ if not all([app_key, app_secret, access_token]):
538
+ raise ValueError("LONGBRIDGE credentials not set")
539
+
540
+ from longport.openapi import Config, QuoteContext
541
+
542
+ config = Config(app_key=app_key, app_secret=app_secret, access_token=access_token)
543
+ ctx = QuoteContext(config)
544
+
545
+ quotes = ctx.quote([symbol])
546
+ if not quotes:
547
+ raise ValueError(f"longbridge returned no quote for {symbol}")
548
+
549
+ q = quotes[0]
550
+ prev_close = float(q.prev_close) if q.prev_close else None
551
+ price = float(q.last_done) if q.last_done else None
552
+ return _clean_row(
553
+ {
554
+ "symbol": symbol,
555
+ "name": getattr(q, "symbol", symbol),
556
+ "price": price,
557
+ "change": (price - prev_close) if price and prev_close else None,
558
+ "change_pct": float(q.change_rate) * 100 if getattr(q, "change_rate", None) else None,
559
+ "volume": int(q.volume) if q.volume else None,
560
+ "turnover": float(q.turnover) if getattr(q, "turnover", None) else None,
561
+ "high": float(q.high) if q.high else None,
562
+ "low": float(q.low) if q.low else None,
563
+ "open": float(q.open) if q.open else None,
564
+ "prev_close": prev_close,
565
+ }
566
+ )
567
+
568
+
569
+ def _kline_alphavantage(symbol: str, period: str, count: int) -> list:
570
+ """Alpha Vantage kline. US stocks only. Requires ALPHAVANTAGE_API_KEY."""
571
+ import os
572
+
573
+ import requests
574
+
575
+ api_key = os.environ.get("ALPHAVANTAGE_API_KEY")
576
+ if not api_key:
577
+ raise ValueError("ALPHAVANTAGE_API_KEY not set")
578
+
579
+ fn_map = {
580
+ "daily": "TIME_SERIES_DAILY_ADJUSTED",
581
+ "weekly": "TIME_SERIES_WEEKLY_ADJUSTED",
582
+ "monthly": "TIME_SERIES_MONTHLY_ADJUSTED",
583
+ }
584
+ ts_key_map = {
585
+ "daily": "Time Series (Daily)",
586
+ "weekly": "Weekly Adjusted Time Series",
587
+ "monthly": "Monthly Adjusted Time Series",
588
+ }
589
+
590
+ resp = requests.get(
591
+ "https://www.alphavantage.co/query",
592
+ params={
593
+ "function": fn_map.get(period, fn_map["daily"]),
594
+ "symbol": symbol,
595
+ "apikey": api_key,
596
+ "outputsize": "compact",
597
+ },
598
+ timeout=20,
599
+ )
600
+ data = resp.json()
601
+ ts_key = ts_key_map.get(period, ts_key_map["daily"])
602
+ ts = data.get(ts_key)
603
+ if not ts:
604
+ raise ValueError(
605
+ f"alphavantage returned no data for {symbol}: {data.get('Note', data.get('Error Message', ''))}"
606
+ )
607
+
608
+ rows = []
609
+ for date_str, vals in sorted(ts.items()):
610
+ rows.append(
611
+ _clean_row(
612
+ {
613
+ "date": date_str,
614
+ "open": float(vals["1. open"]),
615
+ "high": float(vals["2. high"]),
616
+ "low": float(vals["3. low"]),
617
+ "close": float(vals["4. close"]),
618
+ "volume": int(vals.get("6. volume", vals.get("5. volume", 0))),
619
+ }
620
+ )
621
+ )
622
+ return rows[-count:]
623
+
624
+
625
+ def _quote_alphavantage(symbol: str) -> dict:
626
+ """Alpha Vantage quote. US stocks only."""
627
+ import os
628
+
629
+ import requests
630
+
631
+ api_key = os.environ.get("ALPHAVANTAGE_API_KEY")
632
+ if not api_key:
633
+ raise ValueError("ALPHAVANTAGE_API_KEY not set")
634
+
635
+ resp = requests.get(
636
+ "https://www.alphavantage.co/query",
637
+ params={"function": "GLOBAL_QUOTE", "symbol": symbol, "apikey": api_key},
638
+ timeout=20,
639
+ )
640
+ data = resp.json()
641
+ gq = data.get("Global Quote")
642
+ if not gq:
643
+ raise ValueError(f"alphavantage quote failed for {symbol}")
644
+
645
+ return _clean_row(
646
+ {
647
+ "symbol": symbol,
648
+ "price": float(gq.get("05. price", 0)),
649
+ "change": float(gq.get("09. change", 0)),
650
+ "change_pct": float(gq.get("10. change percent", "0").rstrip("%")),
651
+ "volume": int(gq.get("06. volume", 0)),
652
+ "high": float(gq.get("03. high", 0)),
653
+ "low": float(gq.get("04. low", 0)),
654
+ "open": float(gq.get("02. open", 0)),
655
+ "prev_close": float(gq.get("08. previous close", 0)),
656
+ }
657
+ )
658
+
659
+
660
+ def kline_yf(symbol: str, period: str, count: int) -> list:
661
+ """HK/US kline with failover: yfinance → finnhub → longbridge → alphavantage (US only)."""
662
+ sources = [
663
+ ("yfinance", lambda: _kline_yfinance(symbol, period, count)),
664
+ ("finnhub", lambda: _kline_finnhub(symbol, period, count)),
665
+ ("longbridge", lambda: _kline_longbridge(symbol, period, count)),
666
+ ]
667
+ if detect_market(symbol) == "US":
668
+ sources.append(("alphavantage", lambda: _kline_alphavantage(symbol, period, count)))
669
+ return _failover(sources, label=f"kline:{symbol}")
670
+
671
+
672
+ def cmd_kline(args):
673
+ market = detect_market(args.symbol)
674
+ try:
675
+ if market == "A":
676
+ data = kline_a(args.symbol, args.period, args.count)
677
+ else:
678
+ data = kline_yf(args.symbol, args.period, args.count)
679
+ return data
680
+ except Exception as e:
681
+ return {"error": str(e)}
682
+
683
+
684
+ # --------------- quote ---------------
685
+
686
+
687
+ def quote_a(symbol: str) -> dict:
688
+ """A-share quote with failover: akshare → tushare → efinance → pytdx."""
689
+ return _failover(
690
+ [
691
+ ("akshare", lambda: _quote_akshare(symbol)),
692
+ ("tushare", lambda: _quote_tushare(symbol)),
693
+ ("efinance", lambda: _quote_efinance(symbol)),
694
+ ("pytdx", lambda: _quote_pytdx(symbol)),
695
+ ],
696
+ label=f"quote_a:{symbol}",
697
+ )
698
+
699
+
700
+ def _quote_akshare(symbol: str) -> dict:
701
+ import akshare as ak
702
+
703
+ df = _akshare_retry(ak.stock_zh_a_spot_em)
704
+ row = df[df["代码"] == symbol]
705
+ if row.empty:
706
+ raise ValueError(f"Symbol {symbol} not found in akshare")
707
+ r = row.iloc[0]
708
+ return _clean_row(
709
+ {
710
+ "symbol": symbol,
711
+ "name": r.get("名称"),
712
+ "price": r.get("最新价"),
713
+ "change": r.get("涨跌额"),
714
+ "change_pct": r.get("涨跌幅"),
715
+ "volume": r.get("成交量"),
716
+ "turnover": r.get("成交额"),
717
+ "high": r.get("最高"),
718
+ "low": r.get("最低"),
719
+ "open": r.get("今开"),
720
+ "prev_close": r.get("昨收"),
721
+ "market_cap": r.get("总市值"),
722
+ "pe": r.get("市盈率-动态"),
723
+ "pb": r.get("市净率"),
724
+ "turnover_rate": r.get("换手率"),
725
+ "volume_ratio": r.get("量比"),
726
+ "amplitude": r.get("振幅"),
727
+ "change_pct_60d": r.get("60日涨跌幅"),
728
+ }
729
+ )
730
+
731
+
732
+ def _quote_yfinance(symbol: str) -> dict:
733
+ import yfinance as yf
734
+
735
+ t = yf.Ticker(symbol)
736
+ info = t.info
737
+ if not info or "regularMarketPrice" not in info:
738
+ raise ValueError(f"No data for {symbol}")
739
+ return _clean_row(
740
+ {
741
+ "symbol": symbol,
742
+ "name": info.get("shortName"),
743
+ "price": info.get("regularMarketPrice") or info.get("currentPrice"),
744
+ "change": info.get("regularMarketChange"),
745
+ "change_pct": info.get("regularMarketChangePercent"),
746
+ "volume": info.get("regularMarketVolume"),
747
+ "high": info.get("regularMarketDayHigh"),
748
+ "low": info.get("regularMarketDayLow"),
749
+ "open": info.get("regularMarketOpen"),
750
+ "prev_close": info.get("regularMarketPreviousClose"),
751
+ "market_cap": info.get("marketCap"),
752
+ "pe": info.get("trailingPE"),
753
+ "pb": info.get("priceToBook"),
754
+ }
755
+ )
756
+
757
+
758
+ def _quote_finnhub(symbol: str) -> dict:
759
+ import os
760
+
761
+ api_key = os.environ.get("FINNHUB_API_KEY")
762
+ if not api_key:
763
+ raise ValueError("FINNHUB_API_KEY not set")
764
+ import finnhub
765
+
766
+ client = finnhub.Client(api_key=api_key)
767
+ q = client.quote(symbol.replace(".HK", ""))
768
+ if not q or q.get("c") is None or q["c"] == 0:
769
+ raise ValueError(f"finnhub returned no quote for {symbol}")
770
+ return _clean_row(
771
+ {
772
+ "symbol": symbol,
773
+ "price": q["c"],
774
+ "change": q["d"],
775
+ "change_pct": q["dp"],
776
+ "high": q["h"],
777
+ "low": q["l"],
778
+ "open": q["o"],
779
+ "prev_close": q["pc"],
780
+ }
781
+ )
782
+
783
+
784
+ def quote_yf(symbol: str) -> dict:
785
+ """HK/US quote with failover: yfinance → finnhub → longbridge → alphavantage (US only)."""
786
+ sources = [
787
+ ("yfinance", lambda: _quote_yfinance(symbol)),
788
+ ("finnhub", lambda: _quote_finnhub(symbol)),
789
+ ("longbridge", lambda: _quote_longbridge(symbol)),
790
+ ]
791
+ if detect_market(symbol) == "US":
792
+ sources.append(("alphavantage", lambda: _quote_alphavantage(symbol)))
793
+ return _failover(sources, label=f"quote:{symbol}")
794
+
795
+
796
+ def cmd_quote(args):
797
+ market = detect_market(args.symbol)
798
+ try:
799
+ return quote_a(args.symbol) if market == "A" else quote_yf(args.symbol)
800
+ except Exception as e:
801
+ return {"error": str(e)}
802
+
803
+
804
+ # --------------- capital_flow ---------------
805
+
806
+
807
+ def _capital_flow_efinance(symbol: str) -> list:
808
+ """Fallback: fetch individual stock capital flow via efinance."""
809
+ import efinance as ef
810
+ import pandas as pd
811
+
812
+ df = ef.stock.get_today_bill(symbol)
813
+ if df is None or df.empty:
814
+ raise ValueError("efinance capital flow returned empty")
815
+ col_map = {
816
+ "日期": "date",
817
+ "主力净流入": "main_net_inflow",
818
+ "超大单净流入": "super_large_net",
819
+ "大单净流入": "large_net",
820
+ "中单净流入": "medium_net",
821
+ "小单净流入": "small_net",
822
+ }
823
+ df = df.rename(columns=col_map)
824
+ keep = [c for c in col_map.values() if c in df.columns]
825
+ for c in keep:
826
+ if c != "date":
827
+ df[c] = pd.to_numeric(df[c], errors="coerce")
828
+ df = df[keep].tail(10)
829
+ return [_clean_row(r) for r in df.to_dict("records")]
830
+
831
+
832
+ def cmd_capital_flow(args):
833
+ mode = getattr(args, "mode", "detail")
834
+
835
+ if mode == "sector_flow":
836
+ try:
837
+ import akshare as ak
838
+
839
+ df = _akshare_retry(ak.stock_sector_fund_flow_rank)
840
+ if df is None or df.empty:
841
+ return {"error": "Sector fund flow data unavailable"}
842
+ col_map = {
843
+ "名称": "name",
844
+ "今日涨跌幅": "change_pct",
845
+ "今日主力净流入-净额": "main_net_inflow",
846
+ "今日主力净流入-净占比": "main_pct",
847
+ "今日超大单净流入-净额": "super_large_net",
848
+ "今日大单净流入-净额": "large_net",
849
+ }
850
+ df = df.rename(columns=col_map)
851
+ keep = [c for c in col_map.values() if c in df.columns]
852
+ return [_clean_row(r) for r in df[keep].head(20).to_dict("records")]
853
+ except Exception as e:
854
+ return {"error": str(e)}
855
+
856
+ if detect_market(args.symbol) != "A":
857
+ return {"error": "capital_flow only available for A-shares"}
858
+ try:
859
+ import akshare as ak
860
+
861
+ market = "sh" if args.symbol.startswith("6") else "sz"
862
+ df = _akshare_retry(ak.stock_individual_fund_flow, stock=args.symbol, market=market)
863
+ col_map = {
864
+ "日期": "date",
865
+ "主力净流入-净额": "main_net_inflow",
866
+ "主力净流入-净占比": "main_pct",
867
+ "超大单净流入-净额": "super_large_net",
868
+ "大单净流入-净额": "large_net",
869
+ "中单净流入-净额": "medium_net",
870
+ "小单净流入-净额": "small_net",
871
+ }
872
+ df = df.rename(columns=col_map)
873
+ keep = [c for c in col_map.values() if c in df.columns]
874
+
875
+ if mode == "summary":
876
+ import pandas as pd
877
+
878
+ df_all = df[keep].copy()
879
+ for c in ["main_net_inflow", "super_large_net", "large_net", "medium_net", "small_net"]:
880
+ if c in df_all.columns:
881
+ df_all[c] = pd.to_numeric(df_all[c], errors="coerce")
882
+ summary = {"symbol": args.symbol}
883
+ for days, label in [(5, "5d"), (10, "10d"), (20, "20d")]:
884
+ tail = df_all.tail(days)
885
+ summary[f"main_net_{label}"] = _sanitize(tail.get("main_net_inflow", pd.Series()).sum())
886
+ summary[f"super_large_net_{label}"] = _sanitize(tail.get("super_large_net", pd.Series()).sum())
887
+ recent = df_all["main_net_inflow"].tail(5) if "main_net_inflow" in df_all.columns else pd.Series()
888
+ if len(recent) >= 3:
889
+ pos_count = (recent > 0).sum()
890
+ summary["trend"] = "inflow" if pos_count >= 4 else "outflow" if pos_count <= 1 else "mixed"
891
+ return _clean_row(summary)
892
+
893
+ df = df[keep].tail(10)
894
+ return [_clean_row(r) for r in df.to_dict("records")]
895
+ except Exception:
896
+ try:
897
+ return _capital_flow_efinance(args.symbol)
898
+ except Exception as e2:
899
+ return {"error": str(e2)}
900
+
901
+
902
+ # --------------- news ---------------
903
+
904
+
905
+ def _news_search_intel_fallback(symbol: str) -> list:
906
+ """Fallback: use search_intel to find news when primary sources fail."""
907
+ import subprocess
908
+ from pathlib import Path
909
+
910
+ tools_dir = Path(__file__).parent
911
+ try:
912
+ result = subprocess.run(
913
+ [sys.executable, str(tools_dir / "search_intel.py"), "search", f"{symbol} 最新消息"],
914
+ capture_output=True,
915
+ text=True,
916
+ timeout=30,
917
+ )
918
+ except (subprocess.TimeoutExpired, OSError):
919
+ return []
920
+ if result.returncode != 0 or not result.stdout.strip():
921
+ return []
922
+ try:
923
+ data = json.loads(result.stdout.strip())
924
+ if isinstance(data, list):
925
+ return [
926
+ {"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]
927
+ ]
928
+ return []
929
+ except (json.JSONDecodeError, TypeError):
930
+ return []
931
+
932
+
933
+ def cmd_news(args):
934
+ market = detect_market(args.symbol)
935
+ try:
936
+ if market == "A":
937
+ import akshare as ak
938
+
939
+ df = _akshare_retry(ak.stock_news_em, symbol=args.symbol)
940
+ if df is None or df.empty:
941
+ raise ValueError("akshare news empty")
942
+ col_map = {
943
+ "新闻标题": "title",
944
+ "发布时间": "datetime",
945
+ "新闻来源": "source",
946
+ "新闻链接": "url",
947
+ "新闻内容": "content",
948
+ }
949
+ df = df.rename(columns=col_map)
950
+ keep = [c for c in col_map.values() if c in df.columns]
951
+ cutoff = datetime.now() - timedelta(days=args.days)
952
+ df = df[keep]
953
+ if "datetime" in df.columns:
954
+ import pandas as pd
955
+
956
+ df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
957
+ df = df[df["datetime"] >= cutoff]
958
+ return [_clean_row(r) for r in df.head(20).to_dict("records")]
959
+ else:
960
+ import yfinance as yf
961
+
962
+ t = yf.Ticker(args.symbol)
963
+ news = t.news
964
+ if not news:
965
+ raise ValueError("yfinance news empty")
966
+ results = []
967
+ for item in news[:20]:
968
+ results.append(
969
+ {
970
+ "title": item.get("title", ""),
971
+ "publisher": item.get("publisher", ""),
972
+ "url": item.get("link", ""),
973
+ "published": item.get("providerPublishTime", ""),
974
+ "type": item.get("type", ""),
975
+ }
976
+ )
977
+ return results
978
+ except Exception:
979
+ return _news_search_intel_fallback(args.symbol)
980
+
981
+
982
+ # --------------- financials ---------------
983
+
984
+
985
+ def financials_a(symbol: str) -> dict:
986
+ import akshare as ak
987
+
988
+ try:
989
+ df = _akshare_retry(ak.stock_financial_analysis_indicator, symbol=symbol)
990
+ if df is None or df.empty:
991
+ return {"symbol": symbol, "error": "No financial data"}
992
+ r = df.iloc[0]
993
+ return _clean_row(
994
+ {
995
+ "symbol": symbol,
996
+ "report_date": r.get("日期"),
997
+ "roe": r.get("净资产收益率(%)"),
998
+ "net_profit_margin": r.get("销售净利率(%)"),
999
+ "gross_margin": r.get("销售毛利率(%)"),
1000
+ "debt_ratio": r.get("资产负债率(%)"),
1001
+ "current_ratio": r.get("流动比率"),
1002
+ }
1003
+ )
1004
+ except Exception:
1005
+ return {"symbol": symbol, "note": "Financial data unavailable"}
1006
+
1007
+
1008
+ def financials_yf(symbol: str) -> dict:
1009
+ import yfinance as yf
1010
+
1011
+ t = yf.Ticker(symbol)
1012
+ info = t.info
1013
+ return _clean_row(
1014
+ {
1015
+ "symbol": symbol,
1016
+ "name": info.get("shortName"),
1017
+ "market_cap": info.get("marketCap"),
1018
+ "pe": info.get("trailingPE"),
1019
+ "forward_pe": info.get("forwardPE"),
1020
+ "pb": info.get("priceToBook"),
1021
+ "total_revenue": info.get("totalRevenue"),
1022
+ "net_income": info.get("netIncomeToCommon"),
1023
+ "profit_margin": info.get("profitMargins"),
1024
+ "roe": info.get("returnOnEquity"),
1025
+ "debt_to_equity": info.get("debtToEquity"),
1026
+ "dividend_yield": info.get("dividendYield"),
1027
+ }
1028
+ )
1029
+
1030
+
1031
+ def cmd_financials(args):
1032
+ market = detect_market(args.symbol)
1033
+ try:
1034
+ return financials_a(args.symbol) if market == "A" else financials_yf(args.symbol)
1035
+ except Exception as e:
1036
+ return {"error": str(e)}
1037
+
1038
+
1039
+ # --------------- market_snapshot ---------------
1040
+
1041
+
1042
+ def snapshot_a() -> list:
1043
+ try:
1044
+ return _snapshot_akshare()
1045
+ except Exception:
1046
+ pass
1047
+ try:
1048
+ import efinance as ef
1049
+
1050
+ df = ef.stock.get_realtime_quotes()
1051
+ if df is None or df.empty:
1052
+ raise ValueError("efinance snapshot empty")
1053
+ col_map = {
1054
+ "股票代码": "symbol",
1055
+ "股票名称": "name",
1056
+ "最新价": "price",
1057
+ "涨跌幅": "change_pct",
1058
+ "涨跌额": "change",
1059
+ "成交量": "volume",
1060
+ "成交额": "turnover",
1061
+ "市盈率": "pe",
1062
+ "换手率": "turnover_rate",
1063
+ "最高": "high",
1064
+ "最低": "low",
1065
+ "今开": "open",
1066
+ "昨收": "prev_close",
1067
+ }
1068
+ df = df.rename(columns=col_map)
1069
+ keep = [c for c in col_map.values() if c in df.columns]
1070
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1071
+ except Exception:
1072
+ return [{"error": "A-share snapshot unavailable from all sources"}]
1073
+
1074
+
1075
+ def _snapshot_akshare() -> list:
1076
+ import akshare as ak
1077
+
1078
+ df = _akshare_retry(ak.stock_zh_a_spot_em)
1079
+ col_map = {
1080
+ "代码": "symbol",
1081
+ "名称": "name",
1082
+ "最新价": "price",
1083
+ "涨跌幅": "change_pct",
1084
+ "涨跌额": "change",
1085
+ "成交量": "volume",
1086
+ "成交额": "turnover",
1087
+ "市盈率-动态": "pe",
1088
+ "市净率": "pb",
1089
+ "总市值": "market_cap",
1090
+ "换手率": "turnover_rate",
1091
+ "量比": "volume_ratio",
1092
+ "最高": "high",
1093
+ "最低": "low",
1094
+ "今开": "open",
1095
+ "昨收": "prev_close",
1096
+ "60日涨跌幅": "change_pct_60d",
1097
+ }
1098
+ df = df.rename(columns=col_map)
1099
+ keep = [c for c in col_map.values() if c in df.columns]
1100
+ df = df[keep]
1101
+ return [_clean_row(r) for r in df.to_dict("records")]
1102
+
1103
+
1104
+ def snapshot_hk() -> list:
1105
+ try:
1106
+ import akshare as ak
1107
+
1108
+ df = _akshare_retry(ak.stock_hk_spot_em)
1109
+ col_map = {
1110
+ "代码": "symbol",
1111
+ "名称": "name",
1112
+ "最新价": "price",
1113
+ "涨跌幅": "change_pct",
1114
+ "成交量": "volume",
1115
+ "成交额": "turnover",
1116
+ "市盈率": "pe",
1117
+ "市净率": "pb",
1118
+ "总市值": "market_cap",
1119
+ }
1120
+ df = df.rename(columns=col_map)
1121
+ keep = [c for c in col_map.values() if c in df.columns]
1122
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1123
+ except Exception:
1124
+ return [{"error": "HK snapshot unavailable"}]
1125
+
1126
+
1127
+ def snapshot_us() -> list:
1128
+ try:
1129
+ import akshare as ak
1130
+
1131
+ df = _akshare_retry(ak.stock_us_spot_em)
1132
+ col_map = {
1133
+ "代码": "symbol",
1134
+ "名称": "name",
1135
+ "最新价": "price",
1136
+ "涨跌幅": "change_pct",
1137
+ "成交量": "volume",
1138
+ "成交额": "turnover",
1139
+ "市盈率": "pe",
1140
+ "总市值": "market_cap",
1141
+ }
1142
+ df = df.rename(columns=col_map)
1143
+ keep = [c for c in col_map.values() if c in df.columns]
1144
+ return [_clean_row(r) for r in df[keep].to_dict("records")]
1145
+ except Exception:
1146
+ return [{"error": "US snapshot unavailable"}]
1147
+
1148
+
1149
+ def cmd_market_snapshot(args):
1150
+ try:
1151
+ m = args.market.upper()
1152
+ if m == "A":
1153
+ return snapshot_a()
1154
+ elif m == "HK":
1155
+ return snapshot_hk()
1156
+ elif m == "US":
1157
+ return snapshot_us()
1158
+ return {"error": f"Unknown market: {m}"}
1159
+ except Exception as e:
1160
+ return {"error": str(e)}
1161
+
1162
+
1163
+ # --------------- market_indices ---------------
1164
+
1165
+
1166
+ def cmd_market_indices(args):
1167
+ region = args.region.lower()
1168
+ try:
1169
+ if region == "cn":
1170
+ import akshare as ak
1171
+
1172
+ indices = [
1173
+ ("sh000001", "上证指数"),
1174
+ ("sz399001", "深证成指"),
1175
+ ("sz399006", "创业板指"),
1176
+ ("sh000688", "科创50"),
1177
+ ("sh000300", "沪深300"),
1178
+ ("sh000016", "上证50"),
1179
+ ]
1180
+ results = []
1181
+ df = _akshare_retry(ak.stock_zh_index_spot_em)
1182
+ for code, name in indices:
1183
+ clean_code = code[2:] if code[:2] in ("sh", "sz") else code
1184
+ row = df[df["代码"] == clean_code]
1185
+ if row.empty:
1186
+ row = df[df["代码"] == code]
1187
+ if row.empty:
1188
+ results.append({"code": code, "name": name, "note": "data unavailable"})
1189
+ continue
1190
+ r = row.iloc[0]
1191
+ results.append(
1192
+ _clean_row(
1193
+ {
1194
+ "code": code,
1195
+ "name": r.get("名称", name),
1196
+ "price": r.get("最新价"),
1197
+ "change": r.get("涨跌额"),
1198
+ "change_pct": r.get("涨跌幅"),
1199
+ "volume": r.get("成交量"),
1200
+ "turnover": r.get("成交额"),
1201
+ "high": r.get("最高"),
1202
+ "low": r.get("最低"),
1203
+ "open": r.get("今开"),
1204
+ "prev_close": r.get("昨收"),
1205
+ }
1206
+ )
1207
+ )
1208
+ return results
1209
+ elif region in ("hk", "us"):
1210
+ import yfinance as yf
1211
+
1212
+ if region == "hk":
1213
+ symbols = {"^HSI": "恒生指数", "^HSCE": "恒生国企指数", "^HSTECH": "恒生科技指数"}
1214
+ else:
1215
+ symbols = {"^DJI": "道琼斯", "^IXIC": "纳斯达克", "^GSPC": "标普500", "^RUT": "罗素2000"}
1216
+ results = []
1217
+ for sym, name in symbols.items():
1218
+ try:
1219
+ t = yf.Ticker(sym)
1220
+ info = t.info
1221
+ results.append(
1222
+ _clean_row(
1223
+ {
1224
+ "code": sym,
1225
+ "name": name,
1226
+ "price": info.get("regularMarketPrice"),
1227
+ "change": info.get("regularMarketChange"),
1228
+ "change_pct": info.get("regularMarketChangePercent"),
1229
+ "volume": info.get("regularMarketVolume"),
1230
+ "high": info.get("regularMarketDayHigh"),
1231
+ "low": info.get("regularMarketDayLow"),
1232
+ "open": info.get("regularMarketOpen"),
1233
+ "prev_close": info.get("regularMarketPreviousClose"),
1234
+ }
1235
+ )
1236
+ )
1237
+ except Exception:
1238
+ results.append({"code": sym, "name": name, "note": "data unavailable"})
1239
+ return results
1240
+ return {"error": f"Unknown region: {region}"}
1241
+ except Exception as e:
1242
+ return {"error": str(e)}
1243
+
1244
+
1245
+ # --------------- sector_rankings ---------------
1246
+
1247
+
1248
+ def _sector_rankings_efinance(top: int, direction: str):
1249
+ """Fallback: fetch sector rankings via efinance."""
1250
+ import efinance as ef
1251
+ import pandas as pd
1252
+
1253
+ df = ef.stock.get_realtime_quotes(fs=ef.stock.get_belong_board("行业板块"))
1254
+ if df is None or df.empty:
1255
+ raise ValueError("efinance sector data unavailable")
1256
+ col_map = {
1257
+ "股票名称": "name",
1258
+ "股票代码": "code",
1259
+ "涨跌幅": "change_pct",
1260
+ "成交量": "volume",
1261
+ "成交额": "turnover",
1262
+ }
1263
+ df = df.rename(columns=col_map)
1264
+ keep = [c for c in col_map.values() if c in df.columns]
1265
+ df = df[keep]
1266
+ if "change_pct" in df.columns:
1267
+ df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
1268
+ if direction == "bottom":
1269
+ df = df.sort_values("change_pct", ascending=True).head(top)
1270
+ elif direction == "both":
1271
+ top_df = df.sort_values("change_pct", ascending=False).head(top)
1272
+ bottom_df = df.sort_values("change_pct", ascending=True).head(top)
1273
+ return {
1274
+ "top": [_clean_row(r) for r in top_df.to_dict("records")],
1275
+ "bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
1276
+ }
1277
+ else:
1278
+ df = df.sort_values("change_pct", ascending=False).head(top)
1279
+ return [_clean_row(r) for r in df.to_dict("records")]
1280
+
1281
+
1282
+ def cmd_sector_rankings(args):
1283
+ try:
1284
+ import akshare as ak
1285
+ import pandas as pd
1286
+
1287
+ df = _akshare_retry(ak.stock_board_industry_name_em)
1288
+ if df is None or df.empty:
1289
+ raise ValueError("akshare sector data unavailable")
1290
+ col_map = {
1291
+ "板块名称": "name",
1292
+ "板块代码": "code",
1293
+ "最新价": "price",
1294
+ "涨跌幅": "change_pct",
1295
+ "成交量": "volume",
1296
+ "成交额": "turnover",
1297
+ "换手率": "turnover_rate",
1298
+ "总市值": "market_cap",
1299
+ "上涨家数": "up_count",
1300
+ "下跌家数": "down_count",
1301
+ "领涨股票": "leading_stock",
1302
+ "领涨涨跌幅": "leading_change_pct",
1303
+ }
1304
+ df = df.rename(columns=col_map)
1305
+ keep = [c for c in col_map.values() if c in df.columns]
1306
+ df = df[keep]
1307
+ if "change_pct" in df.columns:
1308
+ df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
1309
+
1310
+ direction = getattr(args, "direction", "top")
1311
+ if direction == "bottom":
1312
+ df = df.sort_values("change_pct", ascending=True).head(args.top)
1313
+ elif direction == "both":
1314
+ top_df = df.sort_values("change_pct", ascending=False).head(args.top)
1315
+ bottom_df = df.sort_values("change_pct", ascending=True).head(args.top)
1316
+ return {
1317
+ "top": [_clean_row(r) for r in top_df.to_dict("records")],
1318
+ "bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
1319
+ }
1320
+ else:
1321
+ df = df.head(args.top)
1322
+ return [_clean_row(r) for r in df.to_dict("records")]
1323
+ except Exception:
1324
+ try:
1325
+ direction = getattr(args, "direction", "top")
1326
+ return _sector_rankings_efinance(args.top, direction)
1327
+ except Exception as e2:
1328
+ return {"error": str(e2)}
1329
+
1330
+
1331
+ # --------------- stock_info ---------------
1332
+
1333
+
1334
+ def cmd_stock_info(args):
1335
+ market = detect_market(args.symbol)
1336
+ try:
1337
+ if market == "A":
1338
+ import akshare as ak
1339
+
1340
+ result = {"symbol": args.symbol, "market": "A"}
1341
+ try:
1342
+ df = _akshare_retry(ak.stock_individual_info_em, symbol=args.symbol)
1343
+ if df is not None and not df.empty:
1344
+ info_map = {}
1345
+ for _, row in df.iterrows():
1346
+ info_map[row.iloc[0]] = row.iloc[1]
1347
+ result["name"] = info_map.get("股票简称")
1348
+ result["industry"] = info_map.get("行业")
1349
+ result["listing_date"] = str(info_map.get("上市时间", ""))
1350
+ result["total_shares"] = info_map.get("总股本")
1351
+ result["float_shares"] = info_map.get("流通股")
1352
+ result["total_market_cap"] = info_map.get("总市值")
1353
+ result["float_market_cap"] = info_map.get("流通市值")
1354
+ except Exception:
1355
+ pass
1356
+ try:
1357
+ board_df = _akshare_retry(ak.stock_board_industry_cons_em, symbol=args.symbol)
1358
+ if board_df is not None and not board_df.empty and "板块名称" in board_df.columns:
1359
+ result["boards"] = board_df["板块名称"].tolist()[:10]
1360
+ except Exception:
1361
+ pass
1362
+ return _clean_row(result)
1363
+ else:
1364
+ import yfinance as yf
1365
+
1366
+ t = yf.Ticker(args.symbol)
1367
+ info = t.info
1368
+ return _clean_row(
1369
+ {
1370
+ "symbol": args.symbol,
1371
+ "market": market,
1372
+ "name": info.get("shortName"),
1373
+ "industry": info.get("industry"),
1374
+ "sector": info.get("sector"),
1375
+ "country": info.get("country"),
1376
+ "exchange": info.get("exchange"),
1377
+ "market_cap": info.get("marketCap"),
1378
+ "employees": info.get("fullTimeEmployees"),
1379
+ "website": info.get("website"),
1380
+ "description": (info.get("longBusinessSummary") or "")[:200],
1381
+ }
1382
+ )
1383
+ except Exception as e:
1384
+ return {"error": str(e)}
1385
+
1386
+
1387
+ # --------------- chip_distribution ---------------
1388
+
1389
+
1390
+ def cmd_chip_distribution(args):
1391
+ if detect_market(args.symbol) != "A":
1392
+ return {"error": "chip_distribution only available for A-shares"}
1393
+ try:
1394
+ import akshare as ak
1395
+
1396
+ df = _akshare_retry(ak.stock_cyq_em, symbol=args.symbol)
1397
+ if df is None or df.empty:
1398
+ return {"symbol": args.symbol, "error": "Chip distribution data unavailable"}
1399
+ latest = df.iloc[-1] if len(df) > 0 else {}
1400
+ col_map = {
1401
+ "日期": "date",
1402
+ "获利比例": "profit_ratio",
1403
+ "平均成本": "avg_cost",
1404
+ "90%成本": "cost_90pct",
1405
+ "90成本-低": "cost_90_low",
1406
+ "90成本-高": "cost_90_high",
1407
+ "70%成本": "cost_70pct",
1408
+ "70成本-低": "cost_70_low",
1409
+ "70成本-高": "cost_70_high",
1410
+ "集中度": "concentration",
1411
+ }
1412
+ result = {"symbol": args.symbol}
1413
+ for cn_col, en_col in col_map.items():
1414
+ val = latest.get(cn_col)
1415
+ if val is not None:
1416
+ result[en_col] = _sanitize(val)
1417
+ if "cost_90_high" in result and "cost_90_low" in result:
1418
+ high, low = result.get("cost_90_high", 0), result.get("cost_90_low", 0)
1419
+ if high and low and (high + low) > 0:
1420
+ result["concentration_90"] = round((high - low) / ((high + low) / 2) * 100, 2)
1421
+ if "cost_70_high" in result and "cost_70_low" in result:
1422
+ h70, l70 = result.get("cost_70_high", 0), result.get("cost_70_low", 0)
1423
+ if h70 and l70 and (h70 + l70) > 0:
1424
+ result["concentration_70"] = round((h70 - l70) / ((h70 + l70) / 2) * 100, 2)
1425
+ return result
1426
+ except Exception as e:
1427
+ return {"error": str(e)}
1428
+
1429
+
1430
+ # --------------- market_stats ---------------
1431
+
1432
+
1433
+ def cmd_market_stats(args):
1434
+ try:
1435
+ import numpy as np
1436
+
1437
+ data = snapshot_a()
1438
+ if isinstance(data, dict) and "error" in data:
1439
+ return data
1440
+ if not data:
1441
+ return {"error": "No market data"}
1442
+
1443
+ changes = []
1444
+ turnovers = []
1445
+ limit_ups = []
1446
+ limit_downs = []
1447
+ up_count = down_count = flat_count = 0
1448
+
1449
+ for s in data:
1450
+ chg = s.get("change_pct")
1451
+ if chg is not None:
1452
+ changes.append(float(chg))
1453
+ if chg > 0:
1454
+ up_count += 1
1455
+ elif chg < 0:
1456
+ down_count += 1
1457
+ else:
1458
+ flat_count += 1
1459
+ t = s.get("turnover")
1460
+ if t is not None:
1461
+ turnovers.append(float(t))
1462
+
1463
+ price = s.get("price")
1464
+ prev = s.get("prev_close")
1465
+ sym = s.get("symbol", "")
1466
+ if price and prev and prev > 0:
1467
+ code_info = normalize_stock_code(sym)
1468
+ lp = code_info.get("limit_pct")
1469
+ if lp:
1470
+ limit_up = calc_limit_price(float(prev), lp, "up")
1471
+ limit_down = calc_limit_price(float(prev), lp, "down")
1472
+ if abs(float(price) - limit_up) < 0.01:
1473
+ limit_ups.append({"symbol": sym, "name": s.get("name"), "change_pct": chg})
1474
+ elif abs(float(price) - limit_down) < 0.01:
1475
+ limit_downs.append({"symbol": sym, "name": s.get("name"), "change_pct": chg})
1476
+
1477
+ changes_arr = np.array(changes) if changes else np.array([0])
1478
+ sorted_data = sorted(data, key=lambda x: x.get("change_pct") or 0, reverse=True)
1479
+
1480
+ return _clean_row(
1481
+ {
1482
+ "total_stocks": len(data),
1483
+ "up_count": up_count,
1484
+ "down_count": down_count,
1485
+ "flat_count": flat_count,
1486
+ "limit_up_count": len(limit_ups),
1487
+ "limit_down_count": len(limit_downs),
1488
+ "avg_change_pct": round(float(changes_arr.mean()), 2),
1489
+ "median_change_pct": round(float(np.median(changes_arr)), 2),
1490
+ "total_turnover": round(sum(turnovers), 0) if turnovers else None,
1491
+ "top5_gainers": [
1492
+ {"symbol": s.get("symbol"), "name": s.get("name"), "change_pct": s.get("change_pct")}
1493
+ for s in sorted_data[:5]
1494
+ ],
1495
+ "top5_losers": [
1496
+ {"symbol": s.get("symbol"), "name": s.get("name"), "change_pct": s.get("change_pct")}
1497
+ for s in sorted_data[-5:]
1498
+ ],
1499
+ "limit_up_samples": limit_ups[:5],
1500
+ "limit_down_samples": limit_downs[:5],
1501
+ }
1502
+ )
1503
+ except Exception as e:
1504
+ return {"error": str(e)}
1505
+
1506
+
1507
+ # --------------- fundamental_context ---------------
1508
+
1509
+
1510
+ def cmd_fundamental_context(args):
1511
+ if detect_market(args.symbol) != "A":
1512
+ return {"error": "fundamental_context only available for A-shares"}
1513
+ try:
1514
+ import akshare as ak
1515
+
1516
+ result = {"symbol": args.symbol}
1517
+
1518
+ try:
1519
+ quote = quote_a(args.symbol)
1520
+ result["valuation"] = {
1521
+ "pe": quote.get("pe"),
1522
+ "pb": quote.get("pb"),
1523
+ "market_cap": quote.get("market_cap"),
1524
+ }
1525
+ except Exception:
1526
+ result["valuation"] = {}
1527
+
1528
+ try:
1529
+ df = _akshare_retry(ak.stock_financial_analysis_indicator, symbol=args.symbol)
1530
+ if df is not None and len(df) >= 1:
1531
+ r0 = df.iloc[0]
1532
+ profitability = {
1533
+ "roe": _sanitize(r0.get("净资产收益率(%)")),
1534
+ "gross_margin": _sanitize(r0.get("销售毛利率(%)")),
1535
+ "net_margin": _sanitize(r0.get("销售净利率(%)")),
1536
+ "report_date": _sanitize(r0.get("日期")),
1537
+ }
1538
+ result["profitability"] = profitability
1539
+
1540
+ if len(df) >= 2:
1541
+ growth = {}
1542
+ for field, key in [("主营业务收入增长率(%)", "revenue_yoy"), ("净利润增长率(%)", "net_income_yoy")]:
1543
+ v0 = r0.get(field)
1544
+ if v0 is not None:
1545
+ growth[key] = _sanitize(v0)
1546
+ result["growth"] = growth
1547
+ except Exception:
1548
+ pass
1549
+
1550
+ try:
1551
+ div_df = _akshare_retry(ak.stock_history_dividend_detail, symbol=args.symbol, indicator="分红")
1552
+ if div_df is not None and not div_df.empty:
1553
+ dividends = []
1554
+ for _, row in div_df.head(5).iterrows():
1555
+ dividends.append(
1556
+ _clean_row(
1557
+ {
1558
+ "year": row.get("报告期"),
1559
+ "plan": row.get("分红方案"),
1560
+ "record_date": row.get("股权登记日"),
1561
+ }
1562
+ )
1563
+ )
1564
+ result["dividends"] = dividends
1565
+ except Exception:
1566
+ pass
1567
+
1568
+ return result
1569
+ except Exception as e:
1570
+ return {"error": str(e)}
1571
+
1572
+
1573
+ # --------------- CLI ---------------
1574
+
1575
+
1576
+ def output(data):
1577
+ print(json.dumps(data, ensure_ascii=False, default=str))
1578
+
1579
+
1580
+ def main():
1581
+ parser = argparse.ArgumentParser(description="Stock data fetcher")
1582
+ sub = parser.add_subparsers(dest="command")
1583
+
1584
+ p_kline = sub.add_parser("kline")
1585
+ p_kline.add_argument("symbol")
1586
+ p_kline.add_argument("--period", default="daily", choices=["daily", "weekly", "monthly"])
1587
+ p_kline.add_argument("--count", type=int, default=60)
1588
+
1589
+ p_quote = sub.add_parser("quote")
1590
+ p_quote.add_argument("symbol")
1591
+
1592
+ p_cf = sub.add_parser("capital_flow")
1593
+ p_cf.add_argument("symbol", nargs="?", default="")
1594
+ p_cf.add_argument("--mode", default="detail", choices=["detail", "summary", "sector_flow"])
1595
+
1596
+ p_news = sub.add_parser("news")
1597
+ p_news.add_argument("symbol")
1598
+ p_news.add_argument("--days", type=int, default=3)
1599
+
1600
+ p_fin = sub.add_parser("financials")
1601
+ p_fin.add_argument("symbol")
1602
+
1603
+ p_snap = sub.add_parser("market_snapshot")
1604
+ p_snap.add_argument("--market", default="A", choices=["A", "HK", "US"])
1605
+
1606
+ p_idx = sub.add_parser("market_indices")
1607
+ p_idx.add_argument("--region", default="cn", choices=["cn", "hk", "us"])
1608
+
1609
+ p_sec = sub.add_parser("sector_rankings")
1610
+ p_sec.add_argument("--top", type=int, default=10)
1611
+ p_sec.add_argument("--direction", default="top", choices=["top", "bottom", "both"])
1612
+
1613
+ p_info = sub.add_parser("stock_info")
1614
+ p_info.add_argument("symbol")
1615
+
1616
+ p_chip = sub.add_parser("chip_distribution")
1617
+ p_chip.add_argument("symbol")
1618
+
1619
+ p_stats = sub.add_parser("market_stats")
1620
+ p_stats.add_argument("--market", default="A", choices=["A"])
1621
+
1622
+ p_fund = sub.add_parser("fundamental_context")
1623
+ p_fund.add_argument("symbol")
1624
+
1625
+ args = parser.parse_args()
1626
+ if not args.command:
1627
+ parser.print_help()
1628
+ sys.exit(1)
1629
+
1630
+ dispatch = {
1631
+ "kline": cmd_kline,
1632
+ "quote": cmd_quote,
1633
+ "capital_flow": cmd_capital_flow,
1634
+ "news": cmd_news,
1635
+ "financials": cmd_financials,
1636
+ "market_snapshot": cmd_market_snapshot,
1637
+ "market_indices": cmd_market_indices,
1638
+ "sector_rankings": cmd_sector_rankings,
1639
+ "stock_info": cmd_stock_info,
1640
+ "chip_distribution": cmd_chip_distribution,
1641
+ "market_stats": cmd_market_stats,
1642
+ "fundamental_context": cmd_fundamental_context,
1643
+ }
1644
+ result = dispatch[args.command](args)
1645
+ output(result)
1646
+
1647
+
1648
+ if __name__ == "__main__":
1649
+ main()