openclaw-stock-analysis 0.2.2 → 0.2.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -2
  3. package/dist/index.js +170 -23
  4. package/index.ts +184 -26
  5. package/openclaw.plugin.json +10 -1
  6. package/package.json +1 -1
  7. package/scripts/ci-resolve-llm-host.mjs +29 -0
  8. package/scripts/setup-python.mjs +7 -9
  9. package/skills/event-driven/SKILL.md +6 -0
  10. package/skills/growth-quality/SKILL.md +6 -0
  11. package/skills/hot-theme/SKILL.md +3 -2
  12. package/skills/stock-analysis/SKILL.md +22 -0
  13. package/skills/stock-screener/SKILL.md +19 -1
  14. package/skills/strategy-backtest/SKILL.md +11 -5
  15. package/strategies/examples/bottom_volume.yaml +5 -0
  16. package/strategies/examples/box_oscillation.yaml +5 -0
  17. package/strategies/examples/bull_trend.yaml +11 -3
  18. package/strategies/examples/dragon_head.yaml +4 -2
  19. package/strategies/examples/emotion_cycle.yaml +5 -0
  20. package/strategies/examples/ma_crossover.yaml +10 -3
  21. package/strategies/examples/rsi_oversold.yaml +5 -0
  22. package/strategies/examples/shrink_pullback.yaml +7 -1
  23. package/strategies/examples/volume_breakout.yaml +7 -1
  24. package/tools/_cache.py +61 -0
  25. package/tools/_subproc.py +49 -0
  26. package/tools/alert_rules.py +19 -9
  27. package/tools/anomaly_detect.py +24 -35
  28. package/tools/backtest.py +180 -100
  29. package/tools/capabilities.py +13 -5
  30. package/tools/diagnostics.py +12 -6
  31. package/tools/gather.py +13 -9
  32. package/tools/import_parser.py +2 -5
  33. package/tools/market_regime.py +27 -35
  34. package/tools/market_review.py +56 -9
  35. package/tools/name_resolver.py +2 -5
  36. package/tools/pattern.py +2 -5
  37. package/tools/position_context.py +2 -5
  38. package/tools/report_renderer.py +10 -6
  39. package/tools/requirements.txt +2 -1
  40. package/tools/risk_screening.py +29 -23
  41. package/tools/screener.py +80 -18
  42. package/tools/search_intel.py +5 -13
  43. package/tools/signal_tracker.py +2 -6
  44. package/tools/stock_data.py +520 -169
  45. package/tools/technical.py +136 -40
  46. package/tools/trading_calendar.py +78 -18
  47. package/tools/value_data.py +1368 -0
  48. package/tools/volume_analysis.py +2 -5
  49. package/tools/watchlist.py +2 -5
  50. package/tools/watchlist_context.py +2 -5
@@ -11,12 +11,22 @@ from datetime import datetime, timezone
11
11
  from pathlib import Path
12
12
 
13
13
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+ from _subproc import utf8_stdio
14
15
  from stock_data import detect_market
15
16
 
16
17
  ALL_MARKETS = ["A", "HK", "US", "JP", "KR", "TW"]
17
18
 
18
19
  # tool_name -> {markets: [supported markets], reason: str for unsupported}
19
20
  TOOL_MATRIX = {
21
+ "get_valuation_history": {"markets": ["A", "HK"], "reason": "A/HK historical valuation providers only"},
22
+ "get_index_valuation": {"markets": ["A"], "reason": "Chinese index valuation only"},
23
+ "get_earnings_calendar": {
24
+ "markets": ["A", "HK"],
25
+ "reason": "A-share disclosed calendar / HK single-symbol provider schedule",
26
+ },
27
+ "get_shareholder_structure": {"markets": ["A", "HK"], "reason": "A-share shareholder reports / HK southbound only"},
28
+ "get_etf_details": {"markets": ["A"], "reason": "A-share ETF portfolio/NAV/size only"},
29
+ "get_dividends": {"markets": ["A", "HK"], "reason": "A/HK dividend history and report-year ranking"},
20
30
  "get_kline": {"markets": ALL_MARKETS, "reason": None},
21
31
  "get_quote": {"markets": ALL_MARKETS, "reason": None},
22
32
  "get_news": {"markets": ALL_MARKETS, "reason": None},
@@ -42,6 +52,8 @@ TOOL_MATRIX = {
42
52
  "get_limit_up_pool": {"markets": ["A"], "reason": "A-share only"},
43
53
  "get_dragon_tiger": {"markets": ["A"], "reason": "A-share only"},
44
54
  "get_hot_stocks": {"markets": ["A"], "reason": "A-share only"},
55
+ "get_margin_trading": {"markets": ["A"], "reason": "A-share only"},
56
+ "get_northbound_flow": {"markets": ["A"], "reason": "A-share only"},
45
57
  "get_social_sentiment": {
46
58
  "markets": ["A", "HK", "US"],
47
59
  "reason": "A-share uses Eastmoney/Xueqiu; HK/US require SENTIMENT_API_KEY",
@@ -109,9 +121,5 @@ def main():
109
121
 
110
122
 
111
123
  if __name__ == "__main__":
112
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
113
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
114
- for _s in (sys.stdout, sys.stderr):
115
- if hasattr(_s, "reconfigure"):
116
- _s.reconfigure(encoding="utf-8")
124
+ utf8_stdio()
117
125
  main()
@@ -17,12 +17,22 @@ from datetime import datetime, timezone
17
17
  from pathlib import Path
18
18
 
19
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
20
+ from _subproc import utf8_stdio # noqa: E402
20
21
  from capabilities import ALL_MARKETS # noqa: E402
21
22
 
22
23
  # provider -> (import_name, required_env_vars, markets, note)
23
24
  PROVIDERS = {
24
25
  "akshare": ("akshare", [], ["A"], None),
25
- "tushare": ("tushare", ["TUSHARE_TOKEN"], ["A"], None),
26
+ # tushare is consumed as a pure-HTTP API (requests.post to api.tushare.pro,
27
+ # see stock_data._kline_tushare) — the tushare package is not in requirements,
28
+ # so availability is the token, not a package probe
29
+ "tushare": ("requests", ["TUSHARE_TOKEN"], ["A"], "pure-HTTP API (api.tushare.pro); no tushare package needed"),
30
+ "lixinger": (
31
+ "requests",
32
+ ["LIXINGER_TOKEN"],
33
+ ["A"],
34
+ "optional index PE/PB history; subscription permissions not probed",
35
+ ),
26
36
  "efinance": ("efinance", [], ["A"], None),
27
37
  "tencent": ("requests", [], ["A"], "qt.gtimg.cn quote/kline, no auth (issue #25)"),
28
38
  "sina": (
@@ -150,9 +160,5 @@ def main():
150
160
 
151
161
 
152
162
  if __name__ == "__main__":
153
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
154
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
155
- for _s in (sys.stdout, sys.stderr):
156
- if hasattr(_s, "reconfigure"):
157
- _s.reconfigure(encoding="utf-8")
163
+ utf8_stdio()
158
164
  main()
package/tools/gather.py CHANGED
@@ -8,7 +8,8 @@ from concurrent.futures import ThreadPoolExecutor
8
8
  from pathlib import Path
9
9
 
10
10
  sys.path.insert(0, str(Path(__file__).resolve().parent))
11
- from _subproc import run_tool # noqa: E402
11
+ from _subproc import json_safe, run_tool, utf8_stdio # noqa: E402
12
+ from stock_data import detect_market # noqa: E402
12
13
 
13
14
 
14
15
  # gather fans out the heavier CLIs, so the default timeout stays 60s; raw stdout
@@ -17,6 +18,11 @@ def _run(script, args, timeout=60):
17
18
  return run_tool(script, args, timeout=timeout, parse_json=False)
18
19
 
19
20
 
21
+ def _news_query(symbol: str) -> str:
22
+ # CN sources rank poorly for an English query; US/HK sources for a Chinese one.
23
+ return f"{symbol} 最新消息" if detect_market(symbol) == "A" else f"{symbol} stock news"
24
+
25
+
20
26
  def _parse_json(raw: str | None):
21
27
  if raw is None:
22
28
  return None
@@ -39,7 +45,9 @@ def gather_analysis(symbol: str) -> dict:
39
45
  "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "120"]),
40
46
  "financials": ("stock_data.py", ["financials", symbol]),
41
47
  "capital_flow": ("stock_data.py", ["capital_flow", symbol]),
42
- "news": ("search_intel.py", ["search", f"{symbol} stock news"]),
48
+ "chip_distribution": ("stock_data.py", ["chip_distribution", symbol]),
49
+ "news": ("search_intel.py", ["search", _news_query(symbol)]),
50
+ "social_sentiment": ("search_intel.py", ["sentiment", symbol]),
43
51
  "risk": ("risk_screening.py", ["screen", symbol]),
44
52
  "regime": ("market_regime.py", ["detect"]),
45
53
  }
@@ -70,7 +78,7 @@ def gather_fundamental(symbol: str) -> dict:
70
78
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "60"]),
71
79
  "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]),
72
80
  "financials": ("stock_data.py", ["financials", symbol]),
73
- "news": ("search_intel.py", ["search", f"{symbol} stock news"]),
81
+ "news": ("search_intel.py", ["search", _news_query(symbol)]),
74
82
  "stock_info": ("stock_data.py", ["stock_info", symbol]),
75
83
  "sector_rankings": ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]),
76
84
  }
@@ -111,14 +119,10 @@ def main():
111
119
  parser.print_help()
112
120
  sys.exit(1)
113
121
 
114
- json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
122
+ json.dump(json_safe(result), sys.stdout, ensure_ascii=False, indent=2)
115
123
  print()
116
124
 
117
125
 
118
126
  if __name__ == "__main__":
119
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
120
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
121
- for _s in (sys.stdout, sys.stderr):
122
- if hasattr(_s, "reconfigure"):
123
- _s.reconfigure(encoding="utf-8")
127
+ utf8_stdio()
124
128
  main()
@@ -12,6 +12,7 @@ from datetime import datetime, timezone
12
12
  from pathlib import Path
13
13
 
14
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+ from _subproc import utf8_stdio # noqa: E402
15
16
  from name_resolver import resolve # noqa: E402
16
17
  from stock_data import detect_market # noqa: E402
17
18
 
@@ -271,9 +272,5 @@ def main():
271
272
 
272
273
 
273
274
  if __name__ == "__main__":
274
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
275
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
276
- for _s in (sys.stdout, sys.stderr):
277
- if hasattr(_s, "reconfigure"):
278
- _s.reconfigure(encoding="utf-8")
275
+ utf8_stdio()
279
276
  main()
@@ -6,13 +6,17 @@ import json
6
6
  import os
7
7
  import sys
8
8
 
9
+ import pandas as pd
10
+
9
11
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10
12
 
11
13
  from _subproc import run_tool as _run_tool
14
+ from _subproc import utf8_stdio
15
+ from technical import bollinger_series, ma_series, macd_series, rsi_series
12
16
 
13
17
  INDEX_MAP = {
14
18
  "A": ("000001", "上证综指"),
15
- "HK": ("HSI", "恒生指数"),
19
+ "HK": ("^HSI", "恒生指数"),
16
20
  "US": ("^GSPC", "标普500"),
17
21
  }
18
22
 
@@ -54,14 +58,12 @@ def _compute_indicators(klines: list) -> dict:
54
58
  if len(closes) < 20:
55
59
  return {}
56
60
 
57
- def ma(n):
58
- return np.mean(closes[-n:]) if len(closes) >= n else np.mean(closes)
59
-
60
- ma5 = ma(5)
61
- ma10 = ma(10)
62
- ma20 = ma(20)
63
- ma60 = ma(60) if len(closes) >= 60 else ma(len(closes))
64
- close = closes[-1]
61
+ close_s = pd.Series(closes)
62
+ ma5 = float(ma_series(close_s, 5).iloc[-1])
63
+ ma10 = float(ma_series(close_s, 10).iloc[-1])
64
+ ma20 = float(ma_series(close_s, 20).iloc[-1])
65
+ ma60 = float(ma_series(close_s, 60).iloc[-1]) if len(closes) >= 60 else float(np.mean(closes))
66
+ close = float(closes[-1])
65
67
 
66
68
  highs = np.array([float(k["high"]) for k in klines if k.get("high") is not None])
67
69
  lows = np.array([float(k["low"]) for k in klines if k.get("low") is not None])
@@ -73,30 +75,24 @@ def _compute_indicators(klines: list) -> dict:
73
75
  atr = np.mean(tr_values) if tr_values else 0
74
76
  atr_ratio = atr / close if close > 0 else 0
75
77
 
76
- upper = ma20 + 2 * np.std(closes[-20:])
77
- lower = ma20 - 2 * np.std(closes[-20:])
78
- boll_width = (upper - lower) / ma20 if ma20 > 0 else 0
79
-
80
- gains, losses = [], []
81
- for i in range(1, min(15, len(closes))):
82
- diff = closes[-i] - closes[-i - 1]
83
- if diff > 0:
84
- gains.append(diff)
85
- else:
86
- losses.append(abs(diff))
87
- avg_gain = np.mean(gains) if gains else 0
88
- avg_loss = np.mean(losses) if losses else 1
89
- rs = avg_gain / avg_loss if avg_loss > 0 else 100
90
- rsi14 = 100 - (100 / (1 + rs))
91
-
92
- ema12 = np.mean(closes[-12:])
93
- ema26 = np.mean(closes[-26:]) if len(closes) >= 26 else np.mean(closes)
94
- macd_diff = ema12 - ema26
95
- macd_trend = "bullish" if macd_diff > 0 else "bearish"
78
+ upper, mid, lower = bollinger_series(close_s)
79
+ boll_width = float((upper.iloc[-1] - lower.iloc[-1]) / mid.iloc[-1]) if mid.iloc[-1] > 0 else 0
80
+
81
+ # rsi_series leaves NaN when the window has zero losses: 14 straight up bars
82
+ # is RSI 100, but 14 flat bars (no gains either) is undefined — call it neutral.
83
+ rsi_val = rsi_series(close_s, 14).iloc[-1]
84
+ if pd.isna(rsi_val):
85
+ rsi14 = 100.0 if float(close_s.diff().clip(lower=0).iloc[-14:].sum()) > 0 else 50.0
86
+ else:
87
+ rsi14 = float(rsi_val)
88
+
89
+ # Real EMA12-EMA26 (the old code mislabeled an np.mean simple average as EMA).
90
+ dif, _, _ = macd_series(close_s)
91
+ macd_trend = "bullish" if float(dif.iloc[-1]) > 0 else "bearish"
96
92
 
97
93
  ma_spread = abs(ma5 - ma20) / ma20 if ma20 > 0 else 0
98
94
 
99
- prev_close = closes[-2] if len(closes) >= 2 else close
95
+ prev_close = float(closes[-2]) if len(closes) >= 2 else close
100
96
  change_pct = (close - prev_close) / prev_close * 100 if prev_close > 0 else 0
101
97
 
102
98
  return {
@@ -233,9 +229,5 @@ def main():
233
229
 
234
230
 
235
231
  if __name__ == "__main__":
236
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
237
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
238
- for _s in (sys.stdout, sys.stderr):
239
- if hasattr(_s, "reconfigure"):
240
- _s.reconfigure(encoding="utf-8")
232
+ utf8_stdio()
241
233
  main()
@@ -1,15 +1,25 @@
1
1
  #!/usr/bin/env python3
2
- """Market review — daily market overview with temperature scoring."""
2
+ """Market review — daily market overview with temperature scoring.
3
+
4
+ Review archive: `render_market_report --save` appends the report object to a
5
+ JSONL store so `history` can answer longitudinal questions. Store path:
6
+ $STOCK_REVIEW_STORE, else ~/.stock-analysis/reviews.jsonl (pathlib.Path.home(),
7
+ cross-platform). `history` accepts --store PATH to override (tests point it at
8
+ tmp_path).
9
+ """
3
10
 
4
11
  import argparse
5
12
  import json
6
13
  import os
7
14
  import sys
8
15
  from concurrent.futures import ThreadPoolExecutor
16
+ from pathlib import Path
9
17
 
10
18
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
19
 
12
20
  from _subproc import run_tool as _run_tool
21
+ from _subproc import utf8_stdio
22
+ from signal_tracker import _load_records
13
23
 
14
24
 
15
25
  def calc_temperature(stats: dict, indices: list) -> dict:
@@ -89,10 +99,16 @@ def review_market(market: str = "A") -> dict:
89
99
 
90
100
  results = {}
91
101
  with ThreadPoolExecutor(max_workers=5) as executor:
92
- futures = {key: executor.submit(_run_tool, script, args) for key, (script, args) in tasks.items()}
102
+ futures = {
103
+ # stats fans out to a full-market snapshot — screener gives the same path 240s
104
+ # (screener.fetch_snapshot); the default 30s would silently degrade the
105
+ # temperature to the neutral 50 fallback on a weak network.
106
+ key: executor.submit(_run_tool, script, args, 240 if key == "stats" else 30)
107
+ for key, (script, args) in tasks.items()
108
+ }
93
109
  for key, future in futures.items():
94
110
  try:
95
- results[key] = future.result(timeout=60)
111
+ results[key] = future.result(timeout=300)
96
112
  except Exception:
97
113
  results[key] = None
98
114
 
@@ -120,6 +136,35 @@ def review_all() -> list:
120
136
  return results
121
137
 
122
138
 
139
+ def _default_store() -> Path:
140
+ env = os.environ.get("STOCK_REVIEW_STORE")
141
+ return Path(env) if env else Path.home() / ".stock-analysis" / "reviews.jsonl"
142
+
143
+
144
+ def save_review(report: dict, store: Path | None = None) -> dict:
145
+ """Append one review report object to the JSONL archive (side effect of render --save)."""
146
+ store = store or _default_store()
147
+ try:
148
+ store.parent.mkdir(parents=True, exist_ok=True)
149
+ with store.open("a", encoding="utf-8") as f:
150
+ f.write(json.dumps(report, ensure_ascii=False, default=str) + "\n")
151
+ except OSError as e:
152
+ return {"error": str(e)}
153
+ return {"saved": True, "date": report.get("review_date") or report.get("date")}
154
+
155
+
156
+ def cmd_history(args) -> dict:
157
+ """Recent archived reviews, newest first. Empty store -> clean empty list."""
158
+ try:
159
+ records = _load_records(Path(args.store) if args.store else _default_store())
160
+ except (OSError, UnicodeDecodeError) as e:
161
+ # store is a directory / not UTF-8 — same clean-error contract as save_review
162
+ return {"error": str(e)}
163
+ limit = max(args.limit, 0)
164
+ recent = records[-limit:][::-1] if limit else []
165
+ return {"count": len(recent), "records": recent}
166
+
167
+
123
168
  def main():
124
169
  parser = argparse.ArgumentParser(description="Market review tool")
125
170
  sub = parser.add_subparsers(dest="command")
@@ -127,6 +172,10 @@ def main():
127
172
  p_review = sub.add_parser("review")
128
173
  p_review.add_argument("--market", default="A", choices=["A", "HK", "US", "all"])
129
174
 
175
+ p_hist = sub.add_parser("history", help="Read archived market reviews (newest first)")
176
+ p_hist.add_argument("--limit", type=int, default=10, help="Max archived entries to return (default 10)")
177
+ p_hist.add_argument("--store", default=None, help="JSONL store path override")
178
+
130
179
  args = parser.parse_args()
131
180
  if not args.command:
132
181
  parser.print_help()
@@ -134,13 +183,11 @@ def main():
134
183
 
135
184
  if args.command == "review":
136
185
  result = review_all() if args.market == "all" else review_market(args.market)
137
- print(json.dumps(result, ensure_ascii=False, default=str))
186
+ else: # history
187
+ result = cmd_history(args)
188
+ print(json.dumps(result, ensure_ascii=False, default=str))
138
189
 
139
190
 
140
191
  if __name__ == "__main__":
141
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
142
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
143
- for _s in (sys.stdout, sys.stderr):
144
- if hasattr(_s, "reconfigure"):
145
- _s.reconfigure(encoding="utf-8")
192
+ utf8_stdio()
146
193
  main()
@@ -9,6 +9,7 @@ from pathlib import Path
9
9
 
10
10
  sys.path.insert(0, str(Path(__file__).resolve().parent))
11
11
 
12
+ from _subproc import utf8_stdio # noqa: E402
12
13
  from stock_data import _akshare_retry # noqa: E402
13
14
 
14
15
  _STOCK_MAP_CACHE = None
@@ -122,9 +123,5 @@ def main():
122
123
 
123
124
 
124
125
  if __name__ == "__main__":
125
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
126
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
127
- for _s in (sys.stdout, sys.stderr):
128
- if hasattr(_s, "reconfigure"):
129
- _s.reconfigure(encoding="utf-8")
126
+ utf8_stdio()
130
127
  main()
package/tools/pattern.py CHANGED
@@ -11,6 +11,7 @@ import pandas as pd
11
11
 
12
12
  sys.path.insert(0, str(Path(__file__).resolve().parent))
13
13
 
14
+ from _subproc import utf8_stdio # noqa: E402
14
15
  from technical import fetch_kline, to_dataframe # noqa: E402
15
16
 
16
17
 
@@ -486,9 +487,5 @@ def main():
486
487
 
487
488
 
488
489
  if __name__ == "__main__":
489
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
490
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
491
- for _s in (sys.stdout, sys.stderr):
492
- if hasattr(_s, "reconfigure"):
493
- _s.reconfigure(encoding="utf-8")
490
+ utf8_stdio()
494
491
  main()
@@ -12,6 +12,7 @@ from pathlib import Path
12
12
 
13
13
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
14
  from _subproc import run_tool as _run_json # noqa: E402
15
+ from _subproc import utf8_stdio
15
16
  from stock_data import detect_market # noqa: E402
16
17
 
17
18
 
@@ -135,9 +136,5 @@ def main():
135
136
 
136
137
 
137
138
  if __name__ == "__main__":
138
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
139
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
140
- for _s in (sys.stdout, sys.stderr):
141
- if hasattr(_s, "reconfigure"):
142
- _s.reconfigure(encoding="utf-8")
139
+ utf8_stdio()
143
140
  main()
@@ -1,7 +1,8 @@
1
1
  #!/usr/bin/env python3
2
2
  """Report renderer — turn structured stock/market JSON into markdown via existing j2 templates.
3
3
 
4
- No side effects: does not save, push, or upload. Just returns markdown.
4
+ Side effects: none by default. `market --save` additionally appends the input
5
+ report object to the review JSONL archive (see market_review.save_review).
5
6
  """
6
7
 
7
8
  import argparse
@@ -10,6 +11,10 @@ import sys
10
11
  from datetime import datetime, timezone
11
12
  from pathlib import Path
12
13
 
14
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
15
+ from _subproc import utf8_stdio
16
+ from market_review import save_review
17
+
13
18
  try:
14
19
  from jinja2 import Environment, FileSystemLoader, select_autoescape
15
20
  except ImportError:
@@ -94,6 +99,7 @@ def main():
94
99
  p2 = sub.add_parser("market", help="Render a market review report")
95
100
  p2.add_argument("--input", "-i", default="-", help="JSON file path or '-' for stdin")
96
101
  p2.add_argument("--input-b64", help="Base64-encoded JSON (avoids shell escaping)")
102
+ p2.add_argument("--save", action="store_true", help="Append the report object to the review JSONL archive")
97
103
 
98
104
  args = parser.parse_args()
99
105
  if not args.command:
@@ -102,14 +108,12 @@ def main():
102
108
 
103
109
  report = _load_input(args.input, getattr(args, "input_b64", None))
104
110
  result = render(args.command, getattr(args, "template", "full"), report)
111
+ if args.command == "market" and args.save and "error" not in result:
112
+ result["archived"] = save_review(report)
105
113
  json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
106
114
  print()
107
115
 
108
116
 
109
117
  if __name__ == "__main__":
110
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
111
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
112
- for _s in (sys.stdout, sys.stderr):
113
- if hasattr(_s, "reconfigure"):
114
- _s.reconfigure(encoding="utf-8")
118
+ utf8_stdio()
115
119
  main()
@@ -1,4 +1,5 @@
1
- akshare>=1.14.0
1
+ akshare>=1.18.97; python_version >= "3.11"
2
+ akshare>=1.14.0; python_version < "3.11"
2
3
  yfinance>=0.2.36
3
4
  pandas>=2.0.0
4
5
  numpy>=1.24.0
@@ -5,11 +5,13 @@ import argparse
5
5
  import json
6
6
  import os
7
7
  import sys
8
+ from concurrent.futures import ThreadPoolExecutor
8
9
  from datetime import datetime, timedelta
9
10
 
10
11
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
12
 
12
13
  from _subproc import run_tool as _run_tool
14
+ from _subproc import utf8_stdio
13
15
 
14
16
 
15
17
  def _safe_float(val) -> float | None:
@@ -194,24 +196,32 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
194
196
  "industry": f"{search_name} 行业政策 监管 限制",
195
197
  }
196
198
  result = {"flags": []}
197
- for cat, query in categories.items():
198
- data = _run_tool("search_intel.py", ["search", query, "--count", "3"])
199
- items = []
200
- if isinstance(data, list):
201
- items = data
202
- elif isinstance(data, dict) and "results" in data:
203
- items = data["results"]
204
-
205
- result[cat] = items
206
- if items:
207
- result["flags"].append(
208
- {
209
- "category": cat,
210
- "severity": "medium",
211
- "description": f"发现{len(items)}条相关{_cat_cn(cat)}信息",
212
- "source": "news",
213
- }
214
- )
199
+ # four independent search_intel subprocesses — fan out concurrently (same
200
+ # ThreadPoolExecutor pattern as gather._run_all); iterating `futures` in
201
+ # declaration order keeps result keys and flags stably ordered
202
+ with ThreadPoolExecutor(max_workers=len(categories)) as pool:
203
+ futures = {
204
+ cat: pool.submit(_run_tool, "search_intel.py", ["search", query, "--count", "3"])
205
+ for cat, query in categories.items()
206
+ }
207
+ for cat, future in futures.items():
208
+ data = future.result()
209
+ items = []
210
+ if isinstance(data, list):
211
+ items = data
212
+ elif isinstance(data, dict) and "results" in data:
213
+ items = data["results"]
214
+
215
+ result[cat] = items
216
+ if items:
217
+ result["flags"].append(
218
+ {
219
+ "category": cat,
220
+ "severity": "medium",
221
+ "description": f"发现{len(items)}条相关{_cat_cn(cat)}信息",
222
+ "source": "news",
223
+ }
224
+ )
215
225
  return result
216
226
 
217
227
 
@@ -305,9 +315,5 @@ def main():
305
315
 
306
316
 
307
317
  if __name__ == "__main__":
308
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
309
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
310
- for _s in (sys.stdout, sys.stderr):
311
- if hasattr(_s, "reconfigure"):
312
- _s.reconfigure(encoding="utf-8")
318
+ utf8_stdio()
313
319
  main()