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
package/tools/gather.py CHANGED
@@ -8,7 +8,9 @@ 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
13
+ from technical import analyze_records # noqa: E402
12
14
 
13
15
 
14
16
  # gather fans out the heavier CLIs, so the default timeout stays 60s; raw stdout
@@ -17,6 +19,11 @@ def _run(script, args, timeout=60):
17
19
  return run_tool(script, args, timeout=timeout, parse_json=False)
18
20
 
19
21
 
22
+ def _news_query(symbol: str) -> str:
23
+ # CN sources rank poorly for an English query; US/HK sources for a Chinese one.
24
+ return f"{symbol} 最新消息" if detect_market(symbol) == "A" else f"{symbol} stock news"
25
+
26
+
20
27
  def _parse_json(raw: str | None):
21
28
  if raw is None:
22
29
  return None
@@ -26,34 +33,41 @@ def _parse_json(raw: str | None):
26
33
  return raw
27
34
 
28
35
 
29
- def _run_all(tasks: dict) -> dict:
36
+ def _run_all(tasks: dict, symbol: str) -> dict:
30
37
  with ThreadPoolExecutor(max_workers=len(tasks)) as pool:
31
38
  futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
32
- return {key: _parse_json(f.result()) for f, key in futures.items()}
39
+ result = {key: _parse_json(f.result()) for f, key in futures.items()}
40
+ result["technical"] = analyze_records(symbol, result["kline"]) if result["kline"] is not None else None
41
+ return result
33
42
 
34
43
 
35
44
  def gather_analysis(symbol: str) -> dict:
45
+ market = detect_market(symbol)
36
46
  tasks = {
37
47
  "quote": ("stock_data.py", ["quote", symbol]),
38
48
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "120"]),
39
- "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "120"]),
40
49
  "financials": ("stock_data.py", ["financials", symbol]),
41
50
  "capital_flow": ("stock_data.py", ["capital_flow", symbol]),
42
- "news": ("search_intel.py", ["search", f"{symbol} stock news"]),
51
+ "chip_distribution": ("stock_data.py", ["chip_distribution", symbol]),
52
+ "news": ("search_intel.py", ["search", _news_query(symbol)]),
53
+ "social_sentiment": ("search_intel.py", ["sentiment", symbol]),
43
54
  "risk": ("risk_screening.py", ["screen", symbol]),
44
- "regime": ("market_regime.py", ["detect"]),
45
55
  }
46
- return _run_all(tasks)
56
+ if market in ("A", "HK", "US"):
57
+ tasks["regime"] = ("market_regime.py", ["detect", market])
58
+ result = _run_all(tasks, symbol)
59
+ if market not in ("A", "HK", "US"):
60
+ result["regime"] = {"error": f"Market regime unavailable for {market}"}
61
+ return result
47
62
 
48
63
 
49
64
  def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = False) -> dict:
50
65
  tasks = {
51
66
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(kline_count)]),
52
- "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", str(kline_count)]),
53
67
  }
54
68
  if with_quote:
55
69
  tasks["quote"] = ("stock_data.py", ["quote", symbol])
56
- return _run_all(tasks)
70
+ return _run_all(tasks, symbol)
57
71
 
58
72
 
59
73
  def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -> dict:
@@ -65,16 +79,20 @@ def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -
65
79
 
66
80
 
67
81
  def gather_fundamental(symbol: str) -> dict:
82
+ market = detect_market(symbol)
68
83
  tasks = {
69
84
  "quote": ("stock_data.py", ["quote", symbol]),
70
85
  "kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "60"]),
71
- "technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]),
72
86
  "financials": ("stock_data.py", ["financials", symbol]),
73
- "news": ("search_intel.py", ["search", f"{symbol} stock news"]),
87
+ "news": ("search_intel.py", ["search", _news_query(symbol)]),
74
88
  "stock_info": ("stock_data.py", ["stock_info", symbol]),
75
- "sector_rankings": ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]),
76
89
  }
77
- return _run_all(tasks)
90
+ if market == "A":
91
+ tasks["sector_rankings"] = ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"])
92
+ result = _run_all(tasks, symbol)
93
+ if market != "A":
94
+ result["sector_rankings"] = {"error": f"Sector rankings unavailable for {market}"}
95
+ return result
78
96
 
79
97
 
80
98
  def main():
@@ -111,14 +129,10 @@ def main():
111
129
  parser.print_help()
112
130
  sys.exit(1)
113
131
 
114
- json.dump(result, sys.stdout, ensure_ascii=False, indent=2)
132
+ json.dump(json_safe(result), sys.stdout, ensure_ascii=False, indent=2)
115
133
  print()
116
134
 
117
135
 
118
136
  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")
137
+ utf8_stdio()
124
138
  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()
@@ -0,0 +1,100 @@
1
+ """Optional Lixinger HK non-financial datasets (same env token as index data)."""
2
+
3
+ import os
4
+ from datetime import date, timedelta
5
+
6
+ import requests
7
+ from _cache import DAY, cached
8
+
9
+
10
+ def hk_data(symbol, dataset, metrics):
11
+ code = symbol.split(".")[0].zfill(5)
12
+ end = date.today()
13
+ try:
14
+ start = end.replace(year=end.year - 10)
15
+ except ValueError:
16
+ start = end.replace(year=end.year - 10, day=28) + timedelta(days=1)
17
+
18
+ def fetch():
19
+ response = requests.post(
20
+ f"https://open.lixinger.com/api/hk/company/{dataset}/non_financial",
21
+ json={
22
+ "token": os.environ["LIXINGER_TOKEN"],
23
+ "stockCodes": [code],
24
+ "startDate": start.isoformat(),
25
+ "endDate": end.isoformat(),
26
+ "metricsList": metrics,
27
+ },
28
+ timeout=20,
29
+ )
30
+ response.raise_for_status()
31
+ payload = response.json()
32
+ if payload.get("code") != 1 or not isinstance(payload.get("data"), list) or not payload["data"]:
33
+ raise ValueError("Lixinger HK non-financial data unavailable; check token permissions/company type")
34
+ return payload["data"]
35
+
36
+ return cached(f"lixinger-hk:{dataset}:{code}:{end}:{','.join(metrics)}", DAY, fetch)
37
+
38
+
39
+ def financials_hk(symbol, periods, annual):
40
+ fields = {
41
+ "roe": "m.roe",
42
+ "gross_margin": "ps.gp_m",
43
+ "net_profit_margin": "ps.np_s_r",
44
+ "total_revenue": "ps.toi",
45
+ "net_income": "ps.np",
46
+ "operating_cash_flow": "cfs.ncffoa",
47
+ }
48
+ data = hk_data(symbol, "fs", [f"q.{field}.t" for field in fields.values()])
49
+ history = []
50
+ for row in sorted(data, key=lambda r: r.get("date", ""), reverse=True):
51
+ if annual and row.get("reportType") != "annual_report":
52
+ continue
53
+ if not row.get("date") or row.get("stockCode", symbol.split(".")[0].zfill(5)) != symbol.split(".")[0].zfill(5):
54
+ continue
55
+ entry = {
56
+ "report_date": row["date"][:10],
57
+ "disclosure_date": (row.get("reportDate") or "")[:10] or None,
58
+ "report_type": row.get("reportType"),
59
+ "currency": row.get("currency"),
60
+ "source": "lixinger",
61
+ }
62
+ for key, field in fields.items():
63
+ table, metric = field.split(".")
64
+ value = row.get("q", {}).get(table, {}).get(metric, {}).get("t")
65
+ entry[key] = (
66
+ value * 100 if value is not None and key in ("roe", "gross_margin", "net_profit_margin") else value
67
+ )
68
+ if any(entry.get(key) is not None for key in fields):
69
+ history.append(entry)
70
+ if not history:
71
+ raise ValueError("Lixinger returned no matching financial periods")
72
+ history = history[:periods]
73
+ latest = history[0]
74
+ result = {
75
+ **dict.fromkeys(("name", "market_cap", "pe", "forward_pe", "pb", "debt_to_equity", "dividend_yield")),
76
+ "snapshot_available": False,
77
+ "symbol": symbol,
78
+ "source": "lixinger",
79
+ "report_date": latest["report_date"],
80
+ "currency": latest["currency"],
81
+ "total_revenue": latest["total_revenue"],
82
+ "net_income": latest["net_income"],
83
+ "roe": latest["roe"] / 100 if latest["roe"] is not None else None,
84
+ "profit_margin": latest["net_profit_margin"] / 100 if latest["net_profit_margin"] is not None else None,
85
+ "periods": history,
86
+ "requested_periods": periods,
87
+ "available_periods": len(history),
88
+ "history_units": {
89
+ "roe": "percent",
90
+ "gross_margin": "percent",
91
+ "net_profit_margin": "percent",
92
+ "total_revenue": "reported currency",
93
+ "net_income": "reported currency",
94
+ "operating_cash_flow": "reported currency",
95
+ },
96
+ "accounting_basis": "provider-reported HK financial statements; not normalized to A-share accounting",
97
+ }
98
+ if len(history) < periods:
99
+ result["warnings"] = ["Requested financial history incomplete; only actual available periods returned"]
100
+ return result
@@ -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
 
@@ -50,21 +54,21 @@ def _get_index_kline(market: str) -> list:
50
54
  def _compute_indicators(klines: list) -> dict:
51
55
  import numpy as np
52
56
 
53
- closes = np.array([float(k["close"]) for k in klines if k.get("close") is not None])
57
+ df = pd.DataFrame(klines).reindex(columns=["close", "high", "low"]).apply(pd.to_numeric, errors="coerce")
58
+ df = df[np.isfinite(df).all(axis=1) & (df > 0).all(axis=1)]
59
+ closes = df["close"].to_numpy()
54
60
  if len(closes) < 20:
55
61
  return {}
56
62
 
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]
63
+ close_s = pd.Series(closes)
64
+ ma5 = float(ma_series(close_s, 5).iloc[-1])
65
+ ma10 = float(ma_series(close_s, 10).iloc[-1])
66
+ ma20 = float(ma_series(close_s, 20).iloc[-1])
67
+ ma60 = float(ma_series(close_s, 60).iloc[-1]) if len(closes) >= 60 else float(np.mean(closes))
68
+ close = float(closes[-1])
65
69
 
66
- highs = np.array([float(k["high"]) for k in klines if k.get("high") is not None])
67
- lows = np.array([float(k["low"]) for k in klines if k.get("low") is not None])
70
+ highs = df["high"].to_numpy()
71
+ lows = df["low"].to_numpy()
68
72
 
69
73
  tr_values = []
70
74
  for i in range(-min(14, len(closes) - 1), 0):
@@ -73,30 +77,24 @@ def _compute_indicators(klines: list) -> dict:
73
77
  atr = np.mean(tr_values) if tr_values else 0
74
78
  atr_ratio = atr / close if close > 0 else 0
75
79
 
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"
80
+ upper, mid, lower = bollinger_series(close_s)
81
+ boll_width = float((upper.iloc[-1] - lower.iloc[-1]) / mid.iloc[-1]) if mid.iloc[-1] > 0 else 0
82
+
83
+ # rsi_series leaves NaN when the window has zero losses: 14 straight up bars
84
+ # is RSI 100, but 14 flat bars (no gains either) is undefined — call it neutral.
85
+ rsi_val = rsi_series(close_s, 14).iloc[-1]
86
+ if pd.isna(rsi_val):
87
+ rsi14 = 100.0 if float(close_s.diff().clip(lower=0).iloc[-14:].sum()) > 0 else 50.0
88
+ else:
89
+ rsi14 = float(rsi_val)
90
+
91
+ # Real EMA12-EMA26 (the old code mislabeled an np.mean simple average as EMA).
92
+ dif, _, _ = macd_series(close_s)
93
+ macd_trend = "bullish" if float(dif.iloc[-1]) > 0 else "bearish"
96
94
 
97
95
  ma_spread = abs(ma5 - ma20) / ma20 if ma20 > 0 else 0
98
96
 
99
- prev_close = closes[-2] if len(closes) >= 2 else close
97
+ prev_close = float(closes[-2]) if len(closes) >= 2 else close
100
98
  change_pct = (close - prev_close) / prev_close * 100 if prev_close > 0 else 0
101
99
 
102
100
  return {
@@ -230,12 +228,10 @@ def main():
230
228
  if args.command == "detect":
231
229
  result = detect_regime(args.market)
232
230
  print(json.dumps(result, ensure_ascii=False, default=str))
231
+ if "error" in result:
232
+ sys.exit(1)
233
233
 
234
234
 
235
235
  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")
236
+ utf8_stdio()
241
237
  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 _append_record, _load_records, _store_lock
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,36 @@ 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
+ with _store_lock(store):
149
+ _append_record(store, report)
150
+ except (OSError, ValueError) as e:
151
+ return {"error": str(e)}
152
+ return {"saved": True, "date": report.get("review_date") or report.get("date")}
153
+
154
+
155
+ def cmd_history(args) -> dict:
156
+ """Recent archived reviews, newest first. Empty store -> clean empty list."""
157
+ try:
158
+ store = Path(args.store) if args.store else _default_store()
159
+ with _store_lock(store):
160
+ records = _load_records(store)
161
+ except (OSError, UnicodeDecodeError) as e:
162
+ # store is a directory / not UTF-8 — same clean-error contract as save_review
163
+ return {"error": str(e)}
164
+ limit = max(args.limit, 0)
165
+ recent = records[-limit:][::-1] if limit else []
166
+ return {"count": len(recent), "records": recent}
167
+
168
+
123
169
  def main():
124
170
  parser = argparse.ArgumentParser(description="Market review tool")
125
171
  sub = parser.add_subparsers(dest="command")
@@ -127,6 +173,10 @@ def main():
127
173
  p_review = sub.add_parser("review")
128
174
  p_review.add_argument("--market", default="A", choices=["A", "HK", "US", "all"])
129
175
 
176
+ p_hist = sub.add_parser("history", help="Read archived market reviews (newest first)")
177
+ p_hist.add_argument("--limit", type=int, default=10, help="Max archived entries to return (default 10)")
178
+ p_hist.add_argument("--store", default=None, help="JSONL store path override")
179
+
130
180
  args = parser.parse_args()
131
181
  if not args.command:
132
182
  parser.print_help()
@@ -134,13 +184,11 @@ def main():
134
184
 
135
185
  if args.command == "review":
136
186
  result = review_all() if args.market == "all" else review_market(args.market)
137
- print(json.dumps(result, ensure_ascii=False, default=str))
187
+ else: # history
188
+ result = cmd_history(args)
189
+ print(json.dumps(result, ensure_ascii=False, default=str))
138
190
 
139
191
 
140
192
  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")
193
+ utf8_stdio()
146
194
  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()
@@ -6,12 +6,14 @@ Not a portfolio system. Stateless: user passes cost/quantity/stops each call.
6
6
 
7
7
  import argparse
8
8
  import json
9
+ import math
9
10
  import sys
10
11
  from datetime import datetime, timezone
11
12
  from pathlib import Path
12
13
 
13
14
  sys.path.insert(0, str(Path(__file__).resolve().parent))
14
15
  from _subproc import run_tool as _run_json # noqa: E402
16
+ from _subproc import utf8_stdio
15
17
  from stock_data import detect_market # noqa: E402
16
18
 
17
19
 
@@ -47,13 +49,28 @@ def analyze_position(
47
49
  stop_loss: float | None = None,
48
50
  take_profit: float | None = None,
49
51
  ) -> dict:
52
+ for field, value in (
53
+ ("cost", cost),
54
+ ("quantity", quantity),
55
+ ("stop_loss", stop_loss),
56
+ ("take_profit", take_profit),
57
+ ):
58
+ if value is not None and (not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0):
59
+ return {"symbol": symbol, "error": f"{field} must be finite and positive"}
50
60
  quote = _run_json("stock_data.py", ["quote", symbol]) or {}
51
61
  tech = _run_json("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]) or {}
52
62
 
53
- price = quote.get("price")
63
+ price = quote.get("price") if isinstance(quote, dict) and "error" not in quote else None
54
64
  if price is None:
55
65
  return {"symbol": symbol, "error": "cannot fetch current price"}
56
- price = float(price)
66
+ try:
67
+ price = float(price)
68
+ except (TypeError, ValueError):
69
+ return {"symbol": symbol, "error": "current price must be finite and positive"}
70
+ if not math.isfinite(price) or price <= 0:
71
+ return {"symbol": symbol, "error": "current price must be finite and positive"}
72
+ if not isinstance(tech, dict):
73
+ tech = {}
57
74
 
58
75
  pnl_per_share = price - cost
59
76
  pnl_pct = (pnl_per_share / cost * 100) if cost else 0.0
@@ -132,12 +149,10 @@ def main():
132
149
  )
133
150
  json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
134
151
  print()
152
+ if "error" in result:
153
+ sys.exit(1)
135
154
 
136
155
 
137
156
  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")
157
+ utf8_stdio()
143
158
  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,14 @@ 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()
115
+ if "error" in result:
116
+ sys.exit(1)
107
117
 
108
118
 
109
119
  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")
120
+ utf8_stdio()
115
121
  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