stock-analysis-plugin 0.2.9 → 0.2.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.
@@ -8,15 +8,17 @@ so the host agent can decide what to do next (write daily briefing, dig deeper,
8
8
  import argparse
9
9
  import json
10
10
  import sys
11
- from concurrent.futures import ThreadPoolExecutor, as_completed
12
11
  from datetime import datetime, timezone
13
12
  from pathlib import Path
14
13
 
15
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
16
15
  from _subproc import run_tool as _run_json # noqa: E402
17
16
  from _subproc import scrub_secrets, utf8_stdio
17
+ from anomaly_detect import detect_anomalies # noqa: E402
18
+ from gather import Collection
19
+ from market_review import review_market
18
20
  from stock_data import detect_market # noqa: E402
19
- from watchlist import analyze_watchlist, has_analysis_data # noqa: E402
21
+ from watchlist import analyze_watchlist, has_analysis_data
20
22
 
21
23
 
22
24
  def _suggest_next_tools(market: str, trend: str, anomalies: list, risk_level: str) -> list:
@@ -38,7 +40,7 @@ def _suggest_next_tools(market: str, trend: str, anomalies: list, risk_level: st
38
40
  return [t for t in tools if not (t in seen or seen.add(t))]
39
41
 
40
42
 
41
- def _build_item(symbol: str, data: dict | None) -> dict:
43
+ def _build_item(symbol: str, data: dict | None, *, session=None) -> dict:
42
44
  if not has_analysis_data(data):
43
45
  return {"symbol": symbol, "error": "no data"}
44
46
 
@@ -46,7 +48,19 @@ def _build_item(symbol: str, data: dict | None) -> dict:
46
48
  risk = data.get("risk") or {}
47
49
 
48
50
  # anomalies — separate call (watchlist gather doesn't include them)
49
- anom_result = _run_json("anomaly_detect.py", ["detect", symbol], preserve_errors=True)
51
+ if "kline" in data and "quote" in data:
52
+ records = data["kline"]
53
+ try:
54
+ anom_result = detect_anomalies(
55
+ symbol,
56
+ records=records[-60:] if isinstance(records, list) else records,
57
+ quote=data["quote"],
58
+ run=session.json if session is not None else None,
59
+ )
60
+ except Exception as exc:
61
+ anom_result = {"error": f"Anomaly analysis failed ({type(exc).__name__})"}
62
+ else:
63
+ anom_result = _run_json("anomaly_detect.py", ["detect", symbol], preserve_errors=True)
50
64
  anomaly_ok = (
51
65
  isinstance(anom_result, dict) and "error" not in anom_result and isinstance(anom_result.get("anomalies"), list)
52
66
  )
@@ -88,51 +102,51 @@ def _build_item(symbol: str, data: dict | None) -> dict:
88
102
 
89
103
 
90
104
  def build_context(symbols: list[str], include_market_review: bool = False, workers: int = 3) -> dict:
91
- raw = analyze_watchlist(symbols, workers=workers)
92
- if "error" in raw:
93
- return raw
94
- results = raw.get("results", {})
95
-
96
- items = []
97
- # fetch anomalies in parallel to keep it responsive
98
- with ThreadPoolExecutor(max_workers=min(workers * 2, 6)) as pool:
99
- futures = {pool.submit(_build_item, sym, results.get(sym)): sym for sym in symbols}
100
- for fut in as_completed(futures):
101
- items.append(fut.result())
102
-
103
- # preserve caller order
104
- order = {s: i for i, s in enumerate(symbols)}
105
- items.sort(key=lambda x: order.get(x["symbol"], 999))
106
-
107
- output = {
108
- "meta": {
109
- "provider": "watchlist_context",
110
- "fetched_at": datetime.now(timezone.utc).isoformat(),
111
- "freshness": "realtime_or_latest_trade_day",
112
- "fallback_used": False,
113
- "warnings": [f"{i['symbol']}: {warning}" for i in items for warning in i.get("warnings", [])],
114
- },
115
- "summary": {
116
- "total": len(symbols),
117
- "success": sum(1 for i in items if "error" not in i and i.get("anomaly_status") == "ok"),
118
- "partial": sum(1 for i in items if "error" not in i and i.get("anomaly_status") == "unavailable"),
119
- "failed": sum(1 for i in items if "error" in i),
120
- "high_risk_count": sum(1 for i in items if i.get("risk_level") == "high"),
121
- "veto_count": sum(1 for i in items if i.get("veto_buy")),
122
- },
123
- "items": items,
124
- }
125
-
126
- if include_market_review:
127
- markets = sorted({i.get("market") for i in items if i.get("market")})
128
- review = {}
129
- for m in markets:
130
- r = _run_json("market_review.py", ["review", "--market", m])
131
- if r:
132
- review[m] = r
133
- output["market_review"] = review
134
-
135
- return output
105
+ items_by_symbol = {}
106
+ with Collection() as session:
107
+
108
+ def ready(symbol, data):
109
+ items_by_symbol[symbol] = _build_item(symbol, data, session=session)
110
+
111
+ raw = analyze_watchlist(symbols, workers=workers, session=session, on_result=ready)
112
+ if "error" in raw:
113
+ return raw
114
+ results = raw.get("results", {})
115
+ # Also supports pre-collected watchlists supplied by callers/tests.
116
+ for symbol in symbols:
117
+ if symbol not in items_by_symbol:
118
+ ready(symbol, results.get(symbol))
119
+ items = [items_by_symbol[symbol] for symbol in symbols]
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": [f"{i['symbol']}: {warning}" for i in items for warning in i.get("warnings", [])],
128
+ },
129
+ "summary": {
130
+ "total": len(symbols),
131
+ "success": sum(1 for i in items if "error" not in i and i.get("anomaly_status") == "ok"),
132
+ "partial": sum(1 for i in items if "error" not in i and i.get("anomaly_status") == "unavailable"),
133
+ "failed": sum(1 for i in items if "error" in i),
134
+ "high_risk_count": sum(1 for i in items if i.get("risk_level") == "high"),
135
+ "veto_count": sum(1 for i in items if i.get("veto_buy")),
136
+ },
137
+ "items": items,
138
+ }
139
+
140
+ if include_market_review:
141
+ markets = sorted({i.get("market") for i in items if i.get("market")})
142
+ review = {}
143
+ for m in markets:
144
+ r = review_market(m, run=session.json)
145
+ if r and "error" not in r:
146
+ review[m] = r
147
+ output["market_review"] = review
148
+
149
+ return output
136
150
 
137
151
 
138
152
  def main():