@weaxs/openclaw-stock-analysis 0.1.3 → 0.1.5

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.
@@ -0,0 +1,180 @@
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, 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
+ main()