@weaxs/openclaw-stock-analysis 0.1.15 → 0.2.0

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.
@@ -39,10 +39,6 @@ def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
39
39
  return cal.is_session(d)
40
40
 
41
41
 
42
- def _get_cn_trading_dates(year: int) -> set[str]:
43
- return _cn_holidays(year)
44
-
45
-
46
42
  def is_trading_day(market: str, date_str: str = None) -> dict:
47
43
  if date_str:
48
44
  d = datetime.strptime(date_str, "%Y-%m-%d")
@@ -56,7 +52,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
56
52
  return {"date": date_str, "market": market, "is_trading_day": False, "reason": "weekend"}
57
53
 
58
54
  if market == "CN":
59
- trading_dates = _get_cn_trading_dates(d.year)
55
+ trading_dates = _cn_holidays(d.year)
60
56
  if trading_dates:
61
57
  is_td = date_str in trading_dates
62
58
  return {
@@ -84,7 +80,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
84
80
  }
85
81
  except Exception:
86
82
  pass
87
- trading_dates = _get_cn_trading_dates(d.year)
83
+ trading_dates = _cn_holidays(d.year)
88
84
  if trading_dates:
89
85
  is_td = date_str in trading_dates
90
86
  return {
@@ -179,6 +175,87 @@ def cmd_check(args):
179
175
  return is_trading_day(args.market, args.date)
180
176
 
181
177
 
178
+ # --------------- market phase (trading sessions, market-local time) ---------------
179
+
180
+ # exchange-calendars codes for the six supported markets. Session times and the
181
+ # timezone come from the calendar itself (hard dependency) — no hand-maintained
182
+ # tables to drift out of date (e.g. TSE extended its close to 15:30 in 2024-11).
183
+ _PHASE_CALENDAR = {"CN": "XSHG", "HK": "XHKG", "US": "XNYS", "JP": "XTKS", "KR": "XKRX", "TW": "XTAI"}
184
+
185
+
186
+ def _market_sessions(market: str):
187
+ """(tz, [("HH:MM", "HH:MM"), ...]) for the market's current regular sessions,
188
+ read off the exchange calendar. Markets without a lunch break get one session."""
189
+ import exchange_calendars as xcals
190
+
191
+ cal = xcals.get_calendar(_PHASE_CALENDAR[market])
192
+ open_t, close_t = cal.open_times[-1][1], cal.close_times[-1][1]
193
+ # break_start_times is None for never-broken calendars (XNYS), and its last
194
+ # entry carries None where the break was dropped (XKRX, 2000) — only a real
195
+ # time means lunch
196
+ breaks = cal.break_start_times
197
+ last_break = breaks[-1][1] if breaks else None
198
+ if last_break is not None:
199
+ sessions = [
200
+ (open_t.strftime("%H:%M"), last_break.strftime("%H:%M")),
201
+ (cal.break_end_times[-1][1].strftime("%H:%M"), close_t.strftime("%H:%M")),
202
+ ]
203
+ else:
204
+ sessions = [(open_t.strftime("%H:%M"), close_t.strftime("%H:%M"))]
205
+ return cal.tz, sessions
206
+
207
+
208
+ def market_phase(market: str, at: str = None) -> dict:
209
+ """Trading phase of a market at a market-local time (`at` = "YYYY-MM-DDTHH:MM:SS")."""
210
+ market = market.upper()
211
+ if market not in _PHASE_CALENDAR:
212
+ return {"market": market, "error": f"Unknown market: {market}"}
213
+ try:
214
+ tz, sessions = _market_sessions(market)
215
+ except Exception as e:
216
+ return {"market": market, "error": f"exchange calendar unavailable: {e}"}
217
+ try:
218
+ naive = datetime.strptime(at, "%Y-%m-%dT%H:%M:%S") if at else None
219
+ except ValueError as e:
220
+ return {"market": market, "error": f"invalid --at (want YYYY-MM-DDTHH:MM:SS): {e}"}
221
+ local = datetime.now(tz) if naive is None else naive.replace(tzinfo=tz)
222
+ date_str = local.strftime("%Y-%m-%d")
223
+ is_td = bool(is_trading_day(market, date_str).get("is_trading_day"))
224
+ hm = local.strftime("%H:%M")
225
+ if not is_td:
226
+ phase, label = "closed", "休市"
227
+ elif len(sessions) > 1:
228
+ (m_open, m_close), (a_open, a_close) = sessions
229
+ if hm < m_open:
230
+ phase, label = "pre_market", "盘前"
231
+ elif hm <= m_close:
232
+ phase, label = "morning", "早盘"
233
+ elif hm < a_open:
234
+ phase, label = "lunch_break", "午间休市"
235
+ elif hm <= a_close:
236
+ phase, label = "afternoon", "午盘"
237
+ else:
238
+ phase, label = "post_market", "盘后"
239
+ else:
240
+ s_open, s_close = sessions[0]
241
+ if hm < s_open:
242
+ phase, label = "pre_market", "盘前"
243
+ elif hm <= s_close:
244
+ phase, label = "intraday", "交易中"
245
+ else:
246
+ phase, label = "post_market", "盘后"
247
+ return {
248
+ "market": market,
249
+ "date": date_str,
250
+ "local_time": local.strftime("%Y-%m-%dT%H:%M:%S"),
251
+ "timezone": str(tz),
252
+ "is_trading_day": is_td,
253
+ "phase": phase,
254
+ "phase_label": label,
255
+ "sessions": sessions,
256
+ }
257
+
258
+
182
259
  def cmd_next(args):
183
260
  days = next_trading_days(args.market, args.count, args.date)
184
261
  return {"market": args.market, "next_trading_days": days}
@@ -189,6 +266,10 @@ def cmd_prev(args):
189
266
  return {"market": args.market, "prev_trading_days": days}
190
267
 
191
268
 
269
+ def cmd_phase(args):
270
+ return market_phase(args.market, args.at)
271
+
272
+
192
273
  def main():
193
274
  parser = argparse.ArgumentParser(description="Trading calendar")
194
275
  sub = parser.add_subparsers(dest="command")
@@ -207,12 +288,16 @@ def main():
207
288
  p_prev.add_argument("--count", type=int, default=5)
208
289
  p_prev.add_argument("--date", default=None)
209
290
 
291
+ p_phase = sub.add_parser("phase")
292
+ p_phase.add_argument("market", type=str.upper, choices=MARKETS)
293
+ p_phase.add_argument("--at", default=None, help='Market-local time "YYYY-MM-DDTHH:MM:SS" (default: now)')
294
+
210
295
  args = parser.parse_args()
211
296
  if not args.command:
212
297
  parser.print_help()
213
298
  sys.exit(1)
214
299
 
215
- dispatch = {"check": cmd_check, "next": cmd_next, "prev": cmd_prev}
300
+ dispatch = {"check": cmd_check, "next": cmd_next, "prev": cmd_prev, "phase": cmd_phase}
216
301
  result = dispatch[args.command](args)
217
302
  print(json.dumps(result, ensure_ascii=False, default=str))
218
303
 
@@ -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"