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