@weaxs/openclaw-stock-analysis 0.1.11 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Stock Analysis — OpenClaw Plugin
2
2
 
3
- A股 / 港股 / 美股 / 日股 / 韩股 / 台股 行情、技术分析、筛选与回测。OpenClaw Gateway 加载后即可在对话中调用 39 个工具。
3
+ A股 / 港股 / 美股 / 日股 / 韩股 / 台股 行情、技术分析、筛选与回测。OpenClaw Gateway 加载后即可在对话中调用 41 个工具。
4
4
 
5
5
  ## 安装
6
6
 
@@ -39,6 +39,8 @@ npm install
39
39
  ### 市场全景
40
40
  - `get_market_indices` — 主要指数(CN/HK/US/JP/KR/TW)
41
41
  - `get_sector_rankings` — A股板块涨跌幅排行
42
+ - `get_sector_constituents` — A股板块成分股查询(板块名模糊匹配)
43
+ - `resolve_stock_sectors` — 个股所属板块查询(A股行业+概念 / 港股 GICS)
42
44
  - `get_market_stats` — A股大盘统计
43
45
  - `get_stock_info` — 股票基本信息
44
46
  - `get_chip_distribution` — A股筹码分布
package/dist/index.js CHANGED
@@ -4650,6 +4650,42 @@ var index_default = definePluginEntry({
4650
4650
  return asText(out);
4651
4651
  }
4652
4652
  });
4653
+ api.registerTool({
4654
+ name: "get_sector_constituents",
4655
+ description: "\u67E5\u8BE2A\u80A1\u677F\u5757\u6210\u5206\u80A1\uFF08\u6B63\u5411\u6620\u5C04\uFF1A\u677F\u5757\u2192\u80A1\u7968\u5217\u8868\uFF09\u3002\u677F\u5757\u540D\u652F\u6301\u6A21\u7CCA\u5339\u914D\uFF08\u5982\u300C\u521B\u65B0\u836F\u300D\u81EA\u52A8\u89E3\u6790\u5230\u7CBE\u786E\u677F\u5757\u540D\uFF09\uFF0C\u4E1C\u8D22\u884C\u4E1A/\u6982\u5FF5 + \u65B0\u6D6A\u591A\u6E90 failover\uFF0C\u7ED3\u679C\u7F13\u5B5824\u5C0F\u65F6\u3002\u4EC5\u652F\u6301A\u80A1\uFF1B\u53CD\u5411\u67E5\u4E2A\u80A1\u6240\u5C5E\u677F\u5757\u7528 resolve_stock_sectors",
4656
+ parameters: typebox_exports.Object({
4657
+ sector: typebox_exports.String({ description: "\u677F\u5757\u540D\u79F0\uFF08\u53EF\u6A21\u7CCA\uFF0C\u5982 \u521B\u65B0\u836F\u3001\u534A\u5BFC\u4F53\uFF09" }),
4658
+ board_type: typebox_exports.Optional(
4659
+ typebox_exports.Union(
4660
+ [typebox_exports.Literal("industry"), typebox_exports.Literal("concept"), typebox_exports.Literal("auto")],
4661
+ { description: "\u677F\u5757\u7C7B\u578B\uFF1Aindustry=\u884C\u4E1A\uFF0Cconcept=\u6982\u5FF5\uFF0Cauto=\u81EA\u52A8\uFF08\u9ED8\u8BA4\uFF09" }
4662
+ )
4663
+ )
4664
+ }),
4665
+ async execute(_id, params) {
4666
+ const out = await runPy("stock_data.py", [
4667
+ "sector_constituents",
4668
+ params.sector,
4669
+ "--board-type",
4670
+ params.board_type ?? "auto"
4671
+ ]);
4672
+ return asText(out);
4673
+ }
4674
+ });
4675
+ api.registerTool({
4676
+ name: "resolve_stock_sectors",
4677
+ description: "\u67E5\u8BE2\u4E2A\u80A1\u6240\u5C5E\u677F\u5757\uFF08\u53CD\u5411\u6620\u5C04\uFF1A\u4E2A\u80A1\u2192\u677F\u5757\uFF09\u3002A\u80A1\u8FD4\u56DE\u4E1C\u8D22\u884C\u4E1A + efinance \u6982\u5FF5/\u677F\u5757\uFF08\u96EA\u7403\u884C\u4E1A\u515C\u5E95\uFF0C\u9700 XUEQIU_TOKEN\uFF09\uFF0C\u6E2F\u80A1\u8FD4\u56DE yfinance GICS \u82F1\u6587 sector/industry \u53E3\u5F84\u3002\u677F\u5757\u7EA7\u60C5\u62A5\uFF08\u5982\u300C\u521B\u65B0\u836F\u56DE\u8C03\u300D\uFF09\u6620\u5C04\u5230\u6C60\u5185\u4E2A\u80A1\u65F6\u8C03\u672C\u5DE5\u5177\uFF1B\u6B63\u5411\u67E5\u677F\u5757\u6210\u5206\u80A1\u7528 get_sector_constituents",
4678
+ parameters: typebox_exports.Object({
4679
+ symbol: typebox_exports.String({ description: "\u80A1\u7968\u4EE3\u7801\uFF08A\u80A1\u5982 600519\uFF0C\u6E2F\u80A1\u5982 00700.HK\uFF09" })
4680
+ }),
4681
+ async execute(_id, params) {
4682
+ const out = await runPy("stock_data.py", [
4683
+ "resolve_stock_sectors",
4684
+ params.symbol
4685
+ ]);
4686
+ return asText(out);
4687
+ }
4688
+ });
4653
4689
  api.registerTool({
4654
4690
  name: "get_stock_info",
4655
4691
  description: "\u83B7\u53D6\u80A1\u7968\u57FA\u672C\u4FE1\u606F\uFF08\u884C\u4E1A\u3001\u677F\u5757\u3001\u4E0A\u5E02\u65E5\u671F\u3001\u603B\u80A1\u672C\u7B49\uFF09\u3002A\u80A1\u8FD4\u56DE\u677F\u5757/\u884C\u4E1A\uFF0C\u5176\u4ED6\u5E02\u573A\u8FD4\u56DE\u884C\u4E1A/\u516C\u53F8\u7B80\u4ECB",
package/index.ts CHANGED
@@ -269,6 +269,46 @@ export default definePluginEntry({
269
269
  },
270
270
  });
271
271
 
272
+ api.registerTool({
273
+ name: "get_sector_constituents",
274
+ description:
275
+ "查询A股板块成分股(正向映射:板块→股票列表)。板块名支持模糊匹配(如「创新药」自动解析到精确板块名),东财行业/概念 + 新浪多源 failover,结果缓存24小时。仅支持A股;反向查个股所属板块用 resolve_stock_sectors",
276
+ parameters: Type.Object({
277
+ sector: Type.String({ description: "板块名称(可模糊,如 创新药、半导体)" }),
278
+ board_type: Type.Optional(
279
+ Type.Union(
280
+ [Type.Literal("industry"), Type.Literal("concept"), Type.Literal("auto")],
281
+ { description: "板块类型:industry=行业,concept=概念,auto=自动(默认)" }
282
+ )
283
+ ),
284
+ }),
285
+ async execute(_id, params) {
286
+ const out = await runPy("stock_data.py", [
287
+ "sector_constituents",
288
+ params.sector,
289
+ "--board-type",
290
+ params.board_type ?? "auto",
291
+ ]);
292
+ return asText(out);
293
+ },
294
+ });
295
+
296
+ api.registerTool({
297
+ name: "resolve_stock_sectors",
298
+ description:
299
+ "查询个股所属板块(反向映射:个股→板块)。A股返回东财行业 + efinance 概念/板块(雪球行业兜底,需 XUEQIU_TOKEN),港股返回 yfinance GICS 英文 sector/industry 口径。板块级情报(如「创新药回调」)映射到池内个股时调本工具;正向查板块成分股用 get_sector_constituents",
300
+ parameters: Type.Object({
301
+ symbol: Type.String({ description: "股票代码(A股如 600519,港股如 00700.HK)" }),
302
+ }),
303
+ async execute(_id, params) {
304
+ const out = await runPy("stock_data.py", [
305
+ "resolve_stock_sectors",
306
+ params.symbol,
307
+ ]);
308
+ return asText(out);
309
+ },
310
+ });
311
+
272
312
  api.registerTool({
273
313
  name: "get_stock_info",
274
314
  description:
@@ -13,6 +13,8 @@
13
13
  "analyze_pattern",
14
14
  "get_market_indices",
15
15
  "get_sector_rankings",
16
+ "get_sector_constituents",
17
+ "resolve_stock_sectors",
16
18
  "get_stock_info",
17
19
  "get_chip_distribution",
18
20
  "get_market_stats",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weaxs/openclaw-stock-analysis",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "OpenClaw plugin for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -22,6 +22,8 @@ allowed-tools: Bash(python3:*) Read
22
22
  python3 scripts/gather.py <symbol>
23
23
  ```
24
24
 
25
+ 同时用 resolve_stock_sectors 确认个股所属板块,再用 get_sector_constituents 拉取同板块个股列表——后续「龙头 vs 跟风」的强弱对比都在这个板块池内进行。
26
+
25
27
  ### 2. 龙头股特征识别
26
28
 
27
29
  **一字特征**(最强龙头):
@@ -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
@@ -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", f"capital_flow {symbol} --mode detail")
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", f"quote {symbol}") or {}
494
+ quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
509
495
 
510
496
  anomalies = []
511
497
  anomalies.extend(detect_macd_cross(close))
@@ -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"},
@@ -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),
@@ -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
- TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
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
- if market == "A":
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", [])
@@ -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
- TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
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
- tasks["news"] = ("search_intel.py", "search A股 今日 市场")
87
- tasks["regime"] = ("market_regime.py", "detect A")
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
 
@@ -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
- TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
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", f"quote {symbol}")
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", f"analyze {symbol}")
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", f'search "{query}" --max 3')
198
+ data = _run_tool("search_intel.py", ["search", query, "--count", "3"])
209
199
  items = []
210
200
  if isinstance(data, list):
211
201
  items = data
@@ -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
- """Try each (name, fn) in order; return first success or raise last error."""
74
- last_err = None
75
- for _name, fn in sources:
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
- last_err = e
82
- if last_err:
83
- raise last_err
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
- with api.connect("119.147.212.81", 7709):
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
- with api.connect("119.147.212.81", 7709):
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(symbol, start=start, interval=period_map.get(period, "1d"), progress=False, auto_adjust=True)
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
- board_df = _akshare_retry(ak.stock_board_industry_cons_em, symbol=args.symbol)
1429
- if board_df is not None and not board_df.empty and "板块名称" in board_df.columns:
1430
- result["boards"] = board_df["板块名称"].tolist()[:10]
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,