openclaw-stock-analysis 0.2.1 → 0.2.5
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/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/index.js +170 -23
- package/index.ts +184 -26
- package/openclaw.plugin.json +10 -1
- package/package.json +1 -1
- package/scripts/ci-resolve-llm-host.mjs +29 -0
- package/scripts/setup-python.mjs +7 -9
- package/skills/event-driven/SKILL.md +6 -0
- package/skills/growth-quality/SKILL.md +6 -0
- package/skills/hot-theme/SKILL.md +3 -2
- package/skills/stock-analysis/SKILL.md +22 -0
- package/skills/stock-screener/SKILL.md +19 -1
- package/skills/strategy-backtest/SKILL.md +11 -5
- package/strategies/examples/bottom_volume.yaml +5 -0
- package/strategies/examples/box_oscillation.yaml +5 -0
- package/strategies/examples/bull_trend.yaml +11 -3
- package/strategies/examples/dragon_head.yaml +4 -2
- package/strategies/examples/emotion_cycle.yaml +5 -0
- package/strategies/examples/ma_crossover.yaml +10 -3
- package/strategies/examples/rsi_oversold.yaml +5 -0
- package/strategies/examples/shrink_pullback.yaml +7 -1
- package/strategies/examples/volume_breakout.yaml +7 -1
- package/tools/_cache.py +61 -0
- package/tools/_subproc.py +49 -0
- package/tools/alert_rules.py +19 -9
- package/tools/anomaly_detect.py +24 -35
- package/tools/backtest.py +180 -100
- package/tools/capabilities.py +13 -5
- package/tools/diagnostics.py +12 -6
- package/tools/gather.py +13 -9
- package/tools/import_parser.py +2 -5
- package/tools/market_regime.py +27 -35
- package/tools/market_review.py +56 -9
- package/tools/name_resolver.py +2 -5
- package/tools/pattern.py +2 -5
- package/tools/position_context.py +2 -5
- package/tools/report_renderer.py +10 -6
- package/tools/requirements.txt +2 -1
- package/tools/risk_screening.py +29 -23
- package/tools/screener.py +80 -18
- package/tools/search_intel.py +5 -13
- package/tools/signal_tracker.py +2 -6
- package/tools/stock_data.py +612 -177
- package/tools/technical.py +136 -40
- package/tools/trading_calendar.py +78 -18
- package/tools/value_data.py +1368 -0
- package/tools/volume_analysis.py +2 -5
- package/tools/watchlist.py +2 -5
- package/tools/watchlist_context.py +2 -5
package/tools/anomaly_detect.py
CHANGED
|
@@ -12,8 +12,17 @@ import pandas as pd
|
|
|
12
12
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
13
13
|
|
|
14
14
|
from _subproc import run_tool as _run_tool
|
|
15
|
-
from
|
|
16
|
-
from
|
|
15
|
+
from _subproc import utf8_stdio
|
|
16
|
+
from stock_data import calc_limit_price, detect_market, normalize_stock_code
|
|
17
|
+
from technical import (
|
|
18
|
+
bollinger_series,
|
|
19
|
+
fetch_kline,
|
|
20
|
+
kdj_series,
|
|
21
|
+
ma_series,
|
|
22
|
+
macd_series,
|
|
23
|
+
rsi_series,
|
|
24
|
+
to_dataframe,
|
|
25
|
+
)
|
|
17
26
|
|
|
18
27
|
|
|
19
28
|
def _anomaly(type_: str, severity: str, direction: str, description: str, **extra) -> dict:
|
|
@@ -33,10 +42,7 @@ def _anomaly(type_: str, severity: str, direction: str, description: str, **extr
|
|
|
33
42
|
def detect_macd_cross(close: pd.Series) -> list:
|
|
34
43
|
if len(close) < 30:
|
|
35
44
|
return []
|
|
36
|
-
|
|
37
|
-
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
38
|
-
dif = ema12 - ema26
|
|
39
|
-
dea = dif.ewm(span=9, adjust=False).mean()
|
|
45
|
+
dif, dea, _ = macd_series(close)
|
|
40
46
|
|
|
41
47
|
prev_diff = float(dif.iloc[-2] - dea.iloc[-2])
|
|
42
48
|
curr_diff = float(dif.iloc[-1] - dea.iloc[-1])
|
|
@@ -58,11 +64,7 @@ def detect_macd_cross(close: pd.Series) -> list:
|
|
|
58
64
|
def detect_rsi_extreme(close: pd.Series) -> list:
|
|
59
65
|
if len(close) < 10:
|
|
60
66
|
return []
|
|
61
|
-
|
|
62
|
-
gain = delta.where(delta > 0, 0.0).rolling(6).mean()
|
|
63
|
-
loss = (-delta.where(delta < 0, 0.0)).rolling(6).mean()
|
|
64
|
-
rs = gain / loss.replace(0, np.nan)
|
|
65
|
-
rsi = 100 - 100 / (1 + rs)
|
|
67
|
+
rsi = rsi_series(close, 6)
|
|
66
68
|
|
|
67
69
|
if len(rsi.dropna()) < 2:
|
|
68
70
|
return []
|
|
@@ -166,10 +168,7 @@ def detect_volume_spike(volume: pd.Series) -> list:
|
|
|
166
168
|
def detect_bollinger_breakout(close: pd.Series) -> list:
|
|
167
169
|
if len(close) < 21:
|
|
168
170
|
return []
|
|
169
|
-
|
|
170
|
-
std = close.rolling(20).std()
|
|
171
|
-
upper = mid + 2 * std
|
|
172
|
-
lower = mid - 2 * std
|
|
171
|
+
upper, _, lower = bollinger_series(close)
|
|
173
172
|
|
|
174
173
|
curr_price = float(close.iloc[-1])
|
|
175
174
|
prev_price = float(close.iloc[-2])
|
|
@@ -205,13 +204,7 @@ def detect_bollinger_breakout(close: pd.Series) -> list:
|
|
|
205
204
|
def detect_kdj_extreme(high: pd.Series, low: pd.Series, close: pd.Series) -> list:
|
|
206
205
|
if len(close) < 10:
|
|
207
206
|
return []
|
|
208
|
-
|
|
209
|
-
high_n = high.rolling(9).max()
|
|
210
|
-
rsv = (close - low_n) / (high_n - low_n).replace(0, np.nan) * 100
|
|
211
|
-
rsv = rsv.fillna(50)
|
|
212
|
-
k = rsv.ewm(com=2, adjust=False).mean()
|
|
213
|
-
d = k.ewm(com=2, adjust=False).mean()
|
|
214
|
-
j = 3 * k - 2 * d
|
|
207
|
+
_, _, j = kdj_series(high, low, close)
|
|
215
208
|
|
|
216
209
|
if len(j.dropna()) < 2:
|
|
217
210
|
return []
|
|
@@ -315,8 +308,10 @@ def detect_limit_hit(symbol: str, quote: dict) -> list:
|
|
|
315
308
|
|
|
316
309
|
prev_close = float(prev_close)
|
|
317
310
|
price = float(price)
|
|
318
|
-
|
|
319
|
-
|
|
311
|
+
# Exchange rounding (floor(x*100+0.5)/100), same as stock_data's market_stats,
|
|
312
|
+
# so both tools reach the same limit-up/down conclusion for a given quote.
|
|
313
|
+
limit_up_price = calc_limit_price(prev_close, limit_pct, "up")
|
|
314
|
+
limit_down_price = calc_limit_price(prev_close, limit_pct, "down")
|
|
320
315
|
|
|
321
316
|
anomalies = []
|
|
322
317
|
if abs(price - limit_up_price) < 0.02:
|
|
@@ -383,9 +378,7 @@ def detect_divergence(df: pd.DataFrame) -> list:
|
|
|
383
378
|
if len(df) < 30:
|
|
384
379
|
return []
|
|
385
380
|
close = df["close"]
|
|
386
|
-
|
|
387
|
-
ema26 = close.ewm(span=26, adjust=False).mean()
|
|
388
|
-
dif = ema12 - ema26
|
|
381
|
+
dif, _, _ = macd_series(close)
|
|
389
382
|
|
|
390
383
|
window = min(20, len(df) - 10)
|
|
391
384
|
recent_close = close.iloc[-window:]
|
|
@@ -421,9 +414,9 @@ def detect_divergence(df: pd.DataFrame) -> list:
|
|
|
421
414
|
def detect_ma_cross(close: pd.Series) -> list:
|
|
422
415
|
if len(close) < 21:
|
|
423
416
|
return []
|
|
424
|
-
ma5 = close
|
|
425
|
-
ma10 = close
|
|
426
|
-
ma20 = close
|
|
417
|
+
ma5 = ma_series(close, 5)
|
|
418
|
+
ma10 = ma_series(close, 10)
|
|
419
|
+
ma20 = ma_series(close, 20)
|
|
427
420
|
|
|
428
421
|
anomalies = []
|
|
429
422
|
|
|
@@ -553,9 +546,5 @@ def main():
|
|
|
553
546
|
|
|
554
547
|
|
|
555
548
|
if __name__ == "__main__":
|
|
556
|
-
|
|
557
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
558
|
-
for _s in (sys.stdout, sys.stderr):
|
|
559
|
-
if hasattr(_s, "reconfigure"):
|
|
560
|
-
_s.reconfigure(encoding="utf-8")
|
|
549
|
+
utf8_stdio()
|
|
561
550
|
main()
|
package/tools/backtest.py
CHANGED
|
@@ -6,7 +6,6 @@ import json
|
|
|
6
6
|
import math
|
|
7
7
|
import os
|
|
8
8
|
import re
|
|
9
|
-
import subprocess
|
|
10
9
|
import sys
|
|
11
10
|
from datetime import datetime, timedelta
|
|
12
11
|
|
|
@@ -14,6 +13,11 @@ import numpy as np
|
|
|
14
13
|
import pandas as pd
|
|
15
14
|
import yaml
|
|
16
15
|
|
|
16
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
17
|
+
|
|
18
|
+
from _subproc import json_safe, run_tool, utf8_stdio
|
|
19
|
+
from technical import bollinger_series, ema_series, ma_series, macd_series, rsi_series
|
|
20
|
+
|
|
17
21
|
# --------------- Strategy Loading ---------------
|
|
18
22
|
|
|
19
23
|
|
|
@@ -28,6 +32,8 @@ def load_strategy(path: str) -> dict:
|
|
|
28
32
|
def _resolve_refs(obj, params: dict):
|
|
29
33
|
if isinstance(obj, dict):
|
|
30
34
|
for k, v in obj.items():
|
|
35
|
+
if k == "benchmark":
|
|
36
|
+
continue # benchmark is a symbol string ("000300"), never a {param} reference
|
|
31
37
|
if isinstance(v, str):
|
|
32
38
|
obj[k] = _substitute(v, params)
|
|
33
39
|
else:
|
|
@@ -57,20 +63,17 @@ def _substitute(s: str, params: dict):
|
|
|
57
63
|
|
|
58
64
|
|
|
59
65
|
def fetch_kline(symbol: str, start: str | None, end: str | None) -> pd.DataFrame:
|
|
60
|
-
script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
|
|
61
66
|
count = 500
|
|
62
67
|
if start and end:
|
|
63
68
|
d0 = datetime.strptime(start, "%Y-%m-%d")
|
|
64
69
|
d1 = datetime.strptime(end, "%Y-%m-%d")
|
|
65
70
|
count = max((d1 - d0).days + 60, 300)
|
|
66
71
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
)
|
|
73
|
-
data = json.loads(r.stdout)
|
|
72
|
+
# run_tool gives venv-python + a bounded timeout + None on any failure
|
|
73
|
+
# (non-zero exit, empty/invalid stdout); callers turn that into clean JSON.
|
|
74
|
+
data = run_tool("stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(count)])
|
|
75
|
+
if data is None:
|
|
76
|
+
raise RuntimeError(f"Failed to fetch kline for {symbol}")
|
|
74
77
|
if isinstance(data, dict) and "error" in data:
|
|
75
78
|
raise RuntimeError(data["error"])
|
|
76
79
|
|
|
@@ -88,39 +91,37 @@ def fetch_kline(symbol: str, start: str | None, end: str | None) -> pd.DataFrame
|
|
|
88
91
|
return df.reset_index(drop=True)
|
|
89
92
|
|
|
90
93
|
|
|
91
|
-
# --------------- Indicators
|
|
94
|
+
# --------------- Indicators ---------------
|
|
95
|
+
#
|
|
96
|
+
# Series math lives in technical.py (ma_series/ema_series/macd_series/rsi_series/
|
|
97
|
+
# bollinger_series); the wrappers below only add backtest-specific NaN defaults
|
|
98
|
+
# (rsi → 50, bollinger position → 0.5) so strategy evaluation never sees NaN.
|
|
92
99
|
|
|
93
100
|
|
|
94
101
|
def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
|
|
95
|
-
|
|
96
|
-
gain = delta.where(delta > 0, 0.0).rolling(period).mean()
|
|
97
|
-
loss = (-delta.where(delta < 0, 0.0)).rolling(period).mean()
|
|
98
|
-
rs = gain / loss.replace(0, np.nan)
|
|
99
|
-
return (100 - 100 / (1 + rs)).fillna(50)
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def compute_ma(close: pd.Series, period: int) -> pd.Series:
|
|
103
|
-
return close.rolling(period).mean()
|
|
102
|
+
return rsi_series(close, period).fillna(50)
|
|
104
103
|
|
|
105
104
|
|
|
106
|
-
|
|
107
|
-
|
|
105
|
+
# Pure aliases (identical signatures); the other wrappers below add
|
|
106
|
+
# backtest-specific NaN defaults or pick one leg of the MACD tuple.
|
|
107
|
+
compute_ma = ma_series
|
|
108
|
+
compute_ema = ema_series
|
|
108
109
|
|
|
109
110
|
|
|
110
111
|
def compute_macd_dif(close: pd.Series) -> pd.Series:
|
|
111
|
-
return
|
|
112
|
+
return macd_series(close)[0]
|
|
112
113
|
|
|
113
114
|
|
|
114
115
|
def compute_macd_dea(close: pd.Series) -> pd.Series:
|
|
115
|
-
return
|
|
116
|
+
return macd_series(close)[1]
|
|
116
117
|
|
|
117
118
|
|
|
118
119
|
def compute_macd_hist(close: pd.Series) -> pd.Series:
|
|
119
|
-
return
|
|
120
|
+
return macd_series(close)[2]
|
|
120
121
|
|
|
121
122
|
|
|
122
123
|
def compute_volume_ratio(volume: pd.Series, period: int = 5) -> pd.Series:
|
|
123
|
-
ma = volume
|
|
124
|
+
ma = ma_series(volume, period)
|
|
124
125
|
return (volume / ma.replace(0, np.nan)).fillna(1)
|
|
125
126
|
|
|
126
127
|
|
|
@@ -129,40 +130,40 @@ def compute_price_change(close: pd.Series) -> pd.Series:
|
|
|
129
130
|
|
|
130
131
|
|
|
131
132
|
def compute_bollinger_position(close: pd.Series, period: int = 20) -> pd.Series:
|
|
132
|
-
mid = close
|
|
133
|
-
std = close.rolling(period).std()
|
|
134
|
-
upper = mid + 2 * std
|
|
135
|
-
lower = mid - 2 * std
|
|
133
|
+
upper, mid, lower = bollinger_series(close, period)
|
|
136
134
|
width = (upper - lower).replace(0, np.nan)
|
|
137
135
|
return ((close - lower) / width).fillna(0.5)
|
|
138
136
|
|
|
139
137
|
|
|
140
|
-
def
|
|
141
|
-
"""
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
slow = period % 100
|
|
138
|
+
def _resolve_ma_pair(fast: int | None, slow: int | None, period: int | None, default: tuple) -> tuple:
|
|
139
|
+
"""Explicit fast/slow periods win; a legacy encoded `period` (510 = MA5-MA10,
|
|
140
|
+
500 = MA5-MA20 via the slow==0 → fast*4 fallback) still decodes for old YAMLs."""
|
|
141
|
+
if fast is None and slow is None and period and period >= 100:
|
|
142
|
+
fast, slow = period // 100, period % 100
|
|
145
143
|
if slow == 0:
|
|
146
144
|
slow = fast * 4
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
145
|
+
return fast, slow
|
|
146
|
+
return fast or default[0], slow or default[1]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def compute_ma_diff(
|
|
150
|
+
close: pd.Series, period: int | None = None, fast: int | None = None, slow: int | None = None
|
|
151
|
+
) -> pd.Series:
|
|
152
|
+
"""Difference between two MAs. Prefer explicit fast/slow; `period` keeps the legacy encoding."""
|
|
153
|
+
fast, slow = _resolve_ma_pair(fast, slow, period, (5, 20))
|
|
150
154
|
return compute_ma(close, fast) - compute_ma(close, slow)
|
|
151
155
|
|
|
152
156
|
|
|
153
|
-
def compute_ema_diff(
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if slow == 0:
|
|
158
|
-
slow = fast * 4
|
|
159
|
-
else:
|
|
160
|
-
fast = 12
|
|
161
|
-
slow = 26
|
|
157
|
+
def compute_ema_diff(
|
|
158
|
+
close: pd.Series, period: int | None = None, fast: int | None = None, slow: int | None = None
|
|
159
|
+
) -> pd.Series:
|
|
160
|
+
fast, slow = _resolve_ma_pair(fast, slow, period, (12, 26))
|
|
162
161
|
return compute_ema(close, fast) - compute_ema(close, slow)
|
|
163
162
|
|
|
164
163
|
|
|
165
|
-
def get_indicator(
|
|
164
|
+
def get_indicator(
|
|
165
|
+
df: pd.DataFrame, name: str, period: int | None = None, fast: int | None = None, slow: int | None = None
|
|
166
|
+
) -> pd.Series:
|
|
166
167
|
close = df["close"]
|
|
167
168
|
dispatch = {
|
|
168
169
|
"rsi": lambda: compute_rsi(close, period or 14),
|
|
@@ -171,8 +172,8 @@ def get_indicator(df: pd.DataFrame, name: str, period: int | None = None) -> pd.
|
|
|
171
172
|
"macd_dif": lambda: compute_macd_dif(close),
|
|
172
173
|
"macd_dea": lambda: compute_macd_dea(close),
|
|
173
174
|
"macd": lambda: compute_macd_hist(close),
|
|
174
|
-
"ma_diff": lambda: compute_ma_diff(close, period),
|
|
175
|
-
"ema_diff": lambda: compute_ema_diff(close, period),
|
|
175
|
+
"ma_diff": lambda: compute_ma_diff(close, period, fast, slow),
|
|
176
|
+
"ema_diff": lambda: compute_ema_diff(close, period, fast, slow),
|
|
176
177
|
"volume_ratio": lambda: compute_volume_ratio(df["volume"], period or 5),
|
|
177
178
|
"price_change": lambda: compute_price_change(close),
|
|
178
179
|
"bollinger_position": lambda: compute_bollinger_position(close, period or 20),
|
|
@@ -209,21 +210,27 @@ def check_condition(series: pd.Series, operator: str, value: float, idx: int) ->
|
|
|
209
210
|
return False
|
|
210
211
|
|
|
211
212
|
|
|
213
|
+
def _coerce_int(v):
|
|
214
|
+
if isinstance(v, str):
|
|
215
|
+
try:
|
|
216
|
+
return int(float(v))
|
|
217
|
+
except (ValueError, TypeError):
|
|
218
|
+
return None
|
|
219
|
+
return v
|
|
220
|
+
|
|
221
|
+
|
|
212
222
|
def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int, cache: dict) -> tuple[bool, str]:
|
|
213
223
|
results = []
|
|
214
224
|
reasons = []
|
|
215
225
|
for cond in conditions:
|
|
216
226
|
ind_name = cond["indicator"]
|
|
217
|
-
period = cond.get("period")
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
period = None
|
|
223
|
-
|
|
224
|
-
cache_key = f"{ind_name}_{period}"
|
|
227
|
+
period = _coerce_int(cond.get("period"))
|
|
228
|
+
fast = _coerce_int(cond.get("fast_period"))
|
|
229
|
+
slow = _coerce_int(cond.get("slow_period"))
|
|
230
|
+
|
|
231
|
+
cache_key = f"{ind_name}_{period}_{fast}_{slow}"
|
|
225
232
|
if cache_key not in cache:
|
|
226
|
-
cache[cache_key] = get_indicator(df, ind_name, period)
|
|
233
|
+
cache[cache_key] = get_indicator(df, ind_name, period, fast, slow)
|
|
227
234
|
series = cache[cache_key]
|
|
228
235
|
|
|
229
236
|
op = cond["operator"]
|
|
@@ -232,7 +239,7 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
232
239
|
results.append(hit)
|
|
233
240
|
if hit:
|
|
234
241
|
cur_val = round(float(series.iloc[idx]), 2)
|
|
235
|
-
label = f"{ind_name}({period})" if period else ind_name
|
|
242
|
+
label = f"{ind_name}({fast},{slow})" if fast or slow else f"{ind_name}({period})" if period else ind_name
|
|
236
243
|
reasons.append(f"{label} = {cur_val} {op} {val}")
|
|
237
244
|
|
|
238
245
|
if logic == "all":
|
|
@@ -249,6 +256,13 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
249
256
|
sim_cfg = strategy.get("simulation", {})
|
|
250
257
|
slippage = float(sim_cfg.get("slippage", 0.001))
|
|
251
258
|
commission = float(sim_cfg.get("commission", 0.0015))
|
|
259
|
+
tax_raw = sim_cfg.get("stamp_tax") # sell-side only (e.g. A股印花税); absent/empty = 0 (disabled)
|
|
260
|
+
stamp_tax = float(0.0 if tax_raw is None else tax_raw)
|
|
261
|
+
for name, rate in (("slippage", slippage), ("commission", commission), ("stamp_tax", stamp_tax)):
|
|
262
|
+
if not 0 <= rate < 1:
|
|
263
|
+
raise ValueError(f"simulation.{name} must be a rate in [0, 1), got {rate}")
|
|
264
|
+
if commission + stamp_tax >= 1:
|
|
265
|
+
raise ValueError(f"simulation commission + stamp_tax must be < 1, got {commission + stamp_tax}")
|
|
252
266
|
|
|
253
267
|
entry = strategy.get("entry", {})
|
|
254
268
|
exit_ = strategy.get("exit", {})
|
|
@@ -256,6 +270,8 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
256
270
|
size_frac = float(position_cfg.get("size", 1.0))
|
|
257
271
|
stop_loss = float(exit_.get("stop_loss", -0.10))
|
|
258
272
|
take_profit = float(exit_.get("take_profit", 0.50))
|
|
273
|
+
ts_val = exit_.get("trailing_stop")
|
|
274
|
+
trailing_stop = float(ts_val) if ts_val is not None else None
|
|
259
275
|
|
|
260
276
|
entry_conditions = entry.get("conditions", [])
|
|
261
277
|
entry_logic = entry.get("logic", "all")
|
|
@@ -268,6 +284,8 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
268
284
|
holding = None
|
|
269
285
|
cash = capital
|
|
270
286
|
trade_id = 0
|
|
287
|
+
commission_paid = 0.0
|
|
288
|
+
stamp_tax_paid = 0.0
|
|
271
289
|
|
|
272
290
|
for i in range(1, len(df)):
|
|
273
291
|
row = df.iloc[i]
|
|
@@ -283,6 +301,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
283
301
|
if shares <= 0:
|
|
284
302
|
continue
|
|
285
303
|
cost = shares * buy_price * (1 + commission)
|
|
304
|
+
commission_paid += shares * buy_price * commission
|
|
286
305
|
cash -= cost
|
|
287
306
|
trade_id += 1
|
|
288
307
|
holding = {
|
|
@@ -291,6 +310,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
291
310
|
"buy_price": round(buy_price, 4),
|
|
292
311
|
"shares": shares,
|
|
293
312
|
"cost": cost,
|
|
313
|
+
"peak_close": price,
|
|
294
314
|
}
|
|
295
315
|
trades.append(
|
|
296
316
|
{
|
|
@@ -305,11 +325,19 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
305
325
|
)
|
|
306
326
|
else:
|
|
307
327
|
pnl_pct = (price - holding["buy_price"]) / holding["buy_price"]
|
|
328
|
+
peak_close = max(holding["peak_close"], price)
|
|
329
|
+
holding["peak_close"] = peak_close
|
|
308
330
|
sell = False
|
|
309
331
|
reason = ""
|
|
310
332
|
|
|
311
333
|
if pnl_pct <= stop_loss:
|
|
312
334
|
sell, reason = True, f"止损触发 ({round(pnl_pct * 100, 1)}% <= {round(stop_loss * 100, 1)}%)"
|
|
335
|
+
elif trailing_stop is not None and price <= peak_close * (1 - trailing_stop):
|
|
336
|
+
drawdown = (peak_close - price) / peak_close
|
|
337
|
+
sell, reason = (
|
|
338
|
+
True,
|
|
339
|
+
f"移动止损触发 (较高点回撤 {round(drawdown * 100, 1)}% >= {round(trailing_stop * 100, 1)}%)",
|
|
340
|
+
)
|
|
313
341
|
elif pnl_pct >= take_profit:
|
|
314
342
|
sell, reason = True, f"止盈触发 ({round(pnl_pct * 100, 1)}% >= {round(take_profit * 100, 1)}%)"
|
|
315
343
|
elif exit_conditions:
|
|
@@ -317,7 +345,10 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
317
345
|
|
|
318
346
|
if sell:
|
|
319
347
|
sell_price = price * (1 - slippage)
|
|
320
|
-
|
|
348
|
+
gross = holding["shares"] * sell_price
|
|
349
|
+
proceeds = gross * (1 - commission - stamp_tax)
|
|
350
|
+
commission_paid += gross * commission
|
|
351
|
+
stamp_tax_paid += gross * stamp_tax
|
|
321
352
|
cash += proceeds
|
|
322
353
|
pnl = proceeds - holding["cost"]
|
|
323
354
|
days = 0
|
|
@@ -358,6 +389,13 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
358
389
|
"trades": trades,
|
|
359
390
|
"equity_curve": equity_curve,
|
|
360
391
|
"final_equity": equity_curve[-1]["equity"] if equity_curve else capital,
|
|
392
|
+
"costs": {
|
|
393
|
+
"slippage": slippage,
|
|
394
|
+
"commission": commission,
|
|
395
|
+
"stamp_tax": stamp_tax,
|
|
396
|
+
"commission_paid": round(commission_paid, 2),
|
|
397
|
+
"stamp_tax_paid": round(stamp_tax_paid, 2),
|
|
398
|
+
},
|
|
361
399
|
}
|
|
362
400
|
|
|
363
401
|
|
|
@@ -486,7 +524,7 @@ def diagnose_advanced(metrics: dict, trades: list, equity_curve: list, strategy:
|
|
|
486
524
|
stop_hits = sum(
|
|
487
525
|
1
|
|
488
526
|
for t in sell_trades
|
|
489
|
-
if (t.get("reason") or "").startswith("stop_loss")
|
|
527
|
+
if (t.get("reason") or "").startswith(("stop_loss", "止损触发", "移动止损触发"))
|
|
490
528
|
or (t.get("pnl_pct", 0) is not None and t.get("pnl_pct", 0) <= stop_loss * 100 + 0.5)
|
|
491
529
|
)
|
|
492
530
|
stop_ratio = stop_hits / max(1, len(sell_trades))
|
|
@@ -586,6 +624,23 @@ def sample_curve(curve: list, max_points: int = 200) -> list:
|
|
|
586
624
|
# --------------- Entry Points ---------------
|
|
587
625
|
|
|
588
626
|
|
|
627
|
+
def _benchmark_comparison(symbol: str, start: str, end: str, strategy_return: float) -> dict:
|
|
628
|
+
"""Buy-and-hold benchmark over the same window; degrades to an error note on fetch failure."""
|
|
629
|
+
try:
|
|
630
|
+
df = fetch_kline(symbol, start, end)
|
|
631
|
+
except Exception as e:
|
|
632
|
+
return {"symbol": symbol, "error": str(e)}
|
|
633
|
+
if len(df) < 2:
|
|
634
|
+
return {"symbol": symbol, "error": f"Insufficient benchmark data: {len(df)} rows"}
|
|
635
|
+
first, last = float(df["close"].iloc[0]), float(df["close"].iloc[-1])
|
|
636
|
+
total_return = (last - first) / first if first else 0.0
|
|
637
|
+
return {
|
|
638
|
+
"symbol": symbol,
|
|
639
|
+
"total_return": round(total_return, 4),
|
|
640
|
+
"excess_return": round(strategy_return - total_return, 4),
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
|
|
589
644
|
def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str | None, capital: float) -> dict:
|
|
590
645
|
strategy = load_strategy(strategy_path)
|
|
591
646
|
|
|
@@ -602,18 +657,23 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
|
|
|
602
657
|
final = sim["final_equity"]
|
|
603
658
|
metrics = compute_metrics(sim["trades"], sim["equity_curve"], capital, final, start, end)
|
|
604
659
|
|
|
605
|
-
|
|
660
|
+
result = {
|
|
606
661
|
"strategy": strategy.get("name", "unnamed"),
|
|
607
662
|
"symbol": symbol,
|
|
608
663
|
"period": f"{start} to {end}",
|
|
609
664
|
"initial_capital": capital,
|
|
610
665
|
"final_capital": final,
|
|
666
|
+
"costs": sim["costs"],
|
|
611
667
|
"metrics": metrics,
|
|
612
668
|
"trades": sim["trades"],
|
|
613
669
|
"equity_curve": sample_curve(sim["equity_curve"]),
|
|
614
670
|
"diagnosis": diagnose(metrics),
|
|
615
671
|
"diagnostics": diagnose_advanced(metrics, sim["trades"], sim["equity_curve"], strategy),
|
|
616
672
|
}
|
|
673
|
+
benchmark_symbol = strategy.get("benchmark")
|
|
674
|
+
if benchmark_symbol:
|
|
675
|
+
result["benchmark"] = _benchmark_comparison(str(benchmark_symbol), start, end, metrics["total_return"])
|
|
676
|
+
return result
|
|
617
677
|
|
|
618
678
|
|
|
619
679
|
def evaluate_result(path: str) -> dict:
|
|
@@ -633,41 +693,59 @@ def evaluate_result(path: str) -> dict:
|
|
|
633
693
|
|
|
634
694
|
# --------------- Signal Evaluation ---------------
|
|
635
695
|
|
|
696
|
+
|
|
697
|
+
def _signal_context(df: pd.DataFrame) -> dict:
|
|
698
|
+
"""Precompute every indicator series the signal checkers need, once per
|
|
699
|
+
evaluate_signal call (the old lambdas recomputed them per bar — O(n²))."""
|
|
700
|
+
close = df["close"]
|
|
701
|
+
return {
|
|
702
|
+
"dif": compute_macd_dif(close),
|
|
703
|
+
"dea": compute_macd_dea(close),
|
|
704
|
+
"rsi14": compute_rsi(close, 14),
|
|
705
|
+
"ma5": compute_ma(close, 5),
|
|
706
|
+
"ma20": compute_ma(close, 20),
|
|
707
|
+
"close": close,
|
|
708
|
+
"high": df["high"],
|
|
709
|
+
"low": df["low"],
|
|
710
|
+
"volume": df["volume"],
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
|
|
636
714
|
SIGNAL_DEFINITIONS = {
|
|
637
|
-
"macd_golden_cross": lambda
|
|
715
|
+
"macd_golden_cross": lambda c, i: (
|
|
638
716
|
i >= 1
|
|
639
|
-
and float(
|
|
640
|
-
and float(
|
|
717
|
+
and float(c["dif"].iloc[i]) > float(c["dea"].iloc[i])
|
|
718
|
+
and float(c["dif"].iloc[i - 1]) <= float(c["dea"].iloc[i - 1])
|
|
641
719
|
),
|
|
642
|
-
"macd_death_cross": lambda
|
|
720
|
+
"macd_death_cross": lambda c, i: (
|
|
643
721
|
i >= 1
|
|
644
|
-
and float(
|
|
645
|
-
and float(
|
|
722
|
+
and float(c["dif"].iloc[i]) < float(c["dea"].iloc[i])
|
|
723
|
+
and float(c["dif"].iloc[i - 1]) >= float(c["dea"].iloc[i - 1])
|
|
646
724
|
),
|
|
647
|
-
"rsi_oversold": lambda
|
|
648
|
-
"rsi_overbought": lambda
|
|
649
|
-
"breakout_20d": lambda
|
|
725
|
+
"rsi_oversold": lambda c, i: float(c["rsi14"].iloc[i]) < 30,
|
|
726
|
+
"rsi_overbought": lambda c, i: float(c["rsi14"].iloc[i]) > 70,
|
|
727
|
+
"breakout_20d": lambda c, i: (
|
|
650
728
|
i >= 20
|
|
651
|
-
and float(
|
|
652
|
-
and float(
|
|
729
|
+
and float(c["close"].iloc[i]) > float(c["high"].iloc[i - 20 : i].max())
|
|
730
|
+
and float(c["close"].iloc[i - 1]) <= float(c["high"].iloc[i - 20 : i].max())
|
|
653
731
|
),
|
|
654
|
-
"breakdown_20d": lambda
|
|
732
|
+
"breakdown_20d": lambda c, i: (
|
|
655
733
|
i >= 20
|
|
656
|
-
and float(
|
|
657
|
-
and float(
|
|
734
|
+
and float(c["close"].iloc[i]) < float(c["low"].iloc[i - 20 : i].min())
|
|
735
|
+
and float(c["close"].iloc[i - 1]) >= float(c["low"].iloc[i - 20 : i].min())
|
|
658
736
|
),
|
|
659
|
-
"volume_surge": lambda
|
|
660
|
-
i >= 20 and float(
|
|
737
|
+
"volume_surge": lambda c, i: (
|
|
738
|
+
i >= 20 and float(c["volume"].iloc[i]) > 2.0 * float(c["volume"].iloc[i - 20 : i].mean())
|
|
661
739
|
),
|
|
662
|
-
"ma_golden_cross": lambda
|
|
740
|
+
"ma_golden_cross": lambda c, i: (
|
|
663
741
|
i >= 20
|
|
664
|
-
and float(
|
|
665
|
-
and float(
|
|
742
|
+
and float(c["ma5"].iloc[i]) > float(c["ma20"].iloc[i])
|
|
743
|
+
and float(c["ma5"].iloc[i - 1]) <= float(c["ma20"].iloc[i - 1])
|
|
666
744
|
),
|
|
667
|
-
"ma_death_cross": lambda
|
|
745
|
+
"ma_death_cross": lambda c, i: (
|
|
668
746
|
i >= 20
|
|
669
|
-
and float(
|
|
670
|
-
and float(
|
|
747
|
+
and float(c["ma5"].iloc[i]) < float(c["ma20"].iloc[i])
|
|
748
|
+
and float(c["ma5"].iloc[i - 1]) >= float(c["ma20"].iloc[i - 1])
|
|
671
749
|
),
|
|
672
750
|
}
|
|
673
751
|
|
|
@@ -686,10 +764,11 @@ def evaluate_signal(symbol: str, signal_name: str, forward_days: list[int] = Non
|
|
|
686
764
|
return {"error": f"Insufficient data: {len(df)} rows"}
|
|
687
765
|
|
|
688
766
|
max_fwd = max(forward_days)
|
|
767
|
+
ctx = _signal_context(df)
|
|
689
768
|
occurrences = []
|
|
690
769
|
for i in range(20, len(df) - max_fwd):
|
|
691
770
|
try:
|
|
692
|
-
if checker(
|
|
771
|
+
if checker(ctx, i):
|
|
693
772
|
entry_price = float(df["close"].iloc[i])
|
|
694
773
|
date_str = (
|
|
695
774
|
str(df["date"].iloc[i].date()) if hasattr(df["date"].iloc[i], "date") else str(df["date"].iloc[i])
|
|
@@ -742,23 +821,24 @@ def main():
|
|
|
742
821
|
parser.print_help()
|
|
743
822
|
sys.exit(1)
|
|
744
823
|
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
824
|
+
try:
|
|
825
|
+
if args.command == "run":
|
|
826
|
+
result = run_backtest(args.strategy, args.symbol, args.start, args.end, args.capital)
|
|
827
|
+
elif args.command == "evaluate":
|
|
828
|
+
result = evaluate_result(args.result)
|
|
829
|
+
elif args.command == "evaluate_signal":
|
|
830
|
+
fwd = [int(x) for x in args.forward.split(",")]
|
|
831
|
+
result = evaluate_signal(args.symbol, args.signal, fwd, args.lookback)
|
|
832
|
+
else:
|
|
833
|
+
result = {"error": f"Unknown command: {args.command}"}
|
|
834
|
+
except Exception as e:
|
|
835
|
+
# A traceback would leave stdout empty; hosts need valid JSON even on failure.
|
|
836
|
+
print(json.dumps({"error": str(e)}, ensure_ascii=False))
|
|
837
|
+
sys.exit(1)
|
|
754
838
|
|
|
755
|
-
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
839
|
+
print(json.dumps(json_safe(result), ensure_ascii=False, default=str))
|
|
756
840
|
|
|
757
841
|
|
|
758
842
|
if __name__ == "__main__":
|
|
759
|
-
|
|
760
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
761
|
-
for _s in (sys.stdout, sys.stderr):
|
|
762
|
-
if hasattr(_s, "reconfigure"):
|
|
763
|
-
_s.reconfigure(encoding="utf-8")
|
|
843
|
+
utf8_stdio()
|
|
764
844
|
main()
|