@weaxs/openclaw-stock-analysis 0.2.5 → 0.2.7

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 (47) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +322 -21
  3. package/index.ts +257 -16
  4. package/openclaw.plugin.json +11 -1
  5. package/package.json +1 -1
  6. package/schemas/market_review_schema.json +12 -5
  7. package/schemas/report_schema.json +68 -4
  8. package/scripts/cli-timeout.mjs +27 -0
  9. package/scripts/json-input.mjs +26 -0
  10. package/scripts/setup-python.mjs +6 -6
  11. package/skills/bull-trend/SKILL.md +34 -10
  12. package/skills/bull-trend/references/fat-tails.md +91 -0
  13. package/skills/bull-trend/scripts/tail_analysis.py +132 -0
  14. package/skills/event-driven/SKILL.md +6 -0
  15. package/skills/growth-quality/SKILL.md +6 -0
  16. package/skills/market-review/SKILL.md +2 -0
  17. package/skills/stock-analysis/SKILL.md +25 -5
  18. package/skills/stock-analysis/references/stateless-analysis.md +66 -0
  19. package/skills/stock-screener/SKILL.md +7 -1
  20. package/skills/strategy-backtest/SKILL.md +13 -0
  21. package/skills/wisburg-research/SKILL.md +2 -0
  22. package/templates/market_review/full.md.j2 +7 -0
  23. package/templates/stock_analysis/_evidence.md.j2 +11 -0
  24. package/templates/stock_analysis/brief.md.j2 +6 -1
  25. package/templates/stock_analysis/full.md.j2 +8 -3
  26. package/tools/_subproc.py +66 -11
  27. package/tools/alert_rules.py +32 -4
  28. package/tools/backtest.py +95 -18
  29. package/tools/capabilities.py +11 -0
  30. package/tools/cli_budgets.json +26 -0
  31. package/tools/gather.py +24 -16
  32. package/tools/lixinger.py +100 -0
  33. package/tools/market_regime.py +7 -3
  34. package/tools/market_review.py +37 -15
  35. package/tools/position_context.py +20 -2
  36. package/tools/report_renderer.py +2 -0
  37. package/tools/risk_screening.py +45 -17
  38. package/tools/screener.py +74 -24
  39. package/tools/sec_edgar.py +346 -0
  40. package/tools/sec_holders.py +263 -0
  41. package/tools/signal_tracker.py +218 -24
  42. package/tools/stateless_analysis.py +630 -0
  43. package/tools/stock_data.py +170 -32
  44. package/tools/technical.py +16 -2
  45. package/tools/value_data.py +159 -0
  46. package/tools/watchlist.py +24 -1
  47. package/tools/watchlist_context.py +25 -10
@@ -5,12 +5,15 @@ import argparse
5
5
  import contextlib
6
6
  import hashlib
7
7
  import json
8
+ import math
9
+ import os
8
10
  import re
9
11
  import sys
10
12
  import tempfile
11
13
  import time
12
- from datetime import date, datetime, timedelta
14
+ from datetime import date, datetime, timedelta, timezone
13
15
  from pathlib import Path
16
+ from zoneinfo import ZoneInfo
14
17
 
15
18
  sys.path.insert(0, str(Path(__file__).resolve().parent))
16
19
  from _cache import DAY, WEEK, cached # noqa: E402
@@ -94,7 +97,7 @@ _STICKY_CHAINS = {
94
97
  }
95
98
 
96
99
 
97
- def _failover(sources: list, label: str):
100
+ def _failover(sources: list, label: str, evidence: bool = False):
98
101
  """Return first truthy result; else raise RuntimeError aggregating each source's error.
99
102
 
100
103
  Sticky ordering (issue #25): for chains in _STICKY_CHAINS (keyed by the label
@@ -115,6 +118,21 @@ def _failover(sources: list, label: str):
115
118
  if result:
116
119
  if chain in _STICKY_CHAINS:
117
120
  _disk_cache_set(f"sticky-{chain}", name)
121
+ if evidence:
122
+ fetched_at = datetime.now(timezone.utc).isoformat()
123
+ rows = result if isinstance(result, list) else [result]
124
+ for row in rows:
125
+ if not isinstance(row, dict) or "error" in row:
126
+ continue
127
+ row.update(source=name, fetched_at=fetched_at)
128
+ row.setdefault("data_as_of", row.get("date"))
129
+ if chain.startswith("kline"):
130
+ row.setdefault(
131
+ "adjusted",
132
+ {"yfinance": "total_return", "alphavantage": "total_return", "longbridge": "qfq"}.get(
133
+ name, "unknown"
134
+ ),
135
+ )
118
136
  return result
119
137
  except Exception as e:
120
138
  errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
@@ -206,6 +224,7 @@ def _kline_baostock(symbol: str, period: str, count: int) -> list:
206
224
  for c in ["open", "high", "low", "close", "volume"]:
207
225
  if c in df.columns:
208
226
  df[c] = pd.to_numeric(df[c], errors="coerce")
227
+ df["volume"] /= 100 # Baostock uses shares; the A-share CLI contract uses lots.
209
228
  keep = [c for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct"] if c in df.columns]
210
229
  df = df[keep].tail(count)
211
230
  return [_clean_row(r) for r in df.to_dict("records")]
@@ -274,10 +293,25 @@ def _gbk_var_payload(content: bytes) -> str:
274
293
  return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
275
294
 
276
295
 
296
+ def _unix_quote_time(value) -> str | None:
297
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0:
298
+ with contextlib.suppress(ValueError, OverflowError, OSError):
299
+ return datetime.fromtimestamp(value, timezone.utc).isoformat()
300
+ return None
301
+
302
+
303
+ def _quote_time(value: str, fmt: str) -> str | None:
304
+ try:
305
+ return datetime.strptime(value, fmt).replace(tzinfo=timezone(timedelta(hours=8))).isoformat()
306
+ except ValueError:
307
+ return None
308
+
309
+
277
310
  def _tencent_payload_row(f: list, symbol: str) -> dict:
278
311
  """Build the quote row from one Tencent `~`-separated payload (already split).
279
312
  Shared by _quote_tencent (single) and _tencent_batch_quotes (snapshot leg)."""
280
313
  f += [""] * (50 - len(f)) # pad optional tail fields (pe/pb/market_cap/volume_ratio…) on short payloads
314
+ hk = detect_market(symbol) == "HK"
281
315
  turnover = _parse_float(f[37])
282
316
  market_cap = _parse_float(f[45])
283
317
  return {
@@ -286,36 +320,46 @@ def _tencent_payload_row(f: list, symbol: str) -> dict:
286
320
  "price": _parse_float(f[3]),
287
321
  "change": _parse_float(f[31]),
288
322
  "change_pct": _parse_float(f[32]),
289
- "volume": _parse_float(f[6]), # 手, same as akshare
290
- "turnover": turnover * 1e4 if turnover is not None else None,
323
+ "volume": _parse_float(f[6]), # A: 手; HK: shares, same as yfinance
324
+ "turnover": turnover * (1 if hk else 1e4) if turnover is not None else None,
291
325
  "high": _parse_float(f[33]),
292
326
  "low": _parse_float(f[34]),
293
327
  "open": _parse_float(f[5]),
294
328
  "prev_close": _parse_float(f[4]),
295
329
  "market_cap": market_cap * 1e8 if market_cap is not None else None,
296
330
  "pe": _parse_float(f[39]),
297
- "pb": _parse_float(f[46]),
298
- "turnover_rate": _parse_float(f[38]),
299
- "volume_ratio": _parse_float(f[49]),
331
+ # Tencent's HK map labels f[47] DY and f[49] WK52_Low; neither is an A-share ratio.
332
+ "pb": None if hk else _parse_float(f[46]),
333
+ "turnover_rate": None if hk else _parse_float(f[38]),
334
+ "volume_ratio": None if hk else _parse_float(f[49]),
300
335
  "amplitude": _parse_float(f[43]),
336
+ "data_as_of": _quote_time(f[30], "%Y/%m/%d %H:%M:%S" if hk else "%Y%m%d%H%M%S"),
301
337
  }
302
338
 
303
339
 
304
340
  def _quote_tencent(symbol: str) -> dict:
305
- """Tencent quote via qt.gtimg.cn. GBK-encoded `v_sh600519="1~name~code~..."` fields.
341
+ """Tencent A/HK quote via qt.gtimg.cn, with a GBK-encoded `~` payload.
306
342
 
307
- Units differ from akshare: turnover arrives in 万元 and market_cap in 亿元 —
308
- both are normalized to 元 to match the rest of the chain."""
343
+ A-share turnover is 万元; HK turnover is already HKD. Market cap is 亿元
344
+ (CNY/HKD respectively); normalize monetary fields to currency units."""
309
345
  import requests
310
346
 
311
- resp = requests.get(f"https://qt.gtimg.cn/q={_cn_code(symbol)}", timeout=10)
347
+ hk = detect_market(symbol) == "HK"
348
+ if hk and not re.fullmatch(r"[0-9]{1,5}\.HK", symbol, re.IGNORECASE):
349
+ raise ValueError(f"invalid HK symbol: {symbol}")
350
+ # Tencent's hk feed is delayed 15 minutes; r_hk uses the same fields for live quotes.
351
+ code = f"r_hk{symbol[:-3].zfill(5)}" if hk else _cn_code(symbol)
352
+ resp = requests.get(f"https://qt.gtimg.cn/q={code}", timeout=10)
353
+ resp.raise_for_status()
312
354
  f = _gbk_var_payload(resp.content).split("~")
313
355
  if len(f) < 35 or not f[1]:
314
356
  raise ValueError(f"tencent returned no quote for {symbol}")
315
- row = _tencent_payload_row(f, symbol)
357
+ row = _clean_row(_tencent_payload_row(f, symbol))
358
+ if hk and (row["price"] is None or row["price"] <= 0):
359
+ raise ValueError(f"tencent returned no quote for {symbol}")
316
360
  if normalize_stock_code(symbol)["is_etf"]:
317
361
  row["is_etf"] = True
318
- return _clean_row(row)
362
+ return row
319
363
 
320
364
 
321
365
  def _kline_tencent(symbol: str, period: str, count: int) -> list:
@@ -381,6 +425,7 @@ def _quote_sina(symbol: str) -> dict:
381
425
  "low": _parse_float(f[5]),
382
426
  "open": _parse_float(f[1]),
383
427
  "prev_close": prev_close,
428
+ "data_as_of": _quote_time(f"{f[30]} {f[31]}", "%Y-%m-%d %H:%M:%S") if len(f) > 31 else None,
384
429
  }
385
430
  if normalize_stock_code(symbol)["is_etf"]:
386
431
  row["is_etf"] = True
@@ -450,7 +495,7 @@ def _clean_row(d: dict) -> dict:
450
495
  # --------------- kline ---------------
451
496
 
452
497
 
453
- def kline_a(symbol: str, period: str, count: int) -> list:
498
+ def kline_a(symbol: str, period: str, count: int, evidence: bool = False) -> list:
454
499
  """A-share qfq kline: akshare → tushare → efinance → tencent → baostock.
455
500
 
456
501
  Explicit indices keep raw points; unadjusted stock sources never enter the chain."""
@@ -470,7 +515,7 @@ def kline_a(symbol: str, period: str, count: int) -> list:
470
515
  ("baostock", lambda: _kline_baostock(symbol, period, count)),
471
516
  ]
472
517
  with socket_timeout(25):
473
- return _failover(sources, label=f"kline_a:{symbol}")
518
+ return _failover(sources, label=f"kline_a:{symbol}", evidence=evidence)
474
519
 
475
520
 
476
521
  def _kline_akshare(symbol: str, period: str, count: int) -> list:
@@ -574,6 +619,7 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
574
619
  df = df.merge(factors, on="trade_date", how="left", validate="one_to_one")
575
620
  if df["adj_factor"].isna().any():
576
621
  raise ValueError("tushare adjustment factors missing for price dates")
622
+ df["adjustment_factor"] = df["adj_factor"] / latest_factor
577
623
  df[prices] = df[prices].mul(df["adj_factor"] / latest_factor, axis=0)
578
624
  else:
579
625
  df = df.drop(columns=prices, errors="ignore")
@@ -585,7 +631,11 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
585
631
  df = df.sort_values("date")
586
632
  if "volume" in df.columns:
587
633
  df["volume"] = pd.to_numeric(df["volume"], errors="coerce")
588
- keep = [c for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct"] if c in df.columns]
634
+ keep = [
635
+ c
636
+ for c in ["date", "open", "high", "low", "close", "volume", "turnover", "change_pct", "adjustment_factor"]
637
+ if c in df.columns
638
+ ]
589
639
  df = df[keep].tail(count)
590
640
  return [_clean_row(r) for r in df.to_dict("records")]
591
641
 
@@ -819,11 +869,15 @@ def _quote_longbridge(symbol: str) -> dict:
819
869
  raise ValueError(f"longbridge returned no quote for {symbol}")
820
870
 
821
871
  q = quotes[0]
872
+ timestamp = getattr(q, "timestamp", None)
822
873
  prev_close = float(q.prev_close) if q.prev_close else None
823
874
  price = float(q.last_done) if q.last_done else None
824
875
  return _clean_row(
825
876
  {
826
877
  "symbol": symbol,
878
+ "data_as_of": timestamp.isoformat()
879
+ if isinstance(timestamp, datetime) and timestamp.utcoffset() is not None
880
+ else None,
827
881
  "name": getattr(q, "symbol", symbol),
828
882
  "price": price,
829
883
  "change": (price - prev_close) if price and prev_close else None,
@@ -865,7 +919,7 @@ def _kline_alphavantage(symbol: str, period: str, count: int) -> list:
865
919
  "function": fn_map.get(period, fn_map["daily"]),
866
920
  "symbol": symbol,
867
921
  "apikey": api_key,
868
- "outputsize": "compact",
922
+ "outputsize": "full" if count > 100 else "compact",
869
923
  },
870
924
  timeout=20,
871
925
  )
@@ -879,14 +933,20 @@ def _kline_alphavantage(symbol: str, period: str, count: int) -> list:
879
933
 
880
934
  rows = []
881
935
  for date_str, vals in sorted(ts.items()):
936
+ close = float(vals["4. close"])
937
+ adjusted = float(vals.get("5. adjusted close", "nan"))
938
+ if not math.isfinite(close) or not math.isfinite(adjusted) or close <= 0 or adjusted <= 0:
939
+ raise ValueError("alphavantage returned invalid adjustment prices")
940
+ factor = adjusted / close
882
941
  rows.append(
883
942
  _clean_row(
884
943
  {
885
944
  "date": date_str,
886
- "open": float(vals["1. open"]),
887
- "high": float(vals["2. high"]),
888
- "low": float(vals["3. low"]),
889
- "close": float(vals["4. close"]),
945
+ "open": float(vals["1. open"]) * factor,
946
+ "high": float(vals["2. high"]) * factor,
947
+ "low": float(vals["3. low"]) * factor,
948
+ "close": adjusted,
949
+ "adjustment_factor": factor,
890
950
  "volume": int(vals.get("6. volume", vals.get("5. volume", 0))),
891
951
  }
892
952
  )
@@ -914,9 +974,13 @@ def _quote_alphavantage(symbol: str) -> dict:
914
974
  if not gq:
915
975
  raise ValueError(f"alphavantage quote failed for {symbol}")
916
976
 
977
+ trading_day = None
978
+ with contextlib.suppress(ValueError, TypeError):
979
+ trading_day = date.fromisoformat(gq.get("07. latest trading day")).isoformat()
917
980
  return _clean_row(
918
981
  {
919
982
  "symbol": symbol,
983
+ "data_as_of": trading_day,
920
984
  "price": float(gq.get("05. price", 0)),
921
985
  "change": float(gq.get("09. change", 0)),
922
986
  "change_pct": float(gq.get("10. change percent", "0").rstrip("%")),
@@ -929,7 +993,7 @@ def _quote_alphavantage(symbol: str) -> dict:
929
993
  )
930
994
 
931
995
 
932
- def _yf_failover(symbol: str, yfinance, finnhub, longbridge, alphavantage, label: str):
996
+ def _yf_failover(symbol: str, yfinance, finnhub, longbridge, alphavantage, label: str, evidence: bool = False):
933
997
  """Shared HK/US/JP/KR/TW failover chain: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only).
934
998
 
935
999
  Each provider is a zero-arg callable; callers bind their own symbol/period/count.
@@ -940,10 +1004,10 @@ def _yf_failover(symbol: str, yfinance, finnhub, longbridge, alphavantage, label
940
1004
  sources += [("finnhub", finnhub), ("longbridge", longbridge)]
941
1005
  if market == "US":
942
1006
  sources.append(("alphavantage", alphavantage))
943
- return _failover(sources, label=label)
1007
+ return _failover(sources, label=label, evidence=evidence)
944
1008
 
945
1009
 
946
- def kline_yf(symbol: str, period: str, count: int) -> list:
1010
+ def kline_yf(symbol: str, period: str, count: int, evidence: bool = False) -> list:
947
1011
  """HK/US/JP/KR/TW kline. Failover: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only)."""
948
1012
  return _yf_failover(
949
1013
  symbol,
@@ -952,6 +1016,7 @@ def kline_yf(symbol: str, period: str, count: int) -> list:
952
1016
  lambda: _kline_longbridge(symbol, period, count),
953
1017
  lambda: _kline_alphavantage(symbol, period, count),
954
1018
  label=f"kline:{symbol}",
1019
+ evidence=evidence,
955
1020
  )
956
1021
 
957
1022
 
@@ -959,12 +1024,12 @@ def cmd_kline(args):
959
1024
  market = detect_market(args.symbol)
960
1025
  try:
961
1026
  if market == "A":
962
- data = kline_a(args.symbol, args.period, args.count)
1027
+ data = kline_a(args.symbol, args.period, args.count, evidence=True)
963
1028
  if data:
964
1029
  adjusted = "none" if _A_INDEX_RE.fullmatch(args.symbol) else "qfq"
965
1030
  data = [dict(row, adjusted=adjusted) for row in data]
966
1031
  else:
967
- data = kline_yf(args.symbol, args.period, args.count)
1032
+ data = kline_yf(args.symbol, args.period, args.count, evidence=True)
968
1033
  return data
969
1034
  except Exception as e:
970
1035
  return {"error": str(e)}
@@ -973,7 +1038,7 @@ def cmd_kline(args):
973
1038
  # --------------- quote ---------------
974
1039
 
975
1040
 
976
- def quote_a(symbol: str) -> dict:
1041
+ def quote_a(symbol: str, evidence: bool = False) -> dict:
977
1042
  """A-share quote with failover: akshare → tushare → efinance → tencent → sina → pytdx. ETFs try fund spot first.
978
1043
 
979
1044
  Explicitly-prefixed symbols (sh000001, typically indices) go straight to
@@ -983,7 +1048,7 @@ def quote_a(symbol: str) -> dict:
983
1048
  if _A_PREFIXED_RE.fullmatch(symbol):
984
1049
  sources = [("tencent", lambda: _quote_tencent(symbol)), ("sina", lambda: _quote_sina(symbol))]
985
1050
  with socket_timeout(25):
986
- return _failover(sources, label=f"quote_a:{symbol}")
1051
+ return _failover(sources, label=f"quote_a:{symbol}", evidence=evidence)
987
1052
  is_etf = normalize_stock_code(symbol)["is_etf"]
988
1053
  sources = []
989
1054
  if is_etf:
@@ -998,7 +1063,7 @@ def quote_a(symbol: str) -> dict:
998
1063
  ]
999
1064
  chain = "quote_a_etf" if is_etf else "quote_a"
1000
1065
  with socket_timeout(25):
1001
- return _failover(sources, label=f"{chain}:{symbol}")
1066
+ return _failover(sources, label=f"{chain}:{symbol}", evidence=evidence)
1002
1067
 
1003
1068
 
1004
1069
  def _quote_akshare_etf(symbol: str) -> dict:
@@ -1084,6 +1149,7 @@ def _quote_yfinance(symbol: str) -> dict:
1084
1149
  return _clean_row(
1085
1150
  {
1086
1151
  "symbol": symbol,
1152
+ "data_as_of": _unix_quote_time(info.get("regularMarketTime")),
1087
1153
  "name": info.get("shortName"),
1088
1154
  "price": info.get("regularMarketPrice") or info.get("currentPrice"),
1089
1155
  "change": info.get("regularMarketChange"),
@@ -1115,6 +1181,7 @@ def _quote_finnhub(symbol: str) -> dict:
1115
1181
  return _clean_row(
1116
1182
  {
1117
1183
  "symbol": symbol,
1184
+ "data_as_of": _unix_quote_time(q.get("t")),
1118
1185
  "price": q["c"],
1119
1186
  "change": q["d"],
1120
1187
  "change_pct": q["dp"],
@@ -1126,8 +1193,19 @@ def _quote_finnhub(symbol: str) -> dict:
1126
1193
  )
1127
1194
 
1128
1195
 
1129
- def quote_yf(symbol: str) -> dict:
1130
- """HK/US/JP/KR/TW quote. Failover: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only)."""
1196
+ def quote_yf(symbol: str, evidence: bool = False) -> dict:
1197
+ """HK adds Tencent after yfinance; US/JP/KR/TW keep their existing failover chains."""
1198
+ if detect_market(symbol) == "HK":
1199
+ return _failover(
1200
+ [
1201
+ ("yfinance", lambda: _quote_yfinance(symbol)),
1202
+ ("tencent", lambda: _quote_tencent(symbol)),
1203
+ ("finnhub", lambda: _quote_finnhub(symbol)),
1204
+ ("longbridge", lambda: _quote_longbridge(symbol)),
1205
+ ],
1206
+ label=f"quote:{symbol}",
1207
+ evidence=evidence,
1208
+ )
1131
1209
  return _yf_failover(
1132
1210
  symbol,
1133
1211
  lambda: _quote_yfinance(symbol),
@@ -1135,6 +1213,7 @@ def quote_yf(symbol: str) -> dict:
1135
1213
  lambda: _quote_longbridge(symbol),
1136
1214
  lambda: _quote_alphavantage(symbol),
1137
1215
  label=f"quote:{symbol}",
1216
+ evidence=evidence,
1138
1217
  )
1139
1218
 
1140
1219
 
@@ -1164,6 +1243,7 @@ def _quote_stale_marker(market: str):
1164
1243
  as_of = prev[0]
1165
1244
  return {
1166
1245
  "as_of": as_of,
1246
+ "as_of_basis": "trading_calendar",
1167
1247
  "stale": True,
1168
1248
  "note": f"market is not in a live session; quote is the last completed trading day {as_of}'s close",
1169
1249
  }
@@ -1172,13 +1252,36 @@ def _quote_stale_marker(market: str):
1172
1252
  def cmd_quote(args):
1173
1253
  market = detect_market(args.symbol)
1174
1254
  try:
1175
- result = quote_a(args.symbol) if market == "A" else quote_yf(args.symbol)
1255
+ result = quote_a(args.symbol, evidence=True) if market == "A" else quote_yf(args.symbol, evidence=True)
1176
1256
  except Exception as e:
1177
1257
  return {"error": str(e)}
1178
1258
  if isinstance(result, dict) and "error" not in result:
1179
1259
  marker = _quote_stale_marker(market)
1180
1260
  if marker:
1181
1261
  result.update(marker)
1262
+ result.setdefault("data_as_of", None)
1263
+ if result["data_as_of"]:
1264
+ result["as_of"] = result["data_as_of"]
1265
+ result["as_of_basis"] = "provider"
1266
+ if marker:
1267
+ result["calendar_as_of"] = marker["as_of"]
1268
+ result["note"] = (
1269
+ "Quote time is supplied by the provider; the market calendar is a separate freshness hint"
1270
+ )
1271
+ try:
1272
+ from trading_calendar import market_phase
1273
+
1274
+ info = market_phase("CN" if market == "A" else market)
1275
+ value = result["data_as_of"]
1276
+ quoted_day = date.fromisoformat(value) if len(value) == 10 else None
1277
+ quoted = datetime.fromisoformat(value)
1278
+ if quoted.tzinfo:
1279
+ quoted_day = quoted.astimezone(ZoneInfo(info["timezone"])).date()
1280
+ if quoted_day and quoted_day.isoformat() < info["date"]:
1281
+ result["stale"] = True
1282
+ result["note"] = "Provider quote predates the current market date"
1283
+ except (ValueError, KeyError, TypeError, OSError):
1284
+ pass # Calendar/timestamp unavailable: retain the provider evidence without guessing.
1182
1285
  return result
1183
1286
 
1184
1287
 
@@ -1451,7 +1554,9 @@ def financials_yf(symbol: str, periods: int = 1, annual: bool = False) -> dict:
1451
1554
  {
1452
1555
  "symbol": symbol,
1453
1556
  "name": info.get("shortName"),
1557
+ "currency": info.get("financialCurrency"),
1454
1558
  "market_cap": info.get("marketCap"),
1559
+ "market_cap_currency": info.get("currency"),
1455
1560
  "pe": info.get("trailingPE"),
1456
1561
  "forward_pe": info.get("forwardPE"),
1457
1562
  "pb": info.get("priceToBook"),
@@ -1517,6 +1622,37 @@ def cmd_financials(args):
1517
1622
  annual = getattr(args, "annual", False)
1518
1623
  market = detect_market(args.symbol)
1519
1624
  try:
1625
+ if market == "HK":
1626
+ if os.environ.get("LIXINGER_TOKEN"):
1627
+ try:
1628
+ from lixinger import financials_hk
1629
+
1630
+ result = financials_hk(args.symbol, periods, annual)
1631
+ snapshot = financials_yf(args.symbol, 1, False)
1632
+ result.update(
1633
+ {
1634
+ key: value
1635
+ for key, value in snapshot.items()
1636
+ if key not in ("warnings", "error") and (not snapshot.get("error") or value is not None)
1637
+ }
1638
+ )
1639
+ result["snapshot_available"] = not snapshot.get("error")
1640
+ result["snapshot_source"] = "yfinance" if result["snapshot_available"] else None
1641
+ if result["snapshot_available"]:
1642
+ result["report_date"] = snapshot.get("report_date")
1643
+ if snapshot.get("warnings"):
1644
+ result.setdefault("warnings", []).extend(snapshot["warnings"])
1645
+ return result
1646
+ except Exception:
1647
+ warning = "Lixinger HK unavailable (permissions/company type/provider); existing sources retained"
1648
+ else:
1649
+ warning = "LIXINGER_TOKEN not configured; extended HK financial history unavailable"
1650
+ result = financials_yf(args.symbol, periods, annual)
1651
+ result.setdefault("warnings", []).append(warning)
1652
+ result.setdefault("source", "yfinance/eastmoney")
1653
+ if len(result.get("periods", [])) < periods:
1654
+ result["warnings"].append("Requested HK financial history incomplete")
1655
+ return result
1520
1656
  return (
1521
1657
  financials_a(args.symbol, periods, annual) if market == "A" else financials_yf(args.symbol, periods, annual)
1522
1658
  )
@@ -3253,6 +3389,8 @@ def main():
3253
3389
  with contextlib.redirect_stdout(sys.stderr):
3254
3390
  result = dispatch[args.command](args)
3255
3391
  output(result)
3392
+ if isinstance(result, dict) and "error" in result:
3393
+ sys.exit(1)
3256
3394
 
3257
3395
 
3258
3396
  if __name__ == "__main__":
@@ -642,13 +642,25 @@ def analyze_multi(symbol: str, period: str, count: int, periods: list) -> dict:
642
642
 
643
643
 
644
644
  def analyze(symbol: str, period: str = "daily", count: int = 120) -> dict:
645
- records = fetch_kline(symbol, period, count)
645
+ return analyze_records(symbol, fetch_kline(symbol, period, count), period)
646
+
647
+
648
+ def analyze_records(symbol: str, records: list, period: str = "daily") -> dict:
646
649
  if isinstance(records, dict) and "error" in records:
647
650
  return records
648
- if not records:
651
+ if not isinstance(records, list) or not records:
649
652
  return {"error": "No kline data returned"}
653
+ if any(not isinstance(row, dict) for row in records):
654
+ return {"error": "Invalid kline rows"}
650
655
 
651
656
  df = to_dataframe(records)
657
+ required = ["date", "close", "high", "low", "volume"]
658
+ if any(field not in df for field in required):
659
+ return {"error": "Missing kline fields"}
660
+ if df["date"].isna().any() or not np.isfinite(df[required[1:]]).all().all():
661
+ return {"error": "Invalid kline values"}
662
+ if (df[["close", "high", "low"]] <= 0).any().any() or (df["volume"] < 0).any():
663
+ return {"error": "Kline prices must be positive and volume nonnegative"}
652
664
  if len(df) < 30:
653
665
  return {"error": f"Insufficient data: {len(df)} rows (need at least 30)"}
654
666
 
@@ -731,6 +743,8 @@ def main():
731
743
  else:
732
744
  result = {"error": f"Unknown command: {args.command}"}
733
745
  print(json.dumps(result, ensure_ascii=False, default=str))
746
+ if "error" in result:
747
+ sys.exit(1)
734
748
 
735
749
 
736
750
  if __name__ == "__main__":