stock-analysis-plugin 0.2.2 → 0.2.4
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/LICENSE +21 -0
- package/README.md +33 -11
- package/package.json +5 -5
- package/pi/index.ts +86 -8
- package/scripts/ci-resolve-llm-host.mjs +29 -0
- package/scripts/setup-python.mjs +7 -9
- package/skills/hot-theme/SKILL.md +3 -2
- package/skills/stock-screener/SKILL.md +1 -1
- package/skills/strategy-backtest/SKILL.md +9 -5
- package/strategies/examples/bottom_volume.yaml +5 -0
- package/strategies/examples/box_oscillation.yaml +5 -0
- package/strategies/examples/bull_trend.yaml +11 -3
- package/strategies/examples/dragon_head.yaml +4 -2
- package/strategies/examples/emotion_cycle.yaml +5 -0
- package/strategies/examples/ma_crossover.yaml +10 -3
- package/strategies/examples/rsi_oversold.yaml +5 -0
- package/strategies/examples/shrink_pullback.yaml +7 -1
- package/strategies/examples/volume_breakout.yaml +7 -1
- package/tools/_subproc.py +49 -0
- package/tools/alert_rules.py +19 -9
- package/tools/anomaly_detect.py +24 -35
- package/tools/backtest.py +180 -100
- package/tools/capabilities.py +4 -5
- package/tools/diagnostics.py +6 -6
- package/tools/gather.py +13 -9
- package/tools/import_parser.py +2 -5
- package/tools/market_regime.py +27 -35
- package/tools/market_review.py +56 -9
- package/tools/name_resolver.py +2 -5
- package/tools/pattern.py +2 -5
- package/tools/position_context.py +2 -5
- package/tools/report_renderer.py +10 -6
- package/tools/requirements.txt +2 -1
- package/tools/risk_screening.py +29 -23
- package/tools/screener.py +26 -16
- package/tools/search_intel.py +5 -13
- package/tools/signal_tracker.py +2 -6
- package/tools/stock_data.py +301 -92
- package/tools/technical.py +136 -40
- package/tools/trading_calendar.py +78 -18
- package/tools/volume_analysis.py +2 -5
- package/tools/watchlist.py +2 -5
- package/tools/watchlist_context.py +2 -5
package/tools/stock_data.py
CHANGED
|
@@ -13,7 +13,7 @@ from datetime import datetime, timedelta
|
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
15
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
16
|
-
from _subproc import run_tool # noqa: E402
|
|
16
|
+
from _subproc import run_tool, scrub_secrets, socket_timeout, utf8_stdio # noqa: E402
|
|
17
17
|
|
|
18
18
|
# Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
|
|
19
19
|
# Bare 6-digit codes are always stocks; the prefix is the disambiguation escape
|
|
@@ -40,7 +40,7 @@ def detect_market(symbol: str) -> str:
|
|
|
40
40
|
|
|
41
41
|
def normalize_stock_code(symbol: str) -> dict:
|
|
42
42
|
"""Classify A-share stock code into board/type with limit-up/down ratio."""
|
|
43
|
-
info = {"market": detect_market(symbol), "board": "main", "
|
|
43
|
+
info = {"market": detect_market(symbol), "board": "main", "is_etf": False, "limit_pct": 0.10}
|
|
44
44
|
if info["market"] != "A":
|
|
45
45
|
info["limit_pct"] = None
|
|
46
46
|
return info
|
|
@@ -66,7 +66,7 @@ def normalize_stock_code(symbol: str) -> dict:
|
|
|
66
66
|
|
|
67
67
|
|
|
68
68
|
def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
|
|
69
|
-
"""Calculate limit-up or limit-down price with
|
|
69
|
+
"""Calculate limit-up or limit-down price with exchange rounding (round-half-up: floor(x*100+0.5)/100)."""
|
|
70
70
|
import numpy as np
|
|
71
71
|
|
|
72
72
|
sign = 1 if direction == "up" else -1
|
|
@@ -115,7 +115,7 @@ def _failover(sources: list, label: str):
|
|
|
115
115
|
_disk_cache_set(f"sticky-{chain}", name)
|
|
116
116
|
return result
|
|
117
117
|
except Exception as e:
|
|
118
|
-
errors.append(f"{name}: {type(e).__name__}: {e}")
|
|
118
|
+
errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
|
|
119
119
|
if errors:
|
|
120
120
|
raise RuntimeError(f"{label}: {'; '.join(errors)}")
|
|
121
121
|
return None
|
|
@@ -434,11 +434,11 @@ def _sanitize(obj):
|
|
|
434
434
|
if isinstance(obj, (np.integer,)):
|
|
435
435
|
return int(obj)
|
|
436
436
|
if isinstance(obj, (np.floating,)):
|
|
437
|
-
return
|
|
437
|
+
return round(float(obj), 4) if np.isfinite(obj) else None
|
|
438
438
|
if isinstance(obj, (np.bool_,)):
|
|
439
439
|
return bool(obj)
|
|
440
440
|
if isinstance(obj, float):
|
|
441
|
-
return
|
|
441
|
+
return round(obj, 4) if np.isfinite(obj) else None
|
|
442
442
|
return obj
|
|
443
443
|
|
|
444
444
|
|
|
@@ -470,7 +470,8 @@ def kline_a(symbol: str, period: str, count: int) -> list:
|
|
|
470
470
|
("pytdx", lambda: _kline_pytdx(symbol, period, count)),
|
|
471
471
|
("baostock", lambda: _kline_baostock(symbol, period, count)),
|
|
472
472
|
]
|
|
473
|
-
|
|
473
|
+
with socket_timeout(25):
|
|
474
|
+
return _failover(sources, label=f"kline_a:{symbol}")
|
|
474
475
|
|
|
475
476
|
|
|
476
477
|
def _kline_akshare(symbol: str, period: str, count: int) -> list:
|
|
@@ -984,7 +985,8 @@ def quote_a(symbol: str) -> dict:
|
|
|
984
985
|
(quote_a_etf) so a stock-side winner never demotes the fund-spot source."""
|
|
985
986
|
if _A_PREFIXED_RE.fullmatch(symbol):
|
|
986
987
|
sources = [("tencent", lambda: _quote_tencent(symbol)), ("sina", lambda: _quote_sina(symbol))]
|
|
987
|
-
|
|
988
|
+
with socket_timeout(25):
|
|
989
|
+
return _failover(sources, label=f"quote_a:{symbol}")
|
|
988
990
|
is_etf = normalize_stock_code(symbol)["is_etf"]
|
|
989
991
|
sources = []
|
|
990
992
|
if is_etf:
|
|
@@ -998,11 +1000,18 @@ def quote_a(symbol: str) -> dict:
|
|
|
998
1000
|
("pytdx", lambda: _quote_pytdx(symbol)),
|
|
999
1001
|
]
|
|
1000
1002
|
chain = "quote_a_etf" if is_etf else "quote_a"
|
|
1001
|
-
|
|
1003
|
+
with socket_timeout(25):
|
|
1004
|
+
return _failover(sources, label=f"{chain}:{symbol}")
|
|
1002
1005
|
|
|
1003
1006
|
|
|
1004
1007
|
def _quote_akshare_etf(symbol: str) -> dict:
|
|
1005
|
-
"""A-share ETF realtime quote via akshare fund_etf_spot_em.
|
|
1008
|
+
"""A-share ETF realtime quote via akshare fund_etf_spot_em.
|
|
1009
|
+
|
|
1010
|
+
On top of the stock-shaped fields, the same spot row carries fund-native
|
|
1011
|
+
columns: iopv (盘中实时估值) and fund_shares (最新份额). premium_discount_rate
|
|
1012
|
+
is derived here as (price - iopv) / iopv * 100 — positive = 溢价 (price above
|
|
1013
|
+
IOPV), negative = 折价; None when the fund publishes no intraday IOPV (money/
|
|
1014
|
+
bond ETFs)."""
|
|
1006
1015
|
import akshare as ak
|
|
1007
1016
|
|
|
1008
1017
|
df = _akshare_retry(ak.fund_etf_spot_em)
|
|
@@ -1010,7 +1019,7 @@ def _quote_akshare_etf(symbol: str) -> dict:
|
|
|
1010
1019
|
if row.empty:
|
|
1011
1020
|
raise ValueError(f"ETF {symbol} not found in akshare fund spot")
|
|
1012
1021
|
r = row.iloc[0]
|
|
1013
|
-
|
|
1022
|
+
result = _clean_row(
|
|
1014
1023
|
{
|
|
1015
1024
|
"symbol": symbol,
|
|
1016
1025
|
"name": r.get("名称"),
|
|
@@ -1027,8 +1036,13 @@ def _quote_akshare_etf(symbol: str) -> dict:
|
|
|
1027
1036
|
"turnover_rate": r.get("换手率"),
|
|
1028
1037
|
"volume_ratio": r.get("量比"),
|
|
1029
1038
|
"is_etf": True,
|
|
1039
|
+
"iopv": r.get("IOPV实时估值"),
|
|
1040
|
+
"fund_shares": r.get("最新份额"),
|
|
1030
1041
|
}
|
|
1031
1042
|
)
|
|
1043
|
+
price, iopv = result.get("price"), result.get("iopv")
|
|
1044
|
+
result["premium_discount_rate"] = round((price - iopv) / iopv * 100, 4) if price is not None and iopv else None
|
|
1045
|
+
return result
|
|
1032
1046
|
|
|
1033
1047
|
|
|
1034
1048
|
def _quote_akshare(symbol: str) -> dict:
|
|
@@ -1228,8 +1242,12 @@ def cmd_capital_flow(args):
|
|
|
1228
1242
|
try:
|
|
1229
1243
|
import akshare as ak
|
|
1230
1244
|
|
|
1231
|
-
|
|
1232
|
-
|
|
1245
|
+
# Exchange via the shared prefix helper: bare 9/5-prefix SH codes, BSE
|
|
1246
|
+
# (43/81-83/87/88/92) and explicitly-prefixed input (sh600519) all resolve;
|
|
1247
|
+
# akshare wants the bare 6-digit stock plus market ∈ {sh, sz, bj}.
|
|
1248
|
+
code = _cn_code(args.symbol)
|
|
1249
|
+
market, stock = code[:2], code[2:]
|
|
1250
|
+
df = _akshare_retry(ak.stock_individual_fund_flow, stock=stock, market=market)
|
|
1233
1251
|
col_map = {
|
|
1234
1252
|
"日期": "date",
|
|
1235
1253
|
"主力净流入-净额": "main_net_inflow",
|
|
@@ -1332,35 +1350,62 @@ def cmd_news(args):
|
|
|
1332
1350
|
# --------------- financials ---------------
|
|
1333
1351
|
|
|
1334
1352
|
|
|
1335
|
-
def
|
|
1353
|
+
def _financials_a_row(r) -> dict:
|
|
1354
|
+
return _clean_row(
|
|
1355
|
+
{
|
|
1356
|
+
"report_date": r.get("日期"),
|
|
1357
|
+
"roe": r.get("净资产收益率(%)"),
|
|
1358
|
+
"net_profit_margin": r.get("销售净利率(%)"),
|
|
1359
|
+
"gross_margin": r.get("销售毛利率(%)"),
|
|
1360
|
+
"debt_ratio": r.get("资产负债率(%)"),
|
|
1361
|
+
"current_ratio": r.get("流动比率"),
|
|
1362
|
+
}
|
|
1363
|
+
)
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
def financials_a(symbol: str, periods: int = 1) -> dict:
|
|
1336
1367
|
import akshare as ak
|
|
1337
1368
|
|
|
1338
1369
|
try:
|
|
1339
1370
|
df = _akshare_retry(ak.stock_financial_analysis_indicator, symbol=symbol)
|
|
1340
1371
|
if df is None or df.empty:
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
"roe": r.get("净资产收益率(%)"),
|
|
1348
|
-
"net_profit_margin": r.get("销售净利率(%)"),
|
|
1349
|
-
"gross_margin": r.get("销售毛利率(%)"),
|
|
1350
|
-
"debt_ratio": r.get("资产负债率(%)"),
|
|
1351
|
-
"current_ratio": r.get("流动比率"),
|
|
1352
|
-
}
|
|
1353
|
-
)
|
|
1372
|
+
# error + note coexist (additive): consumers check either key
|
|
1373
|
+
return {"symbol": symbol, "error": "No financial data", "note": "No financial data"}
|
|
1374
|
+
result = {"symbol": symbol, **_financials_a_row(df.iloc[0])}
|
|
1375
|
+
if periods > 1:
|
|
1376
|
+
result["periods"] = [_financials_a_row(r) for r in df.head(periods).to_dict("records")]
|
|
1377
|
+
return result
|
|
1354
1378
|
except Exception:
|
|
1355
|
-
return {"symbol": symbol, "note": "Financial data unavailable"}
|
|
1379
|
+
return {"symbol": symbol, "error": "Financial data unavailable", "note": "Financial data unavailable"}
|
|
1356
1380
|
|
|
1357
1381
|
|
|
1358
|
-
def
|
|
1382
|
+
def _yf_financial_periods(t, periods: int) -> list:
|
|
1383
|
+
"""Best-effort annual history from yfinance's income statement (t.info is a
|
|
1384
|
+
snapshot only). Silent [] on any failure — multi-period is a bonus, never a blocker."""
|
|
1385
|
+
try:
|
|
1386
|
+
fin = t.financials
|
|
1387
|
+
if fin is None or fin.empty:
|
|
1388
|
+
return []
|
|
1389
|
+
return [
|
|
1390
|
+
_clean_row(
|
|
1391
|
+
{
|
|
1392
|
+
"period_end": col,
|
|
1393
|
+
"total_revenue": fin[col].get("Total Revenue"),
|
|
1394
|
+
"net_income": fin[col].get("Net Income"),
|
|
1395
|
+
}
|
|
1396
|
+
)
|
|
1397
|
+
for col in list(fin.columns)[:periods]
|
|
1398
|
+
]
|
|
1399
|
+
except Exception:
|
|
1400
|
+
return []
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
def financials_yf(symbol: str, periods: int = 1) -> dict:
|
|
1359
1404
|
import yfinance as yf
|
|
1360
1405
|
|
|
1361
1406
|
t = yf.Ticker(_yf_hk_symbol(symbol))
|
|
1362
1407
|
info = t.info
|
|
1363
|
-
|
|
1408
|
+
result = _clean_row(
|
|
1364
1409
|
{
|
|
1365
1410
|
"symbol": symbol,
|
|
1366
1411
|
"name": info.get("shortName"),
|
|
@@ -1376,12 +1421,20 @@ def financials_yf(symbol: str) -> dict:
|
|
|
1376
1421
|
"dividend_yield": info.get("dividendYield"),
|
|
1377
1422
|
}
|
|
1378
1423
|
)
|
|
1424
|
+
if periods > 1:
|
|
1425
|
+
history = _yf_financial_periods(t, periods)
|
|
1426
|
+
if history:
|
|
1427
|
+
result["periods"] = history
|
|
1428
|
+
return result
|
|
1379
1429
|
|
|
1380
1430
|
|
|
1381
1431
|
def cmd_financials(args):
|
|
1432
|
+
periods = getattr(args, "periods", 1)
|
|
1433
|
+
if periods < 1:
|
|
1434
|
+
return {"error": f"periods must be a positive integer, got {periods}"}
|
|
1382
1435
|
market = detect_market(args.symbol)
|
|
1383
1436
|
try:
|
|
1384
|
-
return financials_a(args.symbol) if market == "A" else financials_yf(args.symbol)
|
|
1437
|
+
return financials_a(args.symbol, periods) if market == "A" else financials_yf(args.symbol, periods)
|
|
1385
1438
|
except Exception as e:
|
|
1386
1439
|
return {"error": str(e)}
|
|
1387
1440
|
|
|
@@ -1390,29 +1443,21 @@ def cmd_financials(args):
|
|
|
1390
1443
|
|
|
1391
1444
|
|
|
1392
1445
|
def snapshot_a() -> list:
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
# akshare/efinance leave requests timeout-less — on a blackholed network a leg
|
|
1396
|
-
# hangs until the kernel TCP timeout (~2min), and the chain would overrun the
|
|
1397
|
-
# caller's subprocess budget before ever reaching the tencent leg. Bound each
|
|
1398
|
-
# blocking socket op for the chain's duration (explicit per-request timeouts,
|
|
1399
|
-
# like the tencent leg's, still win).
|
|
1400
|
-
old_timeout = socket.getdefaulttimeout()
|
|
1401
|
-
socket.setdefaulttimeout(25)
|
|
1446
|
+
# akshare/efinance leave requests timeout-less — the chain-wide socket bound
|
|
1447
|
+
# (socket_timeout) is what lets the tencent leg get its turn on a dead network.
|
|
1402
1448
|
try:
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1449
|
+
with socket_timeout(25):
|
|
1450
|
+
return _failover(
|
|
1451
|
+
[
|
|
1452
|
+
("akshare", _snapshot_akshare),
|
|
1453
|
+
("efinance", _snapshot_efinance),
|
|
1454
|
+
("sina", _snapshot_sina),
|
|
1455
|
+
("tencent", _snapshot_tencent),
|
|
1456
|
+
],
|
|
1457
|
+
label="snapshot_a",
|
|
1458
|
+
)
|
|
1412
1459
|
except Exception as e:
|
|
1413
1460
|
return [{"error": f"A-share snapshot unavailable from all sources: {e}"}]
|
|
1414
|
-
finally:
|
|
1415
|
-
socket.setdefaulttimeout(old_timeout)
|
|
1416
1461
|
|
|
1417
1462
|
|
|
1418
1463
|
def _snapshot_efinance() -> list:
|
|
@@ -1573,8 +1618,9 @@ def snapshot_hk() -> list:
|
|
|
1573
1618
|
df = df.rename(columns=col_map)
|
|
1574
1619
|
keep = [c for c in col_map.values() if c in df.columns]
|
|
1575
1620
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1576
|
-
except Exception:
|
|
1577
|
-
|
|
1621
|
+
except Exception as e:
|
|
1622
|
+
# summary only (type + short message) — never a stack trace or response body
|
|
1623
|
+
return [{"error": f"HK snapshot unavailable: {type(e).__name__}: {scrub_secrets(str(e))}"[:200]}]
|
|
1578
1624
|
|
|
1579
1625
|
|
|
1580
1626
|
def snapshot_us() -> list:
|
|
@@ -1595,8 +1641,8 @@ def snapshot_us() -> list:
|
|
|
1595
1641
|
df = df.rename(columns=col_map)
|
|
1596
1642
|
keep = [c for c in col_map.values() if c in df.columns]
|
|
1597
1643
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1598
|
-
except Exception:
|
|
1599
|
-
return [{"error": "US snapshot unavailable"}]
|
|
1644
|
+
except Exception as e:
|
|
1645
|
+
return [{"error": f"US snapshot unavailable: {type(e).__name__}: {scrub_secrets(str(e))}"[:200]}]
|
|
1600
1646
|
|
|
1601
1647
|
|
|
1602
1648
|
def cmd_market_snapshot(args):
|
|
@@ -2220,29 +2266,22 @@ def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
|
|
|
2220
2266
|
except _DataMiss as e:
|
|
2221
2267
|
# per-symbol miss (provider answered but doesn't cover this code) —
|
|
2222
2268
|
# not an outage: never poison the leg for every other symbol
|
|
2223
|
-
errors.append(f"{name}: {type(e).__name__}: {e}")
|
|
2269
|
+
errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
|
|
2224
2270
|
except Exception as e:
|
|
2225
|
-
errors.append(f"{name}: {type(e).__name__}: {e}")
|
|
2271
|
+
errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
|
|
2226
2272
|
if negative_cache and not offline_em:
|
|
2227
2273
|
_disk_cache_set(f"resolve-down-{name}", time.time())
|
|
2228
2274
|
|
|
2229
2275
|
if market == "A":
|
|
2230
2276
|
# akshare/efinance leave requests timeout-less — on a blackholed network a leg
|
|
2231
|
-
# hangs until the kernel TCP timeout
|
|
2232
|
-
#
|
|
2233
|
-
|
|
2234
|
-
import socket
|
|
2235
|
-
|
|
2236
|
-
old_timeout = socket.getdefaulttimeout()
|
|
2237
|
-
socket.setdefaulttimeout(25)
|
|
2238
|
-
try:
|
|
2277
|
+
# hangs until the kernel TCP timeout; the chain-wide socket bound
|
|
2278
|
+
# (socket_timeout) gives every leg its turn within the caller's budget.
|
|
2279
|
+
with socket_timeout(25):
|
|
2239
2280
|
run_legs(sources, negative_cache=True)
|
|
2240
2281
|
# cninfo last: the token-free non-eastmoney active fallback (issue #35),
|
|
2241
2282
|
# tried only when everything above yielded nothing
|
|
2242
2283
|
if not sectors:
|
|
2243
2284
|
run_legs([("cninfo", lambda: _stock_boards_cninfo(symbol))], negative_cache=True)
|
|
2244
|
-
finally:
|
|
2245
|
-
socket.setdefaulttimeout(old_timeout)
|
|
2246
2285
|
else:
|
|
2247
2286
|
run_legs(sources, negative_cache=False)
|
|
2248
2287
|
seen = set()
|
|
@@ -2273,6 +2312,9 @@ def cmd_stock_info(args):
|
|
|
2273
2312
|
import akshare as ak
|
|
2274
2313
|
|
|
2275
2314
|
result = {"symbol": args.symbol, "market": "A"}
|
|
2315
|
+
is_etf = normalize_stock_code(args.symbol)["is_etf"]
|
|
2316
|
+
if is_etf:
|
|
2317
|
+
result["is_etf"] = True
|
|
2276
2318
|
info_map = None
|
|
2277
2319
|
try:
|
|
2278
2320
|
df = _akshare_retry(ak.stock_individual_info_em, symbol=args.symbol)
|
|
@@ -2297,6 +2339,26 @@ def cmd_stock_info(args):
|
|
|
2297
2339
|
result["boards"] = boards[:10]
|
|
2298
2340
|
except Exception:
|
|
2299
2341
|
pass
|
|
2342
|
+
if is_etf:
|
|
2343
|
+
try:
|
|
2344
|
+
# ETF 最新净值(天天基金-场内基金历史净值明细)。窄日期窗口 → 单页返回
|
|
2345
|
+
end = datetime.now()
|
|
2346
|
+
start = end - timedelta(days=30)
|
|
2347
|
+
nav_df = _akshare_retry(
|
|
2348
|
+
ak.fund_etf_fund_info_em,
|
|
2349
|
+
fund=args.symbol,
|
|
2350
|
+
start_date=start.strftime("%Y%m%d"),
|
|
2351
|
+
end_date=end.strftime("%Y%m%d"),
|
|
2352
|
+
)
|
|
2353
|
+
if nav_df is not None and not nav_df.empty:
|
|
2354
|
+
latest = nav_df.iloc[-1]
|
|
2355
|
+
result["nav"] = latest.get("单位净值")
|
|
2356
|
+
result["accumulated_nav"] = latest.get("累计净值")
|
|
2357
|
+
nav_date = latest.get("净值日期")
|
|
2358
|
+
if nav_date is not None:
|
|
2359
|
+
result["nav_date"] = str(nav_date)[:10] # datetime.date/Timestamp → ISO date
|
|
2360
|
+
except Exception:
|
|
2361
|
+
pass
|
|
2300
2362
|
return _clean_row(result)
|
|
2301
2363
|
else:
|
|
2302
2364
|
import yfinance as yf
|
|
@@ -2744,24 +2806,6 @@ def _hot_stocks_em() -> list:
|
|
|
2744
2806
|
return [_strip_exchange_prefix(_clean_row(r)) for r in df[keep].to_dict("records")]
|
|
2745
2807
|
|
|
2746
2808
|
|
|
2747
|
-
def _hot_stocks_xq() -> list:
|
|
2748
|
-
"""Xueqiu follow ranking via akshare stock_hot_follow_xq. No 涨跌幅 column;
|
|
2749
|
-
rank is the row position. Codes arrive SH/SZ-prefixed like eastmoney's."""
|
|
2750
|
-
import akshare as ak
|
|
2751
|
-
|
|
2752
|
-
df = _akshare_retry(ak.stock_hot_follow_xq, symbol="最热门")
|
|
2753
|
-
if df is None or df.empty:
|
|
2754
|
-
return []
|
|
2755
|
-
col_map = {
|
|
2756
|
-
"股票代码": "code",
|
|
2757
|
-
"股票简称": "name",
|
|
2758
|
-
"最新价": "price",
|
|
2759
|
-
}
|
|
2760
|
-
df = df.rename(columns=col_map)
|
|
2761
|
-
keep = [c for c in col_map.values() if c in df.columns]
|
|
2762
|
-
return [{"rank": i, **_strip_exchange_prefix(_clean_row(r))} for i, r in enumerate(df[keep].to_dict("records"), 1)]
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
2809
|
def _hot_stocks_baidu() -> list:
|
|
2766
2810
|
"""Baidu 股市通热搜 via akshare stock_hot_search_baidu. No code/price columns —
|
|
2767
2811
|
only the stock name — and 涨跌幅 strings carry a % suffix."""
|
|
@@ -2783,10 +2827,13 @@ def _hot_stocks_baidu() -> list:
|
|
|
2783
2827
|
|
|
2784
2828
|
|
|
2785
2829
|
def cmd_hot_stocks(args):
|
|
2786
|
-
"""A-share popularity ranking (人气榜): eastmoney →
|
|
2830
|
+
"""A-share popularity ranking (人气榜): eastmoney → baidu.
|
|
2831
|
+
|
|
2832
|
+
The xueqiu leg was dropped: akshare's stock_hot_follow_xq accepts no user token
|
|
2833
|
+
and its built-in xq_a_token is stale (xueqiu answers 400016), so the leg could
|
|
2834
|
+
never win — failover errors now name only the sources that actually ran."""
|
|
2787
2835
|
sources = [
|
|
2788
2836
|
_sourced("eastmoney", _hot_stocks_em),
|
|
2789
|
-
_sourced("xueqiu", _hot_stocks_xq),
|
|
2790
2837
|
_sourced("baidu", _hot_stocks_baidu),
|
|
2791
2838
|
]
|
|
2792
2839
|
try:
|
|
@@ -2799,6 +2846,162 @@ def cmd_hot_stocks(args):
|
|
|
2799
2846
|
return {"count": len(items), "items": items, "source": rows[0]["source"]}
|
|
2800
2847
|
|
|
2801
2848
|
|
|
2849
|
+
# --------------- margin_trading / northbound_flow (A-share only) ---------------
|
|
2850
|
+
|
|
2851
|
+
# Exchange margin-detail column layouts differ: SSE carries 融资偿还额/融券偿还量,
|
|
2852
|
+
# SZSE carries 融券余额/融资融券余额 — the output keys below follow the source.
|
|
2853
|
+
_MARGIN_DETAIL_SSE_COLS = {
|
|
2854
|
+
"标的证券代码": "symbol",
|
|
2855
|
+
"标的证券简称": "name",
|
|
2856
|
+
"融资余额": "margin_balance",
|
|
2857
|
+
"融资买入额": "margin_buy",
|
|
2858
|
+
"融资偿还额": "margin_repay",
|
|
2859
|
+
"融券余量": "short_balance_shares",
|
|
2860
|
+
"融券卖出量": "short_sell_shares",
|
|
2861
|
+
"融券偿还量": "short_repay_shares",
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
_MARGIN_DETAIL_SZSE_COLS = {
|
|
2865
|
+
"证券代码": "symbol",
|
|
2866
|
+
"证券简称": "name",
|
|
2867
|
+
"融资买入额": "margin_buy",
|
|
2868
|
+
"融资余额": "margin_balance",
|
|
2869
|
+
"融券卖出量": "short_sell_shares",
|
|
2870
|
+
"融券余量": "short_balance_shares",
|
|
2871
|
+
"融券余额": "short_balance",
|
|
2872
|
+
"融资融券余额": "total_balance",
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
|
|
2876
|
+
def cmd_margin_trading(args):
|
|
2877
|
+
"""Per-stock margin trading detail (融资融券) for the last N trading days.
|
|
2878
|
+
|
|
2879
|
+
akshare has no per-stock margin history endpoint — the exchange detail lists
|
|
2880
|
+
(stock_margin_detail_sse / stock_margin_detail_szse) are per-day, all-stock
|
|
2881
|
+
tables, so each trading day is fetched and filtered to the symbol. Daily fetches
|
|
2882
|
+
are independent and run concurrently (5 workers; a serial 60-day run would
|
|
2883
|
+
overrun the host's 120s subprocess budget), then re-sorted newest-first — the
|
|
2884
|
+
output never depends on completion order. A day that fails or has no data is
|
|
2885
|
+
skipped (两融明细 T 日晚间才发布 — a morning run always misses the latest day);
|
|
2886
|
+
only when every day failed is an error returned. Days where the symbol is
|
|
2887
|
+
absent (non-margin underlying that day) are skipped; if no day yields a row the
|
|
2888
|
+
symbol is reported as not covered."""
|
|
2889
|
+
if detect_market(args.symbol) != "A":
|
|
2890
|
+
return {"error": "margin_trading only available for A-shares"}
|
|
2891
|
+
days = getattr(args, "days", 10)
|
|
2892
|
+
if days < 1:
|
|
2893
|
+
return {"error": f"days must be a positive integer, got {days}"}
|
|
2894
|
+
# One akshare call per day — cap the fan-out so a slow source can't overrun
|
|
2895
|
+
# the host's subprocess budget (rows carry their dates; truncation is evident).
|
|
2896
|
+
days = min(days, 60)
|
|
2897
|
+
code = _cn_code(args.symbol)
|
|
2898
|
+
exchange, bare = code[:2], code[2:]
|
|
2899
|
+
try:
|
|
2900
|
+
import concurrent.futures
|
|
2901
|
+
|
|
2902
|
+
import akshare as ak
|
|
2903
|
+
from trading_calendar import prev_trading_days
|
|
2904
|
+
|
|
2905
|
+
if exchange == "sh":
|
|
2906
|
+
col_map = _MARGIN_DETAIL_SSE_COLS
|
|
2907
|
+
detail_fn = ak.stock_margin_detail_sse
|
|
2908
|
+
elif exchange == "sz":
|
|
2909
|
+
col_map = _MARGIN_DETAIL_SZSE_COLS
|
|
2910
|
+
detail_fn = ak.stock_margin_detail_szse
|
|
2911
|
+
else:
|
|
2912
|
+
return {"error": f"margin_trading: {args.symbol} is a BSE code; only SSE/SZSE margin detail is available"}
|
|
2913
|
+
trade_days = prev_trading_days("CN", days)
|
|
2914
|
+
if not trade_days:
|
|
2915
|
+
return {"error": "margin_trading: trading calendar unavailable"}
|
|
2916
|
+
|
|
2917
|
+
def fetch_day(date_iso):
|
|
2918
|
+
"""Fetch + filter one day's all-stock table, fault-isolated per day."""
|
|
2919
|
+
try:
|
|
2920
|
+
df = _akshare_retry(detail_fn, date=date_iso.replace("-", ""))
|
|
2921
|
+
except Exception as e:
|
|
2922
|
+
return date_iso, [], f"{date_iso}: {type(e).__name__}: {scrub_secrets(str(e))}"
|
|
2923
|
+
if df is None or df.empty:
|
|
2924
|
+
return date_iso, [], None
|
|
2925
|
+
df = df.rename(columns=col_map)
|
|
2926
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2927
|
+
hit = df[df["symbol"].astype(str) == bare] if "symbol" in df.columns else df.iloc[0:0]
|
|
2928
|
+
return date_iso, [{"date": date_iso, **_clean_row(r)} for r in hit[keep].to_dict("records")], None
|
|
2929
|
+
|
|
2930
|
+
rows = []
|
|
2931
|
+
failures = []
|
|
2932
|
+
with socket_timeout(25), concurrent.futures.ThreadPoolExecutor(max_workers=5) as pool:
|
|
2933
|
+
for _date_iso, day_rows, failure in pool.map(fetch_day, trade_days):
|
|
2934
|
+
if failure:
|
|
2935
|
+
failures.append(failure)
|
|
2936
|
+
rows.extend(day_rows)
|
|
2937
|
+
rows.sort(key=lambda r: r["date"], reverse=True)
|
|
2938
|
+
if not rows:
|
|
2939
|
+
if failures:
|
|
2940
|
+
msg = f"margin detail fetch failed for all {len(trade_days)} day(s): {'; '.join(failures)}"
|
|
2941
|
+
return {"symbol": args.symbol, "error": msg}
|
|
2942
|
+
return {"symbol": args.symbol, "error": f"no margin trading data for {args.symbol} (可能不是两融标的)"}
|
|
2943
|
+
return rows
|
|
2944
|
+
except Exception as e:
|
|
2945
|
+
return {"error": str(e)}
|
|
2946
|
+
|
|
2947
|
+
|
|
2948
|
+
def _northbound_row_is_shell(row: dict) -> bool:
|
|
2949
|
+
"""停披期空壳行:date 之外每个数据字段都是 None。持股市值在停披后被回填 0.0
|
|
2950
|
+
(北向持仓市值约 1.9 万亿,0 是缺失哨兵而非真实值),视同 None。"""
|
|
2951
|
+
for k, v in row.items():
|
|
2952
|
+
if k == "date" or v is None:
|
|
2953
|
+
continue
|
|
2954
|
+
if k == "hold_market_cap" and not v:
|
|
2955
|
+
continue
|
|
2956
|
+
return False
|
|
2957
|
+
return True
|
|
2958
|
+
|
|
2959
|
+
|
|
2960
|
+
def cmd_northbound_flow(args):
|
|
2961
|
+
"""Market-level northbound (北向资金) flow history via eastmoney hsgt history.
|
|
2962
|
+
|
|
2963
|
+
Data caliber: the exchanges stopped publishing daily northbound net-buy after
|
|
2964
|
+
2024-08-16 — later rows are shells (date only, flow fields all None,
|
|
2965
|
+
持股市值 backfilled 0.0) except quarter-end rows, which still disclose
|
|
2966
|
+
持股市值. Shell rows are filtered out of the tail(days) window; when nothing
|
|
2967
|
+
real remains, a clean error explains the disclosure stop (increase days to
|
|
2968
|
+
reach pre-2024-08 history). The series comes back ascending — returned
|
|
2969
|
+
newest-first."""
|
|
2970
|
+
days = getattr(args, "days", 10)
|
|
2971
|
+
if days < 1:
|
|
2972
|
+
return {"error": f"days must be a positive integer, got {days}"}
|
|
2973
|
+
try:
|
|
2974
|
+
import akshare as ak
|
|
2975
|
+
|
|
2976
|
+
with socket_timeout(25):
|
|
2977
|
+
df = _akshare_retry(ak.stock_hsgt_hist_em, symbol="北向资金")
|
|
2978
|
+
if df is None or df.empty:
|
|
2979
|
+
return {"error": "northbound flow data unavailable"}
|
|
2980
|
+
col_map = {
|
|
2981
|
+
"日期": "date",
|
|
2982
|
+
"当日成交净买额": "net_buy",
|
|
2983
|
+
"买入成交额": "buy_turnover",
|
|
2984
|
+
"卖出成交额": "sell_turnover",
|
|
2985
|
+
"历史累计净买额": "accum_net_buy",
|
|
2986
|
+
"持股市值": "hold_market_cap",
|
|
2987
|
+
}
|
|
2988
|
+
df = df.rename(columns=col_map)
|
|
2989
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2990
|
+
rows = [_clean_row(r) for r in df[keep].tail(days).to_dict("records")]
|
|
2991
|
+
rows = [r for r in rows if not _northbound_row_is_shell(r)]
|
|
2992
|
+
if not rows:
|
|
2993
|
+
return {
|
|
2994
|
+
"error": (
|
|
2995
|
+
"北向资金日度净买额自 2024-08-16 起交易所停止披露,仅此前历史数据可用"
|
|
2996
|
+
f"(当前 days={days} 窗口内无有效数据,加大 days 可取历史)"
|
|
2997
|
+
)
|
|
2998
|
+
}
|
|
2999
|
+
rows.reverse()
|
|
3000
|
+
return rows
|
|
3001
|
+
except Exception as e:
|
|
3002
|
+
return {"error": str(e)}
|
|
3003
|
+
|
|
3004
|
+
|
|
2802
3005
|
# --------------- CLI ---------------
|
|
2803
3006
|
|
|
2804
3007
|
|
|
@@ -2828,6 +3031,7 @@ def main():
|
|
|
2828
3031
|
|
|
2829
3032
|
p_fin = sub.add_parser("financials")
|
|
2830
3033
|
p_fin.add_argument("symbol")
|
|
3034
|
+
p_fin.add_argument("--periods", type=int, default=1)
|
|
2831
3035
|
|
|
2832
3036
|
p_snap = sub.add_parser("market_snapshot")
|
|
2833
3037
|
p_snap.add_argument("--market", default="A", choices=["A", "HK", "US"])
|
|
@@ -2869,6 +3073,13 @@ def main():
|
|
|
2869
3073
|
p_hot = sub.add_parser("hot_stocks")
|
|
2870
3074
|
p_hot.add_argument("--top", type=int, default=20)
|
|
2871
3075
|
|
|
3076
|
+
p_margin = sub.add_parser("margin_trading")
|
|
3077
|
+
p_margin.add_argument("symbol")
|
|
3078
|
+
p_margin.add_argument("--days", type=int, default=10)
|
|
3079
|
+
|
|
3080
|
+
p_nb = sub.add_parser("northbound_flow")
|
|
3081
|
+
p_nb.add_argument("--days", type=int, default=10)
|
|
3082
|
+
|
|
2872
3083
|
args = parser.parse_args()
|
|
2873
3084
|
if not args.command:
|
|
2874
3085
|
parser.print_help()
|
|
@@ -2892,6 +3103,8 @@ def main():
|
|
|
2892
3103
|
"limit_up_pool": cmd_limit_up_pool,
|
|
2893
3104
|
"dragon_tiger": cmd_dragon_tiger,
|
|
2894
3105
|
"hot_stocks": cmd_hot_stocks,
|
|
3106
|
+
"margin_trading": cmd_margin_trading,
|
|
3107
|
+
"northbound_flow": cmd_northbound_flow,
|
|
2895
3108
|
}
|
|
2896
3109
|
# Provider libraries (baostock etc.) print prose to stdout on failure,
|
|
2897
3110
|
# which would corrupt the JSON-only contract — divert that noise to stderr.
|
|
@@ -2901,9 +3114,5 @@ def main():
|
|
|
2901
3114
|
|
|
2902
3115
|
|
|
2903
3116
|
if __name__ == "__main__":
|
|
2904
|
-
|
|
2905
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
2906
|
-
for _s in (sys.stdout, sys.stderr):
|
|
2907
|
-
if hasattr(_s, "reconfigure"):
|
|
2908
|
-
_s.reconfigure(encoding="utf-8")
|
|
3117
|
+
utf8_stdio()
|
|
2909
3118
|
main()
|