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.
- package/README.md +498 -0
- package/package.json +88 -0
- package/pi/index.ts +1142 -0
- package/schemas/market_review_schema.json +176 -0
- package/schemas/report_schema.json +131 -0
- package/scripts/setup-python.mjs +57 -0
- package/scripts/sync-version.sh +56 -0
- package/scripts/venv-python.mjs +20 -0
- package/skills/bottom-volume/SKILL.md +63 -0
- package/skills/bottom-volume/scripts/gather.py +22 -0
- package/skills/box-oscillation/SKILL.md +72 -0
- package/skills/box-oscillation/scripts/gather.py +22 -0
- package/skills/bull-trend/SKILL.md +60 -0
- package/skills/bull-trend/scripts/gather.py +22 -0
- package/skills/chan-theory/SKILL.md +71 -0
- package/skills/chan-theory/scripts/gather.py +22 -0
- package/skills/dragon-head/SKILL.md +69 -0
- package/skills/dragon-head/scripts/gather.py +22 -0
- package/skills/emotion-cycle/SKILL.md +65 -0
- package/skills/emotion-cycle/scripts/gather.py +22 -0
- package/skills/event-driven/SKILL.md +73 -0
- package/skills/event-driven/scripts/gather.py +22 -0
- package/skills/expectation-repricing/SKILL.md +72 -0
- package/skills/expectation-repricing/scripts/gather.py +22 -0
- package/skills/growth-quality/SKILL.md +74 -0
- package/skills/growth-quality/scripts/gather.py +22 -0
- package/skills/hot-theme/SKILL.md +74 -0
- package/skills/hot-theme/scripts/gather.py +22 -0
- package/skills/ma-crossover/SKILL.md +63 -0
- package/skills/ma-crossover/scripts/gather.py +22 -0
- package/skills/market-review/SKILL.md +70 -0
- package/skills/market-review/scripts/gather.py +23 -0
- package/skills/one-yang-three-yin/SKILL.md +74 -0
- package/skills/one-yang-three-yin/scripts/gather.py +22 -0
- package/skills/shrink-pullback/SKILL.md +59 -0
- package/skills/shrink-pullback/scripts/gather.py +22 -0
- package/skills/stock-analysis/SKILL.md +134 -0
- package/skills/stock-analysis/scripts/gather.py +22 -0
- package/skills/stock-screener/SKILL.md +68 -0
- package/skills/stock-screener/scripts/gather.py +22 -0
- package/skills/strategy-backtest/SKILL.md +129 -0
- package/skills/strategy-backtest/scripts/gather.py +23 -0
- package/skills/volume-breakout/SKILL.md +58 -0
- package/skills/volume-breakout/scripts/gather.py +22 -0
- package/skills/wave-theory/SKILL.md +67 -0
- package/skills/wave-theory/scripts/gather.py +22 -0
- package/skills/wisburg-research/SKILL.md +119 -0
- package/strategies/examples/bottom_volume.yaml +47 -0
- package/strategies/examples/box_oscillation.yaml +41 -0
- package/strategies/examples/bull_trend.yaml +42 -0
- package/strategies/examples/dragon_head.yaml +45 -0
- package/strategies/examples/emotion_cycle.yaml +43 -0
- package/strategies/examples/ma_crossover.yaml +34 -0
- package/strategies/examples/rsi_oversold.yaml +35 -0
- package/strategies/examples/shrink_pullback.yaml +45 -0
- package/strategies/examples/volume_breakout.yaml +42 -0
- package/templates/_macros.j2 +90 -0
- package/templates/market_review/full.md.j2 +103 -0
- package/templates/stock_analysis/brief.md.j2 +28 -0
- package/templates/stock_analysis/full.md.j2 +108 -0
- package/tools/__init__.py +0 -0
- package/tools/alert_rules.py +243 -0
- package/tools/anomaly_detect.py +575 -0
- package/tools/backtest.py +764 -0
- package/tools/capabilities.py +108 -0
- package/tools/diagnostics.py +146 -0
- package/tools/gather.py +157 -0
- package/tools/import_parser.py +279 -0
- package/tools/market_regime.py +252 -0
- package/tools/market_review.py +155 -0
- package/tools/name_resolver.py +136 -0
- package/tools/pattern.py +515 -0
- package/tools/position_context.py +161 -0
- package/tools/report_renderer.py +116 -0
- package/tools/requirements.txt +15 -0
- package/tools/risk_screening.py +323 -0
- package/tools/screener.py +219 -0
- package/tools/search_intel.py +504 -0
- package/tools/stock_data.py +1721 -0
- package/tools/technical.py +642 -0
- package/tools/trading_calendar.py +226 -0
- package/tools/volume_analysis.py +178 -0
- package/tools/watchlist.py +66 -0
- package/tools/watchlist_context.py +185 -0
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Anomaly/event detection — detect edge-crossing transitions and unusual conditions."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
15
|
+
|
|
16
|
+
from stock_data import detect_market, normalize_stock_code
|
|
17
|
+
from technical import fetch_kline, to_dataframe
|
|
18
|
+
|
|
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
|
+
|
|
33
|
+
def _anomaly(type_: str, severity: str, direction: str, description: str, **extra) -> dict:
|
|
34
|
+
result = {
|
|
35
|
+
"type": type_,
|
|
36
|
+
"severity": severity,
|
|
37
|
+
"direction": direction,
|
|
38
|
+
"description": description,
|
|
39
|
+
}
|
|
40
|
+
result.update(extra)
|
|
41
|
+
return result
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# --------------- Detectors ---------------
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def detect_macd_cross(close: pd.Series) -> list:
|
|
48
|
+
if len(close) < 30:
|
|
49
|
+
return []
|
|
50
|
+
ema12 = close.ewm(span=12, adjust=False).mean()
|
|
51
|
+
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
52
|
+
dif = ema12 - ema26
|
|
53
|
+
dea = dif.ewm(span=9, adjust=False).mean()
|
|
54
|
+
|
|
55
|
+
prev_diff = float(dif.iloc[-2] - dea.iloc[-2])
|
|
56
|
+
curr_diff = float(dif.iloc[-1] - dea.iloc[-1])
|
|
57
|
+
|
|
58
|
+
anomalies = []
|
|
59
|
+
if prev_diff <= 0 and curr_diff > 0:
|
|
60
|
+
above_zero = float(dif.iloc[-1]) > 0
|
|
61
|
+
sev = "high" if above_zero else "medium"
|
|
62
|
+
desc = "MACD金叉" + ("(零轴上方,强势信号)" if above_zero else "(零轴下方)")
|
|
63
|
+
anomalies.append(_anomaly("macd_golden_cross", sev, "bullish", desc))
|
|
64
|
+
elif prev_diff >= 0 and curr_diff < 0:
|
|
65
|
+
below_zero = float(dif.iloc[-1]) < 0
|
|
66
|
+
sev = "high" if below_zero else "medium"
|
|
67
|
+
desc = "MACD死叉" + ("(零轴下方,弱势信号)" if below_zero else "(零轴上方)")
|
|
68
|
+
anomalies.append(_anomaly("macd_death_cross", sev, "bearish", desc))
|
|
69
|
+
return anomalies
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def detect_rsi_extreme(close: pd.Series) -> list:
|
|
73
|
+
if len(close) < 10:
|
|
74
|
+
return []
|
|
75
|
+
delta = close.diff()
|
|
76
|
+
gain = delta.where(delta > 0, 0.0).rolling(6).mean()
|
|
77
|
+
loss = (-delta.where(delta < 0, 0.0)).rolling(6).mean()
|
|
78
|
+
rs = gain / loss.replace(0, np.nan)
|
|
79
|
+
rsi = 100 - 100 / (1 + rs)
|
|
80
|
+
|
|
81
|
+
if len(rsi.dropna()) < 2:
|
|
82
|
+
return []
|
|
83
|
+
|
|
84
|
+
curr = float(rsi.iloc[-1])
|
|
85
|
+
prev = float(rsi.iloc[-2])
|
|
86
|
+
anomalies = []
|
|
87
|
+
|
|
88
|
+
if curr > 80 and prev <= 80:
|
|
89
|
+
anomalies.append(
|
|
90
|
+
_anomaly(
|
|
91
|
+
"rsi_overbought_entry",
|
|
92
|
+
"medium",
|
|
93
|
+
"bearish",
|
|
94
|
+
f"RSI6进入超买区({curr:.1f}),短期回调风险增大",
|
|
95
|
+
rsi6=round(curr, 2),
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
elif curr < 20 and prev >= 20:
|
|
99
|
+
anomalies.append(
|
|
100
|
+
_anomaly(
|
|
101
|
+
"rsi_oversold_entry",
|
|
102
|
+
"medium",
|
|
103
|
+
"bullish",
|
|
104
|
+
f"RSI6进入超卖区({curr:.1f}),关注反弹机会",
|
|
105
|
+
rsi6=round(curr, 2),
|
|
106
|
+
)
|
|
107
|
+
)
|
|
108
|
+
return anomalies
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def detect_price_breakout(df: pd.DataFrame) -> list:
|
|
112
|
+
if len(df) < 21:
|
|
113
|
+
return []
|
|
114
|
+
close = df["close"]
|
|
115
|
+
high = df["high"]
|
|
116
|
+
low = df["low"]
|
|
117
|
+
|
|
118
|
+
prev_20_high = float(high.iloc[-21:-1].max())
|
|
119
|
+
prev_20_low = float(low.iloc[-21:-1].min())
|
|
120
|
+
curr_close = float(close.iloc[-1])
|
|
121
|
+
prev_close = float(close.iloc[-2])
|
|
122
|
+
|
|
123
|
+
anomalies = []
|
|
124
|
+
if curr_close > prev_20_high and prev_close <= prev_20_high:
|
|
125
|
+
anomalies.append(
|
|
126
|
+
_anomaly(
|
|
127
|
+
"breakout_20d_high",
|
|
128
|
+
"high",
|
|
129
|
+
"bullish",
|
|
130
|
+
f"突破20日高点{prev_20_high:.2f},创阶段新高",
|
|
131
|
+
level=round(prev_20_high, 2),
|
|
132
|
+
)
|
|
133
|
+
)
|
|
134
|
+
if curr_close < prev_20_low and prev_close >= prev_20_low:
|
|
135
|
+
anomalies.append(
|
|
136
|
+
_anomaly(
|
|
137
|
+
"breakdown_20d_low",
|
|
138
|
+
"high",
|
|
139
|
+
"bearish",
|
|
140
|
+
f"跌破20日低点{prev_20_low:.2f},创阶段新低",
|
|
141
|
+
level=round(prev_20_low, 2),
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
return anomalies
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def detect_volume_spike(volume: pd.Series) -> list:
|
|
148
|
+
if len(volume) < 6:
|
|
149
|
+
return []
|
|
150
|
+
vol_ma5 = float(volume.shift(1).rolling(5).mean().iloc[-1])
|
|
151
|
+
cur_vol = float(volume.iloc[-1])
|
|
152
|
+
if vol_ma5 <= 0 or np.isnan(vol_ma5):
|
|
153
|
+
return []
|
|
154
|
+
|
|
155
|
+
ratio = cur_vol / vol_ma5
|
|
156
|
+
anomalies = []
|
|
157
|
+
if ratio > 3:
|
|
158
|
+
anomalies.append(
|
|
159
|
+
_anomaly(
|
|
160
|
+
"volume_spike_extreme",
|
|
161
|
+
"high",
|
|
162
|
+
"neutral",
|
|
163
|
+
f"成交量异常放大(量比{ratio:.1f}x),远超5日均量",
|
|
164
|
+
volume_ratio=round(ratio, 2),
|
|
165
|
+
)
|
|
166
|
+
)
|
|
167
|
+
elif ratio > 2:
|
|
168
|
+
anomalies.append(
|
|
169
|
+
_anomaly(
|
|
170
|
+
"volume_spike",
|
|
171
|
+
"medium",
|
|
172
|
+
"neutral",
|
|
173
|
+
f"成交量明显放大(量比{ratio:.1f}x),市场关注度骤升",
|
|
174
|
+
volume_ratio=round(ratio, 2),
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
return anomalies
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def detect_bollinger_breakout(close: pd.Series) -> list:
|
|
181
|
+
if len(close) < 21:
|
|
182
|
+
return []
|
|
183
|
+
mid = close.rolling(20).mean()
|
|
184
|
+
std = close.rolling(20).std()
|
|
185
|
+
upper = mid + 2 * std
|
|
186
|
+
lower = mid - 2 * std
|
|
187
|
+
|
|
188
|
+
curr_price = float(close.iloc[-1])
|
|
189
|
+
prev_price = float(close.iloc[-2])
|
|
190
|
+
curr_upper = float(upper.iloc[-1])
|
|
191
|
+
curr_lower = float(lower.iloc[-1])
|
|
192
|
+
prev_upper = float(upper.iloc[-2])
|
|
193
|
+
prev_lower = float(lower.iloc[-2])
|
|
194
|
+
|
|
195
|
+
anomalies = []
|
|
196
|
+
if curr_price > curr_upper and prev_price <= prev_upper:
|
|
197
|
+
anomalies.append(
|
|
198
|
+
_anomaly(
|
|
199
|
+
"bollinger_upper_break",
|
|
200
|
+
"medium",
|
|
201
|
+
"bearish",
|
|
202
|
+
f"突破布林带上轨({curr_upper:.2f}),短期超买或加速上涨",
|
|
203
|
+
upper=round(curr_upper, 2),
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
if curr_price < curr_lower and prev_price >= prev_lower:
|
|
207
|
+
anomalies.append(
|
|
208
|
+
_anomaly(
|
|
209
|
+
"bollinger_lower_break",
|
|
210
|
+
"medium",
|
|
211
|
+
"bullish",
|
|
212
|
+
f"跌破布林带下轨({curr_lower:.2f}),短期超卖或加速下跌",
|
|
213
|
+
lower=round(curr_lower, 2),
|
|
214
|
+
)
|
|
215
|
+
)
|
|
216
|
+
return anomalies
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def detect_kdj_extreme(high: pd.Series, low: pd.Series, close: pd.Series) -> list:
|
|
220
|
+
if len(close) < 10:
|
|
221
|
+
return []
|
|
222
|
+
low_n = low.rolling(9).min()
|
|
223
|
+
high_n = high.rolling(9).max()
|
|
224
|
+
rsv = (close - low_n) / (high_n - low_n).replace(0, np.nan) * 100
|
|
225
|
+
rsv = rsv.fillna(50)
|
|
226
|
+
k = rsv.ewm(com=2, adjust=False).mean()
|
|
227
|
+
d = k.ewm(com=2, adjust=False).mean()
|
|
228
|
+
j = 3 * k - 2 * d
|
|
229
|
+
|
|
230
|
+
if len(j.dropna()) < 2:
|
|
231
|
+
return []
|
|
232
|
+
|
|
233
|
+
curr_j = float(j.iloc[-1])
|
|
234
|
+
prev_j = float(j.iloc[-2])
|
|
235
|
+
anomalies = []
|
|
236
|
+
|
|
237
|
+
if curr_j > 80 and prev_j <= 80:
|
|
238
|
+
anomalies.append(
|
|
239
|
+
_anomaly(
|
|
240
|
+
"kdj_overbought_entry",
|
|
241
|
+
"low",
|
|
242
|
+
"bearish",
|
|
243
|
+
f"KDJ-J值进入超买区({curr_j:.1f}),短期高位风险",
|
|
244
|
+
j_value=round(curr_j, 2),
|
|
245
|
+
)
|
|
246
|
+
)
|
|
247
|
+
elif curr_j < 20 and prev_j >= 20:
|
|
248
|
+
anomalies.append(
|
|
249
|
+
_anomaly(
|
|
250
|
+
"kdj_oversold_entry",
|
|
251
|
+
"low",
|
|
252
|
+
"bullish",
|
|
253
|
+
f"KDJ-J值进入超卖区({curr_j:.1f}),关注低吸机会",
|
|
254
|
+
j_value=round(curr_j, 2),
|
|
255
|
+
)
|
|
256
|
+
)
|
|
257
|
+
return anomalies
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def detect_large_move(quote: dict) -> list:
|
|
261
|
+
change_pct = quote.get("change_pct")
|
|
262
|
+
if change_pct is None:
|
|
263
|
+
return []
|
|
264
|
+
change_pct = float(change_pct)
|
|
265
|
+
anomalies = []
|
|
266
|
+
|
|
267
|
+
if change_pct > 7:
|
|
268
|
+
anomalies.append(
|
|
269
|
+
_anomaly(
|
|
270
|
+
"large_move_up",
|
|
271
|
+
"high",
|
|
272
|
+
"bullish",
|
|
273
|
+
f"单日大涨{change_pct:.2f}%,可能有重大利好或资金抢筹",
|
|
274
|
+
change_pct=round(change_pct, 2),
|
|
275
|
+
)
|
|
276
|
+
)
|
|
277
|
+
elif change_pct > 5:
|
|
278
|
+
anomalies.append(
|
|
279
|
+
_anomaly(
|
|
280
|
+
"large_move_up",
|
|
281
|
+
"medium",
|
|
282
|
+
"bullish",
|
|
283
|
+
f"单日涨幅{change_pct:.2f}%,显著上涨",
|
|
284
|
+
change_pct=round(change_pct, 2),
|
|
285
|
+
)
|
|
286
|
+
)
|
|
287
|
+
elif change_pct < -7:
|
|
288
|
+
anomalies.append(
|
|
289
|
+
_anomaly(
|
|
290
|
+
"large_move_down",
|
|
291
|
+
"high",
|
|
292
|
+
"bearish",
|
|
293
|
+
f"单日大跌{change_pct:.2f}%,可能有重大利空或恐慌抛售",
|
|
294
|
+
change_pct=round(change_pct, 2),
|
|
295
|
+
)
|
|
296
|
+
)
|
|
297
|
+
elif change_pct < -5:
|
|
298
|
+
anomalies.append(
|
|
299
|
+
_anomaly(
|
|
300
|
+
"large_move_down",
|
|
301
|
+
"medium",
|
|
302
|
+
"bearish",
|
|
303
|
+
f"单日跌幅{change_pct:.2f}%,显著下跌",
|
|
304
|
+
change_pct=round(change_pct, 2),
|
|
305
|
+
)
|
|
306
|
+
)
|
|
307
|
+
return anomalies
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def detect_limit_hit(symbol: str, quote: dict) -> list:
|
|
311
|
+
market = detect_market(symbol)
|
|
312
|
+
if market != "A":
|
|
313
|
+
return []
|
|
314
|
+
|
|
315
|
+
price = quote.get("price")
|
|
316
|
+
prev_close = quote.get("prev_close")
|
|
317
|
+
change_pct = quote.get("change_pct")
|
|
318
|
+
if price is None or prev_close is None:
|
|
319
|
+
return []
|
|
320
|
+
|
|
321
|
+
code_info = normalize_stock_code(symbol)
|
|
322
|
+
limit_pct = code_info.get("limit_pct")
|
|
323
|
+
if limit_pct is None:
|
|
324
|
+
return []
|
|
325
|
+
|
|
326
|
+
name = quote.get("name", "")
|
|
327
|
+
if name and "ST" in name.upper() and code_info["board"] == "main":
|
|
328
|
+
limit_pct = 0.05
|
|
329
|
+
|
|
330
|
+
prev_close = float(prev_close)
|
|
331
|
+
price = float(price)
|
|
332
|
+
limit_up_price = round(prev_close * (1 + limit_pct), 2)
|
|
333
|
+
limit_down_price = round(prev_close * (1 - limit_pct), 2)
|
|
334
|
+
|
|
335
|
+
anomalies = []
|
|
336
|
+
if abs(price - limit_up_price) < 0.02:
|
|
337
|
+
pct_str = f"{change_pct:.2f}" if change_pct is not None else f"{limit_pct * 100:.0f}"
|
|
338
|
+
anomalies.append(_anomaly("limit_up", "high", "bullish", f"涨停(涨幅{pct_str}%),封板中"))
|
|
339
|
+
elif abs(price - limit_down_price) < 0.02:
|
|
340
|
+
pct_str = f"{change_pct:.2f}" if change_pct is not None else f"-{limit_pct * 100:.0f}"
|
|
341
|
+
anomalies.append(_anomaly("limit_down", "high", "bearish", f"跌停(跌幅{pct_str}%),恐慌情绪"))
|
|
342
|
+
return anomalies
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def detect_capital_flow_anomaly(symbol: str) -> list:
|
|
346
|
+
market = detect_market(symbol)
|
|
347
|
+
if market != "A":
|
|
348
|
+
return []
|
|
349
|
+
|
|
350
|
+
flow_data = _run_tool("stock_data.py", f"capital_flow {symbol} --mode detail")
|
|
351
|
+
if not flow_data or not isinstance(flow_data, list) or len(flow_data) < 3:
|
|
352
|
+
return []
|
|
353
|
+
|
|
354
|
+
try:
|
|
355
|
+
inflows = [float(d.get("main_net_inflow", 0)) for d in flow_data if d.get("main_net_inflow") is not None]
|
|
356
|
+
except (ValueError, TypeError):
|
|
357
|
+
return []
|
|
358
|
+
|
|
359
|
+
if len(inflows) < 3:
|
|
360
|
+
return []
|
|
361
|
+
|
|
362
|
+
latest = inflows[-1]
|
|
363
|
+
history = inflows[:-1]
|
|
364
|
+
avg = sum(history) / len(history)
|
|
365
|
+
std_val = float(np.std(history)) if len(history) > 2 else abs(avg) * 0.5
|
|
366
|
+
|
|
367
|
+
if std_val == 0:
|
|
368
|
+
return []
|
|
369
|
+
|
|
370
|
+
z_score = (latest - avg) / std_val
|
|
371
|
+
anomalies = []
|
|
372
|
+
|
|
373
|
+
if z_score > 2:
|
|
374
|
+
anomalies.append(
|
|
375
|
+
_anomaly(
|
|
376
|
+
"capital_inflow_surge",
|
|
377
|
+
"medium",
|
|
378
|
+
"bullish",
|
|
379
|
+
f"主力资金大幅净流入(z={z_score:.1f}),显著高于近期均值",
|
|
380
|
+
net_inflow=latest,
|
|
381
|
+
)
|
|
382
|
+
)
|
|
383
|
+
elif z_score < -2:
|
|
384
|
+
anomalies.append(
|
|
385
|
+
_anomaly(
|
|
386
|
+
"capital_outflow_surge",
|
|
387
|
+
"medium",
|
|
388
|
+
"bearish",
|
|
389
|
+
f"主力资金大幅净流出(z={z_score:.1f}),显著高于近期均值",
|
|
390
|
+
net_inflow=latest,
|
|
391
|
+
)
|
|
392
|
+
)
|
|
393
|
+
return anomalies
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def detect_divergence(df: pd.DataFrame) -> list:
|
|
397
|
+
if len(df) < 30:
|
|
398
|
+
return []
|
|
399
|
+
close = df["close"]
|
|
400
|
+
ema12 = close.ewm(span=12, adjust=False).mean()
|
|
401
|
+
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
402
|
+
dif = ema12 - ema26
|
|
403
|
+
|
|
404
|
+
window = min(20, len(df) - 10)
|
|
405
|
+
recent_close = close.iloc[-window:]
|
|
406
|
+
recent_dif = dif.iloc[-window:]
|
|
407
|
+
prior_close = close.iloc[-window * 2 : -window]
|
|
408
|
+
prior_dif = dif.iloc[-window * 2 : -window]
|
|
409
|
+
|
|
410
|
+
if len(prior_close) < 5:
|
|
411
|
+
return []
|
|
412
|
+
|
|
413
|
+
anomalies = []
|
|
414
|
+
if float(recent_close.max()) > float(prior_close.max()) and float(recent_dif.max()) < float(prior_dif.max()):
|
|
415
|
+
anomalies.append(
|
|
416
|
+
_anomaly(
|
|
417
|
+
"top_divergence",
|
|
418
|
+
"high",
|
|
419
|
+
"bearish",
|
|
420
|
+
"顶背离 — 价格创新高但MACD动能减弱,警惕回调",
|
|
421
|
+
)
|
|
422
|
+
)
|
|
423
|
+
if float(recent_close.min()) < float(prior_close.min()) and float(recent_dif.min()) > float(prior_dif.min()):
|
|
424
|
+
anomalies.append(
|
|
425
|
+
_anomaly(
|
|
426
|
+
"bottom_divergence",
|
|
427
|
+
"high",
|
|
428
|
+
"bullish",
|
|
429
|
+
"底背离 — 价格创新低但MACD动能增强,关注反转机会",
|
|
430
|
+
)
|
|
431
|
+
)
|
|
432
|
+
return anomalies
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def detect_ma_cross(close: pd.Series) -> list:
|
|
436
|
+
if len(close) < 21:
|
|
437
|
+
return []
|
|
438
|
+
ma5 = close.rolling(5).mean()
|
|
439
|
+
ma10 = close.rolling(10).mean()
|
|
440
|
+
ma20 = close.rolling(20).mean()
|
|
441
|
+
|
|
442
|
+
anomalies = []
|
|
443
|
+
|
|
444
|
+
if float(ma5.iloc[-2]) <= float(ma10.iloc[-2]) and float(ma5.iloc[-1]) > float(ma10.iloc[-1]):
|
|
445
|
+
anomalies.append(_anomaly("ma5_cross_ma10_golden", "medium", "bullish", "MA5上穿MA10,短线金叉"))
|
|
446
|
+
elif float(ma5.iloc[-2]) >= float(ma10.iloc[-2]) and float(ma5.iloc[-1]) < float(ma10.iloc[-1]):
|
|
447
|
+
anomalies.append(_anomaly("ma5_cross_ma10_death", "medium", "bearish", "MA5下穿MA10,短线死叉"))
|
|
448
|
+
|
|
449
|
+
if float(ma10.iloc[-2]) <= float(ma20.iloc[-2]) and float(ma10.iloc[-1]) > float(ma20.iloc[-1]):
|
|
450
|
+
anomalies.append(_anomaly("ma10_cross_ma20_golden", "medium", "bullish", "MA10上穿MA20,中线金叉"))
|
|
451
|
+
elif float(ma10.iloc[-2]) >= float(ma20.iloc[-2]) and float(ma10.iloc[-1]) < float(ma20.iloc[-1]):
|
|
452
|
+
anomalies.append(_anomaly("ma10_cross_ma20_death", "medium", "bearish", "MA10下穿MA20,中线死叉"))
|
|
453
|
+
|
|
454
|
+
return anomalies
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def detect_gap(df: pd.DataFrame) -> list:
|
|
458
|
+
if len(df) < 2:
|
|
459
|
+
return []
|
|
460
|
+
prev = df.iloc[-2]
|
|
461
|
+
curr = df.iloc[-1]
|
|
462
|
+
|
|
463
|
+
anomalies = []
|
|
464
|
+
if float(curr["low"]) > float(prev["high"]):
|
|
465
|
+
gap_pct = (float(curr["low"]) - float(prev["high"])) / float(prev["close"]) * 100
|
|
466
|
+
anomalies.append(
|
|
467
|
+
_anomaly(
|
|
468
|
+
"gap_up",
|
|
469
|
+
"high" if gap_pct > 3 else "medium",
|
|
470
|
+
"bullish",
|
|
471
|
+
f"向上跳空缺口({gap_pct:.2f}%),强势突破信号",
|
|
472
|
+
gap_pct=round(gap_pct, 2),
|
|
473
|
+
)
|
|
474
|
+
)
|
|
475
|
+
elif float(curr["high"]) < float(prev["low"]):
|
|
476
|
+
gap_pct = (float(prev["low"]) - float(curr["high"])) / float(prev["close"]) * 100
|
|
477
|
+
anomalies.append(
|
|
478
|
+
_anomaly(
|
|
479
|
+
"gap_down",
|
|
480
|
+
"high" if gap_pct > 3 else "medium",
|
|
481
|
+
"bearish",
|
|
482
|
+
f"向下跳空缺口({gap_pct:.2f}%),弱势破位信号",
|
|
483
|
+
gap_pct=round(gap_pct, 2),
|
|
484
|
+
)
|
|
485
|
+
)
|
|
486
|
+
return anomalies
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
# --------------- Orchestration ---------------
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def detect_anomalies(symbol: str) -> dict:
|
|
493
|
+
records = fetch_kline(symbol, "daily", 60)
|
|
494
|
+
if isinstance(records, dict) and "error" in records:
|
|
495
|
+
return {"symbol": symbol, "error": records.get("error", "Failed to fetch kline")}
|
|
496
|
+
if not records:
|
|
497
|
+
return {"symbol": symbol, "error": "No kline data returned"}
|
|
498
|
+
|
|
499
|
+
df = to_dataframe(records)
|
|
500
|
+
if len(df) < 10:
|
|
501
|
+
return {"symbol": symbol, "error": f"Insufficient data: {len(df)} rows"}
|
|
502
|
+
|
|
503
|
+
close = df["close"]
|
|
504
|
+
high = df["high"]
|
|
505
|
+
low = df["low"]
|
|
506
|
+
volume = df["volume"]
|
|
507
|
+
|
|
508
|
+
quote = _run_tool("stock_data.py", f"quote {symbol}") or {}
|
|
509
|
+
|
|
510
|
+
anomalies = []
|
|
511
|
+
anomalies.extend(detect_macd_cross(close))
|
|
512
|
+
anomalies.extend(detect_rsi_extreme(close))
|
|
513
|
+
anomalies.extend(detect_price_breakout(df))
|
|
514
|
+
anomalies.extend(detect_volume_spike(volume))
|
|
515
|
+
anomalies.extend(detect_bollinger_breakout(close))
|
|
516
|
+
anomalies.extend(detect_kdj_extreme(high, low, close))
|
|
517
|
+
anomalies.extend(detect_divergence(df))
|
|
518
|
+
anomalies.extend(detect_ma_cross(close))
|
|
519
|
+
anomalies.extend(detect_gap(df))
|
|
520
|
+
|
|
521
|
+
if quote and "error" not in quote:
|
|
522
|
+
anomalies.extend(detect_limit_hit(symbol, quote))
|
|
523
|
+
anomalies.extend(detect_large_move(quote))
|
|
524
|
+
|
|
525
|
+
anomalies.extend(detect_capital_flow_anomaly(symbol))
|
|
526
|
+
|
|
527
|
+
severity_order = {"high": 0, "medium": 1, "low": 2}
|
|
528
|
+
anomalies.sort(key=lambda a: severity_order.get(a["severity"], 3))
|
|
529
|
+
|
|
530
|
+
high_count = sum(1 for a in anomalies if a["severity"] == "high")
|
|
531
|
+
bullish_count = sum(1 for a in anomalies if a["direction"] == "bullish")
|
|
532
|
+
bearish_count = sum(1 for a in anomalies if a["direction"] == "bearish")
|
|
533
|
+
|
|
534
|
+
return {
|
|
535
|
+
"symbol": symbol,
|
|
536
|
+
"anomaly_count": len(anomalies),
|
|
537
|
+
"summary": {
|
|
538
|
+
"high_severity": high_count,
|
|
539
|
+
"bullish_signals": bullish_count,
|
|
540
|
+
"bearish_signals": bearish_count,
|
|
541
|
+
"overall_bias": (
|
|
542
|
+
"bullish"
|
|
543
|
+
if bullish_count > bearish_count
|
|
544
|
+
else "bearish"
|
|
545
|
+
if bearish_count > bullish_count
|
|
546
|
+
else "neutral"
|
|
547
|
+
),
|
|
548
|
+
},
|
|
549
|
+
"anomalies": anomalies,
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def main():
|
|
554
|
+
parser = argparse.ArgumentParser(description="Anomaly/event detection")
|
|
555
|
+
sub = parser.add_subparsers(dest="command")
|
|
556
|
+
|
|
557
|
+
p = sub.add_parser("detect")
|
|
558
|
+
p.add_argument("symbol", help="Stock symbol (e.g. 600519, AAPL, 00700.HK)")
|
|
559
|
+
|
|
560
|
+
args = parser.parse_args()
|
|
561
|
+
if not args.command:
|
|
562
|
+
parser.print_help()
|
|
563
|
+
sys.exit(1)
|
|
564
|
+
|
|
565
|
+
result = detect_anomalies(args.symbol)
|
|
566
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
if __name__ == "__main__":
|
|
570
|
+
# Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
|
|
571
|
+
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
572
|
+
for _s in (sys.stdout, sys.stderr):
|
|
573
|
+
if hasattr(_s, "reconfigure"):
|
|
574
|
+
_s.reconfigure(encoding="utf-8")
|
|
575
|
+
main()
|