stock-analysis-plugin 0.1.12 → 0.1.13
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 +10 -7
- package/package.json +1 -1
- package/pi/index.ts +50 -0
- package/skills/dragon-head/SKILL.md +2 -0
- package/skills/hot-theme/SKILL.md +3 -3
- package/tools/_subproc.py +33 -0
- package/tools/anomaly_detect.py +3 -17
- package/tools/capabilities.py +2 -0
- package/tools/diagnostics.py +1 -0
- package/tools/market_regime.py +4 -18
- package/tools/market_review.py +14 -23
- package/tools/risk_screening.py +5 -15
- package/tools/stock_data.py +398 -17
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ A 股 / 港股 / 美股 / 日股 / 韩股 / 台股综合分析、多因子选股
|
|
|
31
31
|
|
|
32
32
|
## 功能概览
|
|
33
33
|
|
|
34
|
-
- **
|
|
34
|
+
- **41 个工具** — 行情数据、技术分析、K 线形态、资金流向、财务指标、新闻舆情、风险筛查、市场状态等
|
|
35
35
|
- **20 个 Skills** — 综合分析、全市场选股、策略回测 + 17 个策略方法论(缠论、波浪、龙头、情绪周期等)
|
|
36
36
|
- **策略回测引擎** — YAML DSL 定义策略,参数化条件组合,自动诊断 + LLM 变异优化
|
|
37
37
|
- **多数据源 Failover** — 9 个数据源自动容灾切换(akshare / tushare / efinance / pytdx / baostock / yfinance / finnhub / longbridge / alphavantage)
|
|
@@ -92,7 +92,7 @@ register(ctx)
|
|
|
92
92
|
openclaw plugins install clawhub:@weaxs/openclaw-stock-analysis
|
|
93
93
|
```
|
|
94
94
|
|
|
95
|
-
OpenClaw Gateway 启动后自动加载并注册
|
|
95
|
+
OpenClaw Gateway 启动后自动加载并注册 41 个 tool。安装时 postinstall 会自动建 `.venv` 并装好 Python 依赖(前提:本机有 `python3 >= 3.9`)。
|
|
96
96
|
|
|
97
97
|
详见 [OpenClaw 接入指南](docs/openclaw-integration.md),或 plugin 自身说明 [`openclaw/README.md`](openclaw/README.md)。
|
|
98
98
|
|
|
@@ -103,7 +103,7 @@ dsh plugin --profile <你的profile> add @weaxs/dsh-stock-analysis
|
|
|
103
103
|
dsh --profile <你的profile>
|
|
104
104
|
```
|
|
105
105
|
|
|
106
|
-
作为 dsh bundle 安装:`dsh plugin add` 会把 `cordis.patch.yml` 叠加进 profile 组合,注册
|
|
106
|
+
作为 dsh bundle 安装:`dsh plugin add` 会把 `cordis.patch.yml` 叠加进 profile 组合,注册 41 个 tool + 20 个 skill。postinstall 自动建 `.venv`(pnpm 需在 profile 的 `pnpm-workspace.yaml` 里给本包配 `allowBuilds`,否则回退系统 `python3`)。
|
|
107
107
|
|
|
108
108
|
详见 [`dsh/README.md`](dsh/README.md)。
|
|
109
109
|
|
|
@@ -138,6 +138,7 @@ pip install -r tools/requirements.txt
|
|
|
138
138
|
| `LONGBRIDGE_ACCESS_TOKEN` | Longbridge SDK |
|
|
139
139
|
| `ALPHAVANTAGE_API_KEY` | Alpha Vantage(美股 K 线 / 行情) |
|
|
140
140
|
| `FINNHUB_API_KEY` | Finnhub(港股 / 美股) |
|
|
141
|
+
| `XUEQIU_TOKEN` | 雪球(A 股个股所属板块反查,东财不可用时的兜底) |
|
|
141
142
|
|
|
142
143
|
**搜索引擎(可选,配置任一即可):**
|
|
143
144
|
|
|
@@ -236,6 +237,8 @@ Agent 会自动调用行情 → 技术面 → 基本面 → 资金面 → 消息
|
|
|
236
237
|
| `get_chip_distribution` | 筹码分布 |
|
|
237
238
|
| `get_market_indices` | 主要指数行情 |
|
|
238
239
|
| `get_sector_rankings` | 板块涨跌排行 |
|
|
240
|
+
| `get_sector_constituents` | 板块成分股查询(仅 A 股,板块名模糊匹配) |
|
|
241
|
+
| `resolve_stock_sectors` | 个股所属板块查询(A 股行业+概念 / 港股 GICS) |
|
|
239
242
|
| `get_market_stats` | 市场统计(涨跌家数、涨停等) |
|
|
240
243
|
| `get_fundamental_context` | 基本面综合上下文 |
|
|
241
244
|
|
|
@@ -396,20 +399,20 @@ python tools/market_regime.py detect A
|
|
|
396
399
|
```
|
|
397
400
|
stock-analysis/
|
|
398
401
|
├── pi/ # Pi Agent Extension
|
|
399
|
-
│ └── index.ts # 注册
|
|
402
|
+
│ └── index.ts # 注册 41 个工具 + 20 个 skill
|
|
400
403
|
├── hermes/ # Hermes Agent Plugin
|
|
401
404
|
│ ├── plugin.yaml # 插件清单
|
|
402
405
|
│ ├── __init__.py # register(ctx) 入口
|
|
403
406
|
│ ├── schemas.py # 工具 JSON Schema 定义
|
|
404
|
-
│ └── tools.py #
|
|
407
|
+
│ └── tools.py # 41 个 handler → subprocess 调 CLI
|
|
405
408
|
├── openclaw/ # OpenClaw Plugin
|
|
406
409
|
│ ├── openclaw.plugin.json # manifest(contracts.tools)
|
|
407
410
|
│ ├── package.json # 含 openclaw 块(pluginApi/SDK 版本)
|
|
408
|
-
│ └── index.ts # definePluginEntry + registerTool ×
|
|
411
|
+
│ └── index.ts # definePluginEntry + registerTool ×41
|
|
409
412
|
├── dsh/ # DeepSeek Harness (dsh) Plugin
|
|
410
413
|
│ ├── cordis.patch.yml # bundle patch(insert 插件入口)
|
|
411
414
|
│ ├── package.json # 含 dsh.bundle 块(bundle manifest)
|
|
412
|
-
│ └── index.ts # cordis apply(ctx) + defineTool ×
|
|
415
|
+
│ └── index.ts # cordis apply(ctx) + defineTool ×41
|
|
413
416
|
│
|
|
414
417
|
├── tools/ # 共享 Python CLI 工具(12 个脚本)
|
|
415
418
|
│ ├── stock_data.py # 行情 / 资金流 / 新闻 / 财务
|
package/package.json
CHANGED
package/pi/index.ts
CHANGED
|
@@ -281,6 +281,56 @@ export default (pi: ExtensionAPI) => {
|
|
|
281
281
|
},
|
|
282
282
|
});
|
|
283
283
|
|
|
284
|
+
pi.registerTool({
|
|
285
|
+
name: "get_sector_constituents",
|
|
286
|
+
description:
|
|
287
|
+
"查询A股板块成分股(正向映射:板块→股票列表)。板块名支持模糊匹配(如「创新药」自动解析到精确板块名),东财行业/概念 + 新浪多源 failover,结果缓存24小时。仅支持A股;反向查个股所属板块用 resolve_stock_sectors",
|
|
288
|
+
parameters: {
|
|
289
|
+
type: "object",
|
|
290
|
+
properties: {
|
|
291
|
+
sector: {
|
|
292
|
+
type: "string",
|
|
293
|
+
description: "板块名称(可模糊,如 创新药、半导体)",
|
|
294
|
+
},
|
|
295
|
+
board_type: {
|
|
296
|
+
type: "string",
|
|
297
|
+
enum: ["industry", "concept", "auto"],
|
|
298
|
+
description: "板块类型:industry=行业,concept=概念,auto=自动(默认)",
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
required: ["sector"],
|
|
302
|
+
},
|
|
303
|
+
async execute(_id, { sector, board_type = "auto" }) {
|
|
304
|
+
const result = await py("stock_data.py", [
|
|
305
|
+
"sector_constituents",
|
|
306
|
+
sector,
|
|
307
|
+
"--board-type",
|
|
308
|
+
board_type,
|
|
309
|
+
]);
|
|
310
|
+
return asText(result.stdout);
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
pi.registerTool({
|
|
315
|
+
name: "resolve_stock_sectors",
|
|
316
|
+
description:
|
|
317
|
+
"查询个股所属板块(反向映射:个股→板块)。A股返回东财行业 + efinance 概念/板块(雪球行业兜底,需 XUEQIU_TOKEN),港股返回 yfinance GICS 英文 sector/industry 口径。板块级情报(如「创新药回调」)映射到池内个股时调本工具;正向查板块成分股用 get_sector_constituents",
|
|
318
|
+
parameters: {
|
|
319
|
+
type: "object",
|
|
320
|
+
properties: {
|
|
321
|
+
symbol: {
|
|
322
|
+
type: "string",
|
|
323
|
+
description: "股票代码(A股如 600519,港股如 00700.HK)",
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
required: ["symbol"],
|
|
327
|
+
},
|
|
328
|
+
async execute(_id, { symbol }) {
|
|
329
|
+
const result = await py("stock_data.py", ["resolve_stock_sectors", symbol]);
|
|
330
|
+
return asText(result.stdout);
|
|
331
|
+
},
|
|
332
|
+
});
|
|
333
|
+
|
|
284
334
|
pi.registerTool({
|
|
285
335
|
name: "get_stock_info",
|
|
286
336
|
description:
|
|
@@ -25,15 +25,15 @@ gather 工具返回:
|
|
|
25
25
|
|
|
26
26
|
### 1. 题材强度评估
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
从板块排名、成分股表现和新闻判断(板块成分股用 get_sector_constituents 拉取,板块名支持模糊匹配,如「创新药板块」可命中「创新药」):
|
|
29
29
|
- **板块排名**:领涨板块位次、涨幅
|
|
30
|
-
-
|
|
30
|
+
- **扩散度**:板块内涨停数量、上涨家数占比(对成分股逐个统计)
|
|
31
31
|
- **持续性**:是否连续多日领涨(首日/接力/高潮/退潮)
|
|
32
32
|
- **催化来源**:政策/事件/数据/概念炒作
|
|
33
33
|
|
|
34
34
|
### 2. 个股关联度
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
先用 resolve_stock_sectors 确认个股实际归属的行业/概念板块(避免仅凭股名臆测),再判断个股与题材的关联强度:
|
|
37
37
|
- **实质受益**:业务直接相关,业绩将受益(强关联)
|
|
38
38
|
- **间接受益**:产业链上下游,部分业务相关(中关联)
|
|
39
39
|
- **纯概念**:仅有概念沾边,无实际业务(弱关联)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Shared subprocess helper for tools that call sibling CLIs (stock_data.py etc.).
|
|
2
|
+
|
|
3
|
+
Imported flat (`from _subproc import ...`): each importer puts its own directory
|
|
4
|
+
on sys.path first (the `from stock_data import ...` precedent in anomaly_detect.py),
|
|
5
|
+
so this resolves both when a tool runs as a script (sys.path[0] = tools/) and when
|
|
6
|
+
pytest imports it as tools.*.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def run_tool(script: str, args: list, timeout: int = 30):
|
|
18
|
+
"""Run tools/<script> with an argv list (never a shell). Returns parsed JSON
|
|
19
|
+
stdout, or None on any failure (non-zero exit, empty/invalid output, timeout) —
|
|
20
|
+
callers pick their own sentinel with `or {}` / `or []`."""
|
|
21
|
+
try:
|
|
22
|
+
r = subprocess.run(
|
|
23
|
+
[sys.executable, os.path.join(TOOLS_DIR, script), *args],
|
|
24
|
+
capture_output=True,
|
|
25
|
+
text=True,
|
|
26
|
+
encoding="utf-8",
|
|
27
|
+
timeout=timeout,
|
|
28
|
+
)
|
|
29
|
+
if r.returncode == 0 and r.stdout.strip():
|
|
30
|
+
return json.loads(r.stdout)
|
|
31
|
+
except Exception:
|
|
32
|
+
pass
|
|
33
|
+
return None
|
package/tools/anomaly_detect.py
CHANGED
|
@@ -3,8 +3,6 @@
|
|
|
3
3
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
|
-
import os
|
|
7
|
-
import subprocess
|
|
8
6
|
import sys
|
|
9
7
|
from pathlib import Path
|
|
10
8
|
|
|
@@ -13,22 +11,10 @@ import pandas as pd
|
|
|
13
11
|
|
|
14
12
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
13
|
|
|
14
|
+
from _subproc import run_tool as _run_tool
|
|
16
15
|
from stock_data import detect_market, normalize_stock_code
|
|
17
16
|
from technical import fetch_kline, to_dataframe
|
|
18
17
|
|
|
19
|
-
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def _run_tool(script: str, args: str):
|
|
23
|
-
cmd = f"{sys.executable} {TOOLS_DIR}/{script} {args}"
|
|
24
|
-
try:
|
|
25
|
-
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding="utf-8", timeout=30)
|
|
26
|
-
if r.returncode == 0 and r.stdout.strip():
|
|
27
|
-
return json.loads(r.stdout)
|
|
28
|
-
except Exception:
|
|
29
|
-
pass
|
|
30
|
-
return None
|
|
31
|
-
|
|
32
18
|
|
|
33
19
|
def _anomaly(type_: str, severity: str, direction: str, description: str, **extra) -> dict:
|
|
34
20
|
result = {
|
|
@@ -347,7 +333,7 @@ def detect_capital_flow_anomaly(symbol: str) -> list:
|
|
|
347
333
|
if market != "A":
|
|
348
334
|
return []
|
|
349
335
|
|
|
350
|
-
flow_data = _run_tool("stock_data.py",
|
|
336
|
+
flow_data = _run_tool("stock_data.py", ["capital_flow", symbol, "--mode", "detail"])
|
|
351
337
|
if not flow_data or not isinstance(flow_data, list) or len(flow_data) < 3:
|
|
352
338
|
return []
|
|
353
339
|
|
|
@@ -505,7 +491,7 @@ def detect_anomalies(symbol: str) -> dict:
|
|
|
505
491
|
low = df["low"]
|
|
506
492
|
volume = df["volume"]
|
|
507
493
|
|
|
508
|
-
quote = _run_tool("stock_data.py",
|
|
494
|
+
quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
|
|
509
495
|
|
|
510
496
|
anomalies = []
|
|
511
497
|
anomalies.extend(detect_macd_cross(close))
|
package/tools/capabilities.py
CHANGED
|
@@ -28,12 +28,14 @@ TOOL_MATRIX = {
|
|
|
28
28
|
"get_volume_analysis": {"markets": ALL_MARKETS, "reason": None},
|
|
29
29
|
"detect_anomaly": {"markets": ALL_MARKETS, "reason": None},
|
|
30
30
|
"get_stock_info": {"markets": ALL_MARKETS, "reason": None},
|
|
31
|
+
"resolve_stock_sectors": {"markets": ["A", "HK"], "reason": "A-share and HK only"},
|
|
31
32
|
"detect_market_regime": {"markets": ["A", "HK", "US"], "reason": "index coverage is CN/HK/US only"},
|
|
32
33
|
"get_market_review": {"markets": ["A", "HK", "US"], "reason": "review data coverage is CN/HK/US only"},
|
|
33
34
|
# A-share only
|
|
34
35
|
"get_capital_flow": {"markets": ["A"], "reason": "A-share only (akshare data)"},
|
|
35
36
|
"get_chip_distribution": {"markets": ["A"], "reason": "A-share only"},
|
|
36
37
|
"get_sector_rankings": {"markets": ["A"], "reason": "A-share only"},
|
|
38
|
+
"get_sector_constituents": {"markets": ["A"], "reason": "A-share only"},
|
|
37
39
|
"get_market_stats": {"markets": ["A"], "reason": "A-share only"},
|
|
38
40
|
"get_fundamental_context": {"markets": ["A"], "reason": "A-share only"},
|
|
39
41
|
"resolve_stock_name": {"markets": ["A"], "reason": "A-share name/pinyin index only"},
|
package/tools/diagnostics.py
CHANGED
|
@@ -22,6 +22,7 @@ PROVIDERS = {
|
|
|
22
22
|
"akshare": ("akshare", [], ["A"], None),
|
|
23
23
|
"tushare": ("tushare", ["TUSHARE_TOKEN"], ["A"], None),
|
|
24
24
|
"efinance": ("efinance", [], ["A"], None),
|
|
25
|
+
"xueqiu": ("akshare", ["XUEQIU_TOKEN"], ["A"], "industry board fallback via akshare"),
|
|
25
26
|
"pytdx": ("pytdx", [], ["A"], "connects to public Tencent servers"),
|
|
26
27
|
"yfinance": ("yfinance", [], ["HK", "US", "JP", "KR", "TW"], "quote may be delayed 15-20min"),
|
|
27
28
|
"finnhub": ("finnhub", ["FINNHUB_API_KEY"], ["HK", "US"], None),
|
package/tools/market_regime.py
CHANGED
|
@@ -4,22 +4,11 @@
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import os
|
|
7
|
-
import subprocess
|
|
8
7
|
import sys
|
|
9
8
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def _run_tool(script: str, args: str) -> dict | list:
|
|
14
|
-
cmd = f"python3 {TOOLS_DIR}/{script} {args}"
|
|
15
|
-
try:
|
|
16
|
-
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding="utf-8", timeout=30)
|
|
17
|
-
if r.returncode == 0 and r.stdout.strip():
|
|
18
|
-
return json.loads(r.stdout)
|
|
19
|
-
except Exception:
|
|
20
|
-
pass
|
|
21
|
-
return {}
|
|
9
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
22
10
|
|
|
11
|
+
from _subproc import run_tool as _run_tool
|
|
23
12
|
|
|
24
13
|
INDEX_MAP = {
|
|
25
14
|
"A": ("000001", "上证综指"),
|
|
@@ -49,10 +38,7 @@ SKILL_RECOMMEND = {
|
|
|
49
38
|
|
|
50
39
|
def _get_index_kline(market: str) -> list:
|
|
51
40
|
code, _ = INDEX_MAP[market]
|
|
52
|
-
|
|
53
|
-
data = _run_tool("stock_data.py", f"kline {code} --period daily --count 80")
|
|
54
|
-
else:
|
|
55
|
-
data = _run_tool("stock_data.py", f"kline {code} --period daily --count 80")
|
|
41
|
+
data = _run_tool("stock_data.py", ["kline", code, "--period", "daily", "--count", "80"])
|
|
56
42
|
if isinstance(data, list) and len(data) > 0:
|
|
57
43
|
return data
|
|
58
44
|
return []
|
|
@@ -164,7 +150,7 @@ def classify_regime(ind: dict) -> tuple:
|
|
|
164
150
|
def _detect_sector_heat(market: str) -> bool:
|
|
165
151
|
if market != "A":
|
|
166
152
|
return False
|
|
167
|
-
data = _run_tool("stock_data.py", "sector_rankings --top 5 --direction both")
|
|
153
|
+
data = _run_tool("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"])
|
|
168
154
|
if not isinstance(data, dict):
|
|
169
155
|
return False
|
|
170
156
|
top = data.get("top", [])
|
package/tools/market_review.py
CHANGED
|
@@ -4,22 +4,12 @@
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import os
|
|
7
|
-
import subprocess
|
|
8
7
|
import sys
|
|
9
8
|
from concurrent.futures import ThreadPoolExecutor
|
|
10
9
|
|
|
11
|
-
|
|
10
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
12
11
|
|
|
13
|
-
|
|
14
|
-
def _run_tool(script: str, args: str, timeout: int = 30):
|
|
15
|
-
cmd = [sys.executable, os.path.join(TOOLS_DIR, script)] + args.split()
|
|
16
|
-
try:
|
|
17
|
-
r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=timeout)
|
|
18
|
-
if r.returncode == 0 and r.stdout.strip():
|
|
19
|
-
return json.loads(r.stdout)
|
|
20
|
-
except Exception:
|
|
21
|
-
pass
|
|
22
|
-
return None
|
|
12
|
+
from _subproc import run_tool as _run_tool
|
|
23
13
|
|
|
24
14
|
|
|
25
15
|
def calc_temperature(stats: dict, indices: list) -> dict:
|
|
@@ -80,19 +70,20 @@ def review_market(market: str = "A") -> dict:
|
|
|
80
70
|
tasks = {}
|
|
81
71
|
|
|
82
72
|
if market == "A":
|
|
83
|
-
tasks["indices"] = ("stock_data.py", "market_indices --region cn")
|
|
84
|
-
tasks["stats"] = ("stock_data.py", "market_stats --market A")
|
|
85
|
-
tasks["sectors"] = ("stock_data.py", "sector_rankings --top 5 --direction both")
|
|
86
|
-
|
|
87
|
-
tasks["
|
|
73
|
+
tasks["indices"] = ("stock_data.py", ["market_indices", "--region", "cn"])
|
|
74
|
+
tasks["stats"] = ("stock_data.py", ["market_stats", "--market", "A"])
|
|
75
|
+
tasks["sectors"] = ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"])
|
|
76
|
+
# query 含空格,必须保持单个 argv 元素
|
|
77
|
+
tasks["news"] = ("search_intel.py", ["search", "A股 今日 市场"])
|
|
78
|
+
tasks["regime"] = ("market_regime.py", ["detect", "A"])
|
|
88
79
|
elif market == "HK":
|
|
89
|
-
tasks["indices"] = ("stock_data.py", "market_indices --region hk")
|
|
90
|
-
tasks["news"] = ("search_intel.py", "search 港股 今日 市场")
|
|
91
|
-
tasks["regime"] = ("market_regime.py", "detect HK")
|
|
80
|
+
tasks["indices"] = ("stock_data.py", ["market_indices", "--region", "hk"])
|
|
81
|
+
tasks["news"] = ("search_intel.py", ["search", "港股 今日 市场"])
|
|
82
|
+
tasks["regime"] = ("market_regime.py", ["detect", "HK"])
|
|
92
83
|
elif market == "US":
|
|
93
|
-
tasks["indices"] = ("stock_data.py", "market_indices --region us")
|
|
94
|
-
tasks["news"] = ("search_intel.py", "search 美股 今日 市场")
|
|
95
|
-
tasks["regime"] = ("market_regime.py", "detect US")
|
|
84
|
+
tasks["indices"] = ("stock_data.py", ["market_indices", "--region", "us"])
|
|
85
|
+
tasks["news"] = ("search_intel.py", ["search", "美股 今日 市场"])
|
|
86
|
+
tasks["regime"] = ("market_regime.py", ["detect", "US"])
|
|
96
87
|
else:
|
|
97
88
|
return {"error": f"Unknown market: {market}"}
|
|
98
89
|
|
package/tools/risk_screening.py
CHANGED
|
@@ -4,22 +4,12 @@
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import os
|
|
7
|
-
import subprocess
|
|
8
7
|
import sys
|
|
9
8
|
from datetime import datetime, timedelta
|
|
10
9
|
|
|
11
|
-
|
|
10
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
12
11
|
|
|
13
|
-
|
|
14
|
-
def _run_tool(script: str, args: str) -> dict:
|
|
15
|
-
cmd = f"python3 {TOOLS_DIR}/{script} {args}"
|
|
16
|
-
try:
|
|
17
|
-
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, encoding="utf-8", timeout=30)
|
|
18
|
-
if r.returncode == 0 and r.stdout.strip():
|
|
19
|
-
return json.loads(r.stdout)
|
|
20
|
-
except Exception:
|
|
21
|
-
pass
|
|
22
|
-
return {}
|
|
12
|
+
from _subproc import run_tool as _run_tool
|
|
23
13
|
|
|
24
14
|
|
|
25
15
|
def _safe_float(val) -> float | None:
|
|
@@ -36,7 +26,7 @@ def _safe_float(val) -> float | None:
|
|
|
36
26
|
|
|
37
27
|
|
|
38
28
|
def check_valuation(symbol: str) -> dict:
|
|
39
|
-
quote = _run_tool("stock_data.py",
|
|
29
|
+
quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
|
|
40
30
|
pe = _safe_float(quote.get("pe"))
|
|
41
31
|
pb = _safe_float(quote.get("pb"))
|
|
42
32
|
result = {"pe": pe, "pb": pb, "status": "normal", "flags": []}
|
|
@@ -98,7 +88,7 @@ def check_valuation(symbol: str) -> dict:
|
|
|
98
88
|
|
|
99
89
|
|
|
100
90
|
def check_technical(symbol: str) -> dict:
|
|
101
|
-
ta = _run_tool("technical.py",
|
|
91
|
+
ta = _run_tool("technical.py", ["analyze", symbol])
|
|
102
92
|
result = {"flags": []}
|
|
103
93
|
|
|
104
94
|
if not ta or "error" in ta:
|
|
@@ -205,7 +195,7 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
|
|
|
205
195
|
}
|
|
206
196
|
result = {"flags": []}
|
|
207
197
|
for cat, query in categories.items():
|
|
208
|
-
data = _run_tool("search_intel.py",
|
|
198
|
+
data = _run_tool("search_intel.py", ["search", query, "--count", "3"])
|
|
209
199
|
items = []
|
|
210
200
|
if isinstance(data, list):
|
|
211
201
|
items = data
|
package/tools/stock_data.py
CHANGED
|
@@ -3,11 +3,14 @@
|
|
|
3
3
|
|
|
4
4
|
import argparse
|
|
5
5
|
import contextlib
|
|
6
|
+
import hashlib
|
|
6
7
|
import json
|
|
7
8
|
import re
|
|
8
9
|
import sys
|
|
10
|
+
import tempfile
|
|
9
11
|
import time
|
|
10
12
|
from datetime import datetime, timedelta
|
|
13
|
+
from pathlib import Path
|
|
11
14
|
|
|
12
15
|
|
|
13
16
|
def detect_market(symbol: str) -> str:
|
|
@@ -69,18 +72,18 @@ def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> f
|
|
|
69
72
|
return np.floor(pre_close * (1 + sign * ratio) * 100 + 0.5) / 100.0
|
|
70
73
|
|
|
71
74
|
|
|
72
|
-
def _failover(sources: list, label: str
|
|
73
|
-
"""
|
|
74
|
-
|
|
75
|
-
for
|
|
75
|
+
def _failover(sources: list, label: str):
|
|
76
|
+
"""Return first truthy result; else raise RuntimeError aggregating each source's error."""
|
|
77
|
+
errors = []
|
|
78
|
+
for name, fn in sources:
|
|
76
79
|
try:
|
|
77
80
|
result = fn()
|
|
78
81
|
if result:
|
|
79
82
|
return result
|
|
80
83
|
except Exception as e:
|
|
81
|
-
|
|
82
|
-
if
|
|
83
|
-
raise
|
|
84
|
+
errors.append(f"{name}: {type(e).__name__}: {e}")
|
|
85
|
+
if errors:
|
|
86
|
+
raise RuntimeError(f"{label}: {'; '.join(errors)}")
|
|
84
87
|
return None
|
|
85
88
|
|
|
86
89
|
|
|
@@ -94,7 +97,25 @@ def _akshare_retry(fn, *args, retries=2, delay=1, **kwargs):
|
|
|
94
97
|
time.sleep(delay)
|
|
95
98
|
|
|
96
99
|
|
|
100
|
+
# Index codes collide with SZ stocks in the 000xxx range (000001 is both the
|
|
101
|
+
# SSE Composite and Ping An Bank), so indices need an explicit exchange mapping.
|
|
102
|
+
_BAOSTOCK_INDEX_CODES = {
|
|
103
|
+
"000001": "sh", # 上证综指
|
|
104
|
+
"000016": "sh", # 上证50
|
|
105
|
+
"000300": "sh", # 沪深300
|
|
106
|
+
"000688": "sh", # 科创50
|
|
107
|
+
"000852": "sh", # 中证1000
|
|
108
|
+
"000905": "sh", # 中证500
|
|
109
|
+
"399001": "sz", # 深证成指
|
|
110
|
+
"399005": "sz", # 中小100
|
|
111
|
+
"399006": "sz", # 创业板指
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
97
115
|
def _to_baostock_code(symbol: str) -> str:
|
|
116
|
+
index_exchange = _BAOSTOCK_INDEX_CODES.get(symbol)
|
|
117
|
+
if index_exchange:
|
|
118
|
+
return f"{index_exchange}.{symbol}"
|
|
98
119
|
if symbol.startswith(
|
|
99
120
|
("600", "601", "603", "605", "688", "689", "510", "512", "513", "515", "516", "518", "560", "588")
|
|
100
121
|
):
|
|
@@ -377,6 +398,34 @@ def _quote_tushare(symbol: str) -> dict:
|
|
|
377
398
|
)
|
|
378
399
|
|
|
379
400
|
|
|
401
|
+
# Public TDX quote servers, tried in order — a datacenter IP often gets only
|
|
402
|
+
# some of them refused, so a single hardcoded endpoint is a needless failure mode.
|
|
403
|
+
_TDX_SERVERS = [
|
|
404
|
+
("119.147.212.81", 7709), # Tencent, Shenzhen
|
|
405
|
+
("180.153.18.170", 7709), # Shanghai
|
|
406
|
+
("202.108.253.130", 7709), # Beijing
|
|
407
|
+
("59.173.18.69", 7709), # Wuhan
|
|
408
|
+
]
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _pytdx_connect(api) -> None:
|
|
412
|
+
"""Connect to the first reachable TDX server.
|
|
413
|
+
|
|
414
|
+
pytdx's connect() returns True/False instead of raising (and is not a context
|
|
415
|
+
manager), so wrap it here to keep a failed connection from surfacing as a
|
|
416
|
+
misleading TypeError downstream.
|
|
417
|
+
"""
|
|
418
|
+
errors = []
|
|
419
|
+
for ip, port in _TDX_SERVERS:
|
|
420
|
+
try:
|
|
421
|
+
if api.connect(ip, port):
|
|
422
|
+
return
|
|
423
|
+
errors.append(f"{ip}:{port} refused")
|
|
424
|
+
except Exception as e:
|
|
425
|
+
errors.append(f"{ip}:{port} {e}")
|
|
426
|
+
raise ConnectionError(f"pytdx failed to connect to any TDX server ({'; '.join(errors)})")
|
|
427
|
+
|
|
428
|
+
|
|
380
429
|
def _kline_pytdx(symbol: str, period: str, count: int) -> list:
|
|
381
430
|
"""pytdx kline from TDX market servers. No credentials needed."""
|
|
382
431
|
from pytdx.hq import TdxHq_API
|
|
@@ -385,8 +434,11 @@ def _kline_pytdx(symbol: str, period: str, count: int) -> list:
|
|
|
385
434
|
freq_map = {"daily": 9, "weekly": 5, "monthly": 6}
|
|
386
435
|
|
|
387
436
|
api = TdxHq_API()
|
|
388
|
-
|
|
437
|
+
try:
|
|
438
|
+
_pytdx_connect(api)
|
|
389
439
|
data = api.get_security_bars(freq_map.get(period, 9), market, symbol, 0, count)
|
|
440
|
+
finally:
|
|
441
|
+
api.disconnect()
|
|
390
442
|
|
|
391
443
|
if not data:
|
|
392
444
|
raise ValueError("pytdx returned empty data")
|
|
@@ -416,8 +468,11 @@ def _quote_pytdx(symbol: str) -> dict:
|
|
|
416
468
|
market = 1 if symbol.startswith(("6", "9", "5")) else 0
|
|
417
469
|
|
|
418
470
|
api = TdxHq_API()
|
|
419
|
-
|
|
471
|
+
try:
|
|
472
|
+
_pytdx_connect(api)
|
|
420
473
|
data = api.get_security_quotes([(market, symbol)])
|
|
474
|
+
finally:
|
|
475
|
+
api.disconnect()
|
|
421
476
|
|
|
422
477
|
if not data:
|
|
423
478
|
raise ValueError("pytdx quote returned empty")
|
|
@@ -448,7 +503,9 @@ def _kline_yfinance(symbol: str, period: str, count: int) -> list:
|
|
|
448
503
|
days = count * 2 if period == "daily" else count * 10 if period == "weekly" else count * 35
|
|
449
504
|
start = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
450
505
|
|
|
451
|
-
df = yf.download(
|
|
506
|
+
df = yf.download(
|
|
507
|
+
_yf_hk_symbol(symbol), start=start, interval=period_map.get(period, "1d"), progress=False, auto_adjust=True
|
|
508
|
+
)
|
|
452
509
|
if df.empty:
|
|
453
510
|
raise ValueError(f"yfinance returned empty data for {symbol}")
|
|
454
511
|
df = df.reset_index()
|
|
@@ -792,7 +849,7 @@ def _quote_akshare(symbol: str) -> dict:
|
|
|
792
849
|
def _quote_yfinance(symbol: str) -> dict:
|
|
793
850
|
import yfinance as yf
|
|
794
851
|
|
|
795
|
-
t = yf.Ticker(symbol)
|
|
852
|
+
t = yf.Ticker(_yf_hk_symbol(symbol))
|
|
796
853
|
info = t.info
|
|
797
854
|
if not info or "regularMarketPrice" not in info:
|
|
798
855
|
raise ValueError(f"No data for {symbol}")
|
|
@@ -1020,7 +1077,7 @@ def cmd_news(args):
|
|
|
1020
1077
|
else:
|
|
1021
1078
|
import yfinance as yf
|
|
1022
1079
|
|
|
1023
|
-
t = yf.Ticker(args.symbol)
|
|
1080
|
+
t = yf.Ticker(_yf_hk_symbol(args.symbol))
|
|
1024
1081
|
news = t.news
|
|
1025
1082
|
if not news:
|
|
1026
1083
|
raise ValueError("yfinance news empty")
|
|
@@ -1069,7 +1126,7 @@ def financials_a(symbol: str) -> dict:
|
|
|
1069
1126
|
def financials_yf(symbol: str) -> dict:
|
|
1070
1127
|
import yfinance as yf
|
|
1071
1128
|
|
|
1072
|
-
t = yf.Ticker(symbol)
|
|
1129
|
+
t = yf.Ticker(_yf_hk_symbol(symbol))
|
|
1073
1130
|
info = t.info
|
|
1074
1131
|
return _clean_row(
|
|
1075
1132
|
{
|
|
@@ -1399,6 +1456,318 @@ def cmd_sector_rankings(args):
|
|
|
1399
1456
|
return {"error": str(e2)}
|
|
1400
1457
|
|
|
1401
1458
|
|
|
1459
|
+
# --------------- sector constituents / stock sectors (issue #18) ---------------
|
|
1460
|
+
|
|
1461
|
+
# No repo-wide disk-cache convention exists yet; tempdir keeps this cross-platform
|
|
1462
|
+
# (Windows has no ~/.cache). Sector membership changes slowly — 24h TTL.
|
|
1463
|
+
_SECTOR_CACHE_DIR = Path(tempfile.gettempdir()) / "pi-stock-analysis"
|
|
1464
|
+
_SECTOR_CACHE_TTL = 24 * 3600
|
|
1465
|
+
|
|
1466
|
+
|
|
1467
|
+
def _sector_cache_get(key: str):
|
|
1468
|
+
try:
|
|
1469
|
+
path = _SECTOR_CACHE_DIR / f"{key}.json"
|
|
1470
|
+
if path.exists() and time.time() - path.stat().st_mtime < _SECTOR_CACHE_TTL:
|
|
1471
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
1472
|
+
except Exception:
|
|
1473
|
+
pass
|
|
1474
|
+
return None
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def _sector_cache_set(key: str, data):
|
|
1478
|
+
try:
|
|
1479
|
+
_SECTOR_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
1480
|
+
(_SECTOR_CACHE_DIR / f"{key}.json").write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
1481
|
+
except Exception:
|
|
1482
|
+
pass
|
|
1483
|
+
|
|
1484
|
+
|
|
1485
|
+
def _fuzzy_match_sector(query: str, candidates: list):
|
|
1486
|
+
"""Resolve a possibly-partial sector name. Priority: exact match > the unique
|
|
1487
|
+
candidate containing the query. The query is normalized first (whitespace
|
|
1488
|
+
stripped, trailing 板块/行业/概念 suffix dropped) so 情报 phrasing like
|
|
1489
|
+
「创新药板块」 hits the board 创新药. The reverse direction (candidate inside
|
|
1490
|
+
the query) is deliberately not tried — it would absorb inputs like 创新药ETF
|
|
1491
|
+
into the 创新药 board. Ambiguous or no match returns None."""
|
|
1492
|
+
if query in candidates:
|
|
1493
|
+
return query
|
|
1494
|
+
q = re.sub(r"\s+", "", query)
|
|
1495
|
+
for suffix in ("板块", "行业", "概念"):
|
|
1496
|
+
if q.endswith(suffix):
|
|
1497
|
+
q = q[: -len(suffix)]
|
|
1498
|
+
if not q:
|
|
1499
|
+
return None
|
|
1500
|
+
if q in candidates:
|
|
1501
|
+
return q
|
|
1502
|
+
matches = [c for c in candidates if q in c]
|
|
1503
|
+
return matches[0] if len(matches) == 1 else None
|
|
1504
|
+
|
|
1505
|
+
|
|
1506
|
+
def _constituent_rows(df) -> list:
|
|
1507
|
+
col_map = {"代码": "code", "名称": "name"}
|
|
1508
|
+
df = df.rename(columns=col_map)
|
|
1509
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
1510
|
+
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1511
|
+
|
|
1512
|
+
|
|
1513
|
+
def _constituents_em(sector: str, board_kind: str) -> dict:
|
|
1514
|
+
"""Eastmoney industry/concept board constituents via akshare, fuzzy-resolved."""
|
|
1515
|
+
import akshare as ak
|
|
1516
|
+
|
|
1517
|
+
if board_kind == "industry":
|
|
1518
|
+
name_fn, cons_fn = ak.stock_board_industry_name_em, ak.stock_board_industry_cons_em
|
|
1519
|
+
else:
|
|
1520
|
+
name_fn, cons_fn = ak.stock_board_concept_name_em, ak.stock_board_concept_cons_em
|
|
1521
|
+
names_df = _akshare_retry(name_fn)
|
|
1522
|
+
if names_df is None or names_df.empty or "板块名称" not in names_df.columns:
|
|
1523
|
+
raise ValueError(f"eastmoney {board_kind} board list unavailable")
|
|
1524
|
+
exact = _fuzzy_match_sector(sector, [str(n) for n in names_df["板块名称"].tolist()])
|
|
1525
|
+
if not exact:
|
|
1526
|
+
raise ValueError(f"no eastmoney {board_kind} board matching '{sector}'")
|
|
1527
|
+
df = _akshare_retry(cons_fn, symbol=exact)
|
|
1528
|
+
if df is None or df.empty:
|
|
1529
|
+
raise ValueError(f"eastmoney {board_kind} board '{exact}' returned no constituents")
|
|
1530
|
+
constituents = _constituent_rows(df)
|
|
1531
|
+
return {
|
|
1532
|
+
"sector": exact,
|
|
1533
|
+
"board_type": board_kind,
|
|
1534
|
+
"source": "eastmoney",
|
|
1535
|
+
"constituents": constituents,
|
|
1536
|
+
"count": len(constituents),
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
|
|
1540
|
+
# Sina (indicator, board_type) pairs to search per board_type, tried in order — the
|
|
1541
|
+
# first fuzzy hit wins. 概念 carries concept boards (e.g. 白酒概念) and 地域 regional
|
|
1542
|
+
# ones, so a sina fallback restricted to 新浪行业 missed them entirely (issue #18 smoke test).
|
|
1543
|
+
_SINA_SECTOR_INDICATORS = {
|
|
1544
|
+
"industry": [("新浪行业", "industry"), ("行业", "industry")],
|
|
1545
|
+
"concept": [("概念", "concept")],
|
|
1546
|
+
"auto": [("新浪行业", "industry"), ("行业", "industry"), ("概念", "concept"), ("地域", "region")],
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
|
|
1550
|
+
def _constituents_sina_indicator(sector: str, indicator: str, board_type: str) -> dict:
|
|
1551
|
+
"""One sina indicator query: fuzzy-match the sector in the spot list, then fetch
|
|
1552
|
+
constituents. Raises on any failure so _failover moves to the next indicator."""
|
|
1553
|
+
import akshare as ak
|
|
1554
|
+
|
|
1555
|
+
spot = _akshare_retry(ak.stock_sector_spot, indicator=indicator)
|
|
1556
|
+
if spot is None or spot.empty or "label" not in spot.columns:
|
|
1557
|
+
raise ValueError(f"sina sector list unavailable (indicator={indicator})")
|
|
1558
|
+
name_col = "板块" if "板块" in spot.columns else "label"
|
|
1559
|
+
exact = _fuzzy_match_sector(sector, [str(n) for n in spot[name_col].tolist()])
|
|
1560
|
+
if not exact:
|
|
1561
|
+
raise ValueError(f"no sina board matching '{sector}' (indicator={indicator})")
|
|
1562
|
+
label = str(spot.loc[spot[name_col] == exact, "label"].iloc[0])
|
|
1563
|
+
df = _akshare_retry(ak.stock_sector_detail, sector=label)
|
|
1564
|
+
if df is None or df.empty:
|
|
1565
|
+
raise ValueError(f"sina board '{exact}' returned no constituents")
|
|
1566
|
+
constituents = _constituent_rows(df)
|
|
1567
|
+
return {
|
|
1568
|
+
"sector": exact,
|
|
1569
|
+
"board_type": board_type,
|
|
1570
|
+
"source": "sina",
|
|
1571
|
+
"constituents": constituents,
|
|
1572
|
+
"count": len(constituents),
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
|
|
1576
|
+
def _constituents_sina(sector: str, board_type: str = "auto") -> dict:
|
|
1577
|
+
"""Sina board constituents as fallback, fuzzy-resolved via the spot list(s)
|
|
1578
|
+
selected by board_type; the first indicator with a fuzzy hit wins."""
|
|
1579
|
+
indicators = _SINA_SECTOR_INDICATORS.get(board_type, _SINA_SECTOR_INDICATORS["auto"])
|
|
1580
|
+
sources = [(ind, lambda ind=ind, bt=bt: _constituents_sina_indicator(sector, ind, bt)) for ind, bt in indicators]
|
|
1581
|
+
return _failover(sources, label=f"sina:{sector}")
|
|
1582
|
+
|
|
1583
|
+
|
|
1584
|
+
def sector_constituents_a(sector: str, board_type: str = "auto") -> dict:
|
|
1585
|
+
"""A-share sector → constituents with failover: eastmoney industry/concept → sina."""
|
|
1586
|
+
sources = []
|
|
1587
|
+
if board_type in ("industry", "auto"):
|
|
1588
|
+
sources.append(("eastmoney_industry", lambda: _constituents_em(sector, "industry")))
|
|
1589
|
+
if board_type in ("concept", "auto"):
|
|
1590
|
+
sources.append(("eastmoney_concept", lambda: _constituents_em(sector, "concept")))
|
|
1591
|
+
sources.append(("sina", lambda: _constituents_sina(sector, board_type)))
|
|
1592
|
+
return _failover(sources, label=f"sector_constituents:{sector}")
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
def cmd_sector_constituents(args):
|
|
1596
|
+
# argparse 保证属性存在;空串仍可传入
|
|
1597
|
+
sector = args.sector.strip()
|
|
1598
|
+
if not sector:
|
|
1599
|
+
return {"error": "sector name required"}
|
|
1600
|
+
board_type = args.board_type
|
|
1601
|
+
# Sector names are user input — hash them instead of sanitizing, so names that
|
|
1602
|
+
# differ only in whitespace/punctuation (创新药 vs 创新 药) can't collide.
|
|
1603
|
+
cache_key = hashlib.sha256(f"{sector}|{board_type}".encode()).hexdigest()[:16]
|
|
1604
|
+
cached = _sector_cache_get(cache_key)
|
|
1605
|
+
if cached is not None:
|
|
1606
|
+
return cached
|
|
1607
|
+
try:
|
|
1608
|
+
result = sector_constituents_a(sector, board_type)
|
|
1609
|
+
except Exception as e:
|
|
1610
|
+
return {"error": str(e)}
|
|
1611
|
+
_sector_cache_set(cache_key, result)
|
|
1612
|
+
return result
|
|
1613
|
+
|
|
1614
|
+
|
|
1615
|
+
def _board_entry(name, source: str, board_type: str) -> dict:
|
|
1616
|
+
"""One stock→board membership record; keeps the {name, source, board_type}
|
|
1617
|
+
shape in one place instead of hand-building it per source."""
|
|
1618
|
+
return {"name": str(name), "source": source, "board_type": board_type}
|
|
1619
|
+
|
|
1620
|
+
|
|
1621
|
+
def _stock_boards_em(symbol: str, info_map=None) -> list:
|
|
1622
|
+
"""A-share industry board from eastmoney individual info. Pass an already-fetched
|
|
1623
|
+
info_map (item → value) to reuse it instead of hitting the network again."""
|
|
1624
|
+
if info_map is None:
|
|
1625
|
+
import akshare as ak
|
|
1626
|
+
|
|
1627
|
+
df = _akshare_retry(ak.stock_individual_info_em, symbol=symbol)
|
|
1628
|
+
if df is None or df.empty:
|
|
1629
|
+
raise ValueError("eastmoney individual info unavailable")
|
|
1630
|
+
info_map = {row.iloc[0]: row.iloc[1] for _, row in df.iterrows()}
|
|
1631
|
+
industry = info_map.get("行业")
|
|
1632
|
+
# pandas NaN is truthy — only a real string counts as an industry name
|
|
1633
|
+
if not (isinstance(industry, str) and industry):
|
|
1634
|
+
raise ValueError("eastmoney individual info has no industry")
|
|
1635
|
+
return [_board_entry(industry, "eastmoney", "industry")]
|
|
1636
|
+
|
|
1637
|
+
|
|
1638
|
+
def _stock_boards_efinance(symbol: str) -> list:
|
|
1639
|
+
"""A-share concept/membership boards from efinance."""
|
|
1640
|
+
import efinance as ef
|
|
1641
|
+
|
|
1642
|
+
df = ef.stock.get_belong_board(symbol)
|
|
1643
|
+
if df is None or df.empty or "板块名称" not in df.columns:
|
|
1644
|
+
raise ValueError("efinance belong-board unavailable")
|
|
1645
|
+
# pandas NaN is truthy and str(nan) == "nan" — drop non-string names or they
|
|
1646
|
+
# would pollute the dedup in resolve_stock_sectors as a bogus "nan" board
|
|
1647
|
+
return [
|
|
1648
|
+
_board_entry(name, "efinance", "concept") for name in df["板块名称"].tolist() if isinstance(name, str) and name
|
|
1649
|
+
]
|
|
1650
|
+
|
|
1651
|
+
|
|
1652
|
+
def _xq_symbol(symbol: str) -> str:
|
|
1653
|
+
"""Xueqiu codes are exchange-prefixed: 600519 → SH600519, 000858 → SZ000858."""
|
|
1654
|
+
if symbol.startswith(("4", "8", "92")):
|
|
1655
|
+
return f"BJ{symbol}"
|
|
1656
|
+
return f"SH{symbol}" if symbol.startswith(("5", "6", "9")) else f"SZ{symbol}"
|
|
1657
|
+
|
|
1658
|
+
|
|
1659
|
+
def _stock_boards_xueqiu(symbol: str) -> list:
|
|
1660
|
+
"""A-share industry board from the Xueqiu F10 company profile — the non-eastmoney
|
|
1661
|
+
fallback. Returns [] (source skipped) unless XUEQIU_TOKEN is set: akshare's
|
|
1662
|
+
built-in xq_a_token is stale (xueqiu answers 400016), so a user token is required."""
|
|
1663
|
+
import os
|
|
1664
|
+
|
|
1665
|
+
token = os.environ.get("XUEQIU_TOKEN", "")
|
|
1666
|
+
if not token:
|
|
1667
|
+
return []
|
|
1668
|
+
import akshare as ak
|
|
1669
|
+
|
|
1670
|
+
df = _akshare_retry(ak.stock_individual_basic_info_xq, symbol=_xq_symbol(symbol), token=token)
|
|
1671
|
+
if df is None or df.empty:
|
|
1672
|
+
raise ValueError("xueqiu basic info unavailable")
|
|
1673
|
+
info_map = {row.iloc[0]: row.iloc[1] for _, row in df.iterrows()}
|
|
1674
|
+
# affiliate_industry is a nested dict: {'ind_code': 'BK0025', 'ind_name': '汽车整车'}
|
|
1675
|
+
industry = info_map.get("affiliate_industry")
|
|
1676
|
+
name = industry.get("ind_name") if isinstance(industry, dict) else None
|
|
1677
|
+
# pandas NaN is truthy — only a real string counts as an industry name
|
|
1678
|
+
if not (isinstance(name, str) and name):
|
|
1679
|
+
raise ValueError("xueqiu basic info has no industry")
|
|
1680
|
+
return [_board_entry(name, "xueqiu", "industry")]
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
def _stock_boards_from_cache(symbol: str) -> list:
|
|
1684
|
+
"""Reverse lookup against the get_sector_constituents disk cache — the honest
|
|
1685
|
+
fallback when eastmoney blocks the caller's IP and xueqiu has no token (the two
|
|
1686
|
+
live A-share sources are both eastmoney-flavored). Reads every unexpired
|
|
1687
|
+
constituents payload in the cache dir and returns one entry per cached sector
|
|
1688
|
+
containing the symbol. Cold cache → []; malformed cache files are skipped
|
|
1689
|
+
(_sector_cache_get returns None on expiry, bad JSON, or read errors)."""
|
|
1690
|
+
boards = []
|
|
1691
|
+
for path in _SECTOR_CACHE_DIR.glob("*.json"):
|
|
1692
|
+
data = _sector_cache_get(path.stem)
|
|
1693
|
+
if not isinstance(data, dict):
|
|
1694
|
+
continue
|
|
1695
|
+
sector = data.get("sector")
|
|
1696
|
+
if not sector:
|
|
1697
|
+
continue
|
|
1698
|
+
for row in data.get("constituents") or []:
|
|
1699
|
+
if isinstance(row, dict) and str(row.get("code")) == symbol:
|
|
1700
|
+
boards.append(_board_entry(sector, "cache", data.get("board_type", "")))
|
|
1701
|
+
break
|
|
1702
|
+
return boards
|
|
1703
|
+
|
|
1704
|
+
|
|
1705
|
+
def _yf_hk_symbol(symbol: str) -> str:
|
|
1706
|
+
"""Yahoo HK tickers are zero-padded to exactly 4 digits: 01801.HK → 1801.HK.
|
|
1707
|
+
A bare lstrip('0') would turn 0700.HK into the bogus 700.HK, so pad back."""
|
|
1708
|
+
code, sep, suffix = symbol.upper().partition(".HK")
|
|
1709
|
+
if not sep or not code.isdigit():
|
|
1710
|
+
return symbol
|
|
1711
|
+
return f"{code.lstrip('0').zfill(4)}{sep}{suffix}"
|
|
1712
|
+
|
|
1713
|
+
|
|
1714
|
+
def _stock_sectors_hk(symbol: str) -> list:
|
|
1715
|
+
"""HK stock GICS sector/industry from yfinance (English names). Retries ride on
|
|
1716
|
+
_akshare_retry — despite the name it is a generic fn(*args, retries=2, delay=1) wrapper."""
|
|
1717
|
+
import yfinance as yf
|
|
1718
|
+
|
|
1719
|
+
# 5-digit inputs like 01801.HK 404 on Yahoo — normalize; the caller keeps the
|
|
1720
|
+
# user's original symbol for the result payload.
|
|
1721
|
+
yf_symbol = _yf_hk_symbol(symbol)
|
|
1722
|
+
info = _akshare_retry(lambda: yf.Ticker(yf_symbol).info) or {}
|
|
1723
|
+
sectors = [_board_entry(info[key], "yfinance", "gics") for key in ("sector", "industry") if info.get(key)]
|
|
1724
|
+
if not sectors:
|
|
1725
|
+
raise ValueError(f"no sector info for {symbol}")
|
|
1726
|
+
return sectors
|
|
1727
|
+
|
|
1728
|
+
|
|
1729
|
+
def resolve_stock_sectors(symbol: str, info_map=None) -> dict:
|
|
1730
|
+
"""Reverse map: stock → boards it belongs to (A/HK). A single source failing
|
|
1731
|
+
is not fatal — the other source's boards are still returned. An already-fetched
|
|
1732
|
+
eastmoney info_map is reused for the em source instead of re-fetching."""
|
|
1733
|
+
market = detect_market(symbol)
|
|
1734
|
+
result = {"symbol": symbol, "market": market}
|
|
1735
|
+
if market == "A":
|
|
1736
|
+
sources = [
|
|
1737
|
+
("eastmoney", lambda: _stock_boards_em(symbol, info_map)),
|
|
1738
|
+
("efinance", lambda: _stock_boards_efinance(symbol)),
|
|
1739
|
+
("xueqiu", lambda: _stock_boards_xueqiu(symbol)),
|
|
1740
|
+
("cache", lambda: _stock_boards_from_cache(symbol)),
|
|
1741
|
+
]
|
|
1742
|
+
elif market == "HK":
|
|
1743
|
+
sources = [("yfinance", lambda: _stock_sectors_hk(symbol))]
|
|
1744
|
+
else:
|
|
1745
|
+
result["error"] = f"resolve_stock_sectors only supports A-share and HK stocks, got market {market}"
|
|
1746
|
+
return result
|
|
1747
|
+
sectors, errors = [], []
|
|
1748
|
+
for name, fn in sources:
|
|
1749
|
+
try:
|
|
1750
|
+
sectors.extend(fn() or [])
|
|
1751
|
+
except Exception as e:
|
|
1752
|
+
errors.append(f"{name}: {type(e).__name__}: {e}")
|
|
1753
|
+
seen = set()
|
|
1754
|
+
deduped = []
|
|
1755
|
+
for s in sectors:
|
|
1756
|
+
if s["name"] not in seen:
|
|
1757
|
+
seen.add(s["name"])
|
|
1758
|
+
deduped.append(s)
|
|
1759
|
+
if not deduped:
|
|
1760
|
+
error = "; ".join(errors) or "no sector data"
|
|
1761
|
+
if market == "A":
|
|
1762
|
+
# em/efinance are both eastmoney-flavored and xueqiu is usually untokened,
|
|
1763
|
+
# so an all-empty A-share result almost always means eastmoney blocked us.
|
|
1764
|
+
error += "; 东财不可用且缓存为空,可先跑 get_sector_constituents 预热或设置 XUEQIU_TOKEN"
|
|
1765
|
+
result["error"] = error
|
|
1766
|
+
return result
|
|
1767
|
+
result["sectors"] = deduped
|
|
1768
|
+
return result
|
|
1769
|
+
|
|
1770
|
+
|
|
1402
1771
|
# --------------- stock_info ---------------
|
|
1403
1772
|
|
|
1404
1773
|
|
|
@@ -1409,6 +1778,7 @@ def cmd_stock_info(args):
|
|
|
1409
1778
|
import akshare as ak
|
|
1410
1779
|
|
|
1411
1780
|
result = {"symbol": args.symbol, "market": "A"}
|
|
1781
|
+
info_map = None
|
|
1412
1782
|
try:
|
|
1413
1783
|
df = _akshare_retry(ak.stock_individual_info_em, symbol=args.symbol)
|
|
1414
1784
|
if df is not None and not df.empty:
|
|
@@ -1425,16 +1795,18 @@ def cmd_stock_info(args):
|
|
|
1425
1795
|
except Exception:
|
|
1426
1796
|
pass
|
|
1427
1797
|
try:
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1798
|
+
# boards 复用 resolve_stock_sectors;info_map 透传避免东财二次拉取
|
|
1799
|
+
resolved = resolve_stock_sectors(args.symbol, info_map=info_map)
|
|
1800
|
+
boards = [s["name"] for s in resolved.get("sectors", [])]
|
|
1801
|
+
if boards:
|
|
1802
|
+
result["boards"] = boards[:10]
|
|
1431
1803
|
except Exception:
|
|
1432
1804
|
pass
|
|
1433
1805
|
return _clean_row(result)
|
|
1434
1806
|
else:
|
|
1435
1807
|
import yfinance as yf
|
|
1436
1808
|
|
|
1437
|
-
t = yf.Ticker(args.symbol)
|
|
1809
|
+
t = yf.Ticker(_yf_hk_symbol(args.symbol))
|
|
1438
1810
|
info = t.info
|
|
1439
1811
|
return _clean_row(
|
|
1440
1812
|
{
|
|
@@ -1685,6 +2057,13 @@ def main():
|
|
|
1685
2057
|
p_sec.add_argument("--top", type=int, default=10)
|
|
1686
2058
|
p_sec.add_argument("--direction", default="top", choices=["top", "bottom", "both"])
|
|
1687
2059
|
|
|
2060
|
+
p_cons = sub.add_parser("sector_constituents")
|
|
2061
|
+
p_cons.add_argument("sector")
|
|
2062
|
+
p_cons.add_argument("--board-type", default="auto", choices=["industry", "concept", "auto"])
|
|
2063
|
+
|
|
2064
|
+
p_rss = sub.add_parser("resolve_stock_sectors")
|
|
2065
|
+
p_rss.add_argument("symbol")
|
|
2066
|
+
|
|
1688
2067
|
p_info = sub.add_parser("stock_info")
|
|
1689
2068
|
p_info.add_argument("symbol")
|
|
1690
2069
|
|
|
@@ -1711,6 +2090,8 @@ def main():
|
|
|
1711
2090
|
"market_snapshot": cmd_market_snapshot,
|
|
1712
2091
|
"market_indices": cmd_market_indices,
|
|
1713
2092
|
"sector_rankings": cmd_sector_rankings,
|
|
2093
|
+
"sector_constituents": cmd_sector_constituents,
|
|
2094
|
+
"resolve_stock_sectors": lambda a: resolve_stock_sectors(a.symbol),
|
|
1714
2095
|
"stock_info": cmd_stock_info,
|
|
1715
2096
|
"chip_distribution": cmd_chip_distribution,
|
|
1716
2097
|
"market_stats": cmd_market_stats,
|