@weaxs/openclaw-stock-analysis 0.1.15 → 0.2.0
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 +1 -1
- package/dist/index.js +153 -19
- package/index.ts +164 -17
- package/openclaw.plugin.json +7 -0
- package/package.json +1 -1
- package/skills/dragon-head/SKILL.md +3 -1
- package/skills/emotion-cycle/SKILL.md +2 -0
- package/skills/hot-theme/SKILL.md +2 -1
- package/skills/stock-analysis/SKILL.md +9 -1
- package/tools/alert_rules.py +5 -18
- package/tools/backtest.py +4 -4
- package/tools/capabilities.py +8 -0
- package/tools/gather.py +12 -31
- package/tools/market_review.py +1 -1
- package/tools/name_resolver.py +4 -10
- package/tools/pattern.py +3 -24
- package/tools/report_renderer.py +1 -2
- package/tools/screener.py +2 -16
- package/tools/search_intel.py +1 -24
- package/tools/signal_tracker.py +275 -0
- package/tools/stock_data.py +389 -94
- package/tools/trading_calendar.py +92 -7
- package/tools/volume_analysis.py +3 -23
- package/tools/watchlist_context.py +1 -10
- package/scripts/sync-version.sh +0 -56
package/tools/stock_data.py
CHANGED
|
@@ -12,6 +12,9 @@ import time
|
|
|
12
12
|
from datetime import datetime, timedelta
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
16
|
+
from _subproc import run_tool # noqa: E402
|
|
17
|
+
|
|
15
18
|
# Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
|
|
16
19
|
# Bare 6-digit codes are always stocks; the prefix is the disambiguation escape
|
|
17
20
|
# hatch for index codes (sh000001 = 上证指数, not 平安银行).
|
|
@@ -62,15 +65,6 @@ def normalize_stock_code(symbol: str) -> dict:
|
|
|
62
65
|
return info
|
|
63
66
|
|
|
64
67
|
|
|
65
|
-
def mark_st(info: dict, name: str) -> dict:
|
|
66
|
-
"""Mark ST status from stock name; adjusts limit_pct to 5%."""
|
|
67
|
-
if name and "ST" in name.upper():
|
|
68
|
-
info["is_st"] = True
|
|
69
|
-
if info["board"] == "main":
|
|
70
|
-
info["limit_pct"] = 0.05
|
|
71
|
-
return info
|
|
72
|
-
|
|
73
|
-
|
|
74
68
|
def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
|
|
75
69
|
"""Calculate limit-up or limit-down price with banker's rounding."""
|
|
76
70
|
import numpy as np
|
|
@@ -80,11 +74,22 @@ def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> f
|
|
|
80
74
|
|
|
81
75
|
|
|
82
76
|
# Chains that get sticky ordering: the CN free-source chains, where failures are
|
|
83
|
-
# typically chronic (regional blocking
|
|
77
|
+
# typically chronic (regional blocking / rate-limiting — eastmoney is the primary
|
|
78
|
+
# leg of most of them). The yf chains (`kline:`/`quote:`) are
|
|
84
79
|
# excluded on purpose — their failures are usually transient yfinance blips, and
|
|
85
80
|
# stickiness would let one blip degrade HK/US quote richness (finnhub has no
|
|
86
81
|
# name/market_cap/pe/pb) for the whole TTL.
|
|
87
|
-
_STICKY_CHAINS = {
|
|
82
|
+
_STICKY_CHAINS = {
|
|
83
|
+
"kline_a",
|
|
84
|
+
"quote_a",
|
|
85
|
+
"quote_a_etf",
|
|
86
|
+
"snapshot_a",
|
|
87
|
+
"sector_constituents",
|
|
88
|
+
"sina",
|
|
89
|
+
"sector_rankings",
|
|
90
|
+
"dragon_tiger",
|
|
91
|
+
"hot_stocks",
|
|
92
|
+
}
|
|
88
93
|
|
|
89
94
|
|
|
90
95
|
def _failover(sources: list, label: str):
|
|
@@ -1226,31 +1231,10 @@ def cmd_capital_flow(args):
|
|
|
1226
1231
|
|
|
1227
1232
|
def _news_search_intel_fallback(symbol: str) -> list:
|
|
1228
1233
|
"""Fallback: use search_intel to find news when primary sources fail."""
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
try:
|
|
1234
|
-
result = subprocess.run(
|
|
1235
|
-
[sys.executable, str(tools_dir / "search_intel.py"), "search", f"{symbol} 最新消息"],
|
|
1236
|
-
capture_output=True,
|
|
1237
|
-
text=True,
|
|
1238
|
-
encoding="utf-8",
|
|
1239
|
-
timeout=30,
|
|
1240
|
-
)
|
|
1241
|
-
except (subprocess.TimeoutExpired, OSError):
|
|
1242
|
-
return []
|
|
1243
|
-
if result.returncode != 0 or not result.stdout.strip():
|
|
1244
|
-
return []
|
|
1245
|
-
try:
|
|
1246
|
-
data = json.loads(result.stdout.strip())
|
|
1247
|
-
if isinstance(data, list):
|
|
1248
|
-
return [
|
|
1249
|
-
{"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]
|
|
1250
|
-
]
|
|
1251
|
-
return []
|
|
1252
|
-
except (json.JSONDecodeError, TypeError):
|
|
1253
|
-
return []
|
|
1234
|
+
data = run_tool("search_intel.py", ["search", f"{symbol} 最新消息"], timeout=30)
|
|
1235
|
+
if isinstance(data, list):
|
|
1236
|
+
return [{"title": item.get("title", ""), "url": item.get("url", ""), "source": "search"} for item in data[:10]]
|
|
1237
|
+
return []
|
|
1254
1238
|
|
|
1255
1239
|
|
|
1256
1240
|
def cmd_news(args):
|
|
@@ -1612,8 +1596,9 @@ def cmd_market_indices(args):
|
|
|
1612
1596
|
# --------------- sector_rankings ---------------
|
|
1613
1597
|
|
|
1614
1598
|
|
|
1615
|
-
def _sector_rankings_efinance(
|
|
1616
|
-
"""Fallback: fetch
|
|
1599
|
+
def _sector_rankings_efinance() -> list:
|
|
1600
|
+
"""Fallback: fetch industry board rankings via efinance (raw rows; sorting and
|
|
1601
|
+
top/direction are applied uniformly by cmd_sector_rankings after the failover)."""
|
|
1617
1602
|
import efinance as ef
|
|
1618
1603
|
import pandas as pd
|
|
1619
1604
|
|
|
@@ -1632,67 +1617,141 @@ def _sector_rankings_efinance(top: int, direction: str):
|
|
|
1632
1617
|
df = df[keep]
|
|
1633
1618
|
if "change_pct" in df.columns:
|
|
1634
1619
|
df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
|
|
1635
|
-
if direction == "bottom":
|
|
1636
|
-
df = df.sort_values("change_pct", ascending=True).head(top)
|
|
1637
|
-
elif direction == "both":
|
|
1638
|
-
top_df = df.sort_values("change_pct", ascending=False).head(top)
|
|
1639
|
-
bottom_df = df.sort_values("change_pct", ascending=True).head(top)
|
|
1640
|
-
return {
|
|
1641
|
-
"top": [_clean_row(r) for r in top_df.to_dict("records")],
|
|
1642
|
-
"bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
|
|
1643
|
-
}
|
|
1644
|
-
else:
|
|
1645
|
-
df = df.sort_values("change_pct", ascending=False).head(top)
|
|
1646
1620
|
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1647
1621
|
|
|
1648
1622
|
|
|
1623
|
+
def _sourced(name: str, fn):
|
|
1624
|
+
"""Failover leg wrapper: tag each returned row with the provider name, so the
|
|
1625
|
+
caller can tell which source won (_failover returns only the result)."""
|
|
1626
|
+
|
|
1627
|
+
def run():
|
|
1628
|
+
rows = fn()
|
|
1629
|
+
for r in rows:
|
|
1630
|
+
r["source"] = name
|
|
1631
|
+
return rows
|
|
1632
|
+
|
|
1633
|
+
return name, run
|
|
1634
|
+
|
|
1635
|
+
|
|
1636
|
+
def _sector_rankings_em(board_type: str) -> list:
|
|
1637
|
+
"""Eastmoney board rankings (industry or concept) via akshare."""
|
|
1638
|
+
import akshare as ak
|
|
1639
|
+
import pandas as pd
|
|
1640
|
+
|
|
1641
|
+
fetch = ak.stock_board_industry_name_em if board_type == "industry" else ak.stock_board_concept_name_em
|
|
1642
|
+
df = _akshare_retry(fetch)
|
|
1643
|
+
if df is None or df.empty:
|
|
1644
|
+
raise ValueError("eastmoney sector data unavailable")
|
|
1645
|
+
col_map = {
|
|
1646
|
+
"板块名称": "name",
|
|
1647
|
+
"板块代码": "code",
|
|
1648
|
+
"最新价": "price",
|
|
1649
|
+
"涨跌幅": "change_pct",
|
|
1650
|
+
"成交量": "volume",
|
|
1651
|
+
"成交额": "turnover",
|
|
1652
|
+
"换手率": "turnover_rate",
|
|
1653
|
+
"总市值": "market_cap",
|
|
1654
|
+
"上涨家数": "up_count",
|
|
1655
|
+
"下跌家数": "down_count",
|
|
1656
|
+
"领涨股票": "leading_stock",
|
|
1657
|
+
# industry boards name the column 领涨涨跌幅, concept boards 领涨股票-涨跌幅
|
|
1658
|
+
"领涨涨跌幅": "leading_change_pct",
|
|
1659
|
+
"领涨股票-涨跌幅": "leading_change_pct",
|
|
1660
|
+
}
|
|
1661
|
+
df = df.rename(columns=col_map)
|
|
1662
|
+
keep = list(dict.fromkeys(c for c in col_map.values() if c in df.columns))
|
|
1663
|
+
df = df[keep]
|
|
1664
|
+
if "change_pct" in df.columns:
|
|
1665
|
+
df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
|
|
1666
|
+
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1667
|
+
|
|
1668
|
+
|
|
1669
|
+
def _sector_rankings_ths() -> list:
|
|
1670
|
+
"""THS industry board rankings via akshare stock_board_industry_summary_ths.
|
|
1671
|
+
|
|
1672
|
+
There is no THS *concept* rankings table in this akshare version:
|
|
1673
|
+
stock_board_concept_name_ths returns only name/code columns and
|
|
1674
|
+
stock_board_concept_summary_ths is a concept timeline (日期/驱动事件), so the
|
|
1675
|
+
concept chain falls back to sina instead."""
|
|
1676
|
+
import akshare as ak
|
|
1677
|
+
|
|
1678
|
+
df = _akshare_retry(ak.stock_board_industry_summary_ths)
|
|
1679
|
+
if df is None or df.empty:
|
|
1680
|
+
raise ValueError("ths sector data unavailable")
|
|
1681
|
+
col_map = {
|
|
1682
|
+
"板块": "name",
|
|
1683
|
+
"涨跌幅": "change_pct",
|
|
1684
|
+
"总成交量": "volume",
|
|
1685
|
+
"总成交额": "turnover",
|
|
1686
|
+
"净流入": "net_inflow",
|
|
1687
|
+
"上涨家数": "up_count",
|
|
1688
|
+
"下跌家数": "down_count",
|
|
1689
|
+
"领涨股": "leading_stock",
|
|
1690
|
+
"领涨股-最新价": "leading_price",
|
|
1691
|
+
"领涨股-涨跌幅": "leading_change_pct",
|
|
1692
|
+
}
|
|
1693
|
+
df = df.rename(columns=col_map)
|
|
1694
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1695
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1696
|
+
|
|
1697
|
+
|
|
1698
|
+
def _sector_rankings_sina(indicator: str) -> list:
|
|
1699
|
+
"""Sina board rankings via akshare stock_sector_spot (概念/行业/...).
|
|
1700
|
+
|
|
1701
|
+
Sina has no 上涨家数/下跌家数 — only 公司家数 (stock_count); the leading stock
|
|
1702
|
+
rides along in the same row (股票名称/个股-涨跌幅/个股-当前价)."""
|
|
1703
|
+
import akshare as ak
|
|
1704
|
+
|
|
1705
|
+
df = _akshare_retry(ak.stock_sector_spot, indicator=indicator)
|
|
1706
|
+
if df is None or df.empty:
|
|
1707
|
+
raise ValueError(f"sina sector data unavailable (indicator={indicator})")
|
|
1708
|
+
col_map = {
|
|
1709
|
+
"板块": "name",
|
|
1710
|
+
"公司家数": "stock_count",
|
|
1711
|
+
"涨跌额": "change",
|
|
1712
|
+
"涨跌幅": "change_pct",
|
|
1713
|
+
"总成交量": "volume",
|
|
1714
|
+
"总成交额": "turnover",
|
|
1715
|
+
"股票名称": "leading_stock",
|
|
1716
|
+
"个股-涨跌幅": "leading_change_pct",
|
|
1717
|
+
"个股-当前价": "leading_price",
|
|
1718
|
+
}
|
|
1719
|
+
df = df.rename(columns=col_map)
|
|
1720
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1721
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1722
|
+
|
|
1723
|
+
|
|
1649
1724
|
def cmd_sector_rankings(args):
|
|
1725
|
+
board_type = getattr(args, "board_type", "industry")
|
|
1726
|
+
direction = getattr(args, "direction", "top")
|
|
1727
|
+
sources = [_sourced("eastmoney", lambda: _sector_rankings_em(board_type))]
|
|
1728
|
+
if board_type == "industry":
|
|
1729
|
+
# efinance has no concept boards — it stays an industry-only leg
|
|
1730
|
+
sources.append(_sourced("ths", _sector_rankings_ths))
|
|
1731
|
+
sources.append(_sourced("efinance", _sector_rankings_efinance))
|
|
1732
|
+
else:
|
|
1733
|
+
sources.append(_sourced("sina", lambda: _sector_rankings_sina("概念")))
|
|
1650
1734
|
try:
|
|
1651
|
-
|
|
1652
|
-
|
|
1735
|
+
rows = _failover(sources, label=f"sector_rankings:{board_type}")
|
|
1736
|
+
if not rows:
|
|
1737
|
+
raise ValueError(f"no {board_type} board rankings data")
|
|
1738
|
+
except Exception as e:
|
|
1739
|
+
return {"error": str(e)}
|
|
1740
|
+
for r in rows:
|
|
1741
|
+
r["board_type"] = board_type
|
|
1653
1742
|
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
"
|
|
1663
|
-
"
|
|
1664
|
-
"换手率": "turnover_rate",
|
|
1665
|
-
"总市值": "market_cap",
|
|
1666
|
-
"上涨家数": "up_count",
|
|
1667
|
-
"下跌家数": "down_count",
|
|
1668
|
-
"领涨股票": "leading_stock",
|
|
1669
|
-
"领涨涨跌幅": "leading_change_pct",
|
|
1743
|
+
def _pct(row, default):
|
|
1744
|
+
v = row.get("change_pct")
|
|
1745
|
+
return v if isinstance(v, (int, float)) else default
|
|
1746
|
+
|
|
1747
|
+
if direction == "bottom":
|
|
1748
|
+
return sorted(rows, key=lambda r: _pct(r, float("inf")))[: args.top]
|
|
1749
|
+
if direction == "both":
|
|
1750
|
+
return {
|
|
1751
|
+
"top": sorted(rows, key=lambda r: _pct(r, float("-inf")), reverse=True)[: args.top],
|
|
1752
|
+
"bottom": sorted(rows, key=lambda r: _pct(r, float("inf")))[: args.top],
|
|
1670
1753
|
}
|
|
1671
|
-
|
|
1672
|
-
keep = [c for c in col_map.values() if c in df.columns]
|
|
1673
|
-
df = df[keep]
|
|
1674
|
-
if "change_pct" in df.columns:
|
|
1675
|
-
df["change_pct"] = pd.to_numeric(df["change_pct"], errors="coerce")
|
|
1676
|
-
|
|
1677
|
-
direction = getattr(args, "direction", "top")
|
|
1678
|
-
if direction == "bottom":
|
|
1679
|
-
df = df.sort_values("change_pct", ascending=True).head(args.top)
|
|
1680
|
-
elif direction == "both":
|
|
1681
|
-
top_df = df.sort_values("change_pct", ascending=False).head(args.top)
|
|
1682
|
-
bottom_df = df.sort_values("change_pct", ascending=True).head(args.top)
|
|
1683
|
-
return {
|
|
1684
|
-
"top": [_clean_row(r) for r in top_df.to_dict("records")],
|
|
1685
|
-
"bottom": [_clean_row(r) for r in bottom_df.to_dict("records")],
|
|
1686
|
-
}
|
|
1687
|
-
else:
|
|
1688
|
-
df = df.head(args.top)
|
|
1689
|
-
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1690
|
-
except Exception:
|
|
1691
|
-
try:
|
|
1692
|
-
direction = getattr(args, "direction", "top")
|
|
1693
|
-
return _sector_rankings_efinance(args.top, direction)
|
|
1694
|
-
except Exception as e2:
|
|
1695
|
-
return {"error": str(e2)}
|
|
1754
|
+
return sorted(rows, key=lambda r: _pct(r, float("-inf")), reverse=True)[: args.top]
|
|
1696
1755
|
|
|
1697
1756
|
|
|
1698
1757
|
# --------------- sector constituents / stock sectors (issue #18) ---------------
|
|
@@ -2259,6 +2318,228 @@ def cmd_fundamental_context(args):
|
|
|
2259
2318
|
return {"error": str(e)}
|
|
2260
2319
|
|
|
2261
2320
|
|
|
2321
|
+
# --------------- short-term sentiment: limit_up_pool / dragon_tiger / hot_stocks (A-share only) ---------------
|
|
2322
|
+
|
|
2323
|
+
|
|
2324
|
+
def cmd_limit_up_pool(args):
|
|
2325
|
+
"""A-share limit-up pool (涨停池) for one trading day via eastmoney."""
|
|
2326
|
+
date = (args.date or datetime.now().strftime("%Y%m%d")).replace("-", "")
|
|
2327
|
+
try:
|
|
2328
|
+
import akshare as ak
|
|
2329
|
+
|
|
2330
|
+
df = _akshare_retry(ak.stock_zt_pool_em, date=date)
|
|
2331
|
+
if df is None or df.empty:
|
|
2332
|
+
return {
|
|
2333
|
+
"date": date,
|
|
2334
|
+
"count": 0,
|
|
2335
|
+
"max_consecutive_boards": 0,
|
|
2336
|
+
"pool": [],
|
|
2337
|
+
"note": "no limit-up pool data (non-trading day or no limit-ups)",
|
|
2338
|
+
}
|
|
2339
|
+
col_map = {
|
|
2340
|
+
"代码": "code",
|
|
2341
|
+
"名称": "name",
|
|
2342
|
+
"涨跌幅": "change_pct",
|
|
2343
|
+
"最新价": "price",
|
|
2344
|
+
"成交额": "turnover",
|
|
2345
|
+
"流通市值": "float_market_cap",
|
|
2346
|
+
"总市值": "total_market_cap",
|
|
2347
|
+
"换手率": "turnover_rate",
|
|
2348
|
+
"封板资金": "seal_amount",
|
|
2349
|
+
"首次封板时间": "first_seal_time",
|
|
2350
|
+
"最后封板时间": "last_seal_time",
|
|
2351
|
+
"炸板次数": "break_count",
|
|
2352
|
+
"涨停统计": "limit_up_stat",
|
|
2353
|
+
"连板数": "consecutive_boards",
|
|
2354
|
+
"所属行业": "industry",
|
|
2355
|
+
}
|
|
2356
|
+
df = df.rename(columns=col_map)
|
|
2357
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2358
|
+
pool = [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
2359
|
+
boards = [r["consecutive_boards"] for r in pool if isinstance(r.get("consecutive_boards"), (int, float))]
|
|
2360
|
+
return {
|
|
2361
|
+
"date": date,
|
|
2362
|
+
"count": len(pool),
|
|
2363
|
+
"max_consecutive_boards": max(boards) if boards else 0,
|
|
2364
|
+
"pool": pool,
|
|
2365
|
+
}
|
|
2366
|
+
except Exception as e:
|
|
2367
|
+
return {"error": str(e)}
|
|
2368
|
+
|
|
2369
|
+
|
|
2370
|
+
def _dragon_tiger_em(raw: str) -> list:
|
|
2371
|
+
"""Eastmoney 龙虎榜 via akshare stock_lhb_detail_em."""
|
|
2372
|
+
import akshare as ak
|
|
2373
|
+
import pandas as pd
|
|
2374
|
+
|
|
2375
|
+
df = _akshare_retry(ak.stock_lhb_detail_em, start_date=raw, end_date=raw)
|
|
2376
|
+
if df is None or df.empty:
|
|
2377
|
+
return []
|
|
2378
|
+
col_map = {
|
|
2379
|
+
"代码": "code",
|
|
2380
|
+
"名称": "name",
|
|
2381
|
+
"上榜日": "list_date",
|
|
2382
|
+
"收盘价": "close",
|
|
2383
|
+
"涨跌幅": "change_pct",
|
|
2384
|
+
"龙虎榜净买额": "net_buy",
|
|
2385
|
+
"龙虎榜买入额": "buy_amount",
|
|
2386
|
+
"龙虎榜卖出额": "sell_amount",
|
|
2387
|
+
"龙虎榜成交额": "lhb_turnover",
|
|
2388
|
+
"上榜原因": "reason",
|
|
2389
|
+
"解读": "interpretation",
|
|
2390
|
+
}
|
|
2391
|
+
df = df.rename(columns=col_map)
|
|
2392
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2393
|
+
df = df[keep]
|
|
2394
|
+
if "net_buy" in df.columns:
|
|
2395
|
+
df["net_buy"] = pd.to_numeric(df["net_buy"], errors="coerce")
|
|
2396
|
+
return [_clean_row(r) for r in df.to_dict("records")]
|
|
2397
|
+
|
|
2398
|
+
|
|
2399
|
+
def _dragon_tiger_sina(raw: str) -> list:
|
|
2400
|
+
"""Sina 龙虎榜每日详情 via akshare stock_lhb_detail_daily_sina.
|
|
2401
|
+
|
|
2402
|
+
Sina has no 涨跌幅/净买额/买入额/卖出额/上榜日/解读 — its 指标 column is the
|
|
2403
|
+
listing reason and list_date is filled from the query date. A stock listed for
|
|
2404
|
+
several reasons appears once per reason (sina's page layout)."""
|
|
2405
|
+
import akshare as ak
|
|
2406
|
+
|
|
2407
|
+
df = _akshare_retry(ak.stock_lhb_detail_daily_sina, date=raw)
|
|
2408
|
+
if df is None or df.empty:
|
|
2409
|
+
return []
|
|
2410
|
+
col_map = {
|
|
2411
|
+
"股票代码": "code",
|
|
2412
|
+
"股票名称": "name",
|
|
2413
|
+
"收盘价": "close",
|
|
2414
|
+
"指标": "reason",
|
|
2415
|
+
}
|
|
2416
|
+
df = df.rename(columns=col_map)
|
|
2417
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2418
|
+
rows = [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
2419
|
+
date_iso = f"{raw[:4]}-{raw[4:6]}-{raw[6:8]}"
|
|
2420
|
+
for r in rows:
|
|
2421
|
+
r["list_date"] = date_iso
|
|
2422
|
+
return rows
|
|
2423
|
+
|
|
2424
|
+
|
|
2425
|
+
def cmd_dragon_tiger(args):
|
|
2426
|
+
"""A-share dragon-tiger list (龙虎榜) for one trading day: eastmoney → sina."""
|
|
2427
|
+
raw = (args.date or datetime.now().strftime("%Y-%m-%d")).replace("-", "")
|
|
2428
|
+
date = f"{raw[:4]}-{raw[4:6]}-{raw[6:8]}" if len(raw) == 8 and raw.isdigit() else args.date
|
|
2429
|
+
sources = [
|
|
2430
|
+
_sourced("eastmoney", lambda: _dragon_tiger_em(raw)),
|
|
2431
|
+
_sourced("sina", lambda: _dragon_tiger_sina(raw)),
|
|
2432
|
+
]
|
|
2433
|
+
try:
|
|
2434
|
+
rows = _failover(sources, label=f"dragon_tiger:{raw}")
|
|
2435
|
+
except Exception as e:
|
|
2436
|
+
return {"error": str(e)}
|
|
2437
|
+
if not rows:
|
|
2438
|
+
return {
|
|
2439
|
+
"date": date,
|
|
2440
|
+
"count": 0,
|
|
2441
|
+
"items": [],
|
|
2442
|
+
"note": "no dragon-tiger data (non-trading day or no listings)",
|
|
2443
|
+
}
|
|
2444
|
+
source = rows[0]["source"]
|
|
2445
|
+
if args.symbol:
|
|
2446
|
+
m = re.fullmatch(r"(?:sh|sz|bj)(\d{6})", str(args.symbol), re.IGNORECASE)
|
|
2447
|
+
want = m.group(1) if m else str(args.symbol)
|
|
2448
|
+
rows = [r for r in rows if str(r.get("code")) == want]
|
|
2449
|
+
if any(isinstance(r.get("net_buy"), (int, float)) for r in rows):
|
|
2450
|
+
rows = sorted(
|
|
2451
|
+
rows,
|
|
2452
|
+
key=lambda r: abs(r["net_buy"]) if isinstance(r.get("net_buy"), (int, float)) else 0,
|
|
2453
|
+
reverse=True,
|
|
2454
|
+
)
|
|
2455
|
+
items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
|
|
2456
|
+
return {"date": date, "count": len(items), "items": items, "source": source}
|
|
2457
|
+
|
|
2458
|
+
|
|
2459
|
+
def _strip_exchange_prefix(row: dict) -> dict:
|
|
2460
|
+
"""Bare the exchange prefix on row["code"] ("SZ000001" → "000001", original kept in
|
|
2461
|
+
code_full). Bare 6-digit codes pass through unchanged."""
|
|
2462
|
+
m = re.fullmatch(r"(sh|sz|bj)(\d{6})", str(row.get("code") or ""), re.IGNORECASE)
|
|
2463
|
+
if m:
|
|
2464
|
+
row["code_full"] = row["code"]
|
|
2465
|
+
row["code"] = m.group(2)
|
|
2466
|
+
return row
|
|
2467
|
+
|
|
2468
|
+
|
|
2469
|
+
def _hot_stocks_em() -> list:
|
|
2470
|
+
"""Eastmoney 人气榜 via akshare stock_hot_rank_em."""
|
|
2471
|
+
import akshare as ak
|
|
2472
|
+
|
|
2473
|
+
df = _akshare_retry(ak.stock_hot_rank_em)
|
|
2474
|
+
if df is None or df.empty:
|
|
2475
|
+
return []
|
|
2476
|
+
col_map = {
|
|
2477
|
+
"当前排名": "rank",
|
|
2478
|
+
"代码": "code",
|
|
2479
|
+
"股票名称": "name",
|
|
2480
|
+
"最新价": "price",
|
|
2481
|
+
"涨跌幅": "change_pct",
|
|
2482
|
+
}
|
|
2483
|
+
df = df.rename(columns=col_map)
|
|
2484
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2485
|
+
return [_strip_exchange_prefix(_clean_row(r)) for r in df[keep].to_dict("records")]
|
|
2486
|
+
|
|
2487
|
+
|
|
2488
|
+
def _hot_stocks_xq() -> list:
|
|
2489
|
+
"""Xueqiu follow ranking via akshare stock_hot_follow_xq. No 涨跌幅 column;
|
|
2490
|
+
rank is the row position. Codes arrive SH/SZ-prefixed like eastmoney's."""
|
|
2491
|
+
import akshare as ak
|
|
2492
|
+
|
|
2493
|
+
df = _akshare_retry(ak.stock_hot_follow_xq, symbol="最热门")
|
|
2494
|
+
if df is None or df.empty:
|
|
2495
|
+
return []
|
|
2496
|
+
col_map = {
|
|
2497
|
+
"股票代码": "code",
|
|
2498
|
+
"股票简称": "name",
|
|
2499
|
+
"最新价": "price",
|
|
2500
|
+
}
|
|
2501
|
+
df = df.rename(columns=col_map)
|
|
2502
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
2503
|
+
return [{"rank": i, **_strip_exchange_prefix(_clean_row(r))} for i, r in enumerate(df[keep].to_dict("records"), 1)]
|
|
2504
|
+
|
|
2505
|
+
|
|
2506
|
+
def _hot_stocks_baidu() -> list:
|
|
2507
|
+
"""Baidu 股市通热搜 via akshare stock_hot_search_baidu. No code/price columns —
|
|
2508
|
+
only the stock name — and 涨跌幅 strings carry a % suffix."""
|
|
2509
|
+
import akshare as ak
|
|
2510
|
+
|
|
2511
|
+
df = _akshare_retry(
|
|
2512
|
+
ak.stock_hot_search_baidu,
|
|
2513
|
+
symbol="A股",
|
|
2514
|
+
date=datetime.now().strftime("%Y%m%d"),
|
|
2515
|
+
time="今日",
|
|
2516
|
+
)
|
|
2517
|
+
if df is None or df.empty:
|
|
2518
|
+
return []
|
|
2519
|
+
rows = []
|
|
2520
|
+
for i, r in enumerate(df.to_dict("records"), 1):
|
|
2521
|
+
pct = str(r.get("涨跌幅") or "").replace("%", "")
|
|
2522
|
+
rows.append(_clean_row({"rank": i, "name": r.get("名称/代码"), "change_pct": _parse_float(pct)}))
|
|
2523
|
+
return rows
|
|
2524
|
+
|
|
2525
|
+
|
|
2526
|
+
def cmd_hot_stocks(args):
|
|
2527
|
+
"""A-share popularity ranking (人气榜): eastmoney → xueqiu → baidu."""
|
|
2528
|
+
sources = [
|
|
2529
|
+
_sourced("eastmoney", _hot_stocks_em),
|
|
2530
|
+
_sourced("xueqiu", _hot_stocks_xq),
|
|
2531
|
+
_sourced("baidu", _hot_stocks_baidu),
|
|
2532
|
+
]
|
|
2533
|
+
try:
|
|
2534
|
+
rows = _failover(sources, label="hot_stocks")
|
|
2535
|
+
except Exception as e:
|
|
2536
|
+
return {"error": str(e)}
|
|
2537
|
+
if not rows:
|
|
2538
|
+
return {"count": 0, "items": [], "note": "no hot-rank data available"}
|
|
2539
|
+
items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
|
|
2540
|
+
return {"count": len(items), "items": items, "source": rows[0]["source"]}
|
|
2541
|
+
|
|
2542
|
+
|
|
2262
2543
|
# --------------- CLI ---------------
|
|
2263
2544
|
|
|
2264
2545
|
|
|
@@ -2298,6 +2579,7 @@ def main():
|
|
|
2298
2579
|
p_sec = sub.add_parser("sector_rankings")
|
|
2299
2580
|
p_sec.add_argument("--top", type=int, default=10)
|
|
2300
2581
|
p_sec.add_argument("--direction", default="top", choices=["top", "bottom", "both"])
|
|
2582
|
+
p_sec.add_argument("--board-type", default="industry", choices=["industry", "concept"])
|
|
2301
2583
|
|
|
2302
2584
|
p_cons = sub.add_parser("sector_constituents")
|
|
2303
2585
|
p_cons.add_argument("sector")
|
|
@@ -2312,12 +2594,22 @@ def main():
|
|
|
2312
2594
|
p_chip = sub.add_parser("chip_distribution")
|
|
2313
2595
|
p_chip.add_argument("symbol")
|
|
2314
2596
|
|
|
2315
|
-
|
|
2316
|
-
p_stats.add_argument("--market", default="A", choices=["A"])
|
|
2597
|
+
sub.add_parser("market_stats")
|
|
2317
2598
|
|
|
2318
2599
|
p_fund = sub.add_parser("fundamental_context")
|
|
2319
2600
|
p_fund.add_argument("symbol")
|
|
2320
2601
|
|
|
2602
|
+
p_zt = sub.add_parser("limit_up_pool")
|
|
2603
|
+
p_zt.add_argument("--date", default=None, help="Trading date in YYYYMMDD format (default: today)")
|
|
2604
|
+
|
|
2605
|
+
p_lhb = sub.add_parser("dragon_tiger")
|
|
2606
|
+
p_lhb.add_argument("--date", default=None, help="Trading date in YYYY-MM-DD format (default: today)")
|
|
2607
|
+
p_lhb.add_argument("--symbol", default=None, help="Filter to a single stock code")
|
|
2608
|
+
p_lhb.add_argument("--top", type=int, default=20)
|
|
2609
|
+
|
|
2610
|
+
p_hot = sub.add_parser("hot_stocks")
|
|
2611
|
+
p_hot.add_argument("--top", type=int, default=20)
|
|
2612
|
+
|
|
2321
2613
|
args = parser.parse_args()
|
|
2322
2614
|
if not args.command:
|
|
2323
2615
|
parser.print_help()
|
|
@@ -2338,6 +2630,9 @@ def main():
|
|
|
2338
2630
|
"chip_distribution": cmd_chip_distribution,
|
|
2339
2631
|
"market_stats": cmd_market_stats,
|
|
2340
2632
|
"fundamental_context": cmd_fundamental_context,
|
|
2633
|
+
"limit_up_pool": cmd_limit_up_pool,
|
|
2634
|
+
"dragon_tiger": cmd_dragon_tiger,
|
|
2635
|
+
"hot_stocks": cmd_hot_stocks,
|
|
2341
2636
|
}
|
|
2342
2637
|
# Provider libraries (baostock etc.) print prose to stdout on failure,
|
|
2343
2638
|
# which would corrupt the JSON-only contract — divert that noise to stderr.
|