@weaxs/openclaw-stock-analysis 0.2.2 → 0.2.3

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -2
  3. package/dist/index.js +84 -20
  4. package/index.ts +92 -23
  5. package/openclaw.plugin.json +3 -0
  6. package/package.json +1 -1
  7. package/scripts/ci-resolve-llm-host.mjs +29 -0
  8. package/scripts/setup-python.mjs +7 -9
  9. package/skills/hot-theme/SKILL.md +3 -2
  10. package/skills/stock-screener/SKILL.md +1 -1
  11. package/skills/strategy-backtest/SKILL.md +9 -5
  12. package/strategies/examples/bottom_volume.yaml +5 -0
  13. package/strategies/examples/box_oscillation.yaml +5 -0
  14. package/strategies/examples/bull_trend.yaml +11 -3
  15. package/strategies/examples/dragon_head.yaml +4 -2
  16. package/strategies/examples/emotion_cycle.yaml +5 -0
  17. package/strategies/examples/ma_crossover.yaml +10 -3
  18. package/strategies/examples/rsi_oversold.yaml +5 -0
  19. package/strategies/examples/shrink_pullback.yaml +7 -1
  20. package/strategies/examples/volume_breakout.yaml +7 -1
  21. package/tools/_subproc.py +49 -0
  22. package/tools/alert_rules.py +19 -9
  23. package/tools/anomaly_detect.py +24 -35
  24. package/tools/backtest.py +180 -100
  25. package/tools/capabilities.py +4 -5
  26. package/tools/diagnostics.py +6 -6
  27. package/tools/gather.py +13 -9
  28. package/tools/import_parser.py +2 -5
  29. package/tools/market_regime.py +27 -35
  30. package/tools/market_review.py +56 -9
  31. package/tools/name_resolver.py +2 -5
  32. package/tools/pattern.py +2 -5
  33. package/tools/position_context.py +2 -5
  34. package/tools/report_renderer.py +10 -6
  35. package/tools/requirements.txt +2 -1
  36. package/tools/risk_screening.py +29 -23
  37. package/tools/screener.py +26 -16
  38. package/tools/search_intel.py +5 -13
  39. package/tools/signal_tracker.py +2 -6
  40. package/tools/stock_data.py +301 -92
  41. package/tools/technical.py +136 -40
  42. package/tools/trading_calendar.py +78 -18
  43. package/tools/volume_analysis.py +2 -5
  44. package/tools/watchlist.py +2 -5
  45. package/tools/watchlist_context.py +2 -5
@@ -18,7 +18,8 @@ entry:
18
18
  operator: ">"
19
19
  value: "{volume_threshold}"
20
20
  - indicator: "ma_diff"
21
- period: 510
21
+ fast_period: 5
22
+ slow_period: 10
22
23
  operator: ">"
23
24
  value: 0
24
25
  logic: "all"
@@ -37,8 +38,9 @@ exit:
37
38
  take_profit: "{take_profit}"
38
39
 
39
40
  simulation:
40
- slippage: 0.002
41
+ slippage: 0.002 # 打板策略用更保守的费率:滑点0.2%、佣金万15(其余示例为 0.001/万2.5)
41
42
  commission: 0.0015
43
+ stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
42
44
 
43
45
  position:
44
46
  size: 0.5
@@ -38,6 +38,11 @@ exit:
38
38
  stop_loss: "{stop_loss}"
39
39
  take_profit: "{take_profit}"
40
40
 
41
+ simulation:
42
+ slippage: 0.001 # 滑点(买卖双边)
43
+ commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
44
+ stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
45
+
41
46
  position:
42
47
  size: 0.5
43
48
  max_positions: 1
@@ -1,6 +1,6 @@
1
1
  name: "MA Golden Cross"
2
2
  version: "1.0"
3
- description: "均线金叉策略 — MA5上穿MA20时买入,MA5下穿MA20时卖出。使用 ma_diff 指标(编码: fast*100+slow,如520=MA5-MA20)检测交叉"
3
+ description: "均线金叉策略 — MA5上穿MA20时买入,MA5下穿MA20时卖出。使用 ma_diff 指标(fast_period/slow_period 显式指定快慢均线)检测交叉"
4
4
 
5
5
  parameters:
6
6
  fast_period: 5
@@ -11,7 +11,8 @@ parameters:
11
11
  entry:
12
12
  conditions:
13
13
  - indicator: "ma_diff"
14
- period: 520
14
+ fast_period: "{fast_period}"
15
+ slow_period: "{slow_period}"
15
16
  operator: "cross_above"
16
17
  value: 0
17
18
  - indicator: "volume_ratio"
@@ -22,13 +23,19 @@ entry:
22
23
  exit:
23
24
  conditions:
24
25
  - indicator: "ma_diff"
25
- period: 520
26
+ fast_period: "{fast_period}"
27
+ slow_period: "{slow_period}"
26
28
  operator: "cross_below"
27
29
  value: 0
28
30
  logic: "any"
29
31
  stop_loss: "{stop_loss}"
30
32
  take_profit: "{take_profit}"
31
33
 
34
+ simulation:
35
+ slippage: 0.001 # 滑点(买卖双边)
36
+ commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
37
+ stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
38
+
32
39
  position:
33
40
  size: 1.0
34
41
  max_positions: 1
@@ -30,6 +30,11 @@ exit:
30
30
  stop_loss: "{stop_loss}"
31
31
  take_profit: "{take_profit}"
32
32
 
33
+ simulation:
34
+ slippage: 0.001 # 滑点(买卖双边)
35
+ commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
36
+ stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
37
+
33
38
  position:
34
39
  size: 1.0
35
40
  max_positions: 1
@@ -9,7 +9,8 @@ parameters:
9
9
  entry:
10
10
  conditions:
11
11
  - indicator: "ma_diff"
12
- period: 1020
12
+ fast_period: 10
13
+ slow_period: 20
13
14
  operator: ">"
14
15
  value: 0
15
16
  - indicator: "bollinger_position"
@@ -40,6 +41,11 @@ exit:
40
41
  stop_loss: "{stop_loss}"
41
42
  take_profit: "{take_profit}"
42
43
 
44
+ simulation:
45
+ slippage: 0.001 # 滑点(买卖双边)
46
+ commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
47
+ stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
48
+
43
49
  position:
44
50
  size: 1.0
45
51
  max_positions: 1
@@ -26,7 +26,8 @@ entry:
26
26
  exit:
27
27
  conditions:
28
28
  - indicator: "ma_diff"
29
- period: 510
29
+ fast_period: 5
30
+ slow_period: 10
30
31
  operator: "cross_below"
31
32
  value: 0
32
33
  - indicator: "rsi"
@@ -37,6 +38,11 @@ exit:
37
38
  stop_loss: "{stop_loss}"
38
39
  take_profit: "{take_profit}"
39
40
 
41
+ simulation:
42
+ slippage: 0.001 # 滑点(买卖双边)
43
+ commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
44
+ stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
45
+
40
46
  position:
41
47
  size: 0.8
42
48
  max_positions: 1
package/tools/_subproc.py CHANGED
@@ -6,8 +6,12 @@ so this resolves both when a tool runs as a script (sys.path[0] = tools/) and wh
6
6
  pytest imports it as tools.*.
7
7
  """
8
8
 
9
+ import contextlib
9
10
  import json
11
+ import math
10
12
  import os
13
+ import re
14
+ import socket
11
15
  import subprocess
12
16
  import sys
13
17
 
@@ -44,3 +48,48 @@ def run_tool(script: str, args: list, timeout: int = 30, parse_json: bool = True
44
48
  except Exception:
45
49
  pass
46
50
  return None
51
+
52
+
53
+ def utf8_stdio() -> None:
54
+ """Force UTF-8 stdio. Windows defaults stdio to a legacy code page (cp1252)
55
+ that cannot encode the Chinese text these tools emit — call at CLI entry."""
56
+ for s in (sys.stdout, sys.stderr):
57
+ if hasattr(s, "reconfigure"):
58
+ s.reconfigure(encoding="utf-8")
59
+
60
+
61
+ @contextlib.contextmanager
62
+ def socket_timeout(seconds: float):
63
+ """Bound every blocking socket op for the wrapped chain's duration: akshare/efinance
64
+ leave requests timeout-less, so on a blackholed network a leg hangs until the kernel
65
+ TCP timeout (~2min) and the chain would overrun the caller's subprocess budget before
66
+ ever reaching the plain-HTTPS legs. try/finally always restores the previous default
67
+ (no global-state leak); explicit per-request timeouts (tencent/sina legs) still win."""
68
+ old_timeout = socket.getdefaulttimeout()
69
+ socket.setdefaulttimeout(seconds)
70
+ try:
71
+ yield
72
+ finally:
73
+ socket.setdefaulttimeout(old_timeout)
74
+
75
+
76
+ _SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
77
+
78
+
79
+ def scrub_secrets(msg: str) -> str:
80
+ """Error text may embed request URLs (requests connection errors) — never leak keys
81
+ into stdout JSON."""
82
+ return _SECRET_PARAM_RE.sub(r"\1***", msg)
83
+
84
+
85
+ def json_safe(obj):
86
+ """Replace non-finite floats (inf/-inf/nan, e.g. an all-flat P&L profit_loss_ratio)
87
+ with None so json.dumps never emits the non-standard Infinity/NaN tokens that
88
+ break strict JSON.parse hosts."""
89
+ if isinstance(obj, float):
90
+ return obj if math.isfinite(obj) else None
91
+ if isinstance(obj, dict):
92
+ return {k: json_safe(v) for k, v in obj.items()}
93
+ if isinstance(obj, list):
94
+ return [json_safe(v) for v in obj]
95
+ return obj
@@ -7,11 +7,13 @@ Does NOT store history, does NOT push, does NOT schedule. Host agent decides whe
7
7
  import argparse
8
8
  import json
9
9
  import sys
10
+ from concurrent.futures import ThreadPoolExecutor
10
11
  from datetime import datetime, timezone
11
12
  from pathlib import Path
12
13
 
13
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
15
  from _subproc import run_tool as _run_json # noqa: E402
16
+ from _subproc import utf8_stdio
15
17
  from stock_data import detect_market # noqa: E402
16
18
 
17
19
  RULE_TYPES = {
@@ -127,10 +129,22 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
127
129
  needs_anom = any(r.get("type") == "anomaly" for r in rules)
128
130
  needs_risk = any(r.get("type") in ("risk_veto", "risk_level_at_least") for r in rules)
129
131
 
130
- quote = _run_json("stock_data.py", ["quote", symbol]) or {}
131
- tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) if needs_tech else None
132
- anom = _run_json("anomaly_detect.py", ["detect", symbol]) if needs_anom else None
133
- risk = _run_json("risk_screening.py", ["screen", symbol]) if needs_risk else None
132
+ # the fetches are independent subprocesses — fan out concurrently (same
133
+ # ThreadPoolExecutor pattern as gather._run_all), then read back in fixed order
134
+ jobs = {"quote": ("stock_data.py", ["quote", symbol])}
135
+ if needs_tech:
136
+ jobs["tech"] = ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"])
137
+ if needs_anom:
138
+ jobs["anom"] = ("anomaly_detect.py", ["detect", symbol])
139
+ if needs_risk:
140
+ jobs["risk"] = ("risk_screening.py", ["screen", symbol])
141
+ with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
142
+ futures = {key: pool.submit(_run_json, script, args) for key, (script, args) in jobs.items()}
143
+ fetched = {key: future.result() for key, future in futures.items()}
144
+ quote = fetched["quote"] or {}
145
+ tech = fetched.get("tech")
146
+ anom = fetched.get("anom")
147
+ risk = fetched.get("risk")
134
148
 
135
149
  warnings = []
136
150
  if not quote or quote.get("price") is None:
@@ -203,9 +217,5 @@ def main():
203
217
 
204
218
 
205
219
  if __name__ == "__main__":
206
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
207
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
208
- for _s in (sys.stdout, sys.stderr):
209
- if hasattr(_s, "reconfigure"):
210
- _s.reconfigure(encoding="utf-8")
220
+ utf8_stdio()
211
221
  main()
@@ -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 stock_data import detect_market, normalize_stock_code
16
- from technical import fetch_kline, to_dataframe
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
- ema12 = close.ewm(span=12, adjust=False).mean()
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
- delta = close.diff()
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
- mid = close.rolling(20).mean()
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
- low_n = low.rolling(9).min()
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
- limit_up_price = round(prev_close * (1 + limit_pct), 2)
319
- limit_down_price = round(prev_close * (1 - limit_pct), 2)
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
- ema12 = close.ewm(span=12, adjust=False).mean()
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.rolling(5).mean()
425
- ma10 = close.rolling(10).mean()
426
- ma20 = close.rolling(20).mean()
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
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
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()