stock-analysis-plugin 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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -11
  3. package/package.json +5 -5
  4. package/pi/index.ts +86 -8
  5. package/scripts/ci-resolve-llm-host.mjs +29 -0
  6. package/scripts/setup-python.mjs +7 -9
  7. package/skills/hot-theme/SKILL.md +3 -2
  8. package/skills/stock-screener/SKILL.md +1 -1
  9. package/skills/strategy-backtest/SKILL.md +9 -5
  10. package/strategies/examples/bottom_volume.yaml +5 -0
  11. package/strategies/examples/box_oscillation.yaml +5 -0
  12. package/strategies/examples/bull_trend.yaml +11 -3
  13. package/strategies/examples/dragon_head.yaml +4 -2
  14. package/strategies/examples/emotion_cycle.yaml +5 -0
  15. package/strategies/examples/ma_crossover.yaml +10 -3
  16. package/strategies/examples/rsi_oversold.yaml +5 -0
  17. package/strategies/examples/shrink_pullback.yaml +7 -1
  18. package/strategies/examples/volume_breakout.yaml +7 -1
  19. package/tools/_subproc.py +49 -0
  20. package/tools/alert_rules.py +19 -9
  21. package/tools/anomaly_detect.py +24 -35
  22. package/tools/backtest.py +180 -100
  23. package/tools/capabilities.py +4 -5
  24. package/tools/diagnostics.py +6 -6
  25. package/tools/gather.py +13 -9
  26. package/tools/import_parser.py +2 -5
  27. package/tools/market_regime.py +27 -35
  28. package/tools/market_review.py +56 -9
  29. package/tools/name_resolver.py +2 -5
  30. package/tools/pattern.py +2 -5
  31. package/tools/position_context.py +2 -5
  32. package/tools/report_renderer.py +10 -6
  33. package/tools/requirements.txt +2 -1
  34. package/tools/risk_screening.py +29 -23
  35. package/tools/screener.py +26 -16
  36. package/tools/search_intel.py +5 -13
  37. package/tools/signal_tracker.py +2 -6
  38. package/tools/stock_data.py +301 -92
  39. package/tools/technical.py +136 -40
  40. package/tools/trading_calendar.py +78 -18
  41. package/tools/volume_analysis.py +2 -5
  42. package/tools/watchlist.py +2 -5
  43. package/tools/watchlist_context.py +2 -5
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
- r = subprocess.run(
68
- [sys.executable, script, "kline", symbol, "--period", "daily", "--count", str(count)],
69
- capture_output=True,
70
- text=True,
71
- encoding="utf-8",
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 (inline) ---------------
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
- delta = close.diff()
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
- def compute_ema(close: pd.Series, period: int) -> pd.Series:
107
- return close.ewm(span=period, adjust=False).mean()
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 compute_ema(close, 12) - compute_ema(close, 26)
112
+ return macd_series(close)[0]
112
113
 
113
114
 
114
115
  def compute_macd_dea(close: pd.Series) -> pd.Series:
115
- return compute_macd_dif(close).ewm(span=9, adjust=False).mean()
116
+ return macd_series(close)[1]
116
117
 
117
118
 
118
119
  def compute_macd_hist(close: pd.Series) -> pd.Series:
119
- return 2 * (compute_macd_dif(close) - compute_macd_dea(close))
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.rolling(period).mean()
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.rolling(period).mean()
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 compute_ma_diff(close: pd.Series, period: int | None = None) -> pd.Series:
141
- """Difference between two MAs. Period encodes both: e.g. 510 = MA5 - MA10, 1020 = MA10 - MA20."""
142
- if period and period >= 100:
143
- fast = period // 100
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
- else:
148
- fast = 5
149
- slow = 20
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(close: pd.Series, period: int | None = None) -> pd.Series:
154
- if period and period >= 100:
155
- fast = period // 100
156
- slow = period % 100
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(df: pd.DataFrame, name: str, period: int | None = None) -> pd.Series:
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
- if isinstance(period, str):
219
- try:
220
- period = int(float(period))
221
- except (ValueError, TypeError):
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
- proceeds = holding["shares"] * sell_price * (1 - commission)
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
- return {
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 df, i: (
715
+ "macd_golden_cross": lambda c, i: (
638
716
  i >= 1
639
- and float(compute_macd_dif(df["close"]).iloc[i]) > float(compute_macd_dea(df["close"]).iloc[i])
640
- and float(compute_macd_dif(df["close"]).iloc[i - 1]) <= float(compute_macd_dea(df["close"]).iloc[i - 1])
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 df, i: (
720
+ "macd_death_cross": lambda c, i: (
643
721
  i >= 1
644
- and float(compute_macd_dif(df["close"]).iloc[i]) < float(compute_macd_dea(df["close"]).iloc[i])
645
- and float(compute_macd_dif(df["close"]).iloc[i - 1]) >= float(compute_macd_dea(df["close"]).iloc[i - 1])
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 df, i: float(compute_rsi(df["close"], 14).iloc[i]) < 30,
648
- "rsi_overbought": lambda df, i: float(compute_rsi(df["close"], 14).iloc[i]) > 70,
649
- "breakout_20d": lambda df, i: (
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(df["close"].iloc[i]) > float(df["high"].iloc[i - 20 : i].max())
652
- and float(df["close"].iloc[i - 1]) <= float(df["high"].iloc[i - 20 : i].max())
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 df, i: (
732
+ "breakdown_20d": lambda c, i: (
655
733
  i >= 20
656
- and float(df["close"].iloc[i]) < float(df["low"].iloc[i - 20 : i].min())
657
- and float(df["close"].iloc[i - 1]) >= float(df["low"].iloc[i - 20 : i].min())
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 df, i: (
660
- i >= 20 and float(df["volume"].iloc[i]) > 2.0 * float(df["volume"].iloc[i - 20 : i].mean())
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 df, i: (
740
+ "ma_golden_cross": lambda c, i: (
663
741
  i >= 20
664
- and float(compute_ma(df["close"], 5).iloc[i]) > float(compute_ma(df["close"], 20).iloc[i])
665
- and float(compute_ma(df["close"], 5).iloc[i - 1]) <= float(compute_ma(df["close"], 20).iloc[i - 1])
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 df, i: (
745
+ "ma_death_cross": lambda c, i: (
668
746
  i >= 20
669
- and float(compute_ma(df["close"], 5).iloc[i]) < float(compute_ma(df["close"], 20).iloc[i])
670
- and float(compute_ma(df["close"], 5).iloc[i - 1]) >= float(compute_ma(df["close"], 20).iloc[i - 1])
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(df, i):
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
- if args.command == "run":
746
- result = run_backtest(args.strategy, args.symbol, args.start, args.end, args.capital)
747
- elif args.command == "evaluate":
748
- result = evaluate_result(args.result)
749
- elif args.command == "evaluate_signal":
750
- fwd = [int(x) for x in args.forward.split(",")]
751
- result = evaluate_signal(args.symbol, args.signal, fwd, args.lookback)
752
- else:
753
- result = {"error": f"Unknown command: {args.command}"}
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
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
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()
@@ -11,6 +11,7 @@ from datetime import datetime, timezone
11
11
  from pathlib import Path
12
12
 
13
13
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+ from _subproc import utf8_stdio
14
15
  from stock_data import detect_market
15
16
 
16
17
  ALL_MARKETS = ["A", "HK", "US", "JP", "KR", "TW"]
@@ -42,6 +43,8 @@ TOOL_MATRIX = {
42
43
  "get_limit_up_pool": {"markets": ["A"], "reason": "A-share only"},
43
44
  "get_dragon_tiger": {"markets": ["A"], "reason": "A-share only"},
44
45
  "get_hot_stocks": {"markets": ["A"], "reason": "A-share only"},
46
+ "get_margin_trading": {"markets": ["A"], "reason": "A-share only"},
47
+ "get_northbound_flow": {"markets": ["A"], "reason": "A-share only"},
45
48
  "get_social_sentiment": {
46
49
  "markets": ["A", "HK", "US"],
47
50
  "reason": "A-share uses Eastmoney/Xueqiu; HK/US require SENTIMENT_API_KEY",
@@ -109,9 +112,5 @@ def main():
109
112
 
110
113
 
111
114
  if __name__ == "__main__":
112
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
113
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
114
- for _s in (sys.stdout, sys.stderr):
115
- if hasattr(_s, "reconfigure"):
116
- _s.reconfigure(encoding="utf-8")
115
+ utf8_stdio()
117
116
  main()
@@ -17,12 +17,16 @@ from datetime import datetime, timezone
17
17
  from pathlib import Path
18
18
 
19
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
20
+ from _subproc import utf8_stdio # noqa: E402
20
21
  from capabilities import ALL_MARKETS # noqa: E402
21
22
 
22
23
  # provider -> (import_name, required_env_vars, markets, note)
23
24
  PROVIDERS = {
24
25
  "akshare": ("akshare", [], ["A"], None),
25
- "tushare": ("tushare", ["TUSHARE_TOKEN"], ["A"], None),
26
+ # tushare is consumed as a pure-HTTP API (requests.post to api.tushare.pro,
27
+ # see stock_data._kline_tushare) — the tushare package is not in requirements,
28
+ # so availability is the token, not a package probe
29
+ "tushare": ("requests", ["TUSHARE_TOKEN"], ["A"], "pure-HTTP API (api.tushare.pro); no tushare package needed"),
26
30
  "efinance": ("efinance", [], ["A"], None),
27
31
  "tencent": ("requests", [], ["A"], "qt.gtimg.cn quote/kline, no auth (issue #25)"),
28
32
  "sina": (
@@ -150,9 +154,5 @@ def main():
150
154
 
151
155
 
152
156
  if __name__ == "__main__":
153
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
154
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
155
- for _s in (sys.stdout, sys.stderr):
156
- if hasattr(_s, "reconfigure"):
157
- _s.reconfigure(encoding="utf-8")
157
+ utf8_stdio()
158
158
  main()
package/tools/gather.py CHANGED
@@ -8,7 +8,8 @@ from concurrent.futures import ThreadPoolExecutor
8
8
  from pathlib import Path
9
9
 
10
10
  sys.path.insert(0, str(Path(__file__).resolve().parent))
11
- from _subproc import run_tool # noqa: E402
11
+ from _subproc import json_safe, run_tool, utf8_stdio # noqa: E402
12
+ from stock_data import detect_market # noqa: E402
12
13
 
13
14
 
14
15
  # gather fans out the heavier CLIs, so the default timeout stays 60s; raw stdout
@@ -17,6 +18,11 @@ def _run(script, args, timeout=60):
17
18
  return run_tool(script, args, timeout=timeout, parse_json=False)
18
19
 
19
20
 
21
+ def _news_query(symbol: str) -> str:
22
+ # CN sources rank poorly for an English query; US/HK sources for a Chinese one.
23
+ return f"{symbol} 最新消息" if detect_market(symbol) == "A" else f"{symbol} stock news"
24
+
25
+
20
26
  def _parse_json(raw: str | None):
21
27
  if raw is None:
22
28
  return None
@@ -39,7 +45,9 @@ def gather_analysis(symbol: str) -> dict:
39
45
  "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "120"]),
40
46
  "financials": ("stock_data.py", ["financials", symbol]),
41
47
  "capital_flow": ("stock_data.py", ["capital_flow", symbol]),
42
- "news": ("search_intel.py", ["search", f"{symbol} stock news"]),
48
+ "chip_distribution": ("stock_data.py", ["chip_distribution", symbol]),
49
+ "news": ("search_intel.py", ["search", _news_query(symbol)]),
50
+ "social_sentiment": ("search_intel.py", ["sentiment", symbol]),
43
51
  "risk": ("risk_screening.py", ["screen", symbol]),
44
52
  "regime": ("market_regime.py", ["detect"]),
45
53
  }
@@ -70,7 +78,7 @@ def gather_fundamental(symbol: str) -> dict:
70
78
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "60"]),
71
79
  "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]),
72
80
  "financials": ("stock_data.py", ["financials", symbol]),
73
- "news": ("search_intel.py", ["search", f"{symbol} stock news"]),
81
+ "news": ("search_intel.py", ["search", _news_query(symbol)]),
74
82
  "stock_info": ("stock_data.py", ["stock_info", symbol]),
75
83
  "sector_rankings": ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]),
76
84
  }
@@ -111,14 +119,10 @@ def main():
111
119
  parser.print_help()
112
120
  sys.exit(1)
113
121
 
114
- json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
122
+ json.dump(json_safe(result), sys.stdout, ensure_ascii=False, indent=2)
115
123
  print()
116
124
 
117
125
 
118
126
  if __name__ == "__main__":
119
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
120
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
121
- for _s in (sys.stdout, sys.stderr):
122
- if hasattr(_s, "reconfigure"):
123
- _s.reconfigure(encoding="utf-8")
127
+ utf8_stdio()
124
128
  main()
@@ -12,6 +12,7 @@ from datetime import datetime, timezone
12
12
  from pathlib import Path
13
13
 
14
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+ from _subproc import utf8_stdio # noqa: E402
15
16
  from name_resolver import resolve # noqa: E402
16
17
  from stock_data import detect_market # noqa: E402
17
18
 
@@ -271,9 +272,5 @@ def main():
271
272
 
272
273
 
273
274
  if __name__ == "__main__":
274
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
275
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
276
- for _s in (sys.stdout, sys.stderr):
277
- if hasattr(_s, "reconfigure"):
278
- _s.reconfigure(encoding="utf-8")
275
+ utf8_stdio()
279
276
  main()