dsh-stock-analysis 0.2.1 → 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 +2 -2
  3. package/dist/index.js +68 -15
  4. package/package.json +3 -3
  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 +393 -100
  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
@@ -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()