@weaxs/openclaw-stock-analysis 0.2.6 → 0.2.8

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 (38) hide show
  1. package/README.md +1 -1
  2. package/dist/index.js +284 -19
  3. package/index.ts +214 -12
  4. package/openclaw.plugin.json +9 -1
  5. package/package.json +1 -1
  6. package/schemas/market_review_schema.json +12 -5
  7. package/schemas/report_schema.json +65 -1
  8. package/scripts/cli-timeout.mjs +27 -0
  9. package/scripts/json-input.mjs +26 -0
  10. package/skills/bull-trend/SKILL.md +11 -1
  11. package/skills/bull-trend/references/monthly-trend-strategy.md +47 -0
  12. package/skills/bull-trend/references/trend-horizons.md +43 -0
  13. package/skills/bull-trend/references/trend-temperature.md +57 -0
  14. package/skills/bull-trend/scripts/market_trend.py +78 -0
  15. package/skills/event-driven/SKILL.md +4 -0
  16. package/skills/growth-quality/SKILL.md +4 -0
  17. package/skills/market-review/SKILL.md +2 -0
  18. package/skills/stock-analysis/SKILL.md +17 -3
  19. package/skills/stock-analysis/references/stateless-analysis.md +66 -0
  20. package/skills/stock-screener/SKILL.md +5 -1
  21. package/skills/strategy-backtest/SKILL.md +19 -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 +2 -0
  25. package/templates/stock_analysis/full.md.j2 +2 -0
  26. package/tools/_subproc.py +66 -11
  27. package/tools/backtest.py +143 -19
  28. package/tools/capabilities.py +12 -0
  29. package/tools/cli_budgets.json +27 -0
  30. package/tools/gather.py +4 -6
  31. package/tools/market_review.py +30 -9
  32. package/tools/screener.py +57 -15
  33. package/tools/signal_tracker.py +77 -6
  34. package/tools/stateless_analysis.py +630 -0
  35. package/tools/stock_data.py +90 -15
  36. package/tools/technical.py +186 -0
  37. package/tools/trend_strategy.py +365 -0
  38. package/tools/watchlist_context.py +18 -7
@@ -11,8 +11,9 @@ import re
11
11
  import sys
12
12
  import tempfile
13
13
  import time
14
- from datetime import date, datetime, timedelta
14
+ from datetime import date, datetime, timedelta, timezone
15
15
  from pathlib import Path
16
+ from zoneinfo import ZoneInfo
16
17
 
17
18
  sys.path.insert(0, str(Path(__file__).resolve().parent))
18
19
  from _cache import DAY, WEEK, cached # noqa: E402
@@ -96,7 +97,7 @@ _STICKY_CHAINS = {
96
97
  }
97
98
 
98
99
 
99
- def _failover(sources: list, label: str):
100
+ def _failover(sources: list, label: str, evidence: bool = False):
100
101
  """Return first truthy result; else raise RuntimeError aggregating each source's error.
101
102
 
102
103
  Sticky ordering (issue #25): for chains in _STICKY_CHAINS (keyed by the label
@@ -117,6 +118,21 @@ def _failover(sources: list, label: str):
117
118
  if result:
118
119
  if chain in _STICKY_CHAINS:
119
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
+ )
120
136
  return result
121
137
  except Exception as e:
122
138
  errors.append(f"{name}: {type(e).__name__}: {scrub_secrets(str(e))}")
@@ -277,6 +293,20 @@ def _gbk_var_payload(content: bytes) -> str:
277
293
  return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
278
294
 
279
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
+
280
310
  def _tencent_payload_row(f: list, symbol: str) -> dict:
281
311
  """Build the quote row from one Tencent `~`-separated payload (already split).
282
312
  Shared by _quote_tencent (single) and _tencent_batch_quotes (snapshot leg)."""
@@ -303,6 +333,7 @@ def _tencent_payload_row(f: list, symbol: str) -> dict:
303
333
  "turnover_rate": None if hk else _parse_float(f[38]),
304
334
  "volume_ratio": None if hk else _parse_float(f[49]),
305
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"),
306
337
  }
307
338
 
308
339
 
@@ -394,6 +425,7 @@ def _quote_sina(symbol: str) -> dict:
394
425
  "low": _parse_float(f[5]),
395
426
  "open": _parse_float(f[1]),
396
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,
397
429
  }
398
430
  if normalize_stock_code(symbol)["is_etf"]:
399
431
  row["is_etf"] = True
@@ -463,7 +495,7 @@ def _clean_row(d: dict) -> dict:
463
495
  # --------------- kline ---------------
464
496
 
465
497
 
466
- def kline_a(symbol: str, period: str, count: int) -> list:
498
+ def kline_a(symbol: str, period: str, count: int, evidence: bool = False) -> list:
467
499
  """A-share qfq kline: akshare → tushare → efinance → tencent → baostock.
468
500
 
469
501
  Explicit indices keep raw points; unadjusted stock sources never enter the chain."""
@@ -483,7 +515,7 @@ def kline_a(symbol: str, period: str, count: int) -> list:
483
515
  ("baostock", lambda: _kline_baostock(symbol, period, count)),
484
516
  ]
485
517
  with socket_timeout(25):
486
- return _failover(sources, label=f"kline_a:{symbol}")
518
+ return _failover(sources, label=f"kline_a:{symbol}", evidence=evidence)
487
519
 
488
520
 
489
521
  def _kline_akshare(symbol: str, period: str, count: int) -> list:
@@ -587,6 +619,7 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
587
619
  df = df.merge(factors, on="trade_date", how="left", validate="one_to_one")
588
620
  if df["adj_factor"].isna().any():
589
621
  raise ValueError("tushare adjustment factors missing for price dates")
622
+ df["adjustment_factor"] = df["adj_factor"] / latest_factor
590
623
  df[prices] = df[prices].mul(df["adj_factor"] / latest_factor, axis=0)
591
624
  else:
592
625
  df = df.drop(columns=prices, errors="ignore")
@@ -598,7 +631,11 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
598
631
  df = df.sort_values("date")
599
632
  if "volume" in df.columns:
600
633
  df["volume"] = pd.to_numeric(df["volume"], errors="coerce")
601
- 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
+ ]
602
639
  df = df[keep].tail(count)
603
640
  return [_clean_row(r) for r in df.to_dict("records")]
604
641
 
@@ -832,11 +869,15 @@ def _quote_longbridge(symbol: str) -> dict:
832
869
  raise ValueError(f"longbridge returned no quote for {symbol}")
833
870
 
834
871
  q = quotes[0]
872
+ timestamp = getattr(q, "timestamp", None)
835
873
  prev_close = float(q.prev_close) if q.prev_close else None
836
874
  price = float(q.last_done) if q.last_done else None
837
875
  return _clean_row(
838
876
  {
839
877
  "symbol": symbol,
878
+ "data_as_of": timestamp.isoformat()
879
+ if isinstance(timestamp, datetime) and timestamp.utcoffset() is not None
880
+ else None,
840
881
  "name": getattr(q, "symbol", symbol),
841
882
  "price": price,
842
883
  "change": (price - prev_close) if price and prev_close else None,
@@ -905,6 +946,7 @@ def _kline_alphavantage(symbol: str, period: str, count: int) -> list:
905
946
  "high": float(vals["2. high"]) * factor,
906
947
  "low": float(vals["3. low"]) * factor,
907
948
  "close": adjusted,
949
+ "adjustment_factor": factor,
908
950
  "volume": int(vals.get("6. volume", vals.get("5. volume", 0))),
909
951
  }
910
952
  )
@@ -932,9 +974,13 @@ def _quote_alphavantage(symbol: str) -> dict:
932
974
  if not gq:
933
975
  raise ValueError(f"alphavantage quote failed for {symbol}")
934
976
 
977
+ trading_day = None
978
+ with contextlib.suppress(ValueError, TypeError):
979
+ trading_day = date.fromisoformat(gq.get("07. latest trading day")).isoformat()
935
980
  return _clean_row(
936
981
  {
937
982
  "symbol": symbol,
983
+ "data_as_of": trading_day,
938
984
  "price": float(gq.get("05. price", 0)),
939
985
  "change": float(gq.get("09. change", 0)),
940
986
  "change_pct": float(gq.get("10. change percent", "0").rstrip("%")),
@@ -947,7 +993,7 @@ def _quote_alphavantage(symbol: str) -> dict:
947
993
  )
948
994
 
949
995
 
950
- 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):
951
997
  """Shared HK/US/JP/KR/TW failover chain: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only).
952
998
 
953
999
  Each provider is a zero-arg callable; callers bind their own symbol/period/count.
@@ -958,10 +1004,10 @@ def _yf_failover(symbol: str, yfinance, finnhub, longbridge, alphavantage, label
958
1004
  sources += [("finnhub", finnhub), ("longbridge", longbridge)]
959
1005
  if market == "US":
960
1006
  sources.append(("alphavantage", alphavantage))
961
- return _failover(sources, label=label)
1007
+ return _failover(sources, label=label, evidence=evidence)
962
1008
 
963
1009
 
964
- def kline_yf(symbol: str, period: str, count: int) -> list:
1010
+ def kline_yf(symbol: str, period: str, count: int, evidence: bool = False) -> list:
965
1011
  """HK/US/JP/KR/TW kline. Failover: yfinance → finnhub/longbridge (HK/US) → alphavantage (US only)."""
966
1012
  return _yf_failover(
967
1013
  symbol,
@@ -970,6 +1016,7 @@ def kline_yf(symbol: str, period: str, count: int) -> list:
970
1016
  lambda: _kline_longbridge(symbol, period, count),
971
1017
  lambda: _kline_alphavantage(symbol, period, count),
972
1018
  label=f"kline:{symbol}",
1019
+ evidence=evidence,
973
1020
  )
974
1021
 
975
1022
 
@@ -977,12 +1024,12 @@ def cmd_kline(args):
977
1024
  market = detect_market(args.symbol)
978
1025
  try:
979
1026
  if market == "A":
980
- data = kline_a(args.symbol, args.period, args.count)
1027
+ data = kline_a(args.symbol, args.period, args.count, evidence=True)
981
1028
  if data:
982
1029
  adjusted = "none" if _A_INDEX_RE.fullmatch(args.symbol) else "qfq"
983
1030
  data = [dict(row, adjusted=adjusted) for row in data]
984
1031
  else:
985
- data = kline_yf(args.symbol, args.period, args.count)
1032
+ data = kline_yf(args.symbol, args.period, args.count, evidence=True)
986
1033
  return data
987
1034
  except Exception as e:
988
1035
  return {"error": str(e)}
@@ -991,7 +1038,7 @@ def cmd_kline(args):
991
1038
  # --------------- quote ---------------
992
1039
 
993
1040
 
994
- def quote_a(symbol: str) -> dict:
1041
+ def quote_a(symbol: str, evidence: bool = False) -> dict:
995
1042
  """A-share quote with failover: akshare → tushare → efinance → tencent → sina → pytdx. ETFs try fund spot first.
996
1043
 
997
1044
  Explicitly-prefixed symbols (sh000001, typically indices) go straight to
@@ -1001,7 +1048,7 @@ def quote_a(symbol: str) -> dict:
1001
1048
  if _A_PREFIXED_RE.fullmatch(symbol):
1002
1049
  sources = [("tencent", lambda: _quote_tencent(symbol)), ("sina", lambda: _quote_sina(symbol))]
1003
1050
  with socket_timeout(25):
1004
- return _failover(sources, label=f"quote_a:{symbol}")
1051
+ return _failover(sources, label=f"quote_a:{symbol}", evidence=evidence)
1005
1052
  is_etf = normalize_stock_code(symbol)["is_etf"]
1006
1053
  sources = []
1007
1054
  if is_etf:
@@ -1016,7 +1063,7 @@ def quote_a(symbol: str) -> dict:
1016
1063
  ]
1017
1064
  chain = "quote_a_etf" if is_etf else "quote_a"
1018
1065
  with socket_timeout(25):
1019
- return _failover(sources, label=f"{chain}:{symbol}")
1066
+ return _failover(sources, label=f"{chain}:{symbol}", evidence=evidence)
1020
1067
 
1021
1068
 
1022
1069
  def _quote_akshare_etf(symbol: str) -> dict:
@@ -1102,6 +1149,7 @@ def _quote_yfinance(symbol: str) -> dict:
1102
1149
  return _clean_row(
1103
1150
  {
1104
1151
  "symbol": symbol,
1152
+ "data_as_of": _unix_quote_time(info.get("regularMarketTime")),
1105
1153
  "name": info.get("shortName"),
1106
1154
  "price": info.get("regularMarketPrice") or info.get("currentPrice"),
1107
1155
  "change": info.get("regularMarketChange"),
@@ -1133,6 +1181,7 @@ def _quote_finnhub(symbol: str) -> dict:
1133
1181
  return _clean_row(
1134
1182
  {
1135
1183
  "symbol": symbol,
1184
+ "data_as_of": _unix_quote_time(q.get("t")),
1136
1185
  "price": q["c"],
1137
1186
  "change": q["d"],
1138
1187
  "change_pct": q["dp"],
@@ -1144,7 +1193,7 @@ def _quote_finnhub(symbol: str) -> dict:
1144
1193
  )
1145
1194
 
1146
1195
 
1147
- def quote_yf(symbol: str) -> dict:
1196
+ def quote_yf(symbol: str, evidence: bool = False) -> dict:
1148
1197
  """HK adds Tencent after yfinance; US/JP/KR/TW keep their existing failover chains."""
1149
1198
  if detect_market(symbol) == "HK":
1150
1199
  return _failover(
@@ -1155,6 +1204,7 @@ def quote_yf(symbol: str) -> dict:
1155
1204
  ("longbridge", lambda: _quote_longbridge(symbol)),
1156
1205
  ],
1157
1206
  label=f"quote:{symbol}",
1207
+ evidence=evidence,
1158
1208
  )
1159
1209
  return _yf_failover(
1160
1210
  symbol,
@@ -1163,6 +1213,7 @@ def quote_yf(symbol: str) -> dict:
1163
1213
  lambda: _quote_longbridge(symbol),
1164
1214
  lambda: _quote_alphavantage(symbol),
1165
1215
  label=f"quote:{symbol}",
1216
+ evidence=evidence,
1166
1217
  )
1167
1218
 
1168
1219
 
@@ -1192,6 +1243,7 @@ def _quote_stale_marker(market: str):
1192
1243
  as_of = prev[0]
1193
1244
  return {
1194
1245
  "as_of": as_of,
1246
+ "as_of_basis": "trading_calendar",
1195
1247
  "stale": True,
1196
1248
  "note": f"market is not in a live session; quote is the last completed trading day {as_of}'s close",
1197
1249
  }
@@ -1200,13 +1252,36 @@ def _quote_stale_marker(market: str):
1200
1252
  def cmd_quote(args):
1201
1253
  market = detect_market(args.symbol)
1202
1254
  try:
1203
- 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)
1204
1256
  except Exception as e:
1205
1257
  return {"error": str(e)}
1206
1258
  if isinstance(result, dict) and "error" not in result:
1207
1259
  marker = _quote_stale_marker(market)
1208
1260
  if marker:
1209
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.
1210
1285
  return result
1211
1286
 
1212
1287
 
@@ -47,6 +47,182 @@ def ema_series(close: pd.Series, period: int) -> pd.Series:
47
47
  return close.ewm(span=period, adjust=False).mean()
48
48
 
49
49
 
50
+ def _trend_prices(df: pd.DataFrame) -> tuple[pd.Series, pd.Series]:
51
+ if "date" not in df or "close" not in df:
52
+ raise ValueError("monthly_momentum requires date and close")
53
+ dates = pd.to_datetime(df["date"], errors="coerce")
54
+ if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
55
+ raise ValueError("monthly_momentum dates must be valid, unique and increasing")
56
+ close = pd.to_numeric(df["close"], errors="coerce")
57
+ if not np.isfinite(close).all() or (close <= 0).any():
58
+ raise ValueError("monthly_momentum requires finite positive close prices")
59
+ if "adjusted" in df and df["adjusted"].fillna("unknown").astype(str).nunique() > 1:
60
+ raise ValueError("monthly_momentum requires a consistent adjustment basis")
61
+ if "volume" in df:
62
+ volume = pd.to_numeric(df["volume"], errors="coerce")
63
+ if not np.isfinite(volume).all() or (volume < 0).any():
64
+ raise ValueError("monthly_momentum requires finite nonnegative volume")
65
+ close, dates = close[volume > 0], dates[volume > 0]
66
+ return close, dates
67
+
68
+
69
+ def monthly_momentum_series(df: pd.DataFrame, period: int = 63) -> pd.Series:
70
+ """Past log return observed on each month's first visible close, then held; never a price forecast."""
71
+ if isinstance(period, bool) or not isinstance(period, int) or period < 1:
72
+ raise ValueError("monthly_momentum requires a positive integer period")
73
+ close, dates = _trend_prices(df)
74
+ month = dates.dt.to_period("M")
75
+ first_bar = month.ne(month.shift())
76
+ return (np.log(close) - np.log(close.shift(period))).where(first_bar).reindex(df.index).ffill()
77
+
78
+
79
+ def monthly_market_entry_series(
80
+ df: pd.DataFrame, market: pd.DataFrame, period: int = 63, *, activation: pd.Timestamp | None = None
81
+ ) -> pd.Series:
82
+ """Monthly entry permission; a weak market never cancels an existing positive stock trend."""
83
+ momentum = monthly_momentum_series(df, period)
84
+ _, dates = _trend_prices(df)
85
+ market_close, market_dates = _trend_prices(market)
86
+ context = pd.DataFrame({"date": market_dates, "allowed": market_close > ma_series(market_close, 200)})
87
+ known = pd.merge_asof(pd.DataFrame({"date": dates}), context, on="date", direction="backward")
88
+ allowed = pd.Series(known.allowed.to_numpy(), index=dates.index).reindex(df.index).eq(True)
89
+ months = dates.dt.to_period("M")
90
+ observe = months.ne(months.shift()).reindex(df.index).eq(True)
91
+ active = pd.to_datetime(df.date).ge(activation) if activation is not None else pd.Series(True, index=df.index)
92
+ if activation is not None:
93
+ observe |= pd.to_datetime(df.date).eq(activation)
94
+ permission = ((momentum > 0) & allowed).astype("boolean").where(observe & active, pd.NA)
95
+ return permission.ffill().where(active & momentum.notna(), pd.NA)
96
+
97
+
98
+ def calc_trend_horizons(df: pd.DataFrame, period: str = "daily") -> dict:
99
+ result = {
100
+ "model": "monthly_momentum",
101
+ "experimental": True,
102
+ "validation_status": "not_validated",
103
+ "as_of": str(df["date"].iloc[-1].date()),
104
+ "history_start": str(df["date"].iloc[0].date()),
105
+ "price_basis": str(df["adjusted"].iloc[-1])
106
+ if "adjusted" in df and pd.notna(df["adjusted"].iloc[-1])
107
+ else "unknown",
108
+ "decision_as_of": None,
109
+ "positive_count": None,
110
+ "negative_count": None,
111
+ "neutral_count": None,
112
+ "direction": None,
113
+ "components": [],
114
+ "unavailable_reason": None,
115
+ "warnings": [
116
+ "Descriptive past-return directions, not probabilities or an automatic allocation. "
117
+ "Observed at each month's first visible daily close; any trade uses a later open. "
118
+ "Need 253 closes at the monthly observation; verify the observation bar is closed. "
119
+ "No stable cross-market trading advantage has been established."
120
+ ],
121
+ }
122
+ if period != "daily":
123
+ result["unavailable_reason"] = "requires_daily_bars"
124
+ return result
125
+ try:
126
+ for horizon in (21, 63, 252):
127
+ value = monthly_momentum_series(df, horizon).iloc[-1]
128
+ result["components"].append({"period": horizon, "log_return": float(value) if np.isfinite(value) else None})
129
+ except ValueError as exc:
130
+ result["unavailable_reason"] = str(exc)
131
+ return result
132
+ dates = df.loc[df["volume"] > 0, "date"] if "volume" in df else df["date"]
133
+ month = dates.dt.to_period("M")
134
+ if not dates.empty:
135
+ result["decision_as_of"] = str(dates.loc[month.ne(month.shift())].iloc[-1].date())
136
+ values = [component["log_return"] for component in result["components"]]
137
+ if any(value is None for value in values):
138
+ result["unavailable_reason"] = "insufficient_history_at_monthly_observation"
139
+ return result
140
+ positive = sum(value > 0 for value in values)
141
+ negative = sum(value < 0 for value in values)
142
+ result.update(positive_count=positive, negative_count=negative, neutral_count=3 - positive - negative)
143
+ result["direction"] = (
144
+ "up" if positive >= 2 else "down" if negative >= 2 else "flat" if not positive + negative else "mixed"
145
+ )
146
+ return result
147
+
148
+
149
+ def trend_score_series(df: pd.DataFrame, fast: int = 20, slow: int = 60, atr_period: int = 14) -> pd.Series:
150
+ """Causal EMA spread / SMA true range; an independent, uncalibrated research baseline."""
151
+ if any(isinstance(n, bool) or not isinstance(n, int) or n < 1 for n in (fast, slow, atr_period)) or fast >= slow:
152
+ raise ValueError("trend_score requires positive integer periods and fast_period < slow_period")
153
+ if any(field not in df for field in ("high", "low", "close")):
154
+ raise ValueError("trend_score requires high, low and close")
155
+ prices = df[["high", "low", "close"]].apply(pd.to_numeric, errors="coerce")
156
+ if not np.isfinite(prices).all().all() or (prices <= 0).any().any():
157
+ raise ValueError("trend_score requires finite positive prices")
158
+ high, low, close = prices["high"], prices["low"], prices["close"]
159
+ if ((low > close) | (close > high)).any():
160
+ raise ValueError("trend_score requires low <= close <= high")
161
+ if "date" in df:
162
+ dates = pd.to_datetime(df["date"], errors="coerce")
163
+ if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
164
+ raise ValueError("trend_score dates must be valid, unique and increasing")
165
+ if "adjusted" in df and df["adjusted"].fillna("unknown").astype(str).nunique() > 1:
166
+ raise ValueError("trend_score requires a consistent adjustment basis")
167
+ previous = close.shift(1)
168
+ true_range = pd.concat([high - low, (high - previous).abs(), (low - previous).abs()], axis=1).max(
169
+ axis=1, skipna=False
170
+ )
171
+ atr = true_range.rolling(atr_period).mean()
172
+ score = (ema_series(close, fast) - ema_series(close, slow)) / atr.replace(0, np.nan)
173
+ return score.where(np.arange(len(df)) >= max(slow, atr_period + 1) - 1).replace([np.inf, -np.inf], np.nan)
174
+
175
+
176
+ def calc_trend_temperature(df: pd.DataFrame) -> dict:
177
+ thresholds = [0.5, 1.5, 3.0]
178
+ result = {
179
+ "model": "ema_atr",
180
+ "experimental": True,
181
+ "validation_status": "not_validated",
182
+ "parameters": {"fast_period": 20, "slow_period": 60, "atr_period": 14, "atr_method": "sma_true_range"},
183
+ "thresholds": thresholds,
184
+ "price_basis": str(df["adjusted"].iloc[-1])
185
+ if "adjusted" in df and pd.notna(df["adjusted"].iloc[-1])
186
+ else "unknown",
187
+ "history_start": str(df["date"].iloc[0].date()),
188
+ "score": None,
189
+ "state": None,
190
+ "direction": None,
191
+ "previous_score": None,
192
+ "previous_state": None,
193
+ "previous_direction": None,
194
+ "transition": None,
195
+ "as_of": str(df["date"].iloc[-1].date()),
196
+ "previous_as_of": str(df["date"].iloc[-2].date()) if len(df) > 1 else None,
197
+ "unavailable_reason": None,
198
+ "warnings": [
199
+ "Independent research baseline, not Trend Animal temperature or a Taleb fat-tail metric. "
200
+ "Thresholds are uncalibrated, not probabilities or automatic trade signals. "
201
+ "State labels are not entry rules; direction is only the EMA-spread sign. "
202
+ "EMA initialization depends on the supplied history; periods count bars, not calendar days. "
203
+ "Verify the latest bar is closed and the OHLC adjustment basis is consistent."
204
+ ],
205
+ }
206
+ try:
207
+ scores = trend_score_series(df)
208
+ except ValueError as exc:
209
+ result["unavailable_reason"] = str(exc)
210
+ return result
211
+ for prefix, idx in (("", -1), ("previous_", -2)):
212
+ if len(scores) < abs(idx) or not np.isfinite(scores.iloc[idx]):
213
+ continue
214
+ value = float(scores.iloc[idx])
215
+ magnitude = sum(abs(value) > threshold for threshold in thresholds)
216
+ result[f"{prefix}score"] = value
217
+ result[f"{prefix}direction"] = "up" if value > 0 else "down" if value < 0 else "flat"
218
+ result[f"{prefix}state"] = (("平", "温", "热", "沸") if value >= 0 else ("平", "凉", "寒", "冻"))[magnitude]
219
+ if result["score"] is None:
220
+ result["unavailable_reason"] = "insufficient_history" if len(df) < 60 else "zero_or_nonfinite_atr_or_score"
221
+ elif result["previous_state"] is not None and result["previous_state"] != result["state"]:
222
+ result["transition"] = f"{result['previous_state']}→{result['state']}"
223
+ return result
224
+
225
+
50
226
  def macd_series(close: pd.Series) -> tuple:
51
227
  """Full (dif, dea, macd) series: dif = EMA12-EMA26, dea = EMA9(dif), macd = 2*(dif-dea)."""
52
228
  dif = ema_series(close, 12) - ema_series(close, 26)
@@ -599,6 +775,14 @@ def _period_summary(result: dict) -> dict:
599
775
  return {
600
776
  "period": result["period"],
601
777
  "trend_overall": result["trend"]["overall"],
778
+ "trend_score": result["trend_temperature"]["score"],
779
+ "trend_temperature_state": result["trend_temperature"]["state"],
780
+ "trend_temperature_direction": result["trend_temperature"]["direction"],
781
+ "trend_temperature_validation_status": result["trend_temperature"]["validation_status"],
782
+ "trend_temperature_as_of": result["trend_temperature"]["as_of"],
783
+ "trend_temperature_price_basis": result["trend_temperature"]["price_basis"],
784
+ "trend_temperature_unavailable_reason": result["trend_temperature"]["unavailable_reason"],
785
+ "trend_horizons": result["trend_horizons"],
602
786
  "ma_arrangement": result["moving_averages"]["ma_arrangement"],
603
787
  "macd_signal": result["macd"]["signal"],
604
788
  "rsi_signal": result["rsi"]["signal"],
@@ -697,6 +881,8 @@ def analyze_records(symbol: str, records: list, period: str = "daily") -> dict:
697
881
  "volume": vol_data,
698
882
  "support_resistance": sr_data,
699
883
  "trend": trend_data,
884
+ "trend_temperature": calc_trend_temperature(df),
885
+ "trend_horizons": calc_trend_horizons(df, period),
700
886
  "bias": bias_data,
701
887
  "signal_score": score_data["signal_score"],
702
888
  "buy_signal": score_data["buy_signal"],