openclaw-stock-analysis 0.2.2 → 0.2.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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -2
  3. package/dist/index.js +228 -30
  4. package/index.ts +246 -33
  5. package/openclaw.plugin.json +13 -1
  6. package/package.json +1 -1
  7. package/schemas/report_schema.json +3 -3
  8. package/scripts/ci-resolve-llm-host.mjs +29 -0
  9. package/scripts/setup-python.mjs +11 -13
  10. package/skills/bull-trend/SKILL.md +34 -10
  11. package/skills/bull-trend/references/fat-tails.md +91 -0
  12. package/skills/bull-trend/scripts/tail_analysis.py +132 -0
  13. package/skills/event-driven/SKILL.md +8 -0
  14. package/skills/growth-quality/SKILL.md +8 -0
  15. package/skills/hot-theme/SKILL.md +3 -2
  16. package/skills/stock-analysis/SKILL.md +31 -3
  17. package/skills/stock-screener/SKILL.md +21 -1
  18. package/skills/strategy-backtest/SKILL.md +15 -5
  19. package/skills/wisburg-research/SKILL.md +2 -0
  20. package/strategies/examples/bottom_volume.yaml +5 -0
  21. package/strategies/examples/box_oscillation.yaml +5 -0
  22. package/strategies/examples/bull_trend.yaml +11 -3
  23. package/strategies/examples/dragon_head.yaml +4 -2
  24. package/strategies/examples/emotion_cycle.yaml +5 -0
  25. package/strategies/examples/ma_crossover.yaml +10 -3
  26. package/strategies/examples/rsi_oversold.yaml +5 -0
  27. package/strategies/examples/shrink_pullback.yaml +7 -1
  28. package/strategies/examples/volume_breakout.yaml +7 -1
  29. package/templates/stock_analysis/brief.md.j2 +4 -1
  30. package/templates/stock_analysis/full.md.j2 +6 -3
  31. package/tools/_cache.py +61 -0
  32. package/tools/_subproc.py +49 -0
  33. package/tools/alert_rules.py +51 -13
  34. package/tools/anomaly_detect.py +24 -35
  35. package/tools/backtest.py +202 -104
  36. package/tools/capabilities.py +16 -5
  37. package/tools/diagnostics.py +12 -6
  38. package/tools/gather.py +33 -19
  39. package/tools/import_parser.py +2 -5
  40. package/tools/lixinger.py +100 -0
  41. package/tools/market_regime.py +34 -38
  42. package/tools/market_review.py +57 -9
  43. package/tools/name_resolver.py +2 -5
  44. package/tools/pattern.py +2 -5
  45. package/tools/position_context.py +22 -7
  46. package/tools/report_renderer.py +12 -6
  47. package/tools/requirements.txt +2 -1
  48. package/tools/risk_screening.py +73 -39
  49. package/tools/screener.py +90 -20
  50. package/tools/search_intel.py +5 -13
  51. package/tools/sec_edgar.py +346 -0
  52. package/tools/sec_holders.py +263 -0
  53. package/tools/signal_tracker.py +144 -25
  54. package/tools/stock_data.py +600 -186
  55. package/tools/technical.py +152 -42
  56. package/tools/trading_calendar.py +78 -18
  57. package/tools/value_data.py +1527 -0
  58. package/tools/volume_analysis.py +2 -5
  59. package/tools/watchlist.py +26 -6
  60. package/tools/watchlist_context.py +9 -8
@@ -3,13 +3,16 @@
3
3
 
4
4
  import argparse
5
5
  import json
6
+ import math
6
7
  import os
7
8
  import sys
9
+ from concurrent.futures import ThreadPoolExecutor
8
10
  from datetime import datetime, timedelta
9
11
 
10
12
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
13
 
12
14
  from _subproc import run_tool as _run_tool
15
+ from _subproc import utf8_stdio
13
16
 
14
17
 
15
18
  def _safe_float(val) -> float | None:
@@ -17,7 +20,7 @@ def _safe_float(val) -> float | None:
17
20
  return None
18
21
  try:
19
22
  v = float(val)
20
- return v if v == v else None # NaN check
23
+ return v if math.isfinite(v) else None
21
24
  except (ValueError, TypeError):
22
25
  return None
23
26
 
@@ -27,9 +30,12 @@ def _safe_float(val) -> float | None:
27
30
 
28
31
  def check_valuation(symbol: str) -> dict:
29
32
  quote = _run_tool("stock_data.py", ["quote", symbol]) or {}
33
+ if not isinstance(quote, dict) or "error" in quote:
34
+ quote = {}
30
35
  pe = _safe_float(quote.get("pe"))
31
36
  pb = _safe_float(quote.get("pb"))
32
- result = {"pe": pe, "pb": pb, "status": "normal", "flags": []}
37
+ available = pe is not None or pb is not None
38
+ result = {"pe": pe, "pb": pb, "status": "normal" if available else "unknown", "flags": [], "available": available}
33
39
 
34
40
  if pe is not None:
35
41
  if pe < 0:
@@ -89,14 +95,15 @@ def check_valuation(symbol: str) -> dict:
89
95
 
90
96
  def check_technical(symbol: str) -> dict:
91
97
  ta = _run_tool("technical.py", ["analyze", symbol])
92
- result = {"flags": []}
98
+ result = {"flags": [], "available": False}
93
99
 
94
- if not ta or "error" in ta:
100
+ if not isinstance(ta, dict) or not ta or "error" in ta:
95
101
  return result
96
102
 
97
103
  signal = ta.get("buy_signal", "")
98
104
  score = _safe_float(ta.get("signal_score"))
99
- trend = ta.get("trend", {}).get("overall", "")
105
+ result["available"] = score is not None
106
+ trend = (ta.get("trend") or {}).get("overall", "")
100
107
 
101
108
  if signal in ("STRONG_SELL",):
102
109
  result["flags"].append(
@@ -128,7 +135,7 @@ def check_technical(symbol: str) -> dict:
128
135
  )
129
136
 
130
137
  macd = ta.get("macd", {})
131
- if macd.get("signal") == "death_cross":
138
+ if macd.get("cross") == "death_cross":
132
139
  result["flags"].append(
133
140
  {"category": "technical", "severity": "medium", "description": "MACD死叉", "source": "data"}
134
141
  )
@@ -143,15 +150,27 @@ def check_technical(symbol: str) -> dict:
143
150
 
144
151
 
145
152
  def check_lockup(symbol: str) -> dict:
146
- result = {"upcoming_30d": [], "flags": []}
153
+ result = _run_tool("risk_screening.py", ["lockup", symbol], timeout=25)
154
+ return (
155
+ result
156
+ if isinstance(result, dict) and "error" not in result
157
+ else {"upcoming_30d": [], "flags": [], "available": False}
158
+ )
159
+
160
+
161
+ def _fetch_lockup(symbol: str) -> dict:
162
+ result = {"upcoming_30d": [], "flags": [], "available": False}
147
163
  try:
148
164
  import akshare as ak
149
165
 
150
166
  df = ak.stock_restricted_release_queue_em(symbol=symbol)
151
- if df is None or df.empty:
167
+ if df is None:
168
+ return result
169
+ result["available"] = True
170
+ if df.empty:
152
171
  return result
153
172
 
154
- now = datetime.now()
173
+ now = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
155
174
  cutoff = now + timedelta(days=30)
156
175
 
157
176
  date_col = None
@@ -178,7 +197,7 @@ def check_lockup(symbol: str) -> dict:
178
197
  }
179
198
  )
180
199
  except Exception:
181
- pass
200
+ result["available"] = False
182
201
  return result
183
202
 
184
203
 
@@ -193,25 +212,35 @@ def check_news_risks(symbol: str, name: str = "") -> dict:
193
212
  "regulatory": f"{search_name} 处罚 违规 监管 立案",
194
213
  "industry": f"{search_name} 行业政策 监管 限制",
195
214
  }
196
- 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
- )
215
+ result = {"flags": [], "available": True}
216
+ # four independent search_intel subprocesses — fan out concurrently (same
217
+ # ThreadPoolExecutor pattern as gather._run_all); iterating `futures` in
218
+ # declaration order keeps result keys and flags stably ordered
219
+ with ThreadPoolExecutor(max_workers=len(categories)) as pool:
220
+ futures = {
221
+ cat: pool.submit(_run_tool, "search_intel.py", ["search", query, "--count", "3"])
222
+ for cat, query in categories.items()
223
+ }
224
+ for cat, future in futures.items():
225
+ data = future.result()
226
+ items = []
227
+ if isinstance(data, list):
228
+ items = data
229
+ elif isinstance(data, dict) and "error" not in data and isinstance(data.get("results"), list):
230
+ items = data["results"]
231
+ else:
232
+ result["available"] = False
233
+
234
+ result[cat] = items
235
+ if items:
236
+ result["flags"].append(
237
+ {
238
+ "category": cat,
239
+ "severity": "medium",
240
+ "description": f"发现{len(items)}条相关{_cat_cn(cat)}信息",
241
+ "source": "news",
242
+ }
243
+ )
215
244
  return result
216
245
 
217
246
 
@@ -255,7 +284,7 @@ def screen_risk(symbol: str, name: str = "") -> dict:
255
284
  checks = {}
256
285
 
257
286
  val = check_valuation(symbol)
258
- checks["valuation"] = {"pe": val["pe"], "pb": val["pb"], "status": val["status"]}
287
+ checks["valuation"] = {k: val[k] for k in ("pe", "pb", "status", "available")}
259
288
  all_flags.extend(val["flags"])
260
289
 
261
290
  tech = check_technical(symbol)
@@ -263,11 +292,12 @@ def screen_risk(symbol: str, name: str = "") -> dict:
263
292
  "buy_signal": tech.get("buy_signal"),
264
293
  "signal_score": tech.get("signal_score"),
265
294
  "trend": tech.get("trend"),
295
+ "available": tech["available"],
266
296
  }
267
297
  all_flags.extend(tech["flags"])
268
298
 
269
299
  lockup = check_lockup(symbol)
270
- checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"]}
300
+ checks["lockup"] = {"upcoming_30d": lockup["upcoming_30d"], "available": lockup["available"]}
271
301
  all_flags.extend(lockup["flags"])
272
302
 
273
303
  news = check_news_risks(symbol, name)
@@ -275,12 +305,16 @@ def screen_risk(symbol: str, name: str = "") -> dict:
275
305
  all_flags.extend(news["flags"])
276
306
 
277
307
  risk = compute_risk(all_flags)
308
+ missing = [key for key, value in checks.items() if not value.get("available")]
309
+ complete = not missing
278
310
  return {
279
311
  "symbol": symbol,
280
312
  "name": name,
281
- "risk_level": risk["risk_level"],
282
- "risk_score": risk["risk_score"],
283
- "veto_buy": risk["veto_buy"],
313
+ "risk_level": "unknown" if missing and risk["risk_level"] == "low" else risk["risk_level"],
314
+ "risk_score": risk["risk_score"] if all_flags or complete else None,
315
+ "veto_buy": risk["veto_buy"] if risk["veto_buy"] or complete else None,
316
+ "data_complete": complete,
317
+ "warnings": [f"{key} risk data unavailable or incomplete" for key in missing],
284
318
  "flags": all_flags,
285
319
  "checks": checks,
286
320
  }
@@ -293,6 +327,8 @@ def main():
293
327
  p_screen = sub.add_parser("screen")
294
328
  p_screen.add_argument("symbol")
295
329
  p_screen.add_argument("--name", default="")
330
+ p_lockup = sub.add_parser("lockup", help="Internal bounded lockup query")
331
+ p_lockup.add_argument("symbol")
296
332
 
297
333
  args = parser.parse_args()
298
334
  if not args.command:
@@ -302,12 +338,10 @@ def main():
302
338
  if args.command == "screen":
303
339
  result = screen_risk(args.symbol, args.name)
304
340
  print(json.dumps(result, ensure_ascii=False, default=str))
341
+ elif args.command == "lockup":
342
+ print(json.dumps(_fetch_lockup(args.symbol), ensure_ascii=False, default=str))
305
343
 
306
344
 
307
345
  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")
346
+ utf8_stdio()
313
347
  main()
package/tools/screener.py CHANGED
@@ -18,7 +18,7 @@ import yaml
18
18
 
19
19
  sys.path.insert(0, str(Path(__file__).resolve().parent))
20
20
 
21
- from _subproc import run_tool
21
+ from _subproc import run_tool, utf8_stdio
22
22
  from market_review import calc_temperature
23
23
  from stock_data import compute_market_stats
24
24
 
@@ -73,6 +73,13 @@ def merge_filters(config: dict | None) -> dict:
73
73
 
74
74
  def apply_filters(df: pd.DataFrame, filters: dict) -> pd.DataFrame:
75
75
  conditions = []
76
+ for bound, op in [("dividend_yield_min", "min"), ("dividend_yield_max", "max")]:
77
+ if bound in filters:
78
+ if "dividend_yield" not in df.columns:
79
+ return df.iloc[0:0].copy()
80
+ conditions.append(
81
+ df["dividend_yield"] >= filters[bound] if op == "min" else df["dividend_yield"] <= filters[bound]
82
+ )
76
83
  if "pe" in df.columns:
77
84
  conditions.append(df["pe"] >= filters["pe_min"])
78
85
  conditions.append(df["pe"] <= filters["pe_max"])
@@ -105,6 +112,15 @@ def _minmax(s: pd.Series) -> pd.Series:
105
112
  return ((s - mn) / (mx - mn) * 100).clip(0, 100)
106
113
 
107
114
 
115
+ def _finite(v):
116
+ """NaN/±inf → None. An all-empty factor column min-maxes to NaN, and json.dumps
117
+ would emit bare NaN/Infinity tokens that strict parsers in the host adapters
118
+ reject — so non-finite values never reach the output contract."""
119
+ if isinstance(v, (int, float, np.floating)) and not np.isfinite(v):
120
+ return None
121
+ return v
122
+
123
+
108
124
  def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
109
125
  # Value: lower PE/PB → higher score (inverted)
110
126
  value_parts = []
@@ -112,7 +128,10 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
112
128
  value_parts.append(100 - _minmax(df["pe"]))
113
129
  if "pb" in df.columns:
114
130
  value_parts.append(100 - _minmax(df["pb"]))
115
- df["value_score"] = sum(value_parts) / max(len(value_parts), 1)
131
+ if "dividend_yield" in df.columns:
132
+ df["dividend_score"] = _minmax(df["dividend_yield"])
133
+ value_parts.append(df["dividend_score"])
134
+ df["value_score"] = pd.concat(value_parts, axis=1).mean(axis=1) if value_parts else 0.0
116
135
 
117
136
  # Momentum: higher change_pct and volume_ratio → higher score
118
137
  mom_parts = []
@@ -277,9 +296,10 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
277
296
  groups = factor_scores.get(sym, {})
278
297
  c["enriched"] = bool(enrichments.get(sym))
279
298
  scores = c["scores"]
299
+ # scores are sanitized to None when non-finite; L2 math needs numbers
280
300
  components = {
281
- "value": scores["value"],
282
- "liquidity": scores["liquidity"],
301
+ "value": scores["value"] or 0,
302
+ "liquidity": scores["liquidity"] or 0,
283
303
  }
284
304
  # momentum is L2-only: candidates without kline factors drop the group and renormalize weights.
285
305
  components.update(
@@ -294,9 +314,28 @@ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
294
314
 
295
315
 
296
316
  def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict:
317
+ if config is not None and (not isinstance(config, dict) or not isinstance(config.get("filters", {}), dict)):
318
+ return {"error": "config and filters must be objects", "market": market}
319
+ filters = merge_filters(config)
320
+ supported = set(DEFAULT_FILTERS) | {"dividend_yield_min", "dividend_yield_max"}
321
+ for key, value in filters.items():
322
+ if key not in supported:
323
+ return {"error": f"Unsupported filter: {key}", "market": market}
324
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value):
325
+ return {"error": f"{key} must be a finite number", "market": market}
326
+ dividend_requested = any(k.startswith("dividend_yield_") for k in filters) or (config or {}).get("sort_by") in (
327
+ "dividend_yield",
328
+ "dividend_score",
329
+ )
330
+ if dividend_requested and market not in ("A", "HK"):
331
+ return {"error": "dividend screening currently covers A/HK only", "market": market}
297
332
  raw = fetch_snapshot(market)
298
333
  if isinstance(raw, dict) and "error" in raw:
299
334
  return raw
335
+ # snapshot legs wrap a total failure as a one-row [{"error": ...}] list — surface it
336
+ # instead of letting the error row walk the scoring pipeline as a ghost candidate
337
+ if isinstance(raw, list) and len(raw) == 1 and isinstance(raw[0], dict) and "error" in raw[0]:
338
+ return {**raw[0], "market": market}
300
339
  if raw is None:
301
340
  return {"error": "failed to fetch market snapshot", "market": market}
302
341
 
@@ -316,7 +355,35 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
316
355
  if existing:
317
356
  df = df.dropna(subset=existing)
318
357
 
319
- filters = merge_filters(config)
358
+ dividend_meta = {}
359
+ if dividend_requested:
360
+ try:
361
+ from value_data import dividend_ranking
362
+
363
+ ranked = dividend_ranking(report_date=(config or {}).get("dividend_report_date", ""), market=market)
364
+
365
+ def dividend_key(symbol):
366
+ return symbol.split(".")[0].lstrip("0") if market == "HK" else symbol
367
+
368
+ yields = {dividend_key(r["symbol"]): r["dividend_yield"] for r in ranked["items"]}
369
+ df["dividend_yield"] = df["symbol"].map(dividend_key).map(yields)
370
+ dividend_meta = {
371
+ "dividend_factor": {
372
+ "report_date": ranked["report_date"],
373
+ "yield_basis": ranked.get("yield_basis", "provider report-period cash dividend yield, percent"),
374
+ "missing": "unknown; excluded by dividend filters",
375
+ }
376
+ }
377
+ except Exception:
378
+ return {
379
+ "error": "dividend data unavailable; requested dividend criterion was not applied",
380
+ "market": market,
381
+ }
382
+ explicit = (config or {}).get("filters") or {}
383
+ missing = [key for key in explicit if key.rsplit("_", 1)[0] not in df]
384
+ if missing:
385
+ return {"error": f"Requested filter data unavailable: {', '.join(missing)}", "market": market}
386
+ applied_filters = {key: value for key, value in filters.items() if key.rsplit("_", 1)[0] in df}
320
387
  df = apply_filters(df, filters)
321
388
  filtered_count = len(df)
322
389
 
@@ -326,10 +393,11 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
326
393
  "total_stocks": total,
327
394
  "filtered_count": 0,
328
395
  "returned_count": 0,
329
- "filters_applied": filters,
396
+ "filters_applied": applied_filters,
330
397
  "candidates": [],
331
398
  "market_sentiment": sentiment,
332
399
  "l2_enabled": l2_enabled,
400
+ **dividend_meta,
333
401
  }
334
402
 
335
403
  df = compute_scores(df)
@@ -360,18 +428,21 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
360
428
  "pb",
361
429
  "market_cap",
362
430
  "volume_ratio",
431
+ "dividend_yield",
363
432
  ]:
364
- v = row.get(field)
365
- if v is not None and not (isinstance(v, float) and np.isnan(v)):
433
+ v = _finite(row.get(field))
434
+ if v is not None:
366
435
  entry[field] = round(float(v), 2) if isinstance(v, (float, np.floating)) else v
367
- composite = float(row.get("composite_score", 0))
436
+ composite = _finite(float(row.get("composite_score", 0)))
368
437
  entry["scores"] = {
369
- "value": round(float(row.get("value_score", 0)), 1),
370
- "momentum": round(float(row.get("momentum_score", 0)), 1),
371
- "liquidity": round(float(row.get("liquidity_score", 0)), 1),
372
- "composite": round(composite, 1),
373
- "final": round(composite * multiplier, 1),
438
+ "value": _finite(round(float(row.get("value_score", 0)), 1)),
439
+ "momentum": _finite(round(float(row.get("momentum_score", 0)), 1)),
440
+ "liquidity": _finite(round(float(row.get("liquidity_score", 0)), 1)),
441
+ "composite": None if composite is None else round(composite, 1),
442
+ "final": None if composite is None else round(composite * multiplier, 1),
374
443
  }
444
+ if "dividend_score" in row:
445
+ entry["scores"]["dividend"] = _finite(round(float(row["dividend_score"]), 1))
375
446
  candidates.append(entry)
376
447
 
377
448
  if l2_enabled:
@@ -385,10 +456,11 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
385
456
  "total_stocks": total,
386
457
  "filtered_count": filtered_count,
387
458
  "returned_count": len(candidates),
388
- "filters_applied": filters,
459
+ "filters_applied": applied_filters,
389
460
  "candidates": candidates,
390
461
  "market_sentiment": sentiment,
391
462
  "l2_enabled": l2_enabled,
463
+ **dividend_meta,
392
464
  }
393
465
 
394
466
 
@@ -412,12 +484,10 @@ def main():
412
484
  config = load_config(args.config) if args.config else None
413
485
  result = screen(args.market, args.top, config, l2=args.l2)
414
486
  print(json.dumps(result, ensure_ascii=False, default=str))
487
+ if "error" in result:
488
+ sys.exit(1)
415
489
 
416
490
 
417
491
  if __name__ == "__main__":
418
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
419
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
420
- for _s in (sys.stdout, sys.stderr):
421
- if hasattr(_s, "reconfigure"):
422
- _s.reconfigure(encoding="utf-8")
492
+ utf8_stdio()
423
493
  main()
@@ -8,14 +8,10 @@ import re
8
8
  import sys
9
9
  import time as _time
10
10
 
11
- # --------------- Web Search ---------------
12
-
13
- _SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
11
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
12
+ from _subproc import scrub_secrets, utf8_stdio
14
13
 
15
-
16
- def _scrub_secrets(msg: str) -> str:
17
- """Error text may embed request URLs (requests connection errors) — never leak keys to stdout JSON."""
18
- return _SECRET_PARAM_RE.sub(r"\1***", msg)
14
+ # --------------- Web Search ---------------
19
15
 
20
16
 
21
17
  def _tavily_search(query: str, max_results: int = 5) -> list[dict]:
@@ -197,7 +193,7 @@ def search_news(query: str, max_results: int = 10) -> dict:
197
193
  try:
198
194
  items = fn(query, max_results)
199
195
  except Exception as e:
200
- engines_errors[name] = _scrub_secrets(str(e))
196
+ engines_errors[name] = scrub_secrets(str(e))
201
197
  continue
202
198
  if items:
203
199
  engines_available.append(name)
@@ -497,9 +493,5 @@ def main():
497
493
 
498
494
 
499
495
  if __name__ == "__main__":
500
- # Windows defaults stdio to a legacy code page (cp1252) that cannot encode the
501
- # Chinese text these tools emit — force UTF-8 so stdout never crashes there.
502
- for _s in (sys.stdout, sys.stderr):
503
- if hasattr(_s, "reconfigure"):
504
- _s.reconfigure(encoding="utf-8")
496
+ utf8_stdio()
505
497
  main()