stock-analysis-plugin 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +498 -0
  2. package/package.json +88 -0
  3. package/pi/index.ts +1142 -0
  4. package/schemas/market_review_schema.json +176 -0
  5. package/schemas/report_schema.json +131 -0
  6. package/scripts/setup-python.mjs +57 -0
  7. package/scripts/sync-version.sh +56 -0
  8. package/scripts/venv-python.mjs +20 -0
  9. package/skills/bottom-volume/SKILL.md +63 -0
  10. package/skills/bottom-volume/scripts/gather.py +22 -0
  11. package/skills/box-oscillation/SKILL.md +72 -0
  12. package/skills/box-oscillation/scripts/gather.py +22 -0
  13. package/skills/bull-trend/SKILL.md +60 -0
  14. package/skills/bull-trend/scripts/gather.py +22 -0
  15. package/skills/chan-theory/SKILL.md +71 -0
  16. package/skills/chan-theory/scripts/gather.py +22 -0
  17. package/skills/dragon-head/SKILL.md +69 -0
  18. package/skills/dragon-head/scripts/gather.py +22 -0
  19. package/skills/emotion-cycle/SKILL.md +65 -0
  20. package/skills/emotion-cycle/scripts/gather.py +22 -0
  21. package/skills/event-driven/SKILL.md +73 -0
  22. package/skills/event-driven/scripts/gather.py +22 -0
  23. package/skills/expectation-repricing/SKILL.md +72 -0
  24. package/skills/expectation-repricing/scripts/gather.py +22 -0
  25. package/skills/growth-quality/SKILL.md +74 -0
  26. package/skills/growth-quality/scripts/gather.py +22 -0
  27. package/skills/hot-theme/SKILL.md +74 -0
  28. package/skills/hot-theme/scripts/gather.py +22 -0
  29. package/skills/ma-crossover/SKILL.md +63 -0
  30. package/skills/ma-crossover/scripts/gather.py +22 -0
  31. package/skills/market-review/SKILL.md +70 -0
  32. package/skills/market-review/scripts/gather.py +23 -0
  33. package/skills/one-yang-three-yin/SKILL.md +74 -0
  34. package/skills/one-yang-three-yin/scripts/gather.py +22 -0
  35. package/skills/shrink-pullback/SKILL.md +59 -0
  36. package/skills/shrink-pullback/scripts/gather.py +22 -0
  37. package/skills/stock-analysis/SKILL.md +134 -0
  38. package/skills/stock-analysis/scripts/gather.py +22 -0
  39. package/skills/stock-screener/SKILL.md +68 -0
  40. package/skills/stock-screener/scripts/gather.py +22 -0
  41. package/skills/strategy-backtest/SKILL.md +129 -0
  42. package/skills/strategy-backtest/scripts/gather.py +23 -0
  43. package/skills/volume-breakout/SKILL.md +58 -0
  44. package/skills/volume-breakout/scripts/gather.py +22 -0
  45. package/skills/wave-theory/SKILL.md +67 -0
  46. package/skills/wave-theory/scripts/gather.py +22 -0
  47. package/skills/wisburg-research/SKILL.md +119 -0
  48. package/strategies/examples/bottom_volume.yaml +47 -0
  49. package/strategies/examples/box_oscillation.yaml +41 -0
  50. package/strategies/examples/bull_trend.yaml +42 -0
  51. package/strategies/examples/dragon_head.yaml +45 -0
  52. package/strategies/examples/emotion_cycle.yaml +43 -0
  53. package/strategies/examples/ma_crossover.yaml +34 -0
  54. package/strategies/examples/rsi_oversold.yaml +35 -0
  55. package/strategies/examples/shrink_pullback.yaml +45 -0
  56. package/strategies/examples/volume_breakout.yaml +42 -0
  57. package/templates/_macros.j2 +90 -0
  58. package/templates/market_review/full.md.j2 +103 -0
  59. package/templates/stock_analysis/brief.md.j2 +28 -0
  60. package/templates/stock_analysis/full.md.j2 +108 -0
  61. package/tools/__init__.py +0 -0
  62. package/tools/alert_rules.py +243 -0
  63. package/tools/anomaly_detect.py +575 -0
  64. package/tools/backtest.py +764 -0
  65. package/tools/capabilities.py +108 -0
  66. package/tools/diagnostics.py +146 -0
  67. package/tools/gather.py +157 -0
  68. package/tools/import_parser.py +279 -0
  69. package/tools/market_regime.py +252 -0
  70. package/tools/market_review.py +155 -0
  71. package/tools/name_resolver.py +136 -0
  72. package/tools/pattern.py +515 -0
  73. package/tools/position_context.py +161 -0
  74. package/tools/report_renderer.py +116 -0
  75. package/tools/requirements.txt +15 -0
  76. package/tools/risk_screening.py +323 -0
  77. package/tools/screener.py +219 -0
  78. package/tools/search_intel.py +504 -0
  79. package/tools/stock_data.py +1721 -0
  80. package/tools/technical.py +642 -0
  81. package/tools/trading_calendar.py +226 -0
  82. package/tools/volume_analysis.py +178 -0
  83. package/tools/watchlist.py +66 -0
  84. package/tools/watchlist_context.py +185 -0
@@ -0,0 +1,252 @@
1
+ #!/usr/bin/env python3
2
+ """Market regime detection — classify market phase to guide strategy selection."""
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+
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 {}
22
+
23
+
24
+ INDEX_MAP = {
25
+ "A": ("000001", "上证综指"),
26
+ "HK": ("HSI", "恒生指数"),
27
+ "US": ("^GSPC", "标普500"),
28
+ }
29
+
30
+ REGIME_CN = {
31
+ "trending_up": "上涨趋势",
32
+ "trending_down": "下跌趋势",
33
+ "sideways": "横盘震荡",
34
+ "volatile": "高波动",
35
+ "mixed": "混合状态",
36
+ }
37
+
38
+ SKILL_RECOMMEND = {
39
+ "trending_up": {
40
+ "recommend": ["bull-trend", "volume-breakout", "ma-crossover", "dragon-head"],
41
+ "avoid": ["bottom-volume"],
42
+ },
43
+ "trending_down": {"recommend": ["shrink-pullback", "bottom-volume"], "avoid": ["bull-trend", "volume-breakout"]},
44
+ "sideways": {"recommend": ["box-oscillation", "shrink-pullback"], "avoid": ["dragon-head"]},
45
+ "volatile": {"recommend": ["chan-theory", "wave-theory", "emotion-cycle"], "avoid": ["bull-trend"]},
46
+ "mixed": {"recommend": ["shrink-pullback", "chan-theory"], "avoid": []},
47
+ }
48
+
49
+
50
+ def _get_index_kline(market: str) -> list:
51
+ 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")
56
+ if isinstance(data, list) and len(data) > 0:
57
+ return data
58
+ return []
59
+
60
+
61
+ def _compute_indicators(klines: list) -> dict:
62
+ import numpy as np
63
+
64
+ closes = np.array([float(k["close"]) for k in klines if k.get("close") is not None])
65
+ if len(closes) < 20:
66
+ return {}
67
+
68
+ def ma(n):
69
+ return np.mean(closes[-n:]) if len(closes) >= n else np.mean(closes)
70
+
71
+ ma5 = ma(5)
72
+ ma10 = ma(10)
73
+ ma20 = ma(20)
74
+ ma60 = ma(60) if len(closes) >= 60 else ma(len(closes))
75
+ close = closes[-1]
76
+
77
+ highs = np.array([float(k["high"]) for k in klines if k.get("high") is not None])
78
+ lows = np.array([float(k["low"]) for k in klines if k.get("low") is not None])
79
+
80
+ tr_values = []
81
+ for i in range(-min(14, len(closes) - 1), 0):
82
+ tr = max(highs[i] - lows[i], abs(highs[i] - closes[i - 1]), abs(lows[i] - closes[i - 1]))
83
+ tr_values.append(tr)
84
+ atr = np.mean(tr_values) if tr_values else 0
85
+ atr_ratio = atr / close if close > 0 else 0
86
+
87
+ upper = ma20 + 2 * np.std(closes[-20:])
88
+ lower = ma20 - 2 * np.std(closes[-20:])
89
+ boll_width = (upper - lower) / ma20 if ma20 > 0 else 0
90
+
91
+ gains, losses = [], []
92
+ for i in range(1, min(15, len(closes))):
93
+ diff = closes[-i] - closes[-i - 1]
94
+ if diff > 0:
95
+ gains.append(diff)
96
+ else:
97
+ losses.append(abs(diff))
98
+ avg_gain = np.mean(gains) if gains else 0
99
+ avg_loss = np.mean(losses) if losses else 1
100
+ rs = avg_gain / avg_loss if avg_loss > 0 else 100
101
+ rsi14 = 100 - (100 / (1 + rs))
102
+
103
+ ema12 = np.mean(closes[-12:])
104
+ ema26 = np.mean(closes[-26:]) if len(closes) >= 26 else np.mean(closes)
105
+ macd_diff = ema12 - ema26
106
+ macd_trend = "bullish" if macd_diff > 0 else "bearish"
107
+
108
+ ma_spread = abs(ma5 - ma20) / ma20 if ma20 > 0 else 0
109
+
110
+ prev_close = closes[-2] if len(closes) >= 2 else close
111
+ change_pct = (close - prev_close) / prev_close * 100 if prev_close > 0 else 0
112
+
113
+ return {
114
+ "ma5": round(ma5, 2),
115
+ "ma10": round(ma10, 2),
116
+ "ma20": round(ma20, 2),
117
+ "ma60": round(ma60, 2),
118
+ "close": round(close, 2),
119
+ "change_pct": round(change_pct, 2),
120
+ "atr_ratio": round(atr_ratio, 4),
121
+ "boll_width": round(boll_width, 4),
122
+ "rsi14": round(rsi14, 1),
123
+ "macd_trend": macd_trend,
124
+ "ma_spread_pct": round(ma_spread * 100, 2),
125
+ }
126
+
127
+
128
+ def classify_regime(ind: dict) -> tuple:
129
+ ma5 = ind["ma5"]
130
+ ma10 = ind["ma10"]
131
+ ma20 = ind["ma20"]
132
+ ma60 = ind["ma60"]
133
+ close = ind["close"]
134
+ atr_ratio = ind["atr_ratio"]
135
+ boll_width = ind["boll_width"]
136
+ ma_spread = ind["ma_spread_pct"] / 100
137
+
138
+ bullish_ma = ma5 > ma10 > ma20
139
+ bearish_ma = ma5 < ma10 < ma20
140
+ above_ma60 = close > ma60
141
+ high_volatility = atr_ratio > 0.025 or boll_width > 0.15
142
+ strong_trend = ma_spread > 0.03
143
+
144
+ if bullish_ma and above_ma60 and strong_trend:
145
+ regime = "trending_up"
146
+ confidence = 0.85 + (0.1 if ma_spread > 0.05 else 0)
147
+ elif bearish_ma and not above_ma60 and strong_trend:
148
+ regime = "trending_down"
149
+ confidence = 0.85 + (0.1 if ma_spread > 0.05 else 0)
150
+ elif high_volatility and not strong_trend:
151
+ regime = "volatile"
152
+ confidence = 0.7
153
+ elif not strong_trend and not high_volatility:
154
+ regime = "sideways"
155
+ confidence = 0.75
156
+ else:
157
+ regime = "mixed"
158
+ confidence = 0.5
159
+
160
+ ma_arrangement = "bullish" if bullish_ma else ("bearish" if bearish_ma else "mixed")
161
+ return regime, min(confidence, 0.95), ma_arrangement
162
+
163
+
164
+ def _detect_sector_heat(market: str) -> bool:
165
+ if market != "A":
166
+ return False
167
+ data = _run_tool("stock_data.py", "sector_rankings --top 5 --direction both")
168
+ if not isinstance(data, dict):
169
+ return False
170
+ top = data.get("top", [])
171
+ bottom = data.get("bottom", [])
172
+ if not top or not bottom:
173
+ return False
174
+ try:
175
+ top_pct = float(top[0].get("change_pct", 0))
176
+ bottom_pct = float(bottom[0].get("change_pct", 0))
177
+ return top_pct > 3 and bottom_pct < -1
178
+ except (ValueError, TypeError, IndexError):
179
+ return False
180
+
181
+
182
+ def detect_regime(market: str = "A") -> dict:
183
+ market = market.upper()
184
+ if market not in INDEX_MAP:
185
+ return {"error": f"Unsupported market: {market}. Use A/HK/US"}
186
+
187
+ code, name = INDEX_MAP[market]
188
+ klines = _get_index_kline(market)
189
+ if not klines:
190
+ return {"error": f"Failed to fetch index data for {name}"}
191
+
192
+ ind = _compute_indicators(klines)
193
+ if not ind:
194
+ return {"error": "Insufficient data to compute indicators"}
195
+
196
+ regime, confidence, ma_arrangement = classify_regime(ind)
197
+ sector_heat = _detect_sector_heat(market)
198
+
199
+ skills = SKILL_RECOMMEND.get(regime, {"recommend": [], "avoid": []})
200
+ recommended = list(skills["recommend"])
201
+ avoid = list(skills["avoid"])
202
+ if sector_heat:
203
+ if "dragon-head" not in recommended:
204
+ recommended.append("dragon-head")
205
+ if "emotion-cycle" not in recommended:
206
+ recommended.append("emotion-cycle")
207
+
208
+ return {
209
+ "market": market,
210
+ "index": {"code": code, "name": name, "close": ind["close"], "change_pct": ind["change_pct"]},
211
+ "regime": regime,
212
+ "regime_cn": REGIME_CN.get(regime, regime),
213
+ "confidence": round(confidence, 2),
214
+ "indicators": {
215
+ "ma_arrangement": ma_arrangement,
216
+ "above_ma60": ind["close"] > ind["ma60"],
217
+ "ma_spread_pct": ind["ma_spread_pct"],
218
+ "atr_ratio": ind["atr_ratio"],
219
+ "boll_width": ind["boll_width"],
220
+ "rsi14": ind["rsi14"],
221
+ "macd_trend": ind["macd_trend"],
222
+ },
223
+ "sector_heat": sector_heat,
224
+ "recommended_skills": recommended,
225
+ "avoid_skills": avoid,
226
+ }
227
+
228
+
229
+ def main():
230
+ parser = argparse.ArgumentParser(description="Market regime detection")
231
+ sub = parser.add_subparsers(dest="command")
232
+
233
+ p_detect = sub.add_parser("detect")
234
+ p_detect.add_argument("market", nargs="?", default="A", choices=["A", "HK", "US"])
235
+
236
+ args = parser.parse_args()
237
+ if not args.command:
238
+ parser.print_help()
239
+ sys.exit(1)
240
+
241
+ if args.command == "detect":
242
+ result = detect_regime(args.market)
243
+ print(json.dumps(result, ensure_ascii=False, default=str))
244
+
245
+
246
+ if __name__ == "__main__":
247
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
248
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
249
+ for _s in (sys.stdout, sys.stderr):
250
+ if hasattr(_s, "reconfigure"):
251
+ _s.reconfigure(encoding="utf-8")
252
+ main()
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env python3
2
+ """Market review — daily market overview with temperature scoring."""
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from concurrent.futures import ThreadPoolExecutor
10
+
11
+ TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
12
+
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
23
+
24
+
25
+ def _calc_temperature(stats: dict, indices: list) -> dict:
26
+ """Calculate market temperature score from breadth, index change, and limit data."""
27
+ scores = []
28
+ weights = []
29
+
30
+ if stats and "up_count" in stats and "down_count" in stats:
31
+ up = stats["up_count"] or 0
32
+ down = stats["down_count"] or 0
33
+ total = up + down
34
+ if total > 0:
35
+ breadth = up / total * 100
36
+ scores.append(breadth)
37
+ weights.append(0.45)
38
+
39
+ if indices and isinstance(indices, list):
40
+ changes = [idx.get("change_pct") for idx in indices if idx.get("change_pct") is not None]
41
+ if changes:
42
+ avg_change = sum(changes) / len(changes)
43
+ index_score = max(0, min(100, 50 + avg_change * 12))
44
+ scores.append(index_score)
45
+ weights.append(0.35)
46
+
47
+ if stats:
48
+ limit_up = stats.get("limit_up_count", 0) or 0
49
+ limit_down = stats.get("limit_down_count", 0) or 0
50
+ limit_total = limit_up + limit_down
51
+ if limit_total > 0:
52
+ limit_score = limit_up / limit_total * 100
53
+ scores.append(limit_score)
54
+ weights.append(0.20)
55
+
56
+ if not scores:
57
+ return {"score": 50, "level": "neutral", "signal": "yellow"}
58
+
59
+ total_weight = sum(weights)
60
+ temperature = sum(s * w for s, w in zip(scores, weights)) / total_weight
61
+
62
+ if temperature >= 60:
63
+ level, signal = "constructive", "green"
64
+ elif temperature >= 40:
65
+ level, signal = "neutral", "yellow"
66
+ else:
67
+ level, signal = "weak", "red"
68
+
69
+ return {"score": round(temperature, 1), "level": level, "signal": signal}
70
+
71
+
72
+ def _signal_to_stance(signal: str) -> str:
73
+ return {"green": "offensive", "yellow": "balanced", "red": "defensive"}.get(signal, "balanced")
74
+
75
+
76
+ def review_market(market: str = "A") -> dict:
77
+ """Gather market data and compute review for a single market."""
78
+ from datetime import datetime
79
+
80
+ tasks = {}
81
+
82
+ 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")
88
+ 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")
92
+ 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")
96
+ else:
97
+ return {"error": f"Unknown market: {market}"}
98
+
99
+ results = {}
100
+ with ThreadPoolExecutor(max_workers=5) as executor:
101
+ futures = {key: executor.submit(_run_tool, script, args) for key, (script, args) in tasks.items()}
102
+ for key, future in futures.items():
103
+ try:
104
+ results[key] = future.result(timeout=60)
105
+ except Exception:
106
+ results[key] = None
107
+
108
+ temperature = _calc_temperature(results.get("stats"), results.get("indices"))
109
+
110
+ output = {
111
+ "market": market,
112
+ "date": datetime.now().strftime("%Y-%m-%d"),
113
+ "indices": results.get("indices"),
114
+ "stats": results.get("stats"),
115
+ "sectors": results.get("sectors"),
116
+ "news": results.get("news"),
117
+ "regime": results.get("regime"),
118
+ "temperature": temperature,
119
+ "strategy_stance": _signal_to_stance(temperature["signal"]),
120
+ }
121
+ return output
122
+
123
+
124
+ def review_all() -> list:
125
+ """Review all markets."""
126
+ results = []
127
+ for m in ["A", "HK", "US"]:
128
+ results.append(review_market(m))
129
+ return results
130
+
131
+
132
+ def main():
133
+ parser = argparse.ArgumentParser(description="Market review tool")
134
+ sub = parser.add_subparsers(dest="command")
135
+
136
+ p_review = sub.add_parser("review")
137
+ p_review.add_argument("--market", default="A", choices=["A", "HK", "US", "all"])
138
+
139
+ args = parser.parse_args()
140
+ if not args.command:
141
+ parser.print_help()
142
+ sys.exit(1)
143
+
144
+ if args.command == "review":
145
+ result = review_all() if args.market == "all" else review_market(args.market)
146
+ print(json.dumps(result, ensure_ascii=False, default=str))
147
+
148
+
149
+ if __name__ == "__main__":
150
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
151
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
152
+ for _s in (sys.stdout, sys.stderr):
153
+ if hasattr(_s, "reconfigure"):
154
+ _s.reconfigure(encoding="utf-8")
155
+ main()
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env python3
2
+ """Resolve Chinese stock names / pinyin / fuzzy input to stock codes."""
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ import time
8
+ from difflib import SequenceMatcher
9
+
10
+ _STOCK_MAP_CACHE = None
11
+
12
+
13
+ def _akshare_retry(fn, *args, retries=2, delay=1):
14
+ for attempt in range(retries + 1):
15
+ try:
16
+ return fn(*args)
17
+ except Exception:
18
+ if attempt == retries:
19
+ raise
20
+ time.sleep(delay)
21
+
22
+
23
+ def _load_stock_map() -> list[dict]:
24
+ global _STOCK_MAP_CACHE
25
+ if _STOCK_MAP_CACHE is not None:
26
+ return _STOCK_MAP_CACHE
27
+ try:
28
+ import akshare as ak
29
+
30
+ df = _akshare_retry(ak.stock_zh_a_spot_em)
31
+ records = []
32
+ for _, row in df.iterrows():
33
+ records.append(
34
+ {
35
+ "code": str(row.get("代码", "")),
36
+ "name": str(row.get("名称", "")),
37
+ }
38
+ )
39
+ _STOCK_MAP_CACHE = records
40
+ return records
41
+ except Exception as e:
42
+ raise RuntimeError(f"Failed to load stock list: {e}") from e
43
+
44
+
45
+ def _to_pinyin(text: str) -> str:
46
+ try:
47
+ from pypinyin import lazy_pinyin
48
+
49
+ return "".join(lazy_pinyin(text)).lower()
50
+ except ImportError:
51
+ return text.lower()
52
+
53
+
54
+ def _to_pinyin_initials(text: str) -> str:
55
+ try:
56
+ from pypinyin import lazy_pinyin
57
+
58
+ return "".join(w[0] for w in lazy_pinyin(text) if w).lower()
59
+ except ImportError:
60
+ return ""
61
+
62
+
63
+ def resolve(query: str, top: int = 5) -> list[dict]:
64
+ stocks = _load_stock_map()
65
+ query = query.strip()
66
+ q_lower = query.lower()
67
+
68
+ exact = [s for s in stocks if s["code"] == query or s["name"] == query]
69
+ if exact:
70
+ return exact[:top]
71
+
72
+ prefix_code = [s for s in stocks if s["code"].startswith(query)]
73
+ if prefix_code:
74
+ return prefix_code[:top]
75
+
76
+ contains = [s for s in stocks if query in s["name"]]
77
+ if contains:
78
+ return contains[:top]
79
+
80
+ q_pinyin = _to_pinyin(query)
81
+ q_initials = _to_pinyin_initials(query) if len(query) <= 6 else ""
82
+
83
+ scored = []
84
+ for s in stocks:
85
+ name = s["name"]
86
+ name_pinyin = _to_pinyin(name)
87
+ name_initials = _to_pinyin_initials(name)
88
+
89
+ best = 0.0
90
+ if q_pinyin and q_pinyin in name_pinyin:
91
+ best = max(best, 0.85)
92
+ if q_initials and q_initials == name_initials:
93
+ best = max(best, 0.9)
94
+ elif q_initials and q_initials in name_initials:
95
+ best = max(best, 0.75)
96
+
97
+ ratio = SequenceMatcher(None, q_lower, name.lower()).ratio()
98
+ best = max(best, ratio)
99
+
100
+ pinyin_ratio = SequenceMatcher(None, q_pinyin, name_pinyin).ratio()
101
+ best = max(best, pinyin_ratio * 0.95)
102
+
103
+ if best > 0.4:
104
+ scored.append((best, s))
105
+
106
+ scored.sort(key=lambda x: -x[0])
107
+ return [{"code": s["code"], "name": s["name"], "score": round(sc, 2)} for sc, s in scored[:top]]
108
+
109
+
110
+ def main():
111
+ parser = argparse.ArgumentParser(description="Stock name resolver")
112
+ sub = parser.add_subparsers(dest="command")
113
+
114
+ p = sub.add_parser("resolve")
115
+ p.add_argument("query", help="Stock name, pinyin, or partial code")
116
+ p.add_argument("--top", type=int, default=5)
117
+
118
+ args = parser.parse_args()
119
+ if not args.command:
120
+ parser.print_help()
121
+ sys.exit(1)
122
+
123
+ try:
124
+ result = resolve(args.query, args.top)
125
+ except RuntimeError as e:
126
+ result = {"error": str(e)}
127
+ print(json.dumps(result, ensure_ascii=False))
128
+
129
+
130
+ if __name__ == "__main__":
131
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
132
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
133
+ for _s in (sys.stdout, sys.stderr):
134
+ if hasattr(_s, "reconfigure"):
135
+ _s.reconfigure(encoding="utf-8")
136
+ main()