@weaxs/openclaw-stock-analysis 0.1.15 → 0.2.1

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.
@@ -14,7 +14,21 @@ def _is_weekend(d: datetime) -> bool:
14
14
  return d.weekday() >= 5
15
15
 
16
16
 
17
- def _cn_holidays(year: int) -> set[str]:
17
+ # Process-local memo: one CLI call = one process, and the CN path
18
+ # (is_trading_day / the prev|next_trading_days walk-back) would otherwise
19
+ # re-fetch the sina calendar per step — up to ~5 fetches for one stale check.
20
+ _CN_TRADE_DATES: dict[int, set[str]] = {}
21
+
22
+
23
+ def cn_trade_dates(year: int) -> set[str]:
24
+ """CN trading dates (YYYY-MM-DD) for `year` from the sina trade-date history.
25
+
26
+ Empty set when the calendar can't be fetched (failures are not cached — the
27
+ next call retries); callers treat empty as "weekends are the only non-trading
28
+ days"."""
29
+ cached = _CN_TRADE_DATES.get(year)
30
+ if cached is not None:
31
+ return cached
18
32
  try:
19
33
  import akshare as ak
20
34
 
@@ -25,9 +39,11 @@ def _cn_holidays(year: int) -> set[str]:
25
39
  d = str(val)[:10]
26
40
  if d.startswith(str(year)):
27
41
  dates.add(d)
28
- return dates
29
42
  except Exception:
30
43
  return set()
44
+ if dates:
45
+ _CN_TRADE_DATES[year] = dates
46
+ return dates
31
47
 
32
48
 
33
49
  def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
@@ -39,10 +55,6 @@ def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
39
55
  return cal.is_session(d)
40
56
 
41
57
 
42
- def _get_cn_trading_dates(year: int) -> set[str]:
43
- return _cn_holidays(year)
44
-
45
-
46
58
  def is_trading_day(market: str, date_str: str = None) -> dict:
47
59
  if date_str:
48
60
  d = datetime.strptime(date_str, "%Y-%m-%d")
@@ -56,7 +68,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
56
68
  return {"date": date_str, "market": market, "is_trading_day": False, "reason": "weekend"}
57
69
 
58
70
  if market == "CN":
59
- trading_dates = _get_cn_trading_dates(d.year)
71
+ trading_dates = cn_trade_dates(d.year)
60
72
  if trading_dates:
61
73
  is_td = date_str in trading_dates
62
74
  return {
@@ -84,7 +96,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
84
96
  }
85
97
  except Exception:
86
98
  pass
87
- trading_dates = _get_cn_trading_dates(d.year)
99
+ trading_dates = cn_trade_dates(d.year)
88
100
  if trading_dates:
89
101
  is_td = date_str in trading_dates
90
102
  return {
@@ -179,6 +191,87 @@ def cmd_check(args):
179
191
  return is_trading_day(args.market, args.date)
180
192
 
181
193
 
194
+ # --------------- market phase (trading sessions, market-local time) ---------------
195
+
196
+ # exchange-calendars codes for the six supported markets. Session times and the
197
+ # timezone come from the calendar itself (hard dependency) — no hand-maintained
198
+ # tables to drift out of date (e.g. TSE extended its close to 15:30 in 2024-11).
199
+ _PHASE_CALENDAR = {"CN": "XSHG", "HK": "XHKG", "US": "XNYS", "JP": "XTKS", "KR": "XKRX", "TW": "XTAI"}
200
+
201
+
202
+ def _market_sessions(market: str):
203
+ """(tz, [("HH:MM", "HH:MM"), ...]) for the market's current regular sessions,
204
+ read off the exchange calendar. Markets without a lunch break get one session."""
205
+ import exchange_calendars as xcals
206
+
207
+ cal = xcals.get_calendar(_PHASE_CALENDAR[market])
208
+ open_t, close_t = cal.open_times[-1][1], cal.close_times[-1][1]
209
+ # break_start_times is None for never-broken calendars (XNYS), and its last
210
+ # entry carries None where the break was dropped (XKRX, 2000) — only a real
211
+ # time means lunch
212
+ breaks = cal.break_start_times
213
+ last_break = breaks[-1][1] if breaks else None
214
+ if last_break is not None:
215
+ sessions = [
216
+ (open_t.strftime("%H:%M"), last_break.strftime("%H:%M")),
217
+ (cal.break_end_times[-1][1].strftime("%H:%M"), close_t.strftime("%H:%M")),
218
+ ]
219
+ else:
220
+ sessions = [(open_t.strftime("%H:%M"), close_t.strftime("%H:%M"))]
221
+ return cal.tz, sessions
222
+
223
+
224
+ def market_phase(market: str, at: str = None) -> dict:
225
+ """Trading phase of a market at a market-local time (`at` = "YYYY-MM-DDTHH:MM:SS")."""
226
+ market = market.upper()
227
+ if market not in _PHASE_CALENDAR:
228
+ return {"market": market, "error": f"Unknown market: {market}"}
229
+ try:
230
+ tz, sessions = _market_sessions(market)
231
+ except Exception as e:
232
+ return {"market": market, "error": f"exchange calendar unavailable: {e}"}
233
+ try:
234
+ naive = datetime.strptime(at, "%Y-%m-%dT%H:%M:%S") if at else None
235
+ except ValueError as e:
236
+ return {"market": market, "error": f"invalid --at (want YYYY-MM-DDTHH:MM:SS): {e}"}
237
+ local = datetime.now(tz) if naive is None else naive.replace(tzinfo=tz)
238
+ date_str = local.strftime("%Y-%m-%d")
239
+ is_td = bool(is_trading_day(market, date_str).get("is_trading_day"))
240
+ hm = local.strftime("%H:%M")
241
+ if not is_td:
242
+ phase, label = "closed", "休市"
243
+ elif len(sessions) > 1:
244
+ (m_open, m_close), (a_open, a_close) = sessions
245
+ if hm < m_open:
246
+ phase, label = "pre_market", "盘前"
247
+ elif hm <= m_close:
248
+ phase, label = "morning", "早盘"
249
+ elif hm < a_open:
250
+ phase, label = "lunch_break", "午间休市"
251
+ elif hm <= a_close:
252
+ phase, label = "afternoon", "午盘"
253
+ else:
254
+ phase, label = "post_market", "盘后"
255
+ else:
256
+ s_open, s_close = sessions[0]
257
+ if hm < s_open:
258
+ phase, label = "pre_market", "盘前"
259
+ elif hm <= s_close:
260
+ phase, label = "intraday", "交易中"
261
+ else:
262
+ phase, label = "post_market", "盘后"
263
+ return {
264
+ "market": market,
265
+ "date": date_str,
266
+ "local_time": local.strftime("%Y-%m-%dT%H:%M:%S"),
267
+ "timezone": str(tz),
268
+ "is_trading_day": is_td,
269
+ "phase": phase,
270
+ "phase_label": label,
271
+ "sessions": sessions,
272
+ }
273
+
274
+
182
275
  def cmd_next(args):
183
276
  days = next_trading_days(args.market, args.count, args.date)
184
277
  return {"market": args.market, "next_trading_days": days}
@@ -189,6 +282,10 @@ def cmd_prev(args):
189
282
  return {"market": args.market, "prev_trading_days": days}
190
283
 
191
284
 
285
+ def cmd_phase(args):
286
+ return market_phase(args.market, args.at)
287
+
288
+
192
289
  def main():
193
290
  parser = argparse.ArgumentParser(description="Trading calendar")
194
291
  sub = parser.add_subparsers(dest="command")
@@ -207,12 +304,16 @@ def main():
207
304
  p_prev.add_argument("--count", type=int, default=5)
208
305
  p_prev.add_argument("--date", default=None)
209
306
 
307
+ p_phase = sub.add_parser("phase")
308
+ p_phase.add_argument("market", type=str.upper, choices=MARKETS)
309
+ p_phase.add_argument("--at", default=None, help='Market-local time "YYYY-MM-DDTHH:MM:SS" (default: now)')
310
+
210
311
  args = parser.parse_args()
211
312
  if not args.command:
212
313
  parser.print_help()
213
314
  sys.exit(1)
214
315
 
215
- dispatch = {"check": cmd_check, "next": cmd_next, "prev": cmd_prev}
316
+ dispatch = {"check": cmd_check, "next": cmd_next, "prev": cmd_prev, "phase": cmd_phase}
216
317
  result = dispatch[args.command](args)
217
318
  print(json.dumps(result, ensure_ascii=False, default=str))
218
319
 
@@ -3,34 +3,14 @@
3
3
 
4
4
  import argparse
5
5
  import json
6
- import os
7
- import subprocess
8
6
  import sys
7
+ from pathlib import Path
9
8
 
10
9
  import numpy as np
11
- import pandas as pd
12
10
 
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
13
12
 
14
- def fetch_kline(symbol: str, period: str = "daily", count: int = 60) -> list:
15
- script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
16
- r = subprocess.run(
17
- [sys.executable, script, "kline", symbol, "--period", period, "--count", str(count)],
18
- capture_output=True,
19
- text=True,
20
- encoding="utf-8",
21
- )
22
- return json.loads(r.stdout)
23
-
24
-
25
- def to_dataframe(records: list) -> pd.DataFrame:
26
- df = pd.DataFrame(records)
27
- for c in ["open", "high", "low", "close", "volume"]:
28
- if c in df.columns:
29
- df[c] = pd.to_numeric(df[c], errors="coerce")
30
- if "date" in df.columns:
31
- df["date"] = pd.to_datetime(df["date"], errors="coerce")
32
- df = df.sort_values("date").reset_index(drop=True)
33
- return df
13
+ from technical import fetch_kline, to_dataframe # noqa: E402
34
14
 
35
15
 
36
16
  def analyze_volume(symbol: str, period: str = "daily", count: int = 60) -> dict:
@@ -18,15 +18,6 @@ from stock_data import detect_market # noqa: E402
18
18
  from watchlist import analyze_watchlist # noqa: E402
19
19
 
20
20
 
21
- def _trend_label(overall: str) -> str:
22
- return {
23
- "bullish": "bullish",
24
- "bearish": "bearish",
25
- "neutral": "neutral",
26
- "mixed": "mixed",
27
- }.get(overall, overall or "unknown")
28
-
29
-
30
21
  def _suggest_next_tools(market: str, trend: str, anomalies: list, risk_level: str) -> list:
31
22
  tools = []
32
23
  high_anoms = [a for a in anomalies if a.get("severity") == "high"]
@@ -58,7 +49,7 @@ def _build_item(symbol: str, data: dict | None) -> dict:
58
49
  anomalies = anom_result.get("anomalies", []) if isinstance(anom_result, dict) else []
59
50
 
60
51
  score = tech.get("signal_score")
61
- trend = _trend_label((tech.get("trend") or {}).get("overall", ""))
52
+ trend = (tech.get("trend") or {}).get("overall") or "unknown"
62
53
  risk_level = risk.get("risk_level", "unknown")
63
54
  veto = bool(risk.get("veto_buy", False))
64
55
  buy_signal = tech.get("buy_signal")
@@ -1,56 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Sync all manifest version fields to the version derived from the current
3
- # git tag ($GITHUB_REF_NAME on GitHub Actions, e.g. "v0.1.5" → "0.1.5").
4
- #
5
- # Called by .github/workflows/publish.yml before each publish step. Changes
6
- # are in-CI only — never committed back to the repo.
7
- #
8
- # Manifests updated:
9
- # - pyproject.toml (PyPI package version)
10
- # - package.json (npm root package)
11
- # - package-lock.json (kept in lockstep so `npm publish` doesn't warn)
12
- # - openclaw/package.json (OpenClaw npm package version)
13
- # - dsh/package.json (dsh npm package version)
14
- #
15
- # Idempotent: running twice with the same tag is a no-op.
16
- set -euo pipefail
17
-
18
- TAG="${1:-${GITHUB_REF_NAME:-}}"
19
- if [[ -z "$TAG" ]]; then
20
- echo "usage: $0 <tag> (or set GITHUB_REF_NAME)" >&2
21
- exit 1
22
- fi
23
- VERSION="${TAG#v}"
24
-
25
- # Basic shape check — semver-ish, e.g. 0.1.5 or 1.2.3-rc.1
26
- if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][A-Za-z0-9.]+)?$ ]]; then
27
- echo "sync-version: unexpected tag shape '$TAG' → version '$VERSION'" >&2
28
- exit 1
29
- fi
30
-
31
- echo "sync-version: setting version to $VERSION (from tag $TAG)"
32
-
33
- # pyproject.toml — the only `version = "..."` at file scope
34
- python3 - "$VERSION" <<'PY'
35
- import re, sys, pathlib
36
- version = sys.argv[1]
37
- p = pathlib.Path("pyproject.toml")
38
- text = p.read_text()
39
- new, n = re.subn(r'^version = "[^"]+"', f'version = "{version}"', text, count=1, flags=re.M)
40
- if n != 1:
41
- sys.exit(f"pyproject.toml: expected one version = line, got {n}")
42
- p.write_text(new)
43
- print(f" pyproject.toml: {n} substitution(s)")
44
- PY
45
-
46
- # npm root and host sub-packages
47
- # `npm version` refuses in a workspace unless we bypass with --no-git-tag-version
48
- # --allow-same-version keeps it idempotent when the tag already matches.
49
- for dir in "." "openclaw" "dsh"; do
50
- if [[ -f "$dir/package.json" ]]; then
51
- (cd "$dir" && npm version "$VERSION" --no-git-tag-version --allow-same-version) >/dev/null
52
- echo " $dir/package.json: bumped"
53
- fi
54
- done
55
-
56
- echo "sync-version: done"