@weaxs/openclaw-stock-analysis 0.1.3 → 0.1.6

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,111 @@
1
+ #!/usr/bin/env python3
2
+ """Report renderer — turn structured stock/market JSON into markdown via existing j2 templates.
3
+
4
+ No side effects: does not save, push, or upload. Just returns markdown.
5
+ """
6
+
7
+ import argparse
8
+ import json
9
+ import sys
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ try:
14
+ from jinja2 import Environment, FileSystemLoader, select_autoescape
15
+ except ImportError:
16
+ print(json.dumps({"error": "jinja2 not installed. pip install jinja2"}, ensure_ascii=False))
17
+ sys.exit(1)
18
+
19
+
20
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
21
+ TEMPLATES_ROOT = PROJECT_ROOT / "templates"
22
+
23
+ TEMPLATE_MAP = {
24
+ "stock": {
25
+ "brief": "stock_analysis/brief.md.j2",
26
+ "full": "stock_analysis/full.md.j2",
27
+ },
28
+ "market": {
29
+ "full": "market_review/full.md.j2",
30
+ },
31
+ }
32
+
33
+
34
+ def _env() -> Environment:
35
+ return Environment(
36
+ loader=FileSystemLoader(str(TEMPLATES_ROOT)),
37
+ autoescape=select_autoescape(disabled_extensions=("j2", "md")),
38
+ trim_blocks=True,
39
+ lstrip_blocks=True,
40
+ )
41
+
42
+
43
+ def render(kind: str, template: str, report: dict) -> dict:
44
+ if kind not in TEMPLATE_MAP:
45
+ return {"error": f"unknown kind: {kind}. valid: {list(TEMPLATE_MAP)}"}
46
+ if template not in TEMPLATE_MAP[kind]:
47
+ return {"error": f"unknown template '{template}' for {kind}. valid: {list(TEMPLATE_MAP[kind])}"}
48
+
49
+ tpl_path = TEMPLATE_MAP[kind][template]
50
+ try:
51
+ tpl = _env().get_template(tpl_path)
52
+ except Exception as e:
53
+ return {"error": f"failed to load template {tpl_path}: {e}"}
54
+
55
+ try:
56
+ content = tpl.render(**report)
57
+ except Exception as e:
58
+ return {"error": f"render failed: {e}", "template": tpl_path}
59
+
60
+ return {
61
+ "meta": {
62
+ "provider": "renderer",
63
+ "template": tpl_path,
64
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
65
+ "freshness": "instant",
66
+ "fallback_used": False,
67
+ "warnings": [],
68
+ },
69
+ "format": "markdown",
70
+ "content": content,
71
+ }
72
+
73
+
74
+ def _load_input(path: str | None, b64: str | None) -> dict:
75
+ if b64:
76
+ import base64
77
+
78
+ return json.loads(base64.b64decode(b64).decode("utf-8"))
79
+ if path and path != "-":
80
+ with open(path, encoding="utf-8") as f:
81
+ return json.load(f)
82
+ return json.load(sys.stdin)
83
+
84
+
85
+ def main():
86
+ parser = argparse.ArgumentParser(description="Render stock/market report from structured JSON")
87
+ sub = parser.add_subparsers(dest="command")
88
+
89
+ p = sub.add_parser("stock", help="Render a stock analysis report")
90
+ p.add_argument("--template", default="full", choices=["brief", "full"])
91
+ p.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
92
+ p.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
93
+
94
+ p2 = sub.add_parser("market", help="Render a market review report")
95
+ p2.add_argument("--template", default="full", choices=["full"])
96
+ p2.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
97
+ p2.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
98
+
99
+ args = parser.parse_args()
100
+ if not args.command:
101
+ parser.print_help()
102
+ sys.exit(1)
103
+
104
+ report = _load_input(args.input, getattr(args, "input_b64", None))
105
+ result = render(args.command, args.template, report)
106
+ json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
107
+ print()
108
+
109
+
110
+ if __name__ == "__main__":
111
+ main()
@@ -11,3 +11,5 @@ efinance>=0.5.0
11
11
  baostock>=0.8.8
12
12
  pytdx>=1.72
13
13
  longport>=1.0.0
14
+ finnhub-python>=2.4.0
15
+ jinja2>=3.1.0
@@ -146,6 +146,46 @@ def _bocha_search(query: str, max_results: int = 5) -> list[dict]:
146
146
  return []
147
147
 
148
148
 
149
+ def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
150
+ """SearXNG self-hosted metasearch — no API key, quota-free fallback.
151
+
152
+ Set SEARXNG_BASE_URLS to a comma-separated list of instance URLs,
153
+ e.g. "http://127.0.0.1:8080,https://searx.example.com".
154
+ """
155
+ base_urls = [u.strip().rstrip("/") for u in os.environ.get("SEARXNG_BASE_URLS", "").split(",") if u.strip()]
156
+ if not base_urls:
157
+ return []
158
+ try:
159
+ import requests
160
+ except ImportError:
161
+ return []
162
+ for base in base_urls:
163
+ try:
164
+ resp = requests.get(
165
+ f"{base}/search",
166
+ params={"q": query, "format": "json"},
167
+ headers={"Accept": "application/json"},
168
+ timeout=15,
169
+ )
170
+ if not resp.ok:
171
+ continue
172
+ data = resp.json()
173
+ results = [
174
+ {
175
+ "title": r.get("title", ""),
176
+ "url": r.get("url", ""),
177
+ "snippet": (r.get("content") or "")[:200],
178
+ "source": "searxng",
179
+ }
180
+ for r in data.get("results", [])
181
+ ]
182
+ if results:
183
+ return results
184
+ except Exception:
185
+ continue
186
+ return []
187
+
188
+
149
189
  def search_news(query: str, max_results: int = 10) -> dict:
150
190
  results = []
151
191
  engines_tried = []
@@ -156,6 +196,7 @@ def search_news(query: str, max_results: int = 10) -> dict:
156
196
  ("brave", _brave_search),
157
197
  ("bocha", _bocha_search),
158
198
  ("serpapi", _serpapi_search),
199
+ ("searxng", _searxng_search),
159
200
  ]:
160
201
  engines_tried.append(name)
161
202
  items = fn(query, max_results)
@@ -170,7 +211,10 @@ def search_news(query: str, max_results: int = 10) -> dict:
170
211
  "query": query,
171
212
  "results": [],
172
213
  "engines_tried": engines_tried,
173
- "note": "No search engines configured. Set TAVILY_API_KEY, BRAVE_API_KEY, or SERPAPI_KEY in environment.",
214
+ "note": (
215
+ "No search engines configured. Set TAVILY_API_KEY, BRAVE_API_KEY, BOCHA_API_KEY, "
216
+ "SERPAPI_KEY, or SEARXNG_BASE_URLS in environment."
217
+ ),
174
218
  }
175
219
 
176
220
  seen_urls = set()
@@ -11,8 +11,15 @@ from datetime import datetime, timedelta
11
11
 
12
12
 
13
13
  def detect_market(symbol: str) -> str:
14
- if symbol.upper().endswith(".HK"):
14
+ s = symbol.upper()
15
+ if s.endswith(".HK"):
15
16
  return "HK"
17
+ if s.endswith(".T"):
18
+ return "JP"
19
+ if s.endswith((".KS", ".KQ")):
20
+ return "KR"
21
+ if s.endswith((".TW", ".TWO")):
22
+ return "TW"
16
23
  if re.match(r"^\d{6}$", symbol):
17
24
  return "A"
18
25
  return "US"
@@ -77,10 +84,10 @@ def _failover(sources: list, label: str = ""):
77
84
  return None
78
85
 
79
86
 
80
- def _akshare_retry(fn, *args, retries=2, delay=1):
87
+ def _akshare_retry(fn, *args, retries=2, delay=1, **kwargs):
81
88
  for attempt in range(retries + 1):
82
89
  try:
83
- return fn(*args)
90
+ return fn(*args, **kwargs)
84
91
  except Exception:
85
92
  if attempt == retries:
86
93
  raise
@@ -128,13 +135,18 @@ def _kline_efinance(symbol: str, period: str, count: int) -> list:
128
135
 
129
136
 
130
137
  def _kline_baostock(symbol: str, period: str, count: int) -> list:
138
+ import io
139
+
131
140
  import baostock as bs
132
141
  import pandas as pd
133
142
 
134
143
  freq_map = {"daily": "d", "weekly": "w", "monthly": "m"}
135
144
  end = datetime.now()
136
145
  start = end - timedelta(days=count * 7 if period == "weekly" else count * 31 if period == "monthly" else count * 2)
137
- bs.login()
146
+ # baostock login/logout print status lines to stdout — silence them so the
147
+ # tool's JSON output on stdout stays clean for the calling host.
148
+ with contextlib.redirect_stdout(io.StringIO()):
149
+ bs.login()
138
150
  try:
139
151
  rs = bs.query_history_k_data_plus(
140
152
  _to_baostock_code(symbol),
@@ -149,7 +161,8 @@ def _kline_baostock(symbol: str, period: str, count: int) -> list:
149
161
  rows.append(rs.get_row_data())
150
162
  df = pd.DataFrame(rows, columns=rs.fields)
151
163
  finally:
152
- bs.logout()
164
+ with contextlib.redirect_stdout(io.StringIO()):
165
+ bs.logout()
153
166
  if df.empty:
154
167
  raise ValueError("baostock returned empty data")
155
168
  col_map = {"amount": "turnover", "pctChg": "change_pct"}
@@ -241,8 +254,10 @@ def _kline_akshare(symbol: str, period: str, count: int) -> list:
241
254
  end = datetime.now()
242
255
  start = end - timedelta(days=count * 7 if period == "weekly" else count * 31 if period == "monthly" else count * 2)
243
256
 
257
+ # ETFs (51/52/56/58/15/16/18xxxx) are not covered by stock_zh_a_hist
258
+ hist_fn = ak.fund_etf_hist_em if normalize_stock_code(symbol)["is_etf"] else ak.stock_zh_a_hist
244
259
  df = _akshare_retry(
245
- ak.stock_zh_a_hist,
260
+ hist_fn,
246
261
  symbol=symbol,
247
262
  period=period_map.get(period, "daily"),
248
263
  start_date=start.strftime("%Y%m%d"),
@@ -657,16 +672,30 @@ def _quote_alphavantage(symbol: str) -> dict:
657
672
  )
658
673
 
659
674
 
675
+ def _yf_failover(symbol: str, yfinance, finnhub, longbridge, alphavantage, label: str):
676
+ """Shared HK/US/JP/KR/TW failover chain: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only).
677
+
678
+ Each provider is a zero-arg callable; callers bind their own symbol/period/count.
679
+ """
680
+ market = detect_market(symbol)
681
+ sources = [("yfinance", yfinance)]
682
+ if market in ("HK", "US"):
683
+ sources += [("finnhub", finnhub), ("longbridge", longbridge)]
684
+ if market == "US":
685
+ sources.append(("alphavantage", alphavantage))
686
+ return _failover(sources, label=label)
687
+
688
+
660
689
  def kline_yf(symbol: str, period: str, count: int) -> list:
661
- """HK/US kline with failover: yfinance → finnhub → longbridge → alphavantage (US only)."""
662
- sources = [
663
- ("yfinance", lambda: _kline_yfinance(symbol, period, count)),
664
- ("finnhub", lambda: _kline_finnhub(symbol, period, count)),
665
- ("longbridge", lambda: _kline_longbridge(symbol, period, count)),
666
- ]
667
- if detect_market(symbol) == "US":
668
- sources.append(("alphavantage", lambda: _kline_alphavantage(symbol, period, count)))
669
- return _failover(sources, label=f"kline:{symbol}")
690
+ """HK/US/JP/KR/TW kline. Failover: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only)."""
691
+ return _yf_failover(
692
+ symbol,
693
+ lambda: _kline_yfinance(symbol, period, count),
694
+ lambda: _kline_finnhub(symbol, period, count),
695
+ lambda: _kline_longbridge(symbol, period, count),
696
+ lambda: _kline_alphavantage(symbol, period, count),
697
+ label=f"kline:{symbol}",
698
+ )
670
699
 
671
700
 
672
701
  def cmd_kline(args):
@@ -685,15 +714,46 @@ def cmd_kline(args):
685
714
 
686
715
 
687
716
  def quote_a(symbol: str) -> dict:
688
- """A-share quote with failover: akshare → tushare → efinance → pytdx."""
689
- return _failover(
690
- [
691
- ("akshare", lambda: _quote_akshare(symbol)),
692
- ("tushare", lambda: _quote_tushare(symbol)),
693
- ("efinance", lambda: _quote_efinance(symbol)),
694
- ("pytdx", lambda: _quote_pytdx(symbol)),
695
- ],
696
- label=f"quote_a:{symbol}",
717
+ """A-share quote with failover: akshare → tushare → efinance → pytdx. ETFs try fund spot first."""
718
+ sources = []
719
+ if normalize_stock_code(symbol)["is_etf"]:
720
+ sources.append(("akshare_etf", lambda: _quote_akshare_etf(symbol)))
721
+ sources += [
722
+ ("akshare", lambda: _quote_akshare(symbol)),
723
+ ("tushare", lambda: _quote_tushare(symbol)),
724
+ ("efinance", lambda: _quote_efinance(symbol)),
725
+ ("pytdx", lambda: _quote_pytdx(symbol)),
726
+ ]
727
+ return _failover(sources, label=f"quote_a:{symbol}")
728
+
729
+
730
+ def _quote_akshare_etf(symbol: str) -> dict:
731
+ """A-share ETF realtime quote via akshare fund_etf_spot_em."""
732
+ import akshare as ak
733
+
734
+ df = _akshare_retry(ak.fund_etf_spot_em)
735
+ row = df[df["代码"] == symbol]
736
+ if row.empty:
737
+ raise ValueError(f"ETF {symbol} not found in akshare fund spot")
738
+ r = row.iloc[0]
739
+ return _clean_row(
740
+ {
741
+ "symbol": symbol,
742
+ "name": r.get("名称"),
743
+ "price": r.get("最新价"),
744
+ "change": r.get("涨跌额"),
745
+ "change_pct": r.get("涨跌幅"),
746
+ "volume": r.get("成交量"),
747
+ "turnover": r.get("成交额"),
748
+ "high": r.get("最高价"),
749
+ "low": r.get("最低价"),
750
+ "open": r.get("开盘价"),
751
+ "prev_close": r.get("昨收"),
752
+ "market_cap": r.get("总市值"),
753
+ "turnover_rate": r.get("换手率"),
754
+ "volume_ratio": r.get("量比"),
755
+ "is_etf": True,
756
+ }
697
757
  )
698
758
 
699
759
 
@@ -782,15 +842,15 @@ def _quote_finnhub(symbol: str) -> dict:
782
842
 
783
843
 
784
844
  def quote_yf(symbol: str) -> dict:
785
- """HK/US quote with failover: yfinance → finnhub → longbridge → alphavantage (US only)."""
786
- sources = [
787
- ("yfinance", lambda: _quote_yfinance(symbol)),
788
- ("finnhub", lambda: _quote_finnhub(symbol)),
789
- ("longbridge", lambda: _quote_longbridge(symbol)),
790
- ]
791
- if detect_market(symbol) == "US":
792
- sources.append(("alphavantage", lambda: _quote_alphavantage(symbol)))
793
- return _failover(sources, label=f"quote:{symbol}")
845
+ """HK/US/JP/KR/TW quote. Failover: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only)."""
846
+ return _yf_failover(
847
+ symbol,
848
+ lambda: _quote_yfinance(symbol),
849
+ lambda: _quote_finnhub(symbol),
850
+ lambda: _quote_longbridge(symbol),
851
+ lambda: _quote_alphavantage(symbol),
852
+ label=f"quote:{symbol}",
853
+ )
794
854
 
795
855
 
796
856
  def cmd_quote(args):
@@ -1162,6 +1222,15 @@ def cmd_market_snapshot(args):
1162
1222
 
1163
1223
  # --------------- market_indices ---------------
1164
1224
 
1225
+ # region -> {index symbol -> display name}; CN is handled separately via akshare.
1226
+ _REGION_INDEX_SYMBOLS = {
1227
+ "hk": {"^HSI": "恒生指数", "^HSCE": "恒生国企指数", "^HSTECH": "恒生科技指数"},
1228
+ "us": {"^DJI": "道琼斯", "^IXIC": "纳斯达克", "^GSPC": "标普500", "^RUT": "罗素2000"},
1229
+ "jp": {"^N225": "日经225", "^TOPX": "东证指数"},
1230
+ "kr": {"^KS11": "韩国KOSPI", "^KQ11": "韩国KOSDAQ"},
1231
+ "tw": {"^TWII": "台湾加权指数"},
1232
+ }
1233
+
1165
1234
 
1166
1235
  def cmd_market_indices(args):
1167
1236
  region = args.region.lower()
@@ -1206,13 +1275,10 @@ def cmd_market_indices(args):
1206
1275
  )
1207
1276
  )
1208
1277
  return results
1209
- elif region in ("hk", "us"):
1278
+ elif region in _REGION_INDEX_SYMBOLS:
1210
1279
  import yfinance as yf
1211
1280
 
1212
- if region == "hk":
1213
- symbols = {"^HSI": "恒生指数", "^HSCE": "恒生国企指数", "^HSTECH": "恒生科技指数"}
1214
- else:
1215
- symbols = {"^DJI": "道琼斯", "^IXIC": "纳斯达克", "^GSPC": "标普500", "^RUT": "罗素2000"}
1281
+ symbols = _REGION_INDEX_SYMBOLS[region]
1216
1282
  results = []
1217
1283
  for sym, name in symbols.items():
1218
1284
  try:
@@ -1604,7 +1670,7 @@ def main():
1604
1670
  p_snap.add_argument("--market", default="A", choices=["A", "HK", "US"])
1605
1671
 
1606
1672
  p_idx = sub.add_parser("market_indices")
1607
- p_idx.add_argument("--region", default="cn", choices=["cn", "hk", "us"])
1673
+ p_idx.add_argument("--region", default="cn", choices=["cn", "hk", "us", "jp", "kr", "tw"])
1608
1674
 
1609
1675
  p_sec = sub.add_parser("sector_rankings")
1610
1676
  p_sec.add_argument("--top", type=int, default=10)
@@ -1,11 +1,14 @@
1
1
  #!/usr/bin/env python3
2
- """Trading calendar — determine trading days for CN/HK/US markets."""
2
+ """Trading calendar — determine trading days for CN/HK/US/JP/KR/TW markets."""
3
3
 
4
4
  import argparse
5
5
  import json
6
6
  import sys
7
7
  from datetime import datetime, timedelta
8
8
 
9
+ # Supported markets. argparse uses type=str.upper so lowercase input is accepted too.
10
+ MARKETS = ["CN", "HK", "US", "JP", "KR", "TW"]
11
+
9
12
 
10
13
  def _is_weekend(d: datetime) -> bool:
11
14
  return d.weekday() >= 5
@@ -119,6 +122,26 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
119
122
  return {"date": date_str, "market": market, "is_trading_day": False, "reason": "US_holiday"}
120
123
  return {"date": date_str, "market": market, "is_trading_day": True, "reason": "trading_day"}
121
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
+
122
145
  return {"date": date_str, "market": market, "error": f"Unknown market: {market}"}
123
146
 
124
147
 
@@ -171,16 +194,16 @@ def main():
171
194
  sub = parser.add_subparsers(dest="command")
172
195
 
173
196
  p_check = sub.add_parser("check")
174
- p_check.add_argument("market", choices=["CN", "HK", "US", "cn", "hk", "us"])
197
+ p_check.add_argument("market", type=str.upper, choices=MARKETS)
175
198
  p_check.add_argument("--date", default=None, help="Date in YYYY-MM-DD format")
176
199
 
177
200
  p_next = sub.add_parser("next")
178
- p_next.add_argument("market", choices=["CN", "HK", "US", "cn", "hk", "us"])
201
+ p_next.add_argument("market", type=str.upper, choices=MARKETS)
179
202
  p_next.add_argument("--count", type=int, default=5)
180
203
  p_next.add_argument("--date", default=None)
181
204
 
182
205
  p_prev = sub.add_parser("prev")
183
- p_prev.add_argument("market", choices=["CN", "HK", "US", "cn", "hk", "us"])
206
+ p_prev.add_argument("market", type=str.upper, choices=MARKETS)
184
207
  p_prev.add_argument("--count", type=int, default=5)
185
208
  p_prev.add_argument("--date", default=None)
186
209
 
@@ -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()