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.
Files changed (84) hide show
  1. package/README.md +498 -0
  2. package/package.json +88 -0
  3. package/pi/index.ts +1142 -0
  4. package/schemas/market_review_schema.json +176 -0
  5. package/schemas/report_schema.json +131 -0
  6. package/scripts/setup-python.mjs +57 -0
  7. package/scripts/sync-version.sh +56 -0
  8. package/scripts/venv-python.mjs +20 -0
  9. package/skills/bottom-volume/SKILL.md +63 -0
  10. package/skills/bottom-volume/scripts/gather.py +22 -0
  11. package/skills/box-oscillation/SKILL.md +72 -0
  12. package/skills/box-oscillation/scripts/gather.py +22 -0
  13. package/skills/bull-trend/SKILL.md +60 -0
  14. package/skills/bull-trend/scripts/gather.py +22 -0
  15. package/skills/chan-theory/SKILL.md +71 -0
  16. package/skills/chan-theory/scripts/gather.py +22 -0
  17. package/skills/dragon-head/SKILL.md +69 -0
  18. package/skills/dragon-head/scripts/gather.py +22 -0
  19. package/skills/emotion-cycle/SKILL.md +65 -0
  20. package/skills/emotion-cycle/scripts/gather.py +22 -0
  21. package/skills/event-driven/SKILL.md +73 -0
  22. package/skills/event-driven/scripts/gather.py +22 -0
  23. package/skills/expectation-repricing/SKILL.md +72 -0
  24. package/skills/expectation-repricing/scripts/gather.py +22 -0
  25. package/skills/growth-quality/SKILL.md +74 -0
  26. package/skills/growth-quality/scripts/gather.py +22 -0
  27. package/skills/hot-theme/SKILL.md +74 -0
  28. package/skills/hot-theme/scripts/gather.py +22 -0
  29. package/skills/ma-crossover/SKILL.md +63 -0
  30. package/skills/ma-crossover/scripts/gather.py +22 -0
  31. package/skills/market-review/SKILL.md +70 -0
  32. package/skills/market-review/scripts/gather.py +23 -0
  33. package/skills/one-yang-three-yin/SKILL.md +74 -0
  34. package/skills/one-yang-three-yin/scripts/gather.py +22 -0
  35. package/skills/shrink-pullback/SKILL.md +59 -0
  36. package/skills/shrink-pullback/scripts/gather.py +22 -0
  37. package/skills/stock-analysis/SKILL.md +134 -0
  38. package/skills/stock-analysis/scripts/gather.py +22 -0
  39. package/skills/stock-screener/SKILL.md +68 -0
  40. package/skills/stock-screener/scripts/gather.py +22 -0
  41. package/skills/strategy-backtest/SKILL.md +129 -0
  42. package/skills/strategy-backtest/scripts/gather.py +23 -0
  43. package/skills/volume-breakout/SKILL.md +58 -0
  44. package/skills/volume-breakout/scripts/gather.py +22 -0
  45. package/skills/wave-theory/SKILL.md +67 -0
  46. package/skills/wave-theory/scripts/gather.py +22 -0
  47. package/skills/wisburg-research/SKILL.md +119 -0
  48. package/strategies/examples/bottom_volume.yaml +47 -0
  49. package/strategies/examples/box_oscillation.yaml +41 -0
  50. package/strategies/examples/bull_trend.yaml +42 -0
  51. package/strategies/examples/dragon_head.yaml +45 -0
  52. package/strategies/examples/emotion_cycle.yaml +43 -0
  53. package/strategies/examples/ma_crossover.yaml +34 -0
  54. package/strategies/examples/rsi_oversold.yaml +35 -0
  55. package/strategies/examples/shrink_pullback.yaml +45 -0
  56. package/strategies/examples/volume_breakout.yaml +42 -0
  57. package/templates/_macros.j2 +90 -0
  58. package/templates/market_review/full.md.j2 +103 -0
  59. package/templates/stock_analysis/brief.md.j2 +28 -0
  60. package/templates/stock_analysis/full.md.j2 +108 -0
  61. package/tools/__init__.py +0 -0
  62. package/tools/alert_rules.py +243 -0
  63. package/tools/anomaly_detect.py +575 -0
  64. package/tools/backtest.py +764 -0
  65. package/tools/capabilities.py +108 -0
  66. package/tools/diagnostics.py +146 -0
  67. package/tools/gather.py +157 -0
  68. package/tools/import_parser.py +279 -0
  69. package/tools/market_regime.py +252 -0
  70. package/tools/market_review.py +155 -0
  71. package/tools/name_resolver.py +136 -0
  72. package/tools/pattern.py +515 -0
  73. package/tools/position_context.py +161 -0
  74. package/tools/report_renderer.py +116 -0
  75. package/tools/requirements.txt +15 -0
  76. package/tools/risk_screening.py +323 -0
  77. package/tools/screener.py +219 -0
  78. package/tools/search_intel.py +504 -0
  79. package/tools/stock_data.py +1721 -0
  80. package/tools/technical.py +642 -0
  81. package/tools/trading_calendar.py +226 -0
  82. package/tools/volume_analysis.py +178 -0
  83. package/tools/watchlist.py +66 -0
  84. package/tools/watchlist_context.py +185 -0
@@ -0,0 +1,515 @@
1
+ #!/usr/bin/env python3
2
+ """K-line pattern recognition — detect 12+ candlestick/chart patterns."""
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 = 60) -> 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
+ def _body(row):
37
+ return abs(row["close"] - row["open"])
38
+
39
+
40
+ def _range(row):
41
+ return row["high"] - row["low"]
42
+
43
+
44
+ def _upper_shadow(row):
45
+ return row["high"] - max(row["close"], row["open"])
46
+
47
+
48
+ def _lower_shadow(row):
49
+ return min(row["close"], row["open"]) - row["low"]
50
+
51
+
52
+ def _is_bullish(row):
53
+ return row["close"] > row["open"]
54
+
55
+
56
+ def _is_bearish(row):
57
+ return row["close"] < row["open"]
58
+
59
+
60
+ def _change_pct(row):
61
+ if row["open"] == 0:
62
+ return 0
63
+ return (row["close"] - row["open"]) / row["open"] * 100
64
+
65
+
66
+ def detect_doji(df: pd.DataFrame) -> list:
67
+ """十字星: body < 10% of range, both shadows present."""
68
+ patterns = []
69
+ for i in range(len(df)):
70
+ row = df.iloc[i]
71
+ r = _range(row)
72
+ if r == 0:
73
+ continue
74
+ b = _body(row)
75
+ if b / r < 0.1 and _upper_shadow(row) > r * 0.2 and _lower_shadow(row) > r * 0.2:
76
+ patterns.append(
77
+ {
78
+ "date": str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"]),
79
+ "pattern": "doji",
80
+ "name_cn": "十字星",
81
+ "direction": "neutral",
82
+ "description": "多空力量均衡,可能变盘",
83
+ }
84
+ )
85
+ return patterns
86
+
87
+
88
+ def detect_hammer(df: pd.DataFrame) -> list:
89
+ """锤子线: small body at top, long lower shadow >= 2x body, little upper shadow."""
90
+ patterns = []
91
+ for i in range(1, len(df)):
92
+ row = df.iloc[i]
93
+ prev = df.iloc[i - 1]
94
+ b = _body(row)
95
+ r = _range(row)
96
+ if r == 0 or b == 0:
97
+ continue
98
+ ls = _lower_shadow(row)
99
+ us = _upper_shadow(row)
100
+ if ls >= 2 * b and us < b * 0.5 and _is_bearish(prev):
101
+ patterns.append(
102
+ {
103
+ "date": str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"]),
104
+ "pattern": "hammer",
105
+ "name_cn": "锤子线",
106
+ "direction": "bullish",
107
+ "description": "下跌后出现锤子线,看涨反转信号",
108
+ }
109
+ )
110
+ return patterns
111
+
112
+
113
+ def detect_hanging_man(df: pd.DataFrame) -> list:
114
+ """上吊线: same shape as hammer but after uptrend."""
115
+ patterns = []
116
+ for i in range(1, len(df)):
117
+ row = df.iloc[i]
118
+ prev = df.iloc[i - 1]
119
+ b = _body(row)
120
+ r = _range(row)
121
+ if r == 0 or b == 0:
122
+ continue
123
+ ls = _lower_shadow(row)
124
+ us = _upper_shadow(row)
125
+ if ls >= 2 * b and us < b * 0.5 and _is_bullish(prev):
126
+ patterns.append(
127
+ {
128
+ "date": str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"]),
129
+ "pattern": "hanging_man",
130
+ "name_cn": "上吊线",
131
+ "direction": "bearish",
132
+ "description": "上涨后出现上吊线,看跌反转信号",
133
+ }
134
+ )
135
+ return patterns
136
+
137
+
138
+ def detect_shooting_star(df: pd.DataFrame) -> list:
139
+ """流星线: small body at bottom, long upper shadow >= 2x body, little lower shadow, after uptrend."""
140
+ patterns = []
141
+ for i in range(1, len(df)):
142
+ row = df.iloc[i]
143
+ prev = df.iloc[i - 1]
144
+ b = _body(row)
145
+ if b == 0:
146
+ continue
147
+ us = _upper_shadow(row)
148
+ ls = _lower_shadow(row)
149
+ if us >= 2 * b and ls < b * 0.5 and _is_bullish(prev):
150
+ patterns.append(
151
+ {
152
+ "date": str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"]),
153
+ "pattern": "shooting_star",
154
+ "name_cn": "流星线",
155
+ "direction": "bearish",
156
+ "description": "上涨后出现流星线,看跌反转信号",
157
+ }
158
+ )
159
+ return patterns
160
+
161
+
162
+ def detect_inverted_hammer(df: pd.DataFrame) -> list:
163
+ """倒锤子: long upper shadow, small body at bottom, after downtrend."""
164
+ patterns = []
165
+ for i in range(1, len(df)):
166
+ row = df.iloc[i]
167
+ prev = df.iloc[i - 1]
168
+ b = _body(row)
169
+ if b == 0:
170
+ continue
171
+ us = _upper_shadow(row)
172
+ ls = _lower_shadow(row)
173
+ if us >= 2 * b and ls < b * 0.5 and _is_bearish(prev):
174
+ patterns.append(
175
+ {
176
+ "date": str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"]),
177
+ "pattern": "inverted_hammer",
178
+ "name_cn": "倒锤子线",
179
+ "direction": "bullish",
180
+ "description": "下跌后出现倒锤子线,潜在看涨信号",
181
+ }
182
+ )
183
+ return patterns
184
+
185
+
186
+ def detect_big_candle(df: pd.DataFrame) -> list:
187
+ """大阳线/大阴线: body > 3% of open price."""
188
+ patterns = []
189
+ for i in range(len(df)):
190
+ row = df.iloc[i]
191
+ if row["open"] == 0:
192
+ continue
193
+ pct = abs(row["close"] - row["open"]) / row["open"] * 100
194
+ if pct >= 3:
195
+ is_bull = _is_bullish(row)
196
+ patterns.append(
197
+ {
198
+ "date": str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"]),
199
+ "pattern": "big_bullish_candle" if is_bull else "big_bearish_candle",
200
+ "name_cn": "大阳线" if is_bull else "大阴线",
201
+ "direction": "bullish" if is_bull else "bearish",
202
+ "description": f"{'大阳线' if is_bull else '大阴线'},涨跌幅{pct:.1f}%,{'多方强势' if is_bull else '空方强势'}",
203
+ }
204
+ )
205
+ return patterns
206
+
207
+
208
+ def detect_morning_star(df: pd.DataFrame) -> list:
209
+ """启明星: bearish candle + small body + bullish candle closing above midpoint of first."""
210
+ patterns = []
211
+ for i in range(2, len(df)):
212
+ c1, c2, c3 = df.iloc[i - 2], df.iloc[i - 1], df.iloc[i]
213
+ b1, b2, _ = _body(c1), _body(c2), _body(c3)
214
+ if b1 == 0:
215
+ continue
216
+ mid1 = (c1["open"] + c1["close"]) / 2
217
+ if _is_bearish(c1) and b1 > b2 * 2 and _is_bullish(c3) and c3["close"] > mid1 and c2["close"] < c1["close"]:
218
+ patterns.append(
219
+ {
220
+ "date": str(c3["date"].date()) if hasattr(c3["date"], "date") else str(c3["date"]),
221
+ "pattern": "morning_star",
222
+ "name_cn": "启明星",
223
+ "direction": "bullish",
224
+ "description": "底部启明星形态,强看涨反转信号",
225
+ }
226
+ )
227
+ return patterns
228
+
229
+
230
+ def detect_evening_star(df: pd.DataFrame) -> list:
231
+ """黄昏星: bullish candle + small body + bearish candle closing below midpoint of first."""
232
+ patterns = []
233
+ for i in range(2, len(df)):
234
+ c1, c2, c3 = df.iloc[i - 2], df.iloc[i - 1], df.iloc[i]
235
+ b1, b2, _ = _body(c1), _body(c2), _body(c3)
236
+ if b1 == 0:
237
+ continue
238
+ mid1 = (c1["open"] + c1["close"]) / 2
239
+ if _is_bullish(c1) and b1 > b2 * 2 and _is_bearish(c3) and c3["close"] < mid1 and c2["close"] > c1["close"]:
240
+ patterns.append(
241
+ {
242
+ "date": str(c3["date"].date()) if hasattr(c3["date"], "date") else str(c3["date"]),
243
+ "pattern": "evening_star",
244
+ "name_cn": "黄昏星",
245
+ "direction": "bearish",
246
+ "description": "顶部黄昏星形态,强看跌反转信号",
247
+ }
248
+ )
249
+ return patterns
250
+
251
+
252
+ def detect_bullish_engulfing(df: pd.DataFrame) -> list:
253
+ """看涨吞没: bearish candle followed by larger bullish candle that engulfs it."""
254
+ patterns = []
255
+ for i in range(1, len(df)):
256
+ prev, cur = df.iloc[i - 1], df.iloc[i]
257
+ if _is_bearish(prev) and _is_bullish(cur) and cur["open"] <= prev["close"] and cur["close"] >= prev["open"]:
258
+ patterns.append(
259
+ {
260
+ "date": str(cur["date"].date()) if hasattr(cur["date"], "date") else str(cur["date"]),
261
+ "pattern": "bullish_engulfing",
262
+ "name_cn": "看涨吞没",
263
+ "direction": "bullish",
264
+ "description": "阳线完全包裹前一阴线,看涨反转信号",
265
+ }
266
+ )
267
+ return patterns
268
+
269
+
270
+ def detect_bearish_engulfing(df: pd.DataFrame) -> list:
271
+ """看跌吞没: bullish candle followed by larger bearish candle that engulfs it."""
272
+ patterns = []
273
+ for i in range(1, len(df)):
274
+ prev, cur = df.iloc[i - 1], df.iloc[i]
275
+ if _is_bullish(prev) and _is_bearish(cur) and cur["open"] >= prev["close"] and cur["close"] <= prev["open"]:
276
+ patterns.append(
277
+ {
278
+ "date": str(cur["date"].date()) if hasattr(cur["date"], "date") else str(cur["date"]),
279
+ "pattern": "bearish_engulfing",
280
+ "name_cn": "看跌吞没",
281
+ "direction": "bearish",
282
+ "description": "阴线完全包裹前一阳线,看跌反转信号",
283
+ }
284
+ )
285
+ return patterns
286
+
287
+
288
+ def detect_double_bottom(df: pd.DataFrame) -> list:
289
+ """双底 (W底): two lows within 2% tolerance separated by a peak."""
290
+ patterns = []
291
+ if len(df) < 20:
292
+ return patterns
293
+ lows = df["low"].values
294
+ for i in range(10, len(df) - 2):
295
+ window_left = lows[max(0, i - 10) : i]
296
+ if len(window_left) == 0:
297
+ continue
298
+ left_min_idx = np.argmin(window_left) + max(0, i - 10)
299
+ left_min = lows[left_min_idx]
300
+ right_window = lows[i : min(len(lows), i + 10)]
301
+ if len(right_window) < 3:
302
+ continue
303
+ right_min_idx = np.argmin(right_window) + i
304
+ right_min = lows[right_min_idx]
305
+ if left_min == 0:
306
+ continue
307
+ if abs(left_min - right_min) / left_min < 0.02:
308
+ peak_between = max(df["high"].values[left_min_idx : right_min_idx + 1])
309
+ if peak_between > left_min * 1.03:
310
+ cur = df.iloc[right_min_idx]
311
+ patterns.append(
312
+ {
313
+ "date": str(cur["date"].date()) if hasattr(cur["date"], "date") else str(cur["date"]),
314
+ "pattern": "double_bottom",
315
+ "name_cn": "双底(W底)",
316
+ "direction": "bullish",
317
+ "description": f"双底形态,两次低点{left_min:.2f}/{right_min:.2f},颈线位{peak_between:.2f}",
318
+ }
319
+ )
320
+ break
321
+ return patterns
322
+
323
+
324
+ def detect_breakout(df: pd.DataFrame) -> list:
325
+ """20日突破: close breaks above 20-day high."""
326
+ patterns = []
327
+ if len(df) < 21:
328
+ return patterns
329
+ for i in range(20, len(df)):
330
+ prev_high = df["high"].iloc[i - 20 : i].max()
331
+ cur = df.iloc[i]
332
+ prev = df.iloc[i - 1]
333
+ if cur["close"] > prev_high and prev["close"] <= prev_high:
334
+ patterns.append(
335
+ {
336
+ "date": str(cur["date"].date()) if hasattr(cur["date"], "date") else str(cur["date"]),
337
+ "pattern": "breakout_20d",
338
+ "name_cn": "20日新高突破",
339
+ "direction": "bullish",
340
+ "description": f"收盘价突破20日高点{prev_high:.2f},突破信号",
341
+ }
342
+ )
343
+ return patterns
344
+
345
+
346
+ def detect_breakdown(df: pd.DataFrame) -> list:
347
+ """20日跌破: close breaks below 20-day low."""
348
+ patterns = []
349
+ if len(df) < 21:
350
+ return patterns
351
+ for i in range(20, len(df)):
352
+ prev_low = df["low"].iloc[i - 20 : i].min()
353
+ cur = df.iloc[i]
354
+ prev = df.iloc[i - 1]
355
+ if cur["close"] < prev_low and prev["close"] >= prev_low:
356
+ patterns.append(
357
+ {
358
+ "date": str(cur["date"].date()) if hasattr(cur["date"], "date") else str(cur["date"]),
359
+ "pattern": "breakdown_20d",
360
+ "name_cn": "20日新低跌破",
361
+ "direction": "bearish",
362
+ "description": f"收盘价跌破20日低点{prev_low:.2f},破位信号",
363
+ }
364
+ )
365
+ return patterns
366
+
367
+
368
+ def detect_box_oscillation(df: pd.DataFrame) -> list:
369
+ """箱体震荡: 10-day window with range < 8%."""
370
+ patterns = []
371
+ window = 10
372
+ if len(df) < window + 1:
373
+ return patterns
374
+ for i in range(window, len(df)):
375
+ w = df.iloc[i - window : i + 1]
376
+ max_high = float(w["high"].max())
377
+ min_low = float(w["low"].min())
378
+ if min_low <= 0:
379
+ continue
380
+ range_pct = (max_high - min_low) / min_low * 100
381
+ if range_pct < 8:
382
+ cur = df.iloc[i]
383
+ d = str(cur["date"].date()) if hasattr(cur["date"], "date") else str(cur["date"])
384
+ if not patterns or patterns[-1]["date"] != d:
385
+ patterns.append(
386
+ {
387
+ "date": d,
388
+ "pattern": "box_oscillation",
389
+ "name_cn": "箱体震荡",
390
+ "direction": "neutral",
391
+ "description": f"近{window}日振幅仅{range_pct:.1f}%,箱体区间{min_low:.2f}-{max_high:.2f}",
392
+ "box_high": round(max_high, 2),
393
+ "box_low": round(min_low, 2),
394
+ "box_range_pct": round(range_pct, 2),
395
+ }
396
+ )
397
+ return patterns
398
+
399
+
400
+ PATTERN_STRENGTH = {
401
+ "doji": "弱",
402
+ "inverted_hammer": "弱",
403
+ "hammer": "中",
404
+ "hanging_man": "中",
405
+ "shooting_star": "中",
406
+ "big_candle_up": "中",
407
+ "big_candle_down": "中",
408
+ "double_bottom": "中",
409
+ "box_oscillation": "中",
410
+ "morning_star": "强",
411
+ "evening_star": "强",
412
+ "bullish_engulfing": "强",
413
+ "bearish_engulfing": "强",
414
+ "breakout_20d": "强",
415
+ "breakdown_20d": "强",
416
+ }
417
+
418
+
419
+ ALL_DETECTORS = [
420
+ detect_doji,
421
+ detect_hammer,
422
+ detect_hanging_man,
423
+ detect_shooting_star,
424
+ detect_inverted_hammer,
425
+ detect_big_candle,
426
+ detect_morning_star,
427
+ detect_evening_star,
428
+ detect_bullish_engulfing,
429
+ detect_bearish_engulfing,
430
+ detect_double_bottom,
431
+ detect_breakout,
432
+ detect_breakdown,
433
+ detect_box_oscillation,
434
+ ]
435
+
436
+
437
+ def analyze(symbol: str, period: str = "daily", days: int = 60) -> dict:
438
+ records = fetch_kline(symbol, period, days)
439
+ if isinstance(records, dict) and "error" in records:
440
+ return records
441
+ if not records:
442
+ return {"error": "No kline data returned"}
443
+
444
+ df = to_dataframe(records)
445
+ if len(df) < 5:
446
+ return {"error": f"Insufficient data: {len(df)} rows (need at least 5)"}
447
+
448
+ all_patterns = []
449
+ for detector in ALL_DETECTORS:
450
+ all_patterns.extend(detector(df))
451
+
452
+ for p in all_patterns:
453
+ p["strength"] = PATTERN_STRENGTH.get(p["pattern"], "中")
454
+
455
+ all_patterns.sort(key=lambda p: p["date"], reverse=True)
456
+
457
+ recent = (
458
+ [
459
+ p
460
+ for p in all_patterns
461
+ if p["date"]
462
+ >= str(df["date"].iloc[-5].date() if hasattr(df["date"].iloc[-5], "date") else df["date"].iloc[-5])
463
+ ]
464
+ if len(df) >= 5
465
+ else all_patterns
466
+ )
467
+
468
+ bullish = [p for p in recent if p["direction"] == "bullish"]
469
+ bearish = [p for p in recent if p["direction"] == "bearish"]
470
+
471
+ return {
472
+ "symbol": symbol,
473
+ "period": period,
474
+ "data_points": len(df),
475
+ "recent_patterns": recent[:20],
476
+ "all_patterns_count": len(all_patterns),
477
+ "recent_summary": {
478
+ "bullish_count": len(bullish),
479
+ "bearish_count": len(bearish),
480
+ "neutral_count": len(recent) - len(bullish) - len(bearish),
481
+ "bias": "bullish"
482
+ if len(bullish) > len(bearish)
483
+ else "bearish"
484
+ if len(bearish) > len(bullish)
485
+ else "neutral",
486
+ },
487
+ "all_patterns": all_patterns[-50:],
488
+ }
489
+
490
+
491
+ def main():
492
+ parser = argparse.ArgumentParser(description="K-line pattern recognition")
493
+ sub = parser.add_subparsers(dest="command")
494
+
495
+ p = sub.add_parser("analyze")
496
+ p.add_argument("symbol")
497
+ p.add_argument("--period", default="daily", choices=["daily", "weekly", "monthly"])
498
+ p.add_argument("--days", type=int, default=60)
499
+
500
+ args = parser.parse_args()
501
+ if not args.command:
502
+ parser.print_help()
503
+ sys.exit(1)
504
+
505
+ result = analyze(args.symbol, args.period, args.days)
506
+ print(json.dumps(result, ensure_ascii=False, default=str))
507
+
508
+
509
+ if __name__ == "__main__":
510
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
511
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
512
+ for _s in (sys.stdout, sys.stderr):
513
+ if hasattr(_s, "reconfigure"):
514
+ _s.reconfigure(encoding="utf-8")
515
+ main()
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env python3
2
+ """Position context analyzer — pnl, distance to stop-loss/take-profit, position advice.
3
+
4
+ Not a portfolio system. Stateless: user passes cost/quantity/stops each call.
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ import subprocess
10
+ import sys
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+ from stock_data import detect_market # noqa: E402
16
+
17
+ TOOLS_DIR = Path(__file__).resolve().parent
18
+
19
+
20
+ def _find_python() -> str:
21
+ venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
22
+ return str(venv) if venv.exists() else sys.executable
23
+
24
+
25
+ def _run_json(script: str, args: list[str], timeout: int = 30):
26
+ cmd = [_find_python(), str(TOOLS_DIR / script)] + args
27
+ try:
28
+ r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=timeout)
29
+ if r.returncode == 0 and r.stdout.strip():
30
+ return json.loads(r.stdout)
31
+ except Exception:
32
+ pass
33
+ return None
34
+
35
+
36
+ def _risk_level(distance_to_stop_pct: float, pnl_pct: float, trend: str) -> str:
37
+ # ponytail: simple 3-bucket heuristic, upgrade to volatility-adjusted if needed
38
+ if distance_to_stop_pct is not None and distance_to_stop_pct < 3:
39
+ return "high"
40
+ if pnl_pct < -5 or trend == "bearish":
41
+ return "high"
42
+ if pnl_pct < 0 or (distance_to_stop_pct is not None and distance_to_stop_pct < 6):
43
+ return "medium"
44
+ return "low"
45
+
46
+
47
+ def _advice(pnl_pct: float, distance_to_stop_pct, distance_to_take_pct, trend: str, stop_loss, cost) -> str:
48
+ if distance_to_stop_pct is not None and distance_to_stop_pct < 3:
49
+ return "接近止损,建议减仓或严守止损位"
50
+ if pnl_pct > 15 and distance_to_take_pct is not None and distance_to_take_pct < 5:
51
+ return "接近目标价,考虑分批止盈"
52
+ if pnl_pct > 8 and stop_loss is not None and stop_loss < cost:
53
+ return "已有盈利,建议将止损上移到成本价或以上"
54
+ if pnl_pct < -5 and trend == "bearish":
55
+ return "浮亏且趋势偏空,控制仓位避免加仓"
56
+ if trend == "bullish" and pnl_pct >= 0:
57
+ return "趋势配合,可持有观察后续量能"
58
+ return "维持现有策略,关注关键位变化"
59
+
60
+
61
+ def analyze_position(
62
+ symbol: str,
63
+ cost: float,
64
+ quantity: float,
65
+ stop_loss: float | None = None,
66
+ take_profit: float | None = None,
67
+ ) -> dict:
68
+ quote = _run_json("stock_data.py", ["quote", symbol]) or {}
69
+ tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) or {}
70
+
71
+ price = quote.get("price")
72
+ if price is None:
73
+ return {"symbol": symbol, "error": "cannot fetch current price"}
74
+ price = float(price)
75
+
76
+ pnl_per_share = price - cost
77
+ pnl_pct = (pnl_per_share / cost * 100) if cost else 0.0
78
+ market_value = price * quantity
79
+ total_pnl = pnl_per_share * quantity
80
+
81
+ distance_to_stop_pct = None
82
+ if stop_loss is not None:
83
+ distance_to_stop_pct = (price - stop_loss) / price * 100 if price else None
84
+
85
+ distance_to_take_pct = None
86
+ if take_profit is not None:
87
+ distance_to_take_pct = (take_profit - price) / price * 100 if price else None
88
+
89
+ trend = (tech.get("trend") or {}).get("overall", "unknown")
90
+ support = (tech.get("support_resistance") or {}).get("support")
91
+ resistance = (tech.get("support_resistance") or {}).get("resistance")
92
+
93
+ risk_level = _risk_level(distance_to_stop_pct, pnl_pct, trend)
94
+ advice = _advice(pnl_pct, distance_to_stop_pct, distance_to_take_pct, trend, stop_loss, cost)
95
+
96
+ return {
97
+ "meta": {
98
+ "provider": "position_context",
99
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
100
+ "freshness": "realtime_or_latest_trade_day",
101
+ "fallback_used": False,
102
+ "warnings": [],
103
+ },
104
+ "symbol": symbol,
105
+ "market": detect_market(symbol),
106
+ "name": quote.get("name"),
107
+ "position": {
108
+ "cost": cost,
109
+ "quantity": quantity,
110
+ "current_price": price,
111
+ "market_value": round(market_value, 2),
112
+ "total_pnl": round(total_pnl, 2),
113
+ "pnl_pct": round(pnl_pct, 2),
114
+ },
115
+ "levels": {
116
+ "stop_loss": stop_loss,
117
+ "take_profit": take_profit,
118
+ "support": support,
119
+ "resistance": resistance,
120
+ "distance_to_stop_loss_pct": round(distance_to_stop_pct, 2) if distance_to_stop_pct is not None else None,
121
+ "distance_to_take_profit_pct": round(distance_to_take_pct, 2) if distance_to_take_pct is not None else None,
122
+ },
123
+ "trend": trend,
124
+ "risk_level": risk_level,
125
+ "position_advice": advice,
126
+ }
127
+
128
+
129
+ def main():
130
+ parser = argparse.ArgumentParser(description="Position context analyzer")
131
+ sub = parser.add_subparsers(dest="command")
132
+ p = sub.add_parser("analyze")
133
+ p.add_argument("symbol")
134
+ p.add_argument("--cost", type=float, required=True, help="Cost basis per share")
135
+ p.add_argument("--quantity", type=float, required=True, help="Number of shares held")
136
+ p.add_argument("--stop-loss", type=float, help="Stop loss price")
137
+ p.add_argument("--take-profit", type=float, help="Take profit price")
138
+
139
+ args = parser.parse_args()
140
+ if not args.command:
141
+ parser.print_help()
142
+ sys.exit(1)
143
+
144
+ result = analyze_position(
145
+ args.symbol,
146
+ cost=args.cost,
147
+ quantity=args.quantity,
148
+ stop_loss=args.stop_loss,
149
+ take_profit=args.take_profit,
150
+ )
151
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
152
+ print()
153
+
154
+
155
+ if __name__ == "__main__":
156
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
157
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
158
+ for _s in (sys.stdout, sys.stderr):
159
+ if hasattr(_s, "reconfigure"):
160
+ _s.reconfigure(encoding="utf-8")
161
+ main()