@weaxs/openclaw-stock-analysis 0.1.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 (71) hide show
  1. package/README.md +70 -0
  2. package/index.ts +761 -0
  3. package/openclaw.plugin.json +47 -0
  4. package/package.json +46 -0
  5. package/schemas/report_schema.json +131 -0
  6. package/scripts/setup-python.mjs +52 -0
  7. package/skills/bottom-volume/SKILL.md +63 -0
  8. package/skills/bottom-volume/scripts/gather.py +15 -0
  9. package/skills/box-oscillation/SKILL.md +72 -0
  10. package/skills/box-oscillation/scripts/gather.py +15 -0
  11. package/skills/bull-trend/SKILL.md +60 -0
  12. package/skills/bull-trend/scripts/gather.py +15 -0
  13. package/skills/chan-theory/SKILL.md +71 -0
  14. package/skills/chan-theory/scripts/gather.py +15 -0
  15. package/skills/dragon-head/SKILL.md +69 -0
  16. package/skills/dragon-head/scripts/gather.py +15 -0
  17. package/skills/emotion-cycle/SKILL.md +65 -0
  18. package/skills/emotion-cycle/scripts/gather.py +15 -0
  19. package/skills/event-driven/SKILL.md +73 -0
  20. package/skills/event-driven/scripts/gather.py +15 -0
  21. package/skills/expectation-repricing/SKILL.md +72 -0
  22. package/skills/expectation-repricing/scripts/gather.py +15 -0
  23. package/skills/growth-quality/SKILL.md +74 -0
  24. package/skills/growth-quality/scripts/gather.py +15 -0
  25. package/skills/hot-theme/SKILL.md +74 -0
  26. package/skills/hot-theme/scripts/gather.py +15 -0
  27. package/skills/ma-crossover/SKILL.md +63 -0
  28. package/skills/ma-crossover/scripts/gather.py +15 -0
  29. package/skills/market-review/SKILL.md +70 -0
  30. package/skills/market-review/scripts/gather.py +16 -0
  31. package/skills/one-yang-three-yin/SKILL.md +74 -0
  32. package/skills/one-yang-three-yin/scripts/gather.py +15 -0
  33. package/skills/shrink-pullback/SKILL.md +59 -0
  34. package/skills/shrink-pullback/scripts/gather.py +15 -0
  35. package/skills/stock-analysis/SKILL.md +134 -0
  36. package/skills/stock-analysis/scripts/gather.py +15 -0
  37. package/skills/stock-screener/SKILL.md +68 -0
  38. package/skills/stock-screener/scripts/gather.py +15 -0
  39. package/skills/strategy-backtest/SKILL.md +129 -0
  40. package/skills/strategy-backtest/scripts/gather.py +16 -0
  41. package/skills/volume-breakout/SKILL.md +58 -0
  42. package/skills/volume-breakout/scripts/gather.py +15 -0
  43. package/skills/wave-theory/SKILL.md +67 -0
  44. package/skills/wave-theory/scripts/gather.py +15 -0
  45. package/skills/wisburg-research/SKILL.md +119 -0
  46. package/strategies/examples/bottom_volume.yaml +47 -0
  47. package/strategies/examples/box_oscillation.yaml +41 -0
  48. package/strategies/examples/bull_trend.yaml +42 -0
  49. package/strategies/examples/dragon_head.yaml +45 -0
  50. package/strategies/examples/emotion_cycle.yaml +43 -0
  51. package/strategies/examples/ma_crossover.yaml +34 -0
  52. package/strategies/examples/rsi_oversold.yaml +35 -0
  53. package/strategies/examples/shrink_pullback.yaml +45 -0
  54. package/strategies/examples/volume_breakout.yaml +42 -0
  55. package/tools/__init__.py +0 -0
  56. package/tools/anomaly_detect.py +570 -0
  57. package/tools/backtest.py +643 -0
  58. package/tools/gather.py +152 -0
  59. package/tools/market_regime.py +247 -0
  60. package/tools/market_review.py +150 -0
  61. package/tools/name_resolver.py +131 -0
  62. package/tools/pattern.py +509 -0
  63. package/tools/requirements.txt +13 -0
  64. package/tools/risk_screening.py +318 -0
  65. package/tools/screener.py +213 -0
  66. package/tools/search_intel.py +455 -0
  67. package/tools/stock_data.py +1649 -0
  68. package/tools/technical.py +636 -0
  69. package/tools/trading_calendar.py +198 -0
  70. package/tools/volume_analysis.py +172 -0
  71. package/tools/watchlist.py +61 -0
@@ -0,0 +1,318 @@
1
+ #!/usr/bin/env python3
2
+ """Risk screening — 7-dimension risk checker for A-share stocks."""
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ from datetime import datetime, timedelta
10
+
11
+ TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
12
+
13
+
14
+ def _run_tool(script: str, args: str) -> dict:
15
+ cmd = f"python3 {TOOLS_DIR}/{script} {args}"
16
+ try:
17
+ r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
18
+ if r.returncode == 0 and r.stdout.strip():
19
+ return json.loads(r.stdout)
20
+ except Exception:
21
+ pass
22
+ return {}
23
+
24
+
25
+ def _safe_float(val) -> float | None:
26
+ if val is None:
27
+ return None
28
+ try:
29
+ v = float(val)
30
+ return v if v == v else None # NaN check
31
+ except (ValueError, TypeError):
32
+ return None
33
+
34
+
35
+ # --------------- Check 1: Valuation ---------------
36
+
37
+
38
+ def check_valuation(symbol: str) -> dict:
39
+ quote = _run_tool("stock_data.py", f"quote {symbol}")
40
+ pe = _safe_float(quote.get("pe"))
41
+ pb = _safe_float(quote.get("pb"))
42
+ result = {"pe": pe, "pb": pb, "status": "normal", "flags": []}
43
+
44
+ if pe is not None:
45
+ if pe < 0:
46
+ result["flags"].append(
47
+ {"category": "valuation", "severity": "medium", "description": "PE为负,公司亏损", "source": "data"}
48
+ )
49
+ result["status"] = "warning"
50
+ elif pe > 200:
51
+ result["flags"].append(
52
+ {
53
+ "category": "valuation",
54
+ "severity": "high",
55
+ "description": f"PE={pe:.1f},估值极端偏高",
56
+ "source": "data",
57
+ }
58
+ )
59
+ result["status"] = "extreme"
60
+ elif pe > 100:
61
+ result["flags"].append(
62
+ {
63
+ "category": "valuation",
64
+ "severity": "medium",
65
+ "description": f"PE={pe:.1f},估值偏高",
66
+ "source": "data",
67
+ }
68
+ )
69
+ result["status"] = "warning"
70
+
71
+ if pb is not None:
72
+ if pb > 15:
73
+ result["flags"].append(
74
+ {
75
+ "category": "valuation",
76
+ "severity": "high",
77
+ "description": f"PB={pb:.1f},市净率极端",
78
+ "source": "data",
79
+ }
80
+ )
81
+ result["status"] = "extreme"
82
+ elif pb > 10:
83
+ result["flags"].append(
84
+ {
85
+ "category": "valuation",
86
+ "severity": "medium",
87
+ "description": f"PB={pb:.1f},市净率偏高",
88
+ "source": "data",
89
+ }
90
+ )
91
+ if result["status"] == "normal":
92
+ result["status"] = "warning"
93
+
94
+ return result
95
+
96
+
97
+ # --------------- Check 2: Technical Warning ---------------
98
+
99
+
100
+ def check_technical(symbol: str) -> dict:
101
+ ta = _run_tool("technical.py", f"analyze {symbol}")
102
+ result = {"flags": []}
103
+
104
+ if not ta or "error" in ta:
105
+ return result
106
+
107
+ signal = ta.get("buy_signal", "")
108
+ score = _safe_float(ta.get("signal_score"))
109
+ trend = ta.get("trend", {}).get("overall", "")
110
+
111
+ if signal in ("STRONG_SELL",):
112
+ result["flags"].append(
113
+ {
114
+ "category": "technical",
115
+ "severity": "high",
116
+ "description": f"技术信号: {signal},评分 {score}",
117
+ "source": "data",
118
+ }
119
+ )
120
+ elif signal in ("SELL",):
121
+ result["flags"].append(
122
+ {
123
+ "category": "technical",
124
+ "severity": "medium",
125
+ "description": f"技术信号: {signal},评分 {score}",
126
+ "source": "data",
127
+ }
128
+ )
129
+
130
+ if trend == "bearish" and score is not None and score < 20:
131
+ result["flags"].append(
132
+ {
133
+ "category": "technical",
134
+ "severity": "high",
135
+ "description": "技术面全面走弱(趋势空头+评分<20)",
136
+ "source": "data",
137
+ }
138
+ )
139
+
140
+ macd = ta.get("macd", {})
141
+ if macd.get("signal") == "death_cross":
142
+ result["flags"].append(
143
+ {"category": "technical", "severity": "medium", "description": "MACD死叉", "source": "data"}
144
+ )
145
+
146
+ result["buy_signal"] = signal
147
+ result["signal_score"] = score
148
+ result["trend"] = trend
149
+ return result
150
+
151
+
152
+ # --------------- Check 3: Lock-up Expiry ---------------
153
+
154
+
155
+ def check_lockup(symbol: str) -> dict:
156
+ result = {"upcoming_30d": [], "flags": []}
157
+ try:
158
+ import akshare as ak
159
+
160
+ df = ak.stock_restricted_release_queue_em(symbol=symbol)
161
+ if df is None or df.empty:
162
+ return result
163
+
164
+ now = datetime.now()
165
+ cutoff = now + timedelta(days=30)
166
+
167
+ date_col = None
168
+ for c in df.columns:
169
+ if "日期" in str(c) or "解禁" in str(c):
170
+ date_col = c
171
+ break
172
+ if date_col is None and len(df.columns) > 0:
173
+ date_col = df.columns[0]
174
+
175
+ if date_col:
176
+ import pandas as pd
177
+
178
+ df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
179
+ upcoming = df[(df[date_col] >= now) & (df[date_col] <= cutoff)]
180
+ if not upcoming.empty:
181
+ result["upcoming_30d"] = [str(d.date()) for d in upcoming[date_col].dropna()]
182
+ result["flags"].append(
183
+ {
184
+ "category": "lockup",
185
+ "severity": "medium",
186
+ "description": f"未来30天有{len(upcoming)}批限售股解禁",
187
+ "source": "data",
188
+ }
189
+ )
190
+ except Exception:
191
+ pass
192
+ return result
193
+
194
+
195
+ # --------------- Check 4-7: News-based risks ---------------
196
+
197
+
198
+ def check_news_risks(symbol: str, name: str = "") -> dict:
199
+ search_name = name if name else symbol
200
+ categories = {
201
+ "insider": f"{search_name} 减持 股东减持",
202
+ "earnings": f"{search_name} 业绩预告 亏损 下降",
203
+ "regulatory": f"{search_name} 处罚 违规 监管 立案",
204
+ "industry": f"{search_name} 行业政策 监管 限制",
205
+ }
206
+ result = {"flags": []}
207
+ for cat, query in categories.items():
208
+ data = _run_tool("search_intel.py", f'search "{query}" --max 3')
209
+ items = []
210
+ if isinstance(data, list):
211
+ items = data
212
+ elif isinstance(data, dict) and "results" in data:
213
+ items = data["results"]
214
+
215
+ result[cat] = items
216
+ if items:
217
+ result["flags"].append(
218
+ {
219
+ "category": cat,
220
+ "severity": "medium",
221
+ "description": f"发现{len(items)}条相关{_cat_cn(cat)}信息",
222
+ "source": "news",
223
+ }
224
+ )
225
+ return result
226
+
227
+
228
+ def _cat_cn(cat: str) -> str:
229
+ return {"insider": "内部人减持", "earnings": "业绩预警", "regulatory": "监管处罚", "industry": "行业政策"}.get(
230
+ cat, cat
231
+ )
232
+
233
+
234
+ # --------------- Scoring ---------------
235
+
236
+
237
+ def compute_risk(flags: list) -> dict:
238
+ score = 0
239
+ for f in flags:
240
+ sev = f.get("severity", "low")
241
+ if sev == "high":
242
+ score += 30
243
+ elif sev == "medium":
244
+ score += 15
245
+ else:
246
+ score += 5
247
+ score = min(score, 100)
248
+
249
+ if score >= 60:
250
+ risk_level = "high"
251
+ elif score >= 30:
252
+ risk_level = "medium"
253
+ else:
254
+ risk_level = "low"
255
+
256
+ veto_buy = any(f.get("severity") == "high" for f in flags)
257
+ return {"risk_score": score, "risk_level": risk_level, "veto_buy": veto_buy}
258
+
259
+
260
+ # --------------- Main entry ---------------
261
+
262
+
263
+ def screen_risk(symbol: str, name: str = "") -> dict:
264
+ all_flags = []
265
+ checks = {}
266
+
267
+ val = check_valuation(symbol)
268
+ checks["valuation"] = {"pe": val["pe"], "pb": val["pb"], "status": val["status"]}
269
+ all_flags.extend(val["flags"])
270
+
271
+ tech = check_technical(symbol)
272
+ checks["technical"] = {
273
+ "buy_signal": tech.get("buy_signal"),
274
+ "signal_score": tech.get("signal_score"),
275
+ "trend": tech.get("trend"),
276
+ }
277
+ all_flags.extend(tech["flags"])
278
+
279
+ lockup = check_lockup(symbol)
280
+ checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"]}
281
+ all_flags.extend(lockup["flags"])
282
+
283
+ news = check_news_risks(symbol, name)
284
+ checks["news_risks"] = {k: v for k, v in news.items() if k != "flags"}
285
+ all_flags.extend(news["flags"])
286
+
287
+ risk = compute_risk(all_flags)
288
+ return {
289
+ "symbol": symbol,
290
+ "name": name,
291
+ "risk_level": risk["risk_level"],
292
+ "risk_score": risk["risk_score"],
293
+ "veto_buy": risk["veto_buy"],
294
+ "flags": all_flags,
295
+ "checks": checks,
296
+ }
297
+
298
+
299
+ def main():
300
+ parser = argparse.ArgumentParser(description="Risk screening tool")
301
+ sub = parser.add_subparsers(dest="command")
302
+
303
+ p_screen = sub.add_parser("screen")
304
+ p_screen.add_argument("symbol")
305
+ p_screen.add_argument("--name", default="")
306
+
307
+ args = parser.parse_args()
308
+ if not args.command:
309
+ parser.print_help()
310
+ sys.exit(1)
311
+
312
+ if args.command == "screen":
313
+ result = screen_risk(args.symbol, args.name)
314
+ print(json.dumps(result, ensure_ascii=False, default=str))
315
+
316
+
317
+ if __name__ == "__main__":
318
+ main()
@@ -0,0 +1,213 @@
1
+ #!/usr/bin/env python3
2
+ """AlphaSift L1 — multi-factor stock screener with hard filter + scoring."""
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
+ import yaml
13
+
14
+ DEFAULT_FILTERS = {
15
+ "pe_min": 0,
16
+ "pe_max": 100,
17
+ "pb_min": 0,
18
+ "pb_max": 20,
19
+ "market_cap_min": 5e9,
20
+ "turnover_rate_min": 0.5,
21
+ "turnover_rate_max": 20,
22
+ "change_pct_min": -5,
23
+ "change_pct_max": 9.9,
24
+ "volume_ratio_min": 0.5,
25
+ }
26
+
27
+
28
+ def fetch_snapshot(market: str) -> list:
29
+ script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
30
+ r = subprocess.run(
31
+ [sys.executable, script, "market_snapshot", "--market", market],
32
+ capture_output=True,
33
+ text=True,
34
+ )
35
+ return json.loads(r.stdout)
36
+
37
+
38
+ def load_config(path: str) -> dict:
39
+ with open(path, encoding="utf-8") as f:
40
+ return yaml.safe_load(f)
41
+
42
+
43
+ def merge_filters(config: dict | None) -> dict:
44
+ filters = dict(DEFAULT_FILTERS)
45
+ if config and "filters" in config:
46
+ filters.update(config["filters"])
47
+ return filters
48
+
49
+
50
+ def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
51
+ conditions = []
52
+ if "pe" in df.columns:
53
+ conditions.append(df["pe"] >= filters["pe_min"])
54
+ conditions.append(df["pe"] <= filters["pe_max"])
55
+ if "pb" in df.columns:
56
+ conditions.append(df["pb"] >= filters["pb_min"])
57
+ conditions.append(df["pb"] <= filters["pb_max"])
58
+ if "market_cap" in df.columns:
59
+ conditions.append(df["market_cap"] >= filters["market_cap_min"])
60
+ if "turnover_rate" in df.columns:
61
+ conditions.append(df["turnover_rate"] >= filters["turnover_rate_min"])
62
+ conditions.append(df["turnover_rate"] <= filters["turnover_rate_max"])
63
+ if "change_pct" in df.columns:
64
+ conditions.append(df["change_pct"] >= filters["change_pct_min"])
65
+ conditions.append(df["change_pct"] <= filters["change_pct_max"])
66
+ if "volume_ratio" in df.columns:
67
+ conditions.append(df["volume_ratio"] >= filters["volume_ratio_min"])
68
+
69
+ if conditions:
70
+ mask = conditions[0]
71
+ for c in conditions[1:]:
72
+ mask = mask & c
73
+ return df[mask].copy()
74
+ return df.copy()
75
+
76
+
77
+ def _minmax(s: pd.Series) -> pd.Series:
78
+ mn, mx = s.min(), s.max()
79
+ if mx == mn:
80
+ return pd.Series(50.0, index=s.index)
81
+ return ((s - mn) / (mx - mn) * 100).clip(0, 100)
82
+
83
+
84
+ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
85
+ # Value: lower PE/PB → higher score (inverted)
86
+ value_parts = []
87
+ if "pe" in df.columns:
88
+ value_parts.append(100 - _minmax(df["pe"]))
89
+ if "pb" in df.columns:
90
+ value_parts.append(100 - _minmax(df["pb"]))
91
+ df["value_score"] = sum(value_parts) / max(len(value_parts), 1)
92
+
93
+ # Momentum: higher change_pct and volume_ratio → higher score
94
+ mom_parts = []
95
+ if "change_pct" in df.columns:
96
+ mom_parts.append(_minmax(df["change_pct"]))
97
+ if "volume_ratio" in df.columns:
98
+ mom_parts.append(_minmax(df["volume_ratio"]))
99
+ df["momentum_score"] = sum(mom_parts) / max(len(mom_parts), 1)
100
+
101
+ # Liquidity: higher turnover_rate and volume → higher score
102
+ liq_parts = []
103
+ if "turnover_rate" in df.columns:
104
+ liq_parts.append(_minmax(df["turnover_rate"]))
105
+ if "volume" in df.columns:
106
+ liq_parts.append(_minmax(df["volume"].astype(float)))
107
+ df["liquidity_score"] = sum(liq_parts) / max(len(liq_parts), 1)
108
+
109
+ df["composite_score"] = 0.4 * df["value_score"] + 0.3 * df["momentum_score"] + 0.3 * df["liquidity_score"]
110
+ return df
111
+
112
+
113
+ def screen(market: str, top: int, config: dict | None) -> dict:
114
+ raw = fetch_snapshot(market)
115
+ if isinstance(raw, dict) and "error" in raw:
116
+ return raw
117
+
118
+ df = pd.DataFrame(raw)
119
+ total = len(df)
120
+
121
+ for c in ["price", "change_pct", "volume", "turnover", "pe", "pb", "market_cap", "turnover_rate", "volume_ratio"]:
122
+ if c in df.columns:
123
+ df[c] = pd.to_numeric(df[c], errors="coerce")
124
+
125
+ critical = ["price", "pe", "pb"]
126
+ existing = [c for c in critical if c in df.columns]
127
+ if existing:
128
+ df = df.dropna(subset=existing)
129
+
130
+ filters = merge_filters(config)
131
+ df = apply_filters(df, filters)
132
+ filtered_count = len(df)
133
+
134
+ if df.empty:
135
+ return {
136
+ "market": market,
137
+ "total_stocks": total,
138
+ "filtered_count": 0,
139
+ "returned_count": 0,
140
+ "filters_applied": filters,
141
+ "candidates": [],
142
+ }
143
+
144
+ df = compute_scores(df)
145
+
146
+ sort_by = config.get("sort_by", "composite_score") if config else "composite_score"
147
+ sort_order = config.get("sort_order", "desc") if config else "desc"
148
+ ascending = sort_order == "asc"
149
+
150
+ if sort_by in df.columns:
151
+ df = df.sort_values(sort_by, ascending=ascending)
152
+ else:
153
+ df = df.sort_values("composite_score", ascending=False)
154
+
155
+ df = df.head(top)
156
+
157
+ candidates = []
158
+ for rank, (_, row) in enumerate(df.iterrows(), 1):
159
+ entry = {"rank": rank}
160
+ for field in [
161
+ "symbol",
162
+ "name",
163
+ "price",
164
+ "change_pct",
165
+ "volume",
166
+ "turnover_rate",
167
+ "pe",
168
+ "pb",
169
+ "market_cap",
170
+ "volume_ratio",
171
+ ]:
172
+ v = row.get(field)
173
+ if v is not None and not (isinstance(v, float) and np.isnan(v)):
174
+ entry[field] = round(float(v), 2) if isinstance(v, (float, np.floating)) else v
175
+ entry["scores"] = {
176
+ "value": round(float(row.get("value_score", 0)), 1),
177
+ "momentum": round(float(row.get("momentum_score", 0)), 1),
178
+ "liquidity": round(float(row.get("liquidity_score", 0)), 1),
179
+ "composite": round(float(row.get("composite_score", 0)), 1),
180
+ }
181
+ candidates.append(entry)
182
+
183
+ return {
184
+ "market": market,
185
+ "total_stocks": total,
186
+ "filtered_count": filtered_count,
187
+ "returned_count": len(candidates),
188
+ "filters_applied": filters,
189
+ "candidates": candidates,
190
+ }
191
+
192
+
193
+ def main():
194
+ parser = argparse.ArgumentParser(description="AlphaSift L1 stock screener")
195
+ sub = parser.add_subparsers(dest="command")
196
+
197
+ p = sub.add_parser("screen")
198
+ p.add_argument("--market", default="A", choices=["A", "HK", "US"])
199
+ p.add_argument("--top", type=int, default=20)
200
+ p.add_argument("--config", help="Path to YAML config file")
201
+
202
+ args = parser.parse_args()
203
+ if not args.command:
204
+ parser.print_help()
205
+ sys.exit(1)
206
+
207
+ config = load_config(args.config) if args.config else None
208
+ result = screen(args.market, args.top, config)
209
+ print(json.dumps(result, ensure_ascii=False, default=str))
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()