stock-analysis-plugin 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -11
  3. package/package.json +5 -5
  4. package/pi/index.ts +86 -8
  5. package/scripts/ci-resolve-llm-host.mjs +29 -0
  6. package/scripts/setup-python.mjs +7 -9
  7. package/skills/hot-theme/SKILL.md +3 -2
  8. package/skills/stock-screener/SKILL.md +1 -1
  9. package/skills/strategy-backtest/SKILL.md +9 -5
  10. package/strategies/examples/bottom_volume.yaml +5 -0
  11. package/strategies/examples/box_oscillation.yaml +5 -0
  12. package/strategies/examples/bull_trend.yaml +11 -3
  13. package/strategies/examples/dragon_head.yaml +4 -2
  14. package/strategies/examples/emotion_cycle.yaml +5 -0
  15. package/strategies/examples/ma_crossover.yaml +10 -3
  16. package/strategies/examples/rsi_oversold.yaml +5 -0
  17. package/strategies/examples/shrink_pullback.yaml +7 -1
  18. package/strategies/examples/volume_breakout.yaml +7 -1
  19. package/tools/_subproc.py +49 -0
  20. package/tools/alert_rules.py +19 -9
  21. package/tools/anomaly_detect.py +24 -35
  22. package/tools/backtest.py +180 -100
  23. package/tools/capabilities.py +4 -5
  24. package/tools/diagnostics.py +6 -6
  25. package/tools/gather.py +13 -9
  26. package/tools/import_parser.py +2 -5
  27. package/tools/market_regime.py +27 -35
  28. package/tools/market_review.py +56 -9
  29. package/tools/name_resolver.py +2 -5
  30. package/tools/pattern.py +2 -5
  31. package/tools/position_context.py +2 -5
  32. package/tools/report_renderer.py +10 -6
  33. package/tools/requirements.txt +2 -1
  34. package/tools/risk_screening.py +29 -23
  35. package/tools/screener.py +26 -16
  36. package/tools/search_intel.py +5 -13
  37. package/tools/signal_tracker.py +2 -6
  38. package/tools/stock_data.py +393 -100
  39. package/tools/technical.py +136 -40
  40. package/tools/trading_calendar.py +78 -18
  41. package/tools/volume_analysis.py +2 -5
  42. package/tools/watchlist.py +2 -5
  43. package/tools/watchlist_context.py +2 -5
@@ -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", "is_st": False, "is_etf": False, "limit_pct": 0.10}
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 banker's rounding."""
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 None if np.isnan(obj) else round(float(obj), 4)
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 None if obj != obj else round(obj, 4)
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
- return _failover(sources, label=f"kline_a:{symbol}")
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
- return _failover(sources, label=f"quote_a:{symbol}")
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
- return _failover(sources, label=f"{chain}:{symbol}")
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
- return _clean_row(
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
- market = "sh" if args.symbol.startswith("6") else "sz"
1232
- df = _akshare_retry(ak.stock_individual_fund_flow, stock=args.symbol, market=market)
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 financials_a(symbol: str) -> dict:
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
- return {"symbol": symbol, "error": "No financial data"}
1342
- r = df.iloc[0]
1343
- return _clean_row(
1344
- {
1345
- "symbol": symbol,
1346
- "report_date": r.get("日期"),
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 financials_yf(symbol: str) -> dict:
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
- return _clean_row(
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
- import socket
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
- return _failover(
1404
- [
1405
- ("akshare", _snapshot_akshare),
1406
- ("efinance", _snapshot_efinance),
1407
- ("sina", _snapshot_sina),
1408
- ("tencent", _snapshot_tencent),
1409
- ],
1410
- label="snapshot_a",
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
- return [{"error": "HK snapshot unavailable"}]
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):
@@ -2029,6 +2075,20 @@ def _board_entry(name, source: str, board_type: str) -> dict:
2029
2075
  return {"name": str(name), "source": source, "board_type": board_type}
2030
2076
 
2031
2077
 
2078
+ class _DataMiss(ValueError):
2079
+ """Per-symbol data miss: the provider answered but doesn't cover this code
2080
+ (empty DataFrame / no industry field for an ETF/BSE/uncovered symbol). Never an
2081
+ outage — resolve_stock_sectors' negative cache must not mark the leg down."""
2082
+
2083
+
2084
+ def _require_industry(value, source: str) -> str:
2085
+ """Unwrap a provider's industry field into a real name. pandas NaN is truthy —
2086
+ only a non-empty string counts; a missing one is a _DataMiss, not an outage."""
2087
+ if not (isinstance(value, str) and value):
2088
+ raise _DataMiss(f"{source} has no industry")
2089
+ return value
2090
+
2091
+
2032
2092
  def _stock_boards_em(symbol: str, info_map=None) -> list:
2033
2093
  """A-share industry board from eastmoney individual info. Pass an already-fetched
2034
2094
  info_map (item → value) to reuse it instead of hitting the network again."""
@@ -2037,12 +2097,9 @@ def _stock_boards_em(symbol: str, info_map=None) -> list:
2037
2097
 
2038
2098
  df = _akshare_retry(ak.stock_individual_info_em, symbol=symbol)
2039
2099
  if df is None or df.empty:
2040
- raise ValueError("eastmoney individual info unavailable")
2100
+ raise _DataMiss("eastmoney individual info unavailable")
2041
2101
  info_map = {row.iloc[0]: row.iloc[1] for _, row in df.iterrows()}
2042
- industry = info_map.get("行业")
2043
- # pandas NaN is truthy — only a real string counts as an industry name
2044
- if not (isinstance(industry, str) and industry):
2045
- raise ValueError("eastmoney individual info has no industry")
2102
+ industry = _require_industry(info_map.get("行业"), "eastmoney individual info")
2046
2103
  return [_board_entry(industry, "eastmoney", "industry")]
2047
2104
 
2048
2105
 
@@ -2052,7 +2109,7 @@ def _stock_boards_efinance(symbol: str) -> list:
2052
2109
 
2053
2110
  df = ef.stock.get_belong_board(symbol)
2054
2111
  if df is None or df.empty or "板块名称" not in df.columns:
2055
- raise ValueError("efinance belong-board unavailable")
2112
+ raise _DataMiss("efinance belong-board unavailable")
2056
2113
  # pandas NaN is truthy and str(nan) == "nan" — drop non-string names or they
2057
2114
  # would pollute the dedup in resolve_stock_sectors as a bogus "nan" board
2058
2115
  return [
@@ -2080,17 +2137,30 @@ def _stock_boards_xueqiu(symbol: str) -> list:
2080
2137
 
2081
2138
  df = _akshare_retry(ak.stock_individual_basic_info_xq, symbol=_xq_symbol(symbol), token=token)
2082
2139
  if df is None or df.empty:
2083
- raise ValueError("xueqiu basic info unavailable")
2140
+ raise _DataMiss("xueqiu basic info unavailable")
2084
2141
  info_map = {row.iloc[0]: row.iloc[1] for _, row in df.iterrows()}
2085
2142
  # affiliate_industry is a nested dict: {'ind_code': 'BK0025', 'ind_name': '汽车整车'}
2086
2143
  industry = info_map.get("affiliate_industry")
2087
- name = industry.get("ind_name") if isinstance(industry, dict) else None
2088
- # pandas NaN is truthy — only a real string counts as an industry name
2089
- if not (isinstance(name, str) and name):
2090
- raise ValueError("xueqiu basic info has no industry")
2144
+ name = _require_industry(industry.get("ind_name") if isinstance(industry, dict) else None, "xueqiu basic info")
2091
2145
  return [_board_entry(name, "xueqiu", "industry")]
2092
2146
 
2093
2147
 
2148
+ def _stock_boards_cninfo(symbol: str) -> list:
2149
+ """A-share industry from cninfo (官方披露站) via akshare stock_profile_cninfo —
2150
+ the token-free, non-eastmoney active leg (issue #35). Runs only as the
2151
+ last-resort fallback: its industry naming follows the CSRC classification
2152
+ (酒、饮料和精制茶制造业), not eastmoney board names (酿酒行业), so its entries
2153
+ don't resolve against eastmoney/sina board lists downstream."""
2154
+ import akshare as ak
2155
+
2156
+ bare = symbol[2:] if _A_PREFIXED_RE.fullmatch(symbol) else symbol
2157
+ df = _akshare_retry(ak.stock_profile_cninfo, symbol=bare)
2158
+ if df is None or df.empty or "所属行业" not in df.columns:
2159
+ raise _DataMiss("cninfo profile unavailable")
2160
+ industry = _require_industry(df.iloc[0].get("所属行业"), "cninfo profile")
2161
+ return [_board_entry(industry, "cninfo", "industry")]
2162
+
2163
+
2094
2164
  def _stock_boards_from_cache(symbol: str) -> list:
2095
2165
  """Reverse lookup against the get_sector_constituents disk cache — the honest
2096
2166
  fallback when eastmoney blocks the caller's IP and xueqiu has no token (the two
@@ -2137,10 +2207,34 @@ def _stock_sectors_hk(symbol: str) -> list:
2137
2207
  return sectors
2138
2208
 
2139
2209
 
2210
+ # A failed A-share resolve leg is skipped for this long on subsequent calls
2211
+ # (issue #35): the motivating failure mode — regional blocking of eastmoney — is
2212
+ # chronic, while a 1h TTL keeps a transient blip from degrading the merged result
2213
+ # for the whole day. An expired marker costs one retried attempt (self-healing).
2214
+ _RESOLVE_DOWN_TTL = 3600
2215
+
2216
+
2217
+ def _resolve_leg_down(name: str) -> bool:
2218
+ """True while leg `name`'s failure marker is fresh. The marker stores a plain
2219
+ timestamp — the effective TTL above is shorter than the 24h file lifetime that
2220
+ _disk_cache_get enforces on the shared cache dir."""
2221
+ ts = _disk_cache_get(f"resolve-down-{name}")
2222
+ return isinstance(ts, (int, float)) and time.time() - ts < _RESOLVE_DOWN_TTL
2223
+
2224
+
2140
2225
  def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
2141
- """Reverse map: stock → boards it belongs to (A/HK). A single source failing
2142
- is not fatal — the other source's boards are still returned. An already-fetched
2143
- eastmoney info_map is reused for the em source instead of re-fetching."""
2226
+ """Reverse map: stock → boards it belongs to (A/HK). Sources are merged (a single
2227
+ source failing is not fatal — the others' boards are still returned) rather than
2228
+ first-hit failover: each source covers a different flavor (industry vs concept).
2229
+ An already-fetched eastmoney info_map is reused for the em source instead of
2230
+ re-fetching; that leg then needs no network and bypasses the failure cache.
2231
+
2232
+ A-share legs are socket-timeout-bounded and negative-cached per leg (issue #35):
2233
+ on an eastmoney-blackholed host the first call pays each dead leg's bounded
2234
+ timeout once, later calls skip them until the marker expires. The cninfo leg
2235
+ runs only when every other active leg came up empty — its CSRC industry names
2236
+ don't resolve against eastmoney/sina board lists, so it is a fallback, not an
2237
+ always-on flavor."""
2144
2238
  market = detect_market(symbol)
2145
2239
  result = {"symbol": symbol, "market": market}
2146
2240
  if market == "A":
@@ -2156,11 +2250,40 @@ def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
2156
2250
  result["error"] = f"resolve_stock_sectors only supports A-share and HK stocks, got market {market}"
2157
2251
  return result
2158
2252
  sectors, errors = [], []
2159
- for name, fn in sources:
2160
- try:
2161
- sectors.extend(fn() or [])
2162
- except Exception as e:
2163
- errors.append(f"{name}: {type(e).__name__}: {e}")
2253
+
2254
+ def run_legs(legs, negative_cache: bool):
2255
+ for name, fn in legs:
2256
+ # em with an info_map in hand is a pure dict lookup — never skip it, and
2257
+ # a lookup miss must not mark a network leg down
2258
+ offline_em = name == "eastmoney" and info_map is not None
2259
+ if negative_cache and not offline_em and _resolve_leg_down(name):
2260
+ errors.append(f"{name}: skipped (failed within {_RESOLVE_DOWN_TTL}s)")
2261
+ continue
2262
+ try:
2263
+ sectors.extend(fn() or [])
2264
+ if negative_cache and not offline_em:
2265
+ _disk_cache_set(f"resolve-down-{name}", 0) # success clears the marker
2266
+ except _DataMiss as e:
2267
+ # per-symbol miss (provider answered but doesn't cover this code) —
2268
+ # not an outage: never poison the leg for every other symbol
2269
+ errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
2270
+ except Exception as e:
2271
+ errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
2272
+ if negative_cache and not offline_em:
2273
+ _disk_cache_set(f"resolve-down-{name}", time.time())
2274
+
2275
+ if market == "A":
2276
+ # akshare/efinance leave requests timeout-less — on a blackholed network a leg
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):
2280
+ run_legs(sources, negative_cache=True)
2281
+ # cninfo last: the token-free non-eastmoney active fallback (issue #35),
2282
+ # tried only when everything above yielded nothing
2283
+ if not sectors:
2284
+ run_legs([("cninfo", lambda: _stock_boards_cninfo(symbol))], negative_cache=True)
2285
+ else:
2286
+ run_legs(sources, negative_cache=False)
2164
2287
  seen = set()
2165
2288
  deduped = []
2166
2289
  for s in sectors:
@@ -2172,7 +2295,7 @@ def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
2172
2295
  if market == "A":
2173
2296
  # em/efinance are both eastmoney-flavored and xueqiu is usually untokened,
2174
2297
  # so an all-empty A-share result almost always means eastmoney blocked us.
2175
- error += "; 东财不可用且缓存为空,可先跑 get_sector_constituents 预热或设置 XUEQIU_TOKEN"
2298
+ error += "; 东财/cninfo 均不可用且缓存为空,可先跑 get_sector_constituents 预热或设置 XUEQIU_TOKEN"
2176
2299
  result["error"] = error
2177
2300
  return result
2178
2301
  result["sectors"] = deduped
@@ -2189,6 +2312,9 @@ def cmd_stock_info(args):
2189
2312
  import akshare as ak
2190
2313
 
2191
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
2192
2318
  info_map = None
2193
2319
  try:
2194
2320
  df = _akshare_retry(ak.stock_individual_info_em, symbol=args.symbol)
@@ -2213,6 +2339,26 @@ def cmd_stock_info(args):
2213
2339
  result["boards"] = boards[:10]
2214
2340
  except Exception:
2215
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
2216
2362
  return _clean_row(result)
2217
2363
  else:
2218
2364
  import yfinance as yf
@@ -2660,24 +2806,6 @@ def _hot_stocks_em() -> list:
2660
2806
  return [_strip_exchange_prefix(_clean_row(r)) for r in df[keep].to_dict("records")]
2661
2807
 
2662
2808
 
2663
- def _hot_stocks_xq() -> list:
2664
- """Xueqiu follow ranking via akshare stock_hot_follow_xq. No 涨跌幅 column;
2665
- rank is the row position. Codes arrive SH/SZ-prefixed like eastmoney's."""
2666
- import akshare as ak
2667
-
2668
- df = _akshare_retry(ak.stock_hot_follow_xq, symbol="最热门")
2669
- if df is None or df.empty:
2670
- return []
2671
- col_map = {
2672
- "股票代码": "code",
2673
- "股票简称": "name",
2674
- "最新价": "price",
2675
- }
2676
- df = df.rename(columns=col_map)
2677
- keep = [c for c in col_map.values() if c in df.columns]
2678
- return [{"rank": i, **_strip_exchange_prefix(_clean_row(r))} for i, r in enumerate(df[keep].to_dict("records"), 1)]
2679
-
2680
-
2681
2809
  def _hot_stocks_baidu() -> list:
2682
2810
  """Baidu 股市通热搜 via akshare stock_hot_search_baidu. No code/price columns —
2683
2811
  only the stock name — and 涨跌幅 strings carry a % suffix."""
@@ -2699,10 +2827,13 @@ def _hot_stocks_baidu() -> list:
2699
2827
 
2700
2828
 
2701
2829
  def cmd_hot_stocks(args):
2702
- """A-share popularity ranking (人气榜): eastmoney → xueqiu → baidu."""
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."""
2703
2835
  sources = [
2704
2836
  _sourced("eastmoney", _hot_stocks_em),
2705
- _sourced("xueqiu", _hot_stocks_xq),
2706
2837
  _sourced("baidu", _hot_stocks_baidu),
2707
2838
  ]
2708
2839
  try:
@@ -2715,6 +2846,162 @@ def cmd_hot_stocks(args):
2715
2846
  return {"count": len(items), "items": items, "source": rows[0]["source"]}
2716
2847
 
2717
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
+
2718
3005
  # --------------- CLI ---------------
2719
3006
 
2720
3007
 
@@ -2744,6 +3031,7 @@ def main():
2744
3031
 
2745
3032
  p_fin = sub.add_parser("financials")
2746
3033
  p_fin.add_argument("symbol")
3034
+ p_fin.add_argument("--periods", type=int, default=1)
2747
3035
 
2748
3036
  p_snap = sub.add_parser("market_snapshot")
2749
3037
  p_snap.add_argument("--market", default="A", choices=["A", "HK", "US"])
@@ -2785,6 +3073,13 @@ def main():
2785
3073
  p_hot = sub.add_parser("hot_stocks")
2786
3074
  p_hot.add_argument("--top", type=int, default=20)
2787
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
+
2788
3083
  args = parser.parse_args()
2789
3084
  if not args.command:
2790
3085
  parser.print_help()
@@ -2808,6 +3103,8 @@ def main():
2808
3103
  "limit_up_pool": cmd_limit_up_pool,
2809
3104
  "dragon_tiger": cmd_dragon_tiger,
2810
3105
  "hot_stocks": cmd_hot_stocks,
3106
+ "margin_trading": cmd_margin_trading,
3107
+ "northbound_flow": cmd_northbound_flow,
2811
3108
  }
2812
3109
  # Provider libraries (baostock etc.) print prose to stdout on failure,
2813
3110
  # which would corrupt the JSON-only contract — divert that noise to stderr.
@@ -2817,9 +3114,5 @@ def main():
2817
3114
 
2818
3115
 
2819
3116
  if __name__ == "__main__":
2820
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
2821
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
2822
- for _s in (sys.stdout, sys.stderr):
2823
- if hasattr(_s, "reconfigure"):
2824
- _s.reconfigure(encoding="utf-8")
3117
+ utf8_stdio()
2825
3118
  main()