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,226 @@
1
+ #!/usr/bin/env python3
2
+ """Trading calendar — determine trading days for CN/HK/US/JP/KR/TW markets."""
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from datetime import datetime, timedelta
8
+
9
+ # Supported markets. argparse uses type=str.upper so lowercase input is accepted too.
10
+ MARKETS = ["CN", "HK", "US", "JP", "KR", "TW"]
11
+
12
+
13
+ def _is_weekend(d: datetime) -> bool:
14
+ return d.weekday() >= 5
15
+
16
+
17
+ def _cn_holidays(year: int) -> set[str]:
18
+ try:
19
+ import akshare as ak
20
+
21
+ df = ak.tool_trade_date_hist_sina()
22
+ dates = set()
23
+ for _, row in df.iterrows():
24
+ val = row.iloc[0]
25
+ d = str(val)[:10]
26
+ if d.startswith(str(year)):
27
+ dates.add(d)
28
+ return dates
29
+ except Exception:
30
+ return set()
31
+
32
+
33
+ def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
34
+ import exchange_calendars as xcals
35
+ import pandas as pd
36
+
37
+ cal = xcals.get_calendar(exchange_code)
38
+ d = pd.Timestamp(date_str)
39
+ return cal.is_session(d)
40
+
41
+
42
+ def _get_cn_trading_dates(year: int) -> set[str]:
43
+ return _cn_holidays(year)
44
+
45
+
46
+ def is_trading_day(market: str, date_str: str = None) -> dict:
47
+ if date_str:
48
+ d = datetime.strptime(date_str, "%Y-%m-%d")
49
+ else:
50
+ d = datetime.now()
51
+ date_str = d.strftime("%Y-%m-%d")
52
+
53
+ market = market.upper()
54
+
55
+ if _is_weekend(d):
56
+ return {"date": date_str, "market": market, "is_trading_day": False, "reason": "weekend"}
57
+
58
+ if market == "CN":
59
+ trading_dates = _get_cn_trading_dates(d.year)
60
+ if trading_dates:
61
+ is_td = date_str in trading_dates
62
+ return {
63
+ "date": date_str,
64
+ "market": market,
65
+ "is_trading_day": is_td,
66
+ "reason": "trading_day" if is_td else "holiday",
67
+ }
68
+ return {
69
+ "date": date_str,
70
+ "market": market,
71
+ "is_trading_day": True,
72
+ "reason": "assumed_trading_day (calendar unavailable)",
73
+ }
74
+
75
+ elif market == "HK":
76
+ try:
77
+ is_td = _is_exchange_trading_day("XHKG", date_str)
78
+ return {
79
+ "date": date_str,
80
+ "market": market,
81
+ "is_trading_day": is_td,
82
+ "reason": "trading_day" if is_td else "holiday",
83
+ "source": "exchange-calendars",
84
+ }
85
+ except Exception:
86
+ pass
87
+ trading_dates = _get_cn_trading_dates(d.year)
88
+ if trading_dates:
89
+ is_td = date_str in trading_dates
90
+ return {
91
+ "date": date_str,
92
+ "market": market,
93
+ "is_trading_day": is_td,
94
+ "reason": "trading_day" if is_td else "holiday (approx, based on CN calendar)",
95
+ }
96
+ return {"date": date_str, "market": market, "is_trading_day": True, "reason": "assumed_trading_day"}
97
+
98
+ elif market == "US":
99
+ try:
100
+ is_td = _is_exchange_trading_day("XNYS", date_str)
101
+ return {
102
+ "date": date_str,
103
+ "market": market,
104
+ "is_trading_day": is_td,
105
+ "reason": "trading_day" if is_td else "holiday",
106
+ "source": "exchange-calendars",
107
+ }
108
+ except Exception:
109
+ pass
110
+ us_holidays = {
111
+ (1, 1),
112
+ (1, 20),
113
+ (2, 17),
114
+ (5, 26),
115
+ (6, 19),
116
+ (7, 4),
117
+ (9, 1),
118
+ (11, 27),
119
+ (12, 25),
120
+ }
121
+ if (d.month, d.day) in us_holidays:
122
+ return {"date": date_str, "market": market, "is_trading_day": False, "reason": "US_holiday"}
123
+ return {"date": date_str, "market": market, "is_trading_day": True, "reason": "trading_day"}
124
+
125
+ elif market in ("JP", "KR", "TW"):
126
+ exchange_map = {"JP": "XTKS", "KR": "XKRX", "TW": "XTAI"}
127
+ try:
128
+ is_td = _is_exchange_trading_day(exchange_map[market], date_str)
129
+ return {
130
+ "date": date_str,
131
+ "market": market,
132
+ "is_trading_day": is_td,
133
+ "reason": "trading_day" if is_td else "holiday",
134
+ "source": "exchange-calendars",
135
+ }
136
+ except Exception:
137
+ pass
138
+ return {
139
+ "date": date_str,
140
+ "market": market,
141
+ "is_trading_day": True,
142
+ "reason": "assumed_trading_day (calendar unavailable)",
143
+ }
144
+
145
+ return {"date": date_str, "market": market, "error": f"Unknown market: {market}"}
146
+
147
+
148
+ def next_trading_days(market: str, count: int = 5, from_date: str = None) -> list[str]:
149
+ d = datetime.strptime(from_date, "%Y-%m-%d") if from_date else datetime.now()
150
+
151
+ result = []
152
+ max_search = count * 4
153
+ for _ in range(max_search):
154
+ d += timedelta(days=1)
155
+ info = is_trading_day(market, d.strftime("%Y-%m-%d"))
156
+ if info.get("is_trading_day"):
157
+ result.append(d.strftime("%Y-%m-%d"))
158
+ if len(result) >= count:
159
+ break
160
+ return result
161
+
162
+
163
+ def prev_trading_days(market: str, count: int = 5, from_date: str = None) -> list[str]:
164
+ d = datetime.strptime(from_date, "%Y-%m-%d") if from_date else datetime.now()
165
+
166
+ result = []
167
+ max_search = count * 4
168
+ for _ in range(max_search):
169
+ d -= timedelta(days=1)
170
+ info = is_trading_day(market, d.strftime("%Y-%m-%d"))
171
+ if info.get("is_trading_day"):
172
+ result.append(d.strftime("%Y-%m-%d"))
173
+ if len(result) >= count:
174
+ break
175
+ return result
176
+
177
+
178
+ def cmd_check(args):
179
+ return is_trading_day(args.market, args.date)
180
+
181
+
182
+ def cmd_next(args):
183
+ days = next_trading_days(args.market, args.count, args.date)
184
+ return {"market": args.market, "next_trading_days": days}
185
+
186
+
187
+ def cmd_prev(args):
188
+ days = prev_trading_days(args.market, args.count, args.date)
189
+ return {"market": args.market, "prev_trading_days": days}
190
+
191
+
192
+ def main():
193
+ parser = argparse.ArgumentParser(description="Trading calendar")
194
+ sub = parser.add_subparsers(dest="command")
195
+
196
+ p_check = sub.add_parser("check")
197
+ p_check.add_argument("market", type=str.upper, choices=MARKETS)
198
+ p_check.add_argument("--date", default=None, help="Date in YYYY-MM-DD format")
199
+
200
+ p_next = sub.add_parser("next")
201
+ p_next.add_argument("market", type=str.upper, choices=MARKETS)
202
+ p_next.add_argument("--count", type=int, default=5)
203
+ p_next.add_argument("--date", default=None)
204
+
205
+ p_prev = sub.add_parser("prev")
206
+ p_prev.add_argument("market", type=str.upper, choices=MARKETS)
207
+ p_prev.add_argument("--count", type=int, default=5)
208
+ p_prev.add_argument("--date", default=None)
209
+
210
+ args = parser.parse_args()
211
+ if not args.command:
212
+ parser.print_help()
213
+ sys.exit(1)
214
+
215
+ dispatch = {"check": cmd_check, "next": cmd_next, "prev": cmd_prev}
216
+ result = dispatch[args.command](args)
217
+ print(json.dumps(result, ensure_ascii=False, default=str))
218
+
219
+
220
+ if __name__ == "__main__":
221
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
222
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
223
+ for _s in (sys.stdout, sys.stderr):
224
+ if hasattr(_s, "reconfigure"):
225
+ _s.reconfigure(encoding="utf-8")
226
+ main()
@@ -0,0 +1,178 @@
1
+ #!/usr/bin/env python3
2
+ """Volume-price analysis — correlation, up/down day ratios, trend, pattern interpretation."""
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 analyze_volume(symbol: str, period: str = "daily", count: int = 60) -> dict:
37
+ records = fetch_kline(symbol, period, count)
38
+ if isinstance(records, dict) and "error" in records:
39
+ return records
40
+ if not records:
41
+ return {"error": "No kline data returned"}
42
+
43
+ df = to_dataframe(records)
44
+ if len(df) < 10:
45
+ return {"error": f"Insufficient data: {len(df)} rows (need at least 10)"}
46
+
47
+ close = df["close"]
48
+ volume = df["volume"]
49
+ price_change = close.pct_change().dropna()
50
+ vol_change = volume.pct_change().dropna()
51
+
52
+ min_len = min(len(price_change), len(vol_change))
53
+ pc = price_change.tail(min_len).values
54
+ vc = vol_change.tail(min_len).values
55
+ mask = ~(np.isnan(pc) | np.isnan(vc))
56
+ corr = float(np.corrcoef(pc[mask], vc[mask])[0, 1]) if mask.sum() > 2 else None
57
+
58
+ up_days = df[close > close.shift(1)]
59
+ down_days = df[close < close.shift(1)]
60
+ avg_vol_up = float(up_days["volume"].mean()) if len(up_days) > 0 else 0
61
+ avg_vol_down = float(down_days["volume"].mean()) if len(down_days) > 0 else 0
62
+ up_down_ratio = round(avg_vol_up / avg_vol_down, 2) if avg_vol_down > 0 else None
63
+
64
+ vol_ma5 = volume.rolling(5).mean()
65
+ vol_ma20 = volume.rolling(20).mean()
66
+ cur_vol = float(volume.iloc[-1])
67
+ vol_ratio_5 = round(cur_vol / float(vol_ma5.iloc[-1]), 2) if float(vol_ma5.iloc[-1]) > 0 else None
68
+ vol_ratio_20 = (
69
+ round(cur_vol / float(vol_ma20.iloc[-1]), 2)
70
+ if len(vol_ma20.dropna()) > 0 and float(vol_ma20.iloc[-1]) > 0
71
+ else None
72
+ )
73
+
74
+ recent_vol = volume.tail(5).mean()
75
+ prior_vol = volume.tail(20).head(15).mean()
76
+ if prior_vol > 0:
77
+ vol_trend_ratio = float(recent_vol / prior_vol)
78
+ if vol_trend_ratio > 1.5:
79
+ vol_trend = "increasing"
80
+ elif vol_trend_ratio < 0.7:
81
+ vol_trend = "decreasing"
82
+ else:
83
+ vol_trend = "stable"
84
+ else:
85
+ vol_trend = "unknown"
86
+ vol_trend_ratio = None
87
+
88
+ patterns = []
89
+ latest_price_up = float(close.iloc[-1]) > float(close.iloc[-2]) if len(close) >= 2 else None
90
+ latest_heavy = vol_ratio_5 and vol_ratio_5 > 1.5
91
+
92
+ if latest_heavy and latest_price_up:
93
+ patterns.append(
94
+ {"type": "heavy_volume_rally", "signal": "bullish", "desc": "放量上涨 — 资金积极入场,短期看多"}
95
+ )
96
+ elif latest_heavy and latest_price_up is False:
97
+ patterns.append({"type": "heavy_volume_decline", "signal": "bearish", "desc": "放量下跌 — 资金出逃,短期看空"})
98
+ elif vol_ratio_5 and vol_ratio_5 < 0.6 and latest_price_up is False:
99
+ patterns.append(
100
+ {"type": "shrink_volume_decline", "signal": "neutral_to_bullish", "desc": "缩量回调 — 抛压减轻,可能蓄势"}
101
+ )
102
+ elif vol_ratio_5 and vol_ratio_5 < 0.6 and latest_price_up:
103
+ patterns.append(
104
+ {"type": "shrink_volume_rally", "signal": "weak_bullish", "desc": "缩量上涨 — 追高意愿不强,持续性存疑"}
105
+ )
106
+
107
+ if up_down_ratio and up_down_ratio > 1.3:
108
+ patterns.append(
109
+ {
110
+ "type": "bullish_volume_bias",
111
+ "signal": "bullish",
112
+ "desc": f"上涨日均量远高于下跌日(比值{up_down_ratio}),资金偏多",
113
+ }
114
+ )
115
+ elif up_down_ratio and up_down_ratio < 0.7:
116
+ patterns.append(
117
+ {
118
+ "type": "bearish_volume_bias",
119
+ "signal": "bearish",
120
+ "desc": f"下跌日均量高于上涨日(比值{up_down_ratio}),资金偏空",
121
+ }
122
+ )
123
+
124
+ if corr is not None and corr > 0.5:
125
+ patterns.append(
126
+ {"type": "positive_vol_price_corr", "signal": "healthy", "desc": f"量价正相关({corr:.2f}),价量配合良好"}
127
+ )
128
+ elif corr is not None and corr < -0.3:
129
+ patterns.append(
130
+ {"type": "vol_price_divergence", "signal": "warning", "desc": f"量价背离({corr:.2f}),关注趋势转折"}
131
+ )
132
+
133
+ high_vol_mask = volume > vol_ma20 * 2
134
+ high_volume_days = int(high_vol_mask.tail(20).sum()) if len(vol_ma20.dropna()) > 0 else 0
135
+
136
+ return {
137
+ "symbol": symbol,
138
+ "period": period,
139
+ "data_points": len(df),
140
+ "current_volume": int(cur_vol),
141
+ "vol_ratio_5d": vol_ratio_5,
142
+ "vol_ratio_20d": vol_ratio_20,
143
+ "avg_volume_up_days": round(avg_vol_up) if avg_vol_up else None,
144
+ "avg_volume_down_days": round(avg_vol_down) if avg_vol_down else None,
145
+ "up_down_volume_ratio": up_down_ratio,
146
+ "vol_price_correlation": round(corr, 3) if corr is not None else None,
147
+ "volume_trend": vol_trend,
148
+ "volume_trend_ratio": round(vol_trend_ratio, 2) if vol_trend_ratio else None,
149
+ "high_volume_days_20d": high_volume_days,
150
+ "patterns": patterns,
151
+ }
152
+
153
+
154
+ def main():
155
+ parser = argparse.ArgumentParser(description="Volume-price analysis")
156
+ sub = parser.add_subparsers(dest="command")
157
+
158
+ p = sub.add_parser("analyze")
159
+ p.add_argument("symbol")
160
+ p.add_argument("--period", default="daily", choices=["daily", "weekly", "monthly"])
161
+ p.add_argument("--count", type=int, default=60)
162
+
163
+ args = parser.parse_args()
164
+ if not args.command:
165
+ parser.print_help()
166
+ sys.exit(1)
167
+
168
+ result = analyze_volume(args.symbol, args.period, args.count)
169
+ print(json.dumps(result, ensure_ascii=False, default=str))
170
+
171
+
172
+ if __name__ == "__main__":
173
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
174
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
175
+ for _s in (sys.stdout, sys.stderr):
176
+ if hasattr(_s, "reconfigure"):
177
+ _s.reconfigure(encoding="utf-8")
178
+ main()
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env python3
2
+ """Batch watchlist analysis — run gather_analysis for multiple stocks with concurrency control."""
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from pathlib import Path
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
11
+ from gather import gather_analysis
12
+
13
+
14
+ def analyze_watchlist(symbols: list[str], workers: int = 3) -> dict:
15
+ results = {}
16
+ success = 0
17
+ failed = 0
18
+
19
+ with ThreadPoolExecutor(max_workers=workers) as pool:
20
+ futures = {pool.submit(gather_analysis, sym): sym for sym in symbols}
21
+ for future in as_completed(futures):
22
+ sym = futures[future]
23
+ try:
24
+ data = future.result()
25
+ results[sym] = data
26
+ success += 1
27
+ except Exception:
28
+ results[sym] = None
29
+ failed += 1
30
+
31
+ return {
32
+ "results": results,
33
+ "summary": {"total": len(symbols), "success": success, "failed": failed},
34
+ }
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description="Batch watchlist analysis")
39
+ sub = parser.add_subparsers(dest="command")
40
+
41
+ p_analyze = sub.add_parser("analyze")
42
+ p_analyze.add_argument("symbols", help="Comma-separated stock codes")
43
+ p_analyze.add_argument("--workers", type=int, default=3, help="Concurrency level (default 3)")
44
+
45
+ args = parser.parse_args()
46
+
47
+ if args.command == "analyze":
48
+ codes = [c.strip() for c in args.symbols.split(",") if c.strip()]
49
+ if not codes:
50
+ print(json.dumps({"error": "No valid symbols provided"}))
51
+ sys.exit(1)
52
+ result = analyze_watchlist(codes, workers=args.workers)
53
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
54
+ print()
55
+ else:
56
+ parser.print_help()
57
+ sys.exit(1)
58
+
59
+
60
+ if __name__ == "__main__":
61
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
62
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
63
+ for _s in (sys.stdout, sys.stderr):
64
+ if hasattr(_s, "reconfigure"):
65
+ _s.reconfigure(encoding="utf-8")
66
+ main()
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ """Watchlist context builder — condense watchlist analysis into agent-friendly summaries.
3
+
4
+ Not a report renderer. Outputs per-symbol score/trend/anomalies/risk + suggested next tools,
5
+ so the host agent can decide what to do next (write daily briefing, dig deeper, alert, etc.).
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import subprocess
11
+ import sys
12
+ from concurrent.futures import ThreadPoolExecutor, as_completed
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
17
+ from stock_data import detect_market # noqa: E402
18
+ from watchlist import analyze_watchlist # noqa: E402
19
+
20
+ TOOLS_DIR = Path(__file__).resolve().parent
21
+
22
+
23
+ def _find_python() -> str:
24
+ venv = TOOLS_DIR.parent / ".venv" / "bin" / "python3"
25
+ return str(venv) if venv.exists() else sys.executable
26
+
27
+
28
+ def _run_json(script: str, args: list[str], timeout: int = 30):
29
+ cmd = [_find_python(), str(TOOLS_DIR / script)] + args
30
+ try:
31
+ r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", timeout=timeout)
32
+ if r.returncode == 0 and r.stdout.strip():
33
+ return json.loads(r.stdout)
34
+ except Exception:
35
+ pass
36
+ return None
37
+
38
+
39
+ def _trend_label(overall: str) -> str:
40
+ return {
41
+ "bullish": "bullish",
42
+ "bearish": "bearish",
43
+ "neutral": "neutral",
44
+ "mixed": "mixed",
45
+ }.get(overall, overall or "unknown")
46
+
47
+
48
+ def _suggest_next_tools(market: str, trend: str, anomalies: list, risk_level: str) -> list:
49
+ tools = []
50
+ high_anoms = [a for a in anomalies if a.get("severity") == "high"]
51
+
52
+ if market == "A" and (trend == "bullish" or high_anoms):
53
+ tools.append("get_capital_flow")
54
+ if high_anoms:
55
+ tools.append("search_comprehensive_intel")
56
+ if risk_level in ("high", "medium"):
57
+ tools.append("screen_risk")
58
+ if trend == "bullish":
59
+ tools.append("get_technical_analysis")
60
+ if any(a.get("type", "").startswith("volume_") for a in anomalies):
61
+ tools.append("get_volume_analysis")
62
+ # dedupe, preserve order
63
+ seen = set()
64
+ return [t for t in tools if not (t in seen or seen.add(t))]
65
+
66
+
67
+ def _build_item(symbol: str, data: dict | None) -> dict:
68
+ if not data:
69
+ return {"symbol": symbol, "error": "no data"}
70
+
71
+ tech = data.get("technical") or {}
72
+ risk = data.get("risk") or {}
73
+
74
+ # anomalies — separate call (watchlist gather doesn't include them)
75
+ anom_result = _run_json("anomaly_detect.py", ["detect", symbol]) or {}
76
+ anomalies = anom_result.get("anomalies", []) if isinstance(anom_result, dict) else []
77
+
78
+ score = tech.get("signal_score")
79
+ trend = _trend_label((tech.get("trend") or {}).get("overall", ""))
80
+ risk_level = risk.get("risk_level", "unknown")
81
+ veto = bool(risk.get("veto_buy", False))
82
+ buy_signal = tech.get("buy_signal")
83
+ market = detect_market(symbol)
84
+
85
+ quote = data.get("quote") or {}
86
+
87
+ return {
88
+ "symbol": symbol,
89
+ "market": market,
90
+ "name": quote.get("name"),
91
+ "price": quote.get("price"),
92
+ "change_pct": quote.get("change_pct"),
93
+ "score": score,
94
+ "trend": trend,
95
+ "buy_signal": buy_signal,
96
+ "risk_level": risk_level,
97
+ "veto_buy": veto,
98
+ "anomalies": [
99
+ {"type": a.get("type"), "severity": a.get("severity"), "direction": a.get("direction")} for a in anomalies
100
+ ],
101
+ "anomaly_count": len(anomalies),
102
+ "next_tools": _suggest_next_tools(market, trend, anomalies, risk_level),
103
+ }
104
+
105
+
106
+ def build_context(symbols: list[str], include_market_review: bool = False, workers: int = 3) -> dict:
107
+ raw = analyze_watchlist(symbols, workers=workers)
108
+ results = raw.get("results", {})
109
+
110
+ items = []
111
+ # fetch anomalies in parallel to keep it responsive
112
+ with ThreadPoolExecutor(max_workers=min(workers * 2, 6)) as pool:
113
+ futures = {pool.submit(_build_item, sym, results.get(sym)): sym for sym in symbols}
114
+ for fut in as_completed(futures):
115
+ items.append(fut.result())
116
+
117
+ # preserve caller order
118
+ order = {s: i for i, s in enumerate(symbols)}
119
+ items.sort(key=lambda x: order.get(x["symbol"], 999))
120
+
121
+ output = {
122
+ "meta": {
123
+ "provider": "watchlist_context",
124
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
125
+ "freshness": "realtime_or_latest_trade_day",
126
+ "fallback_used": False,
127
+ "warnings": [],
128
+ },
129
+ "summary": {
130
+ "total": len(symbols),
131
+ "success": sum(1 for i in items if "error" not in i),
132
+ "failed": sum(1 for i in items if "error" in i),
133
+ "high_risk_count": sum(1 for i in items if i.get("risk_level") == "high"),
134
+ "veto_count": sum(1 for i in items if i.get("veto_buy")),
135
+ },
136
+ "items": items,
137
+ }
138
+
139
+ if include_market_review:
140
+ markets = sorted({i.get("market") for i in items if i.get("market")})
141
+ review = {}
142
+ for m in markets:
143
+ r = _run_json("market_review.py", ["review", "--market", m], timeout=60)
144
+ if r:
145
+ review[m] = r
146
+ output["market_review"] = review
147
+
148
+ return output
149
+
150
+
151
+ def main():
152
+ parser = argparse.ArgumentParser(description="Build watchlist context for host agent")
153
+ sub = parser.add_subparsers(dest="command")
154
+
155
+ p = sub.add_parser("build")
156
+ p.add_argument("symbols", help="Comma-separated symbols")
157
+ p.add_argument(
158
+ "--include-market-review",
159
+ action="store_true",
160
+ help="Also fetch market review per involved market",
161
+ )
162
+ p.add_argument("--workers", type=int, default=3)
163
+
164
+ args = parser.parse_args()
165
+ if not args.command:
166
+ parser.print_help()
167
+ sys.exit(1)
168
+
169
+ codes = [c.strip() for c in args.symbols.split(",") if c.strip()]
170
+ if not codes:
171
+ print(json.dumps({"error": "No valid symbols"}))
172
+ sys.exit(1)
173
+
174
+ result = build_context(codes, include_market_review=args.include_market_review, workers=args.workers)
175
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
176
+ print()
177
+
178
+
179
+ if __name__ == "__main__":
180
+ # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
181
+ # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
182
+ for _s in (sys.stdout, sys.stderr):
183
+ if hasattr(_s, "reconfigure"):
184
+ _s.reconfigure(encoding="utf-8")
185
+ main()