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,642 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Technical indicator analysis — MA, MACD, RSI, BOLL, KDJ, volume."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def fetch_kline(symbol: str, period: str = "daily", count: int = 120) -> list:
|
|
15
|
+
script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
|
|
16
|
+
r = subprocess.run(
|
|
17
|
+
[sys.executable, script, "kline", symbol, "--period", period, "--count", str(count)],
|
|
18
|
+
capture_output=True,
|
|
19
|
+
text=True,
|
|
20
|
+
encoding="utf-8",
|
|
21
|
+
)
|
|
22
|
+
return json.loads(r.stdout)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def to_dataframe(records: list) -> pd.DataFrame:
|
|
26
|
+
df = pd.DataFrame(records)
|
|
27
|
+
for c in ["open", "high", "low", "close", "volume"]:
|
|
28
|
+
if c in df.columns:
|
|
29
|
+
df[c] = pd.to_numeric(df[c], errors="coerce")
|
|
30
|
+
if "date" in df.columns:
|
|
31
|
+
df["date"] = pd.to_datetime(df["date"], errors="coerce")
|
|
32
|
+
df = df.sort_values("date").reset_index(drop=True)
|
|
33
|
+
return df
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# --------------- Indicators ---------------
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def calc_ma(close: pd.Series) -> dict:
|
|
40
|
+
mas = {}
|
|
41
|
+
for n in [5, 10, 20, 60]:
|
|
42
|
+
ma = close.rolling(n).mean()
|
|
43
|
+
mas[f"ma{n}"] = round(float(ma.iloc[-1]), 2) if len(ma.dropna()) > 0 else None
|
|
44
|
+
vals = [mas.get(f"ma{n}") for n in [5, 10, 20, 60]]
|
|
45
|
+
valid = [v for v in vals if v is not None]
|
|
46
|
+
if len(valid) >= 3:
|
|
47
|
+
if valid == sorted(valid, reverse=True):
|
|
48
|
+
mas["ma_arrangement"] = "bullish"
|
|
49
|
+
elif valid == sorted(valid):
|
|
50
|
+
mas["ma_arrangement"] = "bearish"
|
|
51
|
+
else:
|
|
52
|
+
mas["ma_arrangement"] = "mixed"
|
|
53
|
+
else:
|
|
54
|
+
mas["ma_arrangement"] = "insufficient_data"
|
|
55
|
+
return mas
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def calc_macd(close: pd.Series) -> dict:
|
|
59
|
+
ema12 = close.ewm(span=12, adjust=False).mean()
|
|
60
|
+
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
61
|
+
dif = ema12 - ema26
|
|
62
|
+
dea = dif.ewm(span=9, adjust=False).mean()
|
|
63
|
+
macd = 2 * (dif - dea)
|
|
64
|
+
d, de, m = float(dif.iloc[-1]), float(dea.iloc[-1]), float(macd.iloc[-1])
|
|
65
|
+
signal = "bullish" if d > de else "bearish"
|
|
66
|
+
prev_cross = (
|
|
67
|
+
"golden_cross"
|
|
68
|
+
if len(dif) >= 2 and dif.iloc[-2] <= dea.iloc[-2] and d > de
|
|
69
|
+
else "death_cross"
|
|
70
|
+
if len(dif) >= 2 and dif.iloc[-2] >= dea.iloc[-2] and d < de
|
|
71
|
+
else None
|
|
72
|
+
)
|
|
73
|
+
result = {"dif": round(d, 2), "dea": round(de, 2), "macd": round(m, 2), "signal": signal}
|
|
74
|
+
if prev_cross:
|
|
75
|
+
result["cross"] = prev_cross
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def calc_rsi(close: pd.Series) -> dict:
|
|
80
|
+
result = {}
|
|
81
|
+
for n in [6, 12, 24]:
|
|
82
|
+
delta = close.diff()
|
|
83
|
+
gain = delta.where(delta > 0, 0.0).rolling(n).mean()
|
|
84
|
+
loss = (-delta.where(delta < 0, 0.0)).rolling(n).mean()
|
|
85
|
+
rs = gain / loss.replace(0, np.nan)
|
|
86
|
+
rsi = 100 - 100 / (1 + rs)
|
|
87
|
+
val = float(rsi.iloc[-1]) if not np.isnan(rsi.iloc[-1]) else None
|
|
88
|
+
result[f"rsi{n}"] = round(val, 2) if val is not None else None
|
|
89
|
+
|
|
90
|
+
r6 = result.get("rsi6")
|
|
91
|
+
if r6 is not None:
|
|
92
|
+
if r6 > 80:
|
|
93
|
+
result["signal"] = "overbought"
|
|
94
|
+
elif r6 < 20:
|
|
95
|
+
result["signal"] = "oversold"
|
|
96
|
+
elif r6 > 70:
|
|
97
|
+
result["signal"] = "approaching_overbought"
|
|
98
|
+
elif r6 < 30:
|
|
99
|
+
result["signal"] = "approaching_oversold"
|
|
100
|
+
else:
|
|
101
|
+
result["signal"] = "neutral"
|
|
102
|
+
else:
|
|
103
|
+
result["signal"] = "insufficient_data"
|
|
104
|
+
return result
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def calc_bollinger(close: pd.Series) -> dict:
|
|
108
|
+
mid = close.rolling(20).mean()
|
|
109
|
+
std = close.rolling(20).std()
|
|
110
|
+
upper = mid + 2 * std
|
|
111
|
+
lower = mid - 2 * std
|
|
112
|
+
u, m, l_ = float(upper.iloc[-1]), float(mid.iloc[-1]), float(lower.iloc[-1])
|
|
113
|
+
price = float(close.iloc[-1])
|
|
114
|
+
bw = (u - l_) / m * 100 if m != 0 else 0
|
|
115
|
+
pos = (price - l_) / (u - l_) if (u - l_) != 0 else 0.5
|
|
116
|
+
if pos > 0.8:
|
|
117
|
+
position = "near_upper"
|
|
118
|
+
elif pos < 0.2:
|
|
119
|
+
position = "near_lower"
|
|
120
|
+
elif pos > 0.5:
|
|
121
|
+
position = "upper_half"
|
|
122
|
+
else:
|
|
123
|
+
position = "lower_half"
|
|
124
|
+
return {
|
|
125
|
+
"upper": round(u, 2),
|
|
126
|
+
"mid": round(m, 2),
|
|
127
|
+
"lower": round(l_, 2),
|
|
128
|
+
"position": position,
|
|
129
|
+
"bandwidth": round(bw, 2),
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def calc_kdj(high: pd.Series, low: pd.Series, close: pd.Series) -> dict:
|
|
134
|
+
low_n = low.rolling(9).min()
|
|
135
|
+
high_n = high.rolling(9).max()
|
|
136
|
+
rsv = (close - low_n) / (high_n - low_n).replace(0, np.nan) * 100
|
|
137
|
+
rsv = rsv.fillna(50)
|
|
138
|
+
k = rsv.ewm(com=2, adjust=False).mean()
|
|
139
|
+
d = k.ewm(com=2, adjust=False).mean()
|
|
140
|
+
j = 3 * k - 2 * d
|
|
141
|
+
kv, dv, jv = float(k.iloc[-1]), float(d.iloc[-1]), float(j.iloc[-1])
|
|
142
|
+
if jv > 80:
|
|
143
|
+
signal = "overbought"
|
|
144
|
+
elif jv < 20:
|
|
145
|
+
signal = "oversold"
|
|
146
|
+
else:
|
|
147
|
+
signal = "neutral"
|
|
148
|
+
return {"k": round(kv, 2), "d": round(dv, 2), "j": round(jv, 2), "signal": signal}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def calc_volume(volume: pd.Series) -> dict:
|
|
152
|
+
vol_ma5 = float(volume.rolling(5).mean().iloc[-1])
|
|
153
|
+
vol_ma10 = float(volume.rolling(10).mean().iloc[-1])
|
|
154
|
+
cur = float(volume.iloc[-1])
|
|
155
|
+
ratio = cur / vol_ma5 if vol_ma5 > 0 else 0
|
|
156
|
+
if ratio > 3:
|
|
157
|
+
signal = "extremely_heavy"
|
|
158
|
+
elif ratio > 2:
|
|
159
|
+
signal = "heavy"
|
|
160
|
+
elif ratio < 0.5:
|
|
161
|
+
signal = "light"
|
|
162
|
+
else:
|
|
163
|
+
signal = "normal"
|
|
164
|
+
return {
|
|
165
|
+
"current": int(cur),
|
|
166
|
+
"vol_ma5": round(vol_ma5, 0),
|
|
167
|
+
"vol_ma10": round(vol_ma10, 0),
|
|
168
|
+
"volume_ratio": round(ratio, 2),
|
|
169
|
+
"signal": signal,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def calc_support_resistance(close: pd.Series, high: pd.Series, low: pd.Series, boll: dict, ma: dict) -> dict:
|
|
174
|
+
recent_high = round(float(high.tail(20).max()), 2)
|
|
175
|
+
recent_low = round(float(low.tail(20).min()), 2)
|
|
176
|
+
resistance = sorted(set(filter(None, [boll.get("upper"), recent_high, ma.get("ma60")])), reverse=True)[:3]
|
|
177
|
+
support = sorted(set(filter(None, [boll.get("lower"), recent_low, ma.get("ma60")])))[:3]
|
|
178
|
+
return {"resistance": resistance, "support": support}
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def calc_trend(ma: dict) -> dict:
|
|
182
|
+
def _cmp(a, b):
|
|
183
|
+
if a is None or b is None:
|
|
184
|
+
return "unknown"
|
|
185
|
+
return "bullish" if a > b else "bearish" if a < b else "neutral"
|
|
186
|
+
|
|
187
|
+
short = _cmp(ma.get("ma5"), ma.get("ma10"))
|
|
188
|
+
medium = _cmp(ma.get("ma10"), ma.get("ma20"))
|
|
189
|
+
long_ = _cmp(ma.get("ma20"), ma.get("ma60"))
|
|
190
|
+
scores = {"bullish": 1, "neutral": 0, "bearish": -1, "unknown": 0}
|
|
191
|
+
total = scores[short] + scores[medium] + scores[long_]
|
|
192
|
+
overall = "bullish" if total >= 2 else "bearish" if total <= -2 else "neutral"
|
|
193
|
+
return {"short_term": short, "medium_term": medium, "long_term": long_, "overall": overall}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def calc_bias(close: pd.Series, ma_data: dict) -> dict:
|
|
197
|
+
price = float(close.iloc[-1])
|
|
198
|
+
result = {}
|
|
199
|
+
for n in [5, 10, 20]:
|
|
200
|
+
ma_val = ma_data.get(f"ma{n}")
|
|
201
|
+
if ma_val and ma_val > 0:
|
|
202
|
+
result[f"bias_ma{n}"] = round((price - ma_val) / ma_val * 100, 2)
|
|
203
|
+
else:
|
|
204
|
+
result[f"bias_ma{n}"] = None
|
|
205
|
+
return result
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def calc_volume_direction(close: pd.Series, volume: pd.Series) -> str:
|
|
209
|
+
if len(close) < 2:
|
|
210
|
+
return "normal"
|
|
211
|
+
price_up = float(close.iloc[-1]) > float(close.iloc[-2])
|
|
212
|
+
vol_ma5 = float(volume.rolling(5).mean().iloc[-1])
|
|
213
|
+
cur_vol = float(volume.iloc[-1])
|
|
214
|
+
heavy = cur_vol > vol_ma5 * 1.5
|
|
215
|
+
shrink = cur_vol < vol_ma5 * 0.7
|
|
216
|
+
if heavy and price_up:
|
|
217
|
+
return "heavy_volume_up"
|
|
218
|
+
elif heavy and not price_up:
|
|
219
|
+
return "heavy_volume_down"
|
|
220
|
+
elif shrink and not price_up:
|
|
221
|
+
return "shrink_volume_down"
|
|
222
|
+
elif shrink and price_up:
|
|
223
|
+
return "shrink_volume_up"
|
|
224
|
+
return "normal"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def calc_ma_support(close: pd.Series, ma_data: dict) -> dict:
|
|
228
|
+
price = float(close.iloc[-1])
|
|
229
|
+
tolerance = 0.02
|
|
230
|
+
support_ma5 = False
|
|
231
|
+
support_ma10 = False
|
|
232
|
+
if ma_data.get("ma5"):
|
|
233
|
+
diff = (price - ma_data["ma5"]) / ma_data["ma5"]
|
|
234
|
+
if -tolerance <= diff <= tolerance * 2:
|
|
235
|
+
support_ma5 = True
|
|
236
|
+
if ma_data.get("ma10"):
|
|
237
|
+
diff = (price - ma_data["ma10"]) / ma_data["ma10"]
|
|
238
|
+
if -tolerance <= diff <= tolerance * 2:
|
|
239
|
+
support_ma10 = True
|
|
240
|
+
return {"support_ma5": support_ma5, "support_ma10": support_ma10}
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def generate_signal_score(
|
|
244
|
+
ma_data: dict,
|
|
245
|
+
macd_data: dict,
|
|
246
|
+
rsi_data: dict,
|
|
247
|
+
vol_data: dict,
|
|
248
|
+
trend_data: dict,
|
|
249
|
+
bias_data: dict,
|
|
250
|
+
close: pd.Series,
|
|
251
|
+
volume: pd.Series,
|
|
252
|
+
) -> dict:
|
|
253
|
+
score = 0
|
|
254
|
+
reasons = []
|
|
255
|
+
risks = []
|
|
256
|
+
|
|
257
|
+
# --- Trend score (30 points) ---
|
|
258
|
+
arrangement = ma_data.get("ma_arrangement", "mixed")
|
|
259
|
+
overall = trend_data.get("overall", "neutral")
|
|
260
|
+
short_t = trend_data.get("short_term", "neutral")
|
|
261
|
+
medium_t = trend_data.get("medium_term", "neutral")
|
|
262
|
+
long_t = trend_data.get("long_term", "neutral")
|
|
263
|
+
|
|
264
|
+
bull_count = sum(1 for t in [short_t, medium_t, long_t] if t == "bullish")
|
|
265
|
+
bear_count = sum(1 for t in [short_t, medium_t, long_t] if t == "bearish")
|
|
266
|
+
|
|
267
|
+
if arrangement == "bullish" and bull_count == 3:
|
|
268
|
+
trend_score = 30
|
|
269
|
+
reasons.append("均线完美多头排列,趋势强劲")
|
|
270
|
+
elif arrangement == "bullish":
|
|
271
|
+
trend_score = 26
|
|
272
|
+
reasons.append("均线多头排列,趋势向好")
|
|
273
|
+
elif bull_count >= 2:
|
|
274
|
+
trend_score = 18
|
|
275
|
+
reasons.append("短中期趋势偏多")
|
|
276
|
+
elif arrangement == "mixed":
|
|
277
|
+
trend_score = 12
|
|
278
|
+
elif bear_count >= 2:
|
|
279
|
+
trend_score = 8
|
|
280
|
+
risks.append("中长期趋势偏空")
|
|
281
|
+
elif arrangement == "bearish" and bear_count == 3:
|
|
282
|
+
trend_score = 0
|
|
283
|
+
risks.append("均线空头排列,趋势极弱")
|
|
284
|
+
elif arrangement == "bearish":
|
|
285
|
+
trend_score = 4
|
|
286
|
+
risks.append("均线空头排列,不宜做多")
|
|
287
|
+
else:
|
|
288
|
+
trend_score = 12
|
|
289
|
+
score += trend_score
|
|
290
|
+
|
|
291
|
+
# --- Bias score (20 points) ---
|
|
292
|
+
is_strong_bull = (
|
|
293
|
+
arrangement == "bullish"
|
|
294
|
+
and bull_count == 3
|
|
295
|
+
and trend_score >= 21
|
|
296
|
+
and ma_data.get("ma5")
|
|
297
|
+
and ma_data.get("ma20")
|
|
298
|
+
and ma_data["ma20"] > 0
|
|
299
|
+
and (ma_data["ma5"] - ma_data["ma20"]) / ma_data["ma20"] > 0.05
|
|
300
|
+
)
|
|
301
|
+
bias_threshold = 7.5 if is_strong_bull else 5.0
|
|
302
|
+
|
|
303
|
+
bias5 = bias_data.get("bias_ma5")
|
|
304
|
+
if bias5 is not None:
|
|
305
|
+
if bias5 < 0:
|
|
306
|
+
if bias5 > -3:
|
|
307
|
+
score += 20
|
|
308
|
+
reasons.append(f"价格略低于MA5({bias5:.1f}%),回踩买点")
|
|
309
|
+
elif bias5 > -5:
|
|
310
|
+
score += 16
|
|
311
|
+
reasons.append(f"价格回踩MA5({bias5:.1f}%),观察支撑")
|
|
312
|
+
else:
|
|
313
|
+
score += 8
|
|
314
|
+
risks.append(f"乖离率过大({bias5:.1f}%),可能破位")
|
|
315
|
+
elif bias5 < 2:
|
|
316
|
+
score += 18
|
|
317
|
+
reasons.append(f"价格贴近MA5({bias5:.1f}%),介入好时机")
|
|
318
|
+
elif bias5 < 5:
|
|
319
|
+
score += 14
|
|
320
|
+
reasons.append(f"价格略高于MA5({bias5:.1f}%),可小仓介入")
|
|
321
|
+
elif is_strong_bull and bias5 < bias_threshold:
|
|
322
|
+
score += 10
|
|
323
|
+
reasons.append(f"强势趋势下乖离({bias5:.1f}%)尚可,可轻仓追踪")
|
|
324
|
+
else:
|
|
325
|
+
score += 4
|
|
326
|
+
risks.append(f"乖离率过高({bias5:.1f}%),严禁追高")
|
|
327
|
+
else:
|
|
328
|
+
score += 10
|
|
329
|
+
|
|
330
|
+
# --- Volume score (15 points) ---
|
|
331
|
+
vol_dir = calc_volume_direction(close, volume)
|
|
332
|
+
vol_scores = {
|
|
333
|
+
"shrink_volume_down": 15,
|
|
334
|
+
"heavy_volume_up": 12,
|
|
335
|
+
"normal": 10,
|
|
336
|
+
"shrink_volume_up": 6,
|
|
337
|
+
"heavy_volume_down": 0,
|
|
338
|
+
}
|
|
339
|
+
vol_score = vol_scores.get(vol_dir, 8)
|
|
340
|
+
score += vol_score
|
|
341
|
+
if vol_dir == "shrink_volume_down":
|
|
342
|
+
reasons.append("缩量回调,主力洗盘特征")
|
|
343
|
+
elif vol_dir == "heavy_volume_down":
|
|
344
|
+
risks.append("放量下跌,注意风险")
|
|
345
|
+
elif vol_dir == "heavy_volume_up":
|
|
346
|
+
reasons.append("放量上涨,资金积极入场")
|
|
347
|
+
|
|
348
|
+
# --- Support score (10 points) ---
|
|
349
|
+
ma_support = calc_ma_support(close, ma_data)
|
|
350
|
+
if ma_support["support_ma5"]:
|
|
351
|
+
score += 5
|
|
352
|
+
reasons.append("MA5支撑有效")
|
|
353
|
+
if ma_support["support_ma10"]:
|
|
354
|
+
score += 5
|
|
355
|
+
reasons.append("MA10支撑有效")
|
|
356
|
+
|
|
357
|
+
# --- MACD score (15 points) ---
|
|
358
|
+
cross = macd_data.get("cross")
|
|
359
|
+
macd_sig = macd_data.get("signal", "bearish")
|
|
360
|
+
dif = macd_data.get("dif", 0)
|
|
361
|
+
|
|
362
|
+
if cross == "golden_cross" and dif > 0:
|
|
363
|
+
macd_score = 15
|
|
364
|
+
reasons.append("MACD零轴上金叉,强势信号")
|
|
365
|
+
elif cross == "golden_cross":
|
|
366
|
+
macd_score = 12
|
|
367
|
+
reasons.append("MACD金叉,短期看多")
|
|
368
|
+
elif macd_sig == "bullish" and dif > 0:
|
|
369
|
+
macd_score = 10
|
|
370
|
+
reasons.append("MACD多头且位于零轴上方")
|
|
371
|
+
elif macd_sig == "bullish":
|
|
372
|
+
macd_score = 8
|
|
373
|
+
elif cross == "death_cross":
|
|
374
|
+
macd_score = 0
|
|
375
|
+
risks.append("MACD死叉,短期看空")
|
|
376
|
+
elif macd_sig == "bearish":
|
|
377
|
+
macd_score = 2
|
|
378
|
+
else:
|
|
379
|
+
macd_score = 5
|
|
380
|
+
score += macd_score
|
|
381
|
+
|
|
382
|
+
# --- RSI score (10 points) ---
|
|
383
|
+
rsi_sig = rsi_data.get("signal", "neutral")
|
|
384
|
+
rsi12 = rsi_data.get("rsi12")
|
|
385
|
+
if rsi_sig == "oversold" or rsi_sig == "approaching_oversold":
|
|
386
|
+
rsi_score = 10
|
|
387
|
+
reasons.append(f"RSI超卖区间({rsi12}),反弹机会大")
|
|
388
|
+
elif rsi_sig == "neutral" and rsi12 and rsi12 < 50:
|
|
389
|
+
rsi_score = 8
|
|
390
|
+
elif rsi_sig == "neutral":
|
|
391
|
+
rsi_score = 5
|
|
392
|
+
elif rsi_sig == "approaching_overbought":
|
|
393
|
+
rsi_score = 3
|
|
394
|
+
risks.append(f"RSI接近超买({rsi12}),注意回调")
|
|
395
|
+
elif rsi_sig == "overbought":
|
|
396
|
+
rsi_score = 0
|
|
397
|
+
risks.append(f"RSI超买({rsi12}),回调风险高")
|
|
398
|
+
else:
|
|
399
|
+
rsi_score = 5
|
|
400
|
+
score += rsi_score
|
|
401
|
+
|
|
402
|
+
# --- Buy signal classification ---
|
|
403
|
+
if score >= 75 and overall == "bullish":
|
|
404
|
+
buy_signal = "STRONG_BUY"
|
|
405
|
+
elif score >= 60 and overall in ("bullish", "neutral"):
|
|
406
|
+
buy_signal = "BUY"
|
|
407
|
+
elif score >= 45:
|
|
408
|
+
buy_signal = "HOLD"
|
|
409
|
+
elif score >= 30:
|
|
410
|
+
buy_signal = "WAIT"
|
|
411
|
+
elif overall == "bearish" and score < 20:
|
|
412
|
+
buy_signal = "STRONG_SELL"
|
|
413
|
+
else:
|
|
414
|
+
buy_signal = "SELL"
|
|
415
|
+
|
|
416
|
+
return {
|
|
417
|
+
"signal_score": score,
|
|
418
|
+
"buy_signal": buy_signal,
|
|
419
|
+
"signal_reasons": reasons,
|
|
420
|
+
"risk_factors": risks,
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def generate_signals(
|
|
425
|
+
ma_data: dict, macd_data: dict, rsi_data: dict, boll_data: dict, kdj_data: dict, vol_data: dict, trend_data: dict
|
|
426
|
+
) -> list:
|
|
427
|
+
signals = []
|
|
428
|
+
if macd_data.get("cross") == "golden_cross":
|
|
429
|
+
signals.append("MACD金叉,短期看多")
|
|
430
|
+
elif macd_data.get("cross") == "death_cross":
|
|
431
|
+
signals.append("MACD死叉,短期看空")
|
|
432
|
+
|
|
433
|
+
if macd_data["signal"] == "bullish":
|
|
434
|
+
signals.append("MACD多头排列(DIF > DEA)")
|
|
435
|
+
else:
|
|
436
|
+
signals.append("MACD空头排列(DIF < DEA)")
|
|
437
|
+
|
|
438
|
+
rsi_sig = rsi_data.get("signal", "")
|
|
439
|
+
if "overbought" in rsi_sig:
|
|
440
|
+
signals.append(f"RSI超买区间(RSI6={rsi_data.get('rsi6')}),注意回调风险")
|
|
441
|
+
elif "oversold" in rsi_sig:
|
|
442
|
+
signals.append(f"RSI超卖区间(RSI6={rsi_data.get('rsi6')}),关注反弹机会")
|
|
443
|
+
else:
|
|
444
|
+
signals.append(f"RSI处于中性区间(RSI6={rsi_data.get('rsi6')})")
|
|
445
|
+
|
|
446
|
+
bp = boll_data.get("position", "")
|
|
447
|
+
if bp == "near_upper":
|
|
448
|
+
signals.append("股价接近布林带上轨,短期压力较大")
|
|
449
|
+
elif bp == "near_lower":
|
|
450
|
+
signals.append("股价接近布林带下轨,可能存在支撑")
|
|
451
|
+
elif bp == "upper_half":
|
|
452
|
+
signals.append("股价运行于布林带上半区,偏强势")
|
|
453
|
+
else:
|
|
454
|
+
signals.append("股价运行于布林带下半区,偏弱势")
|
|
455
|
+
|
|
456
|
+
if kdj_data["signal"] == "overbought":
|
|
457
|
+
signals.append(f"KDJ超买(J={kdj_data['j']}),注意高位风险")
|
|
458
|
+
elif kdj_data["signal"] == "oversold":
|
|
459
|
+
signals.append(f"KDJ超卖(J={kdj_data['j']}),关注低位机会")
|
|
460
|
+
|
|
461
|
+
vs = vol_data.get("signal", "")
|
|
462
|
+
if "heavy" in vs:
|
|
463
|
+
signals.append(f"成交量放大(量比={vol_data['volume_ratio']}),市场关注度高")
|
|
464
|
+
elif vs == "light":
|
|
465
|
+
signals.append(f"缩量交易(量比={vol_data['volume_ratio']}),市场观望情绪浓")
|
|
466
|
+
|
|
467
|
+
arr = ma_data.get("ma_arrangement")
|
|
468
|
+
if arr == "bullish":
|
|
469
|
+
signals.append("均线多头排列,趋势向好")
|
|
470
|
+
elif arr == "bearish":
|
|
471
|
+
signals.append("均线空头排列,趋势偏弱")
|
|
472
|
+
|
|
473
|
+
return signals
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
# --------------- Standalone MA calculator ---------------
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def calculate_ma_standalone(
|
|
480
|
+
symbol: str, periods: list[int] = None, kline_period: str = "daily", count: int = 120
|
|
481
|
+
) -> dict:
|
|
482
|
+
if periods is None:
|
|
483
|
+
periods = [5, 10, 20, 30, 60, 120, 250]
|
|
484
|
+
|
|
485
|
+
records = fetch_kline(symbol, kline_period, count)
|
|
486
|
+
if isinstance(records, dict) and "error" in records:
|
|
487
|
+
return records
|
|
488
|
+
if not records:
|
|
489
|
+
return {"error": "No kline data returned"}
|
|
490
|
+
|
|
491
|
+
df = to_dataframe(records)
|
|
492
|
+
close = df["close"]
|
|
493
|
+
price = float(close.iloc[-1])
|
|
494
|
+
|
|
495
|
+
mas = {}
|
|
496
|
+
for n in periods:
|
|
497
|
+
if len(close) < n:
|
|
498
|
+
mas[f"ma{n}"] = None
|
|
499
|
+
continue
|
|
500
|
+
val = float(close.rolling(n).mean().iloc[-1])
|
|
501
|
+
mas[f"ma{n}"] = round(val, 2)
|
|
502
|
+
|
|
503
|
+
bias = {}
|
|
504
|
+
for n in periods:
|
|
505
|
+
ma_val = mas.get(f"ma{n}")
|
|
506
|
+
if ma_val and ma_val > 0:
|
|
507
|
+
bias[f"bias_ma{n}"] = round((price - ma_val) / ma_val * 100, 2)
|
|
508
|
+
else:
|
|
509
|
+
bias[f"bias_ma{n}"] = None
|
|
510
|
+
|
|
511
|
+
valid_mas = [(n, mas[f"ma{n}"]) for n in periods if mas.get(f"ma{n}") is not None]
|
|
512
|
+
if len(valid_mas) >= 3:
|
|
513
|
+
vals = [v for _, v in valid_mas]
|
|
514
|
+
if vals == sorted(vals, reverse=True):
|
|
515
|
+
alignment = "bullish"
|
|
516
|
+
elif vals == sorted(vals):
|
|
517
|
+
alignment = "bearish"
|
|
518
|
+
else:
|
|
519
|
+
alignment = "mixed"
|
|
520
|
+
else:
|
|
521
|
+
alignment = "insufficient_data"
|
|
522
|
+
|
|
523
|
+
cross_signals = []
|
|
524
|
+
for fast, slow in [(5, 10), (5, 20), (10, 20), (20, 60)]:
|
|
525
|
+
if fast not in periods or slow not in periods:
|
|
526
|
+
continue
|
|
527
|
+
if len(close) < max(fast, slow) + 1:
|
|
528
|
+
continue
|
|
529
|
+
ma_fast = close.rolling(fast).mean()
|
|
530
|
+
ma_slow = close.rolling(slow).mean()
|
|
531
|
+
if len(ma_fast.dropna()) >= 2 and len(ma_slow.dropna()) >= 2:
|
|
532
|
+
prev_diff = float(ma_fast.iloc[-2]) - float(ma_slow.iloc[-2])
|
|
533
|
+
curr_diff = float(ma_fast.iloc[-1]) - float(ma_slow.iloc[-1])
|
|
534
|
+
if prev_diff <= 0 and curr_diff > 0:
|
|
535
|
+
cross_signals.append({"type": "golden_cross", "fast": f"MA{fast}", "slow": f"MA{slow}"})
|
|
536
|
+
elif prev_diff >= 0 and curr_diff < 0:
|
|
537
|
+
cross_signals.append({"type": "death_cross", "fast": f"MA{fast}", "slow": f"MA{slow}"})
|
|
538
|
+
|
|
539
|
+
return {
|
|
540
|
+
"symbol": symbol,
|
|
541
|
+
"period": kline_period,
|
|
542
|
+
"price": price,
|
|
543
|
+
"moving_averages": mas,
|
|
544
|
+
"bias": bias,
|
|
545
|
+
"alignment": alignment,
|
|
546
|
+
"cross_signals": cross_signals,
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
# --------------- Main ---------------
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def analyze(symbol: str, period: str = "daily", count: int = 120) -> dict:
|
|
554
|
+
records = fetch_kline(symbol, period, count)
|
|
555
|
+
if isinstance(records, dict) and "error" in records:
|
|
556
|
+
return records
|
|
557
|
+
if not records:
|
|
558
|
+
return {"error": "No kline data returned"}
|
|
559
|
+
|
|
560
|
+
df = to_dataframe(records)
|
|
561
|
+
if len(df) < 30:
|
|
562
|
+
return {"error": f"Insufficient data: {len(df)} rows (need at least 30)"}
|
|
563
|
+
|
|
564
|
+
close, high, low, volume = df["close"], df["high"], df["low"], df["volume"]
|
|
565
|
+
|
|
566
|
+
ma_data = calc_ma(close)
|
|
567
|
+
macd_data = calc_macd(close)
|
|
568
|
+
rsi_data = calc_rsi(close)
|
|
569
|
+
boll_data = calc_bollinger(close)
|
|
570
|
+
kdj_data = calc_kdj(high, low, close)
|
|
571
|
+
vol_data = calc_volume(volume)
|
|
572
|
+
sr_data = calc_support_resistance(close, high, low, boll_data, ma_data)
|
|
573
|
+
trend_data = calc_trend(ma_data)
|
|
574
|
+
bias_data = calc_bias(close, ma_data)
|
|
575
|
+
sig_list = generate_signals(ma_data, macd_data, rsi_data, boll_data, kdj_data, vol_data, trend_data)
|
|
576
|
+
score_data = generate_signal_score(ma_data, macd_data, rsi_data, vol_data, trend_data, bias_data, close, volume)
|
|
577
|
+
|
|
578
|
+
return {
|
|
579
|
+
"symbol": symbol,
|
|
580
|
+
"period": period,
|
|
581
|
+
"data_points": len(df),
|
|
582
|
+
"latest": {
|
|
583
|
+
"date": str(df["date"].iloc[-1].date())
|
|
584
|
+
if hasattr(df["date"].iloc[-1], "date")
|
|
585
|
+
else str(df["date"].iloc[-1]),
|
|
586
|
+
"close": round(float(close.iloc[-1]), 2),
|
|
587
|
+
"volume": int(volume.iloc[-1]),
|
|
588
|
+
},
|
|
589
|
+
"moving_averages": ma_data,
|
|
590
|
+
"macd": macd_data,
|
|
591
|
+
"rsi": rsi_data,
|
|
592
|
+
"bollinger": boll_data,
|
|
593
|
+
"kdj": kdj_data,
|
|
594
|
+
"volume": vol_data,
|
|
595
|
+
"support_resistance": sr_data,
|
|
596
|
+
"trend": trend_data,
|
|
597
|
+
"bias": bias_data,
|
|
598
|
+
"signal_score": score_data["signal_score"],
|
|
599
|
+
"buy_signal": score_data["buy_signal"],
|
|
600
|
+
"signal_reasons": score_data["signal_reasons"],
|
|
601
|
+
"risk_factors": score_data["risk_factors"],
|
|
602
|
+
"signals": sig_list,
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def main():
|
|
607
|
+
parser = argparse.ArgumentParser(description="Technical indicator analysis")
|
|
608
|
+
sub = parser.add_subparsers(dest="command")
|
|
609
|
+
|
|
610
|
+
p = sub.add_parser("analyze")
|
|
611
|
+
p.add_argument("symbol")
|
|
612
|
+
p.add_argument("--period", default="daily", choices=["daily", "weekly", "monthly"])
|
|
613
|
+
p.add_argument("--count", type=int, default=120)
|
|
614
|
+
|
|
615
|
+
p_ma = sub.add_parser("calculate_ma")
|
|
616
|
+
p_ma.add_argument("symbol")
|
|
617
|
+
p_ma.add_argument("--periods", default="5,10,20,30,60,120,250", help="Comma-separated MA periods")
|
|
618
|
+
p_ma.add_argument("--period", default="daily", choices=["daily", "weekly", "monthly"])
|
|
619
|
+
p_ma.add_argument("--count", type=int, default=250)
|
|
620
|
+
|
|
621
|
+
args = parser.parse_args()
|
|
622
|
+
if not args.command:
|
|
623
|
+
parser.print_help()
|
|
624
|
+
sys.exit(1)
|
|
625
|
+
|
|
626
|
+
if args.command == "analyze":
|
|
627
|
+
result = analyze(args.symbol, args.period, args.count)
|
|
628
|
+
elif args.command == "calculate_ma":
|
|
629
|
+
periods = [int(x.strip()) for x in args.periods.split(",")]
|
|
630
|
+
result = calculate_ma_standalone(args.symbol, periods, args.period, args.count)
|
|
631
|
+
else:
|
|
632
|
+
result = {"error": f"Unknown command: {args.command}"}
|
|
633
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
if __name__ == "__main__":
|
|
637
|
+
# Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
|
|
638
|
+
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
639
|
+
for _s in (sys.stdout, sys.stderr):
|
|
640
|
+
if hasattr(_s, "reconfigure"):
|
|
641
|
+
_s.reconfigure(encoding="utf-8")
|
|
642
|
+
main()
|