@weaxs/openclaw-stock-analysis 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -0
- package/index.ts +761 -0
- package/openclaw.plugin.json +47 -0
- package/package.json +46 -0
- package/schemas/report_schema.json +131 -0
- package/scripts/setup-python.mjs +52 -0
- package/skills/bottom-volume/SKILL.md +63 -0
- package/skills/bottom-volume/scripts/gather.py +15 -0
- package/skills/box-oscillation/SKILL.md +72 -0
- package/skills/box-oscillation/scripts/gather.py +15 -0
- package/skills/bull-trend/SKILL.md +60 -0
- package/skills/bull-trend/scripts/gather.py +15 -0
- package/skills/chan-theory/SKILL.md +71 -0
- package/skills/chan-theory/scripts/gather.py +15 -0
- package/skills/dragon-head/SKILL.md +69 -0
- package/skills/dragon-head/scripts/gather.py +15 -0
- package/skills/emotion-cycle/SKILL.md +65 -0
- package/skills/emotion-cycle/scripts/gather.py +15 -0
- package/skills/event-driven/SKILL.md +73 -0
- package/skills/event-driven/scripts/gather.py +15 -0
- package/skills/expectation-repricing/SKILL.md +72 -0
- package/skills/expectation-repricing/scripts/gather.py +15 -0
- package/skills/growth-quality/SKILL.md +74 -0
- package/skills/growth-quality/scripts/gather.py +15 -0
- package/skills/hot-theme/SKILL.md +74 -0
- package/skills/hot-theme/scripts/gather.py +15 -0
- package/skills/ma-crossover/SKILL.md +63 -0
- package/skills/ma-crossover/scripts/gather.py +15 -0
- package/skills/market-review/SKILL.md +70 -0
- package/skills/market-review/scripts/gather.py +16 -0
- package/skills/one-yang-three-yin/SKILL.md +74 -0
- package/skills/one-yang-three-yin/scripts/gather.py +15 -0
- package/skills/shrink-pullback/SKILL.md +59 -0
- package/skills/shrink-pullback/scripts/gather.py +15 -0
- package/skills/stock-analysis/SKILL.md +134 -0
- package/skills/stock-analysis/scripts/gather.py +15 -0
- package/skills/stock-screener/SKILL.md +68 -0
- package/skills/stock-screener/scripts/gather.py +15 -0
- package/skills/strategy-backtest/SKILL.md +129 -0
- package/skills/strategy-backtest/scripts/gather.py +16 -0
- package/skills/volume-breakout/SKILL.md +58 -0
- package/skills/volume-breakout/scripts/gather.py +15 -0
- package/skills/wave-theory/SKILL.md +67 -0
- package/skills/wave-theory/scripts/gather.py +15 -0
- package/skills/wisburg-research/SKILL.md +119 -0
- package/strategies/examples/bottom_volume.yaml +47 -0
- package/strategies/examples/box_oscillation.yaml +41 -0
- package/strategies/examples/bull_trend.yaml +42 -0
- package/strategies/examples/dragon_head.yaml +45 -0
- package/strategies/examples/emotion_cycle.yaml +43 -0
- package/strategies/examples/ma_crossover.yaml +34 -0
- package/strategies/examples/rsi_oversold.yaml +35 -0
- package/strategies/examples/shrink_pullback.yaml +45 -0
- package/strategies/examples/volume_breakout.yaml +42 -0
- package/tools/__init__.py +0 -0
- package/tools/anomaly_detect.py +570 -0
- package/tools/backtest.py +643 -0
- package/tools/gather.py +152 -0
- package/tools/market_regime.py +247 -0
- package/tools/market_review.py +150 -0
- package/tools/name_resolver.py +131 -0
- package/tools/pattern.py +509 -0
- package/tools/requirements.txt +13 -0
- package/tools/risk_screening.py +318 -0
- package/tools/screener.py +213 -0
- package/tools/search_intel.py +455 -0
- package/tools/stock_data.py +1649 -0
- package/tools/technical.py +636 -0
- package/tools/trading_calendar.py +198 -0
- package/tools/volume_analysis.py +172 -0
- package/tools/watchlist.py +61 -0
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Trading calendar — determine trading days for CN/HK/US markets."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime, timedelta
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _is_weekend(d: datetime) -> bool:
|
|
11
|
+
return d.weekday() >= 5
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _cn_holidays(year: int) -> set[str]:
|
|
15
|
+
try:
|
|
16
|
+
import akshare as ak
|
|
17
|
+
|
|
18
|
+
df = ak.tool_trade_date_hist_sina()
|
|
19
|
+
dates = set()
|
|
20
|
+
for _, row in df.iterrows():
|
|
21
|
+
val = row.iloc[0]
|
|
22
|
+
d = str(val)[:10]
|
|
23
|
+
if d.startswith(str(year)):
|
|
24
|
+
dates.add(d)
|
|
25
|
+
return dates
|
|
26
|
+
except Exception:
|
|
27
|
+
return set()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
|
|
31
|
+
import exchange_calendars as xcals
|
|
32
|
+
import pandas as pd
|
|
33
|
+
|
|
34
|
+
cal = xcals.get_calendar(exchange_code)
|
|
35
|
+
d = pd.Timestamp(date_str)
|
|
36
|
+
return cal.is_session(d)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _get_cn_trading_dates(year: int) -> set[str]:
|
|
40
|
+
return _cn_holidays(year)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_trading_day(market: str, date_str: str = None) -> dict:
|
|
44
|
+
if date_str:
|
|
45
|
+
d = datetime.strptime(date_str, "%Y-%m-%d")
|
|
46
|
+
else:
|
|
47
|
+
d = datetime.now()
|
|
48
|
+
date_str = d.strftime("%Y-%m-%d")
|
|
49
|
+
|
|
50
|
+
market = market.upper()
|
|
51
|
+
|
|
52
|
+
if _is_weekend(d):
|
|
53
|
+
return {"date": date_str, "market": market, "is_trading_day": False, "reason": "weekend"}
|
|
54
|
+
|
|
55
|
+
if market == "CN":
|
|
56
|
+
trading_dates = _get_cn_trading_dates(d.year)
|
|
57
|
+
if trading_dates:
|
|
58
|
+
is_td = date_str in trading_dates
|
|
59
|
+
return {
|
|
60
|
+
"date": date_str,
|
|
61
|
+
"market": market,
|
|
62
|
+
"is_trading_day": is_td,
|
|
63
|
+
"reason": "trading_day" if is_td else "holiday",
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
"date": date_str,
|
|
67
|
+
"market": market,
|
|
68
|
+
"is_trading_day": True,
|
|
69
|
+
"reason": "assumed_trading_day (calendar unavailable)",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
elif market == "HK":
|
|
73
|
+
try:
|
|
74
|
+
is_td = _is_exchange_trading_day("XHKG", date_str)
|
|
75
|
+
return {
|
|
76
|
+
"date": date_str,
|
|
77
|
+
"market": market,
|
|
78
|
+
"is_trading_day": is_td,
|
|
79
|
+
"reason": "trading_day" if is_td else "holiday",
|
|
80
|
+
"source": "exchange-calendars",
|
|
81
|
+
}
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
trading_dates = _get_cn_trading_dates(d.year)
|
|
85
|
+
if trading_dates:
|
|
86
|
+
is_td = date_str in trading_dates
|
|
87
|
+
return {
|
|
88
|
+
"date": date_str,
|
|
89
|
+
"market": market,
|
|
90
|
+
"is_trading_day": is_td,
|
|
91
|
+
"reason": "trading_day" if is_td else "holiday (approx, based on CN calendar)",
|
|
92
|
+
}
|
|
93
|
+
return {"date": date_str, "market": market, "is_trading_day": True, "reason": "assumed_trading_day"}
|
|
94
|
+
|
|
95
|
+
elif market == "US":
|
|
96
|
+
try:
|
|
97
|
+
is_td = _is_exchange_trading_day("XNYS", date_str)
|
|
98
|
+
return {
|
|
99
|
+
"date": date_str,
|
|
100
|
+
"market": market,
|
|
101
|
+
"is_trading_day": is_td,
|
|
102
|
+
"reason": "trading_day" if is_td else "holiday",
|
|
103
|
+
"source": "exchange-calendars",
|
|
104
|
+
}
|
|
105
|
+
except Exception:
|
|
106
|
+
pass
|
|
107
|
+
us_holidays = {
|
|
108
|
+
(1, 1),
|
|
109
|
+
(1, 20),
|
|
110
|
+
(2, 17),
|
|
111
|
+
(5, 26),
|
|
112
|
+
(6, 19),
|
|
113
|
+
(7, 4),
|
|
114
|
+
(9, 1),
|
|
115
|
+
(11, 27),
|
|
116
|
+
(12, 25),
|
|
117
|
+
}
|
|
118
|
+
if (d.month, d.day) in us_holidays:
|
|
119
|
+
return {"date": date_str, "market": market, "is_trading_day": False, "reason": "US_holiday"}
|
|
120
|
+
return {"date": date_str, "market": market, "is_trading_day": True, "reason": "trading_day"}
|
|
121
|
+
|
|
122
|
+
return {"date": date_str, "market": market, "error": f"Unknown market: {market}"}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def next_trading_days(market: str, count: int = 5, from_date: str = None) -> list[str]:
|
|
126
|
+
d = datetime.strptime(from_date, "%Y-%m-%d") if from_date else datetime.now()
|
|
127
|
+
|
|
128
|
+
result = []
|
|
129
|
+
max_search = count * 4
|
|
130
|
+
for _ in range(max_search):
|
|
131
|
+
d += timedelta(days=1)
|
|
132
|
+
info = is_trading_day(market, d.strftime("%Y-%m-%d"))
|
|
133
|
+
if info.get("is_trading_day"):
|
|
134
|
+
result.append(d.strftime("%Y-%m-%d"))
|
|
135
|
+
if len(result) >= count:
|
|
136
|
+
break
|
|
137
|
+
return result
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def prev_trading_days(market: str, count: int = 5, from_date: str = None) -> list[str]:
|
|
141
|
+
d = datetime.strptime(from_date, "%Y-%m-%d") if from_date else datetime.now()
|
|
142
|
+
|
|
143
|
+
result = []
|
|
144
|
+
max_search = count * 4
|
|
145
|
+
for _ in range(max_search):
|
|
146
|
+
d -= timedelta(days=1)
|
|
147
|
+
info = is_trading_day(market, d.strftime("%Y-%m-%d"))
|
|
148
|
+
if info.get("is_trading_day"):
|
|
149
|
+
result.append(d.strftime("%Y-%m-%d"))
|
|
150
|
+
if len(result) >= count:
|
|
151
|
+
break
|
|
152
|
+
return result
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def cmd_check(args):
|
|
156
|
+
return is_trading_day(args.market, args.date)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def cmd_next(args):
|
|
160
|
+
days = next_trading_days(args.market, args.count, args.date)
|
|
161
|
+
return {"market": args.market, "next_trading_days": days}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def cmd_prev(args):
|
|
165
|
+
days = prev_trading_days(args.market, args.count, args.date)
|
|
166
|
+
return {"market": args.market, "prev_trading_days": days}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def main():
|
|
170
|
+
parser = argparse.ArgumentParser(description="Trading calendar")
|
|
171
|
+
sub = parser.add_subparsers(dest="command")
|
|
172
|
+
|
|
173
|
+
p_check = sub.add_parser("check")
|
|
174
|
+
p_check.add_argument("market", choices=["CN", "HK", "US", "cn", "hk", "us"])
|
|
175
|
+
p_check.add_argument("--date", default=None, help="Date in YYYY-MM-DD format")
|
|
176
|
+
|
|
177
|
+
p_next = sub.add_parser("next")
|
|
178
|
+
p_next.add_argument("market", choices=["CN", "HK", "US", "cn", "hk", "us"])
|
|
179
|
+
p_next.add_argument("--count", type=int, default=5)
|
|
180
|
+
p_next.add_argument("--date", default=None)
|
|
181
|
+
|
|
182
|
+
p_prev = sub.add_parser("prev")
|
|
183
|
+
p_prev.add_argument("market", choices=["CN", "HK", "US", "cn", "hk", "us"])
|
|
184
|
+
p_prev.add_argument("--count", type=int, default=5)
|
|
185
|
+
p_prev.add_argument("--date", default=None)
|
|
186
|
+
|
|
187
|
+
args = parser.parse_args()
|
|
188
|
+
if not args.command:
|
|
189
|
+
parser.print_help()
|
|
190
|
+
sys.exit(1)
|
|
191
|
+
|
|
192
|
+
dispatch = {"check": cmd_check, "next": cmd_next, "prev": cmd_prev}
|
|
193
|
+
result = dispatch[args.command](args)
|
|
194
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
if __name__ == "__main__":
|
|
198
|
+
main()
|
|
@@ -0,0 +1,172 @@
|
|
|
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
|
+
)
|
|
21
|
+
return json.loads(r.stdout)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def to_dataframe(records: list) -> pd.DataFrame:
|
|
25
|
+
df = pd.DataFrame(records)
|
|
26
|
+
for c in ["open", "high", "low", "close", "volume"]:
|
|
27
|
+
if c in df.columns:
|
|
28
|
+
df[c] = pd.to_numeric(df[c], errors="coerce")
|
|
29
|
+
if "date" in df.columns:
|
|
30
|
+
df["date"] = pd.to_datetime(df["date"], errors="coerce")
|
|
31
|
+
df = df.sort_values("date").reset_index(drop=True)
|
|
32
|
+
return df
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def analyze_volume(symbol: str, period: str = "daily", count: int = 60) -> dict:
|
|
36
|
+
records = fetch_kline(symbol, period, count)
|
|
37
|
+
if isinstance(records, dict) and "error" in records:
|
|
38
|
+
return records
|
|
39
|
+
if not records:
|
|
40
|
+
return {"error": "No kline data returned"}
|
|
41
|
+
|
|
42
|
+
df = to_dataframe(records)
|
|
43
|
+
if len(df) < 10:
|
|
44
|
+
return {"error": f"Insufficient data: {len(df)} rows (need at least 10)"}
|
|
45
|
+
|
|
46
|
+
close = df["close"]
|
|
47
|
+
volume = df["volume"]
|
|
48
|
+
price_change = close.pct_change().dropna()
|
|
49
|
+
vol_change = volume.pct_change().dropna()
|
|
50
|
+
|
|
51
|
+
min_len = min(len(price_change), len(vol_change))
|
|
52
|
+
pc = price_change.tail(min_len).values
|
|
53
|
+
vc = vol_change.tail(min_len).values
|
|
54
|
+
mask = ~(np.isnan(pc) | np.isnan(vc))
|
|
55
|
+
corr = float(np.corrcoef(pc[mask], vc[mask])[0, 1]) if mask.sum() > 2 else None
|
|
56
|
+
|
|
57
|
+
up_days = df[close > close.shift(1)]
|
|
58
|
+
down_days = df[close < close.shift(1)]
|
|
59
|
+
avg_vol_up = float(up_days["volume"].mean()) if len(up_days) > 0 else 0
|
|
60
|
+
avg_vol_down = float(down_days["volume"].mean()) if len(down_days) > 0 else 0
|
|
61
|
+
up_down_ratio = round(avg_vol_up / avg_vol_down, 2) if avg_vol_down > 0 else None
|
|
62
|
+
|
|
63
|
+
vol_ma5 = volume.rolling(5).mean()
|
|
64
|
+
vol_ma20 = volume.rolling(20).mean()
|
|
65
|
+
cur_vol = float(volume.iloc[-1])
|
|
66
|
+
vol_ratio_5 = round(cur_vol / float(vol_ma5.iloc[-1]), 2) if float(vol_ma5.iloc[-1]) > 0 else None
|
|
67
|
+
vol_ratio_20 = (
|
|
68
|
+
round(cur_vol / float(vol_ma20.iloc[-1]), 2)
|
|
69
|
+
if len(vol_ma20.dropna()) > 0 and float(vol_ma20.iloc[-1]) > 0
|
|
70
|
+
else None
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
recent_vol = volume.tail(5).mean()
|
|
74
|
+
prior_vol = volume.tail(20).head(15).mean()
|
|
75
|
+
if prior_vol > 0:
|
|
76
|
+
vol_trend_ratio = float(recent_vol / prior_vol)
|
|
77
|
+
if vol_trend_ratio > 1.5:
|
|
78
|
+
vol_trend = "increasing"
|
|
79
|
+
elif vol_trend_ratio < 0.7:
|
|
80
|
+
vol_trend = "decreasing"
|
|
81
|
+
else:
|
|
82
|
+
vol_trend = "stable"
|
|
83
|
+
else:
|
|
84
|
+
vol_trend = "unknown"
|
|
85
|
+
vol_trend_ratio = None
|
|
86
|
+
|
|
87
|
+
patterns = []
|
|
88
|
+
latest_price_up = float(close.iloc[-1]) > float(close.iloc[-2]) if len(close) >= 2 else None
|
|
89
|
+
latest_heavy = vol_ratio_5 and vol_ratio_5 > 1.5
|
|
90
|
+
|
|
91
|
+
if latest_heavy and latest_price_up:
|
|
92
|
+
patterns.append(
|
|
93
|
+
{"type": "heavy_volume_rally", "signal": "bullish", "desc": "放量上涨 — 资金积极入场,短期看多"}
|
|
94
|
+
)
|
|
95
|
+
elif latest_heavy and latest_price_up is False:
|
|
96
|
+
patterns.append({"type": "heavy_volume_decline", "signal": "bearish", "desc": "放量下跌 — 资金出逃,短期看空"})
|
|
97
|
+
elif vol_ratio_5 and vol_ratio_5 < 0.6 and latest_price_up is False:
|
|
98
|
+
patterns.append(
|
|
99
|
+
{"type": "shrink_volume_decline", "signal": "neutral_to_bullish", "desc": "缩量回调 — 抛压减轻,可能蓄势"}
|
|
100
|
+
)
|
|
101
|
+
elif vol_ratio_5 and vol_ratio_5 < 0.6 and latest_price_up:
|
|
102
|
+
patterns.append(
|
|
103
|
+
{"type": "shrink_volume_rally", "signal": "weak_bullish", "desc": "缩量上涨 — 追高意愿不强,持续性存疑"}
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if up_down_ratio and up_down_ratio > 1.3:
|
|
107
|
+
patterns.append(
|
|
108
|
+
{
|
|
109
|
+
"type": "bullish_volume_bias",
|
|
110
|
+
"signal": "bullish",
|
|
111
|
+
"desc": f"上涨日均量远高于下跌日(比值{up_down_ratio}),资金偏多",
|
|
112
|
+
}
|
|
113
|
+
)
|
|
114
|
+
elif up_down_ratio and up_down_ratio < 0.7:
|
|
115
|
+
patterns.append(
|
|
116
|
+
{
|
|
117
|
+
"type": "bearish_volume_bias",
|
|
118
|
+
"signal": "bearish",
|
|
119
|
+
"desc": f"下跌日均量高于上涨日(比值{up_down_ratio}),资金偏空",
|
|
120
|
+
}
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
if corr is not None and corr > 0.5:
|
|
124
|
+
patterns.append(
|
|
125
|
+
{"type": "positive_vol_price_corr", "signal": "healthy", "desc": f"量价正相关({corr:.2f}),价量配合良好"}
|
|
126
|
+
)
|
|
127
|
+
elif corr is not None and corr < -0.3:
|
|
128
|
+
patterns.append(
|
|
129
|
+
{"type": "vol_price_divergence", "signal": "warning", "desc": f"量价背离({corr:.2f}),关注趋势转折"}
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
high_vol_mask = volume > vol_ma20 * 2
|
|
133
|
+
high_volume_days = int(high_vol_mask.tail(20).sum()) if len(vol_ma20.dropna()) > 0 else 0
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
"symbol": symbol,
|
|
137
|
+
"period": period,
|
|
138
|
+
"data_points": len(df),
|
|
139
|
+
"current_volume": int(cur_vol),
|
|
140
|
+
"vol_ratio_5d": vol_ratio_5,
|
|
141
|
+
"vol_ratio_20d": vol_ratio_20,
|
|
142
|
+
"avg_volume_up_days": round(avg_vol_up) if avg_vol_up else None,
|
|
143
|
+
"avg_volume_down_days": round(avg_vol_down) if avg_vol_down else None,
|
|
144
|
+
"up_down_volume_ratio": up_down_ratio,
|
|
145
|
+
"vol_price_correlation": round(corr, 3) if corr is not None else None,
|
|
146
|
+
"volume_trend": vol_trend,
|
|
147
|
+
"volume_trend_ratio": round(vol_trend_ratio, 2) if vol_trend_ratio else None,
|
|
148
|
+
"high_volume_days_20d": high_volume_days,
|
|
149
|
+
"patterns": patterns,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def main():
|
|
154
|
+
parser = argparse.ArgumentParser(description="Volume-price analysis")
|
|
155
|
+
sub = parser.add_subparsers(dest="command")
|
|
156
|
+
|
|
157
|
+
p = sub.add_parser("analyze")
|
|
158
|
+
p.add_argument("symbol")
|
|
159
|
+
p.add_argument("--period", default="daily", choices=["daily", "weekly", "monthly"])
|
|
160
|
+
p.add_argument("--count", type=int, default=60)
|
|
161
|
+
|
|
162
|
+
args = parser.parse_args()
|
|
163
|
+
if not args.command:
|
|
164
|
+
parser.print_help()
|
|
165
|
+
sys.exit(1)
|
|
166
|
+
|
|
167
|
+
result = analyze_volume(args.symbol, args.period, args.count)
|
|
168
|
+
print(json.dumps(result, ensure_ascii=False, default=str))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
if __name__ == "__main__":
|
|
172
|
+
main()
|
|
@@ -0,0 +1,61 @@
|
|
|
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
|
+
main()
|