openclaw-stock-analysis 0.2.13 → 0.2.14
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.
- package/package.json +3 -3
- package/tools/screener.py +1 -1
- package/tools/stock_data.py +90 -67
- package/tools/value_data.py +2 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openclaw-stock-analysis",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.14",
|
|
4
4
|
"description": "OpenClaw plugin for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.ts",
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
"minGatewayVersion": "2026.3.24-beta.2"
|
|
14
14
|
},
|
|
15
15
|
"build": {
|
|
16
|
-
"openclawVersion": "2026.11.
|
|
17
|
-
"pluginSdkVersion": "2026.11.
|
|
16
|
+
"openclawVersion": "2026.11.5",
|
|
17
|
+
"pluginSdkVersion": "2026.11.5"
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
package/tools/screener.py
CHANGED
|
@@ -374,7 +374,7 @@ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict
|
|
|
374
374
|
pool.shutdown(wait=False)
|
|
375
375
|
snapshot = fetch_snapshot(market, filters)
|
|
376
376
|
if isinstance(snapshot, dict) and "error" in snapshot:
|
|
377
|
-
return snapshot
|
|
377
|
+
return {**snapshot, "market": market}
|
|
378
378
|
if not isinstance(snapshot, dict) or not isinstance(snapshot.get("rows"), list):
|
|
379
379
|
return {"error": "failed to fetch market snapshot", "market": market}
|
|
380
380
|
|
package/tools/stock_data.py
CHANGED
|
@@ -362,12 +362,16 @@ def _tencent_us_code(symbol: str) -> str:
|
|
|
362
362
|
return "us" + symbol.upper().replace("-", ".")
|
|
363
363
|
|
|
364
364
|
|
|
365
|
-
def
|
|
365
|
+
def _tencent_raw(codes: str) -> bytes:
|
|
366
366
|
import requests
|
|
367
367
|
|
|
368
|
-
resp = requests.get(f"https://qt.gtimg.cn/q={
|
|
368
|
+
resp = requests.get(f"https://qt.gtimg.cn/q={codes}", timeout=10)
|
|
369
369
|
resp.raise_for_status()
|
|
370
|
-
return
|
|
370
|
+
return resp.content
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _tencent_fields(code: str) -> list:
|
|
374
|
+
return _gbk_var_payload(_tencent_raw(code)).split("~")
|
|
371
375
|
|
|
372
376
|
|
|
373
377
|
def _quote_tencent(symbol: str) -> dict:
|
|
@@ -626,17 +630,32 @@ def _kline_akshare(symbol: str, period: str, count: int) -> list:
|
|
|
626
630
|
return [_clean_row(r) for r in df.to_dict("records")]
|
|
627
631
|
|
|
628
632
|
|
|
629
|
-
def
|
|
630
|
-
"""
|
|
633
|
+
def _tushare(api_name: str, params: dict, fields: str | None = None, error: str = "tushare returned no data"):
|
|
634
|
+
"""POST one tushare HTTP API call; returns (fields, items) or raises with the API message."""
|
|
631
635
|
import os
|
|
632
636
|
|
|
633
|
-
import pandas as pd
|
|
634
637
|
import requests
|
|
635
638
|
|
|
636
639
|
token = os.environ.get("TUSHARE_TOKEN")
|
|
637
640
|
if not token:
|
|
638
641
|
raise ValueError("TUSHARE_TOKEN not set")
|
|
642
|
+
body = {"api_name": api_name, "token": token, "params": params}
|
|
643
|
+
if fields:
|
|
644
|
+
body["fields"] = fields
|
|
645
|
+
data = requests.post("http://api.tushare.pro", json=body, timeout=15).json()
|
|
646
|
+
if data.get("code") != 0 or not data.get("data", {}).get("items"):
|
|
647
|
+
raise ValueError(f"{error}: {data.get('msg', '')}")
|
|
648
|
+
return data["data"]["fields"], data["data"]["items"]
|
|
639
649
|
|
|
650
|
+
|
|
651
|
+
def _kline_tushare(symbol: str, period: str, count: int) -> list:
|
|
652
|
+
"""Tushare qfq kline via daily factors or the adjusted week/month endpoint."""
|
|
653
|
+
import os
|
|
654
|
+
|
|
655
|
+
import pandas as pd
|
|
656
|
+
|
|
657
|
+
if not os.environ.get("TUSHARE_TOKEN"):
|
|
658
|
+
raise ValueError("TUSHARE_TOKEN not set")
|
|
640
659
|
if normalize_stock_code(symbol)["is_etf"]:
|
|
641
660
|
raise ValueError("tushare stock adjustment does not cover ETFs")
|
|
642
661
|
end = _cn_now()
|
|
@@ -653,33 +672,17 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
|
|
|
653
672
|
params["freq"] = "week" if period == "weekly" else "month"
|
|
654
673
|
fields = prices if period == "daily" else [f"{c}_qfq" for c in prices]
|
|
655
674
|
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
"api_name": "daily" if period == "daily" else "stk_week_month_adj",
|
|
660
|
-
"token": token,
|
|
661
|
-
"params": params,
|
|
662
|
-
"fields": ",".join(["trade_date", *fields, "vol", "amount", "pct_chg"]),
|
|
663
|
-
},
|
|
664
|
-
timeout=15,
|
|
665
|
-
)
|
|
666
|
-
data = resp.json()
|
|
667
|
-
if data.get("code") != 0 or not data.get("data", {}).get("items"):
|
|
668
|
-
raise ValueError(f"tushare returned no data: {data.get('msg', '')}")
|
|
669
|
-
|
|
670
|
-
df = pd.DataFrame(data["data"]["items"], columns=data["data"]["fields"])
|
|
675
|
+
api = "daily" if period == "daily" else "stk_week_month_adj"
|
|
676
|
+
columns, items = _tushare(api, params, ",".join(["trade_date", *fields, "vol", "amount", "pct_chg"]))
|
|
677
|
+
df = pd.DataFrame(items, columns=columns)
|
|
671
678
|
if not set(fields).issubset(df.columns):
|
|
672
679
|
raise ValueError("tushare returned incomplete adjusted prices")
|
|
673
680
|
df[fields] = df[fields].apply(pd.to_numeric, errors="coerce")
|
|
674
681
|
if period == "daily":
|
|
675
|
-
|
|
676
|
-
"
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
).json()
|
|
680
|
-
if factor_resp.get("code") != 0 or not factor_resp.get("data", {}).get("items"):
|
|
681
|
-
raise ValueError("tushare returned no adjustment factors")
|
|
682
|
-
factors = pd.DataFrame(factor_resp["data"]["items"], columns=factor_resp["data"]["fields"])
|
|
682
|
+
columns, items = _tushare(
|
|
683
|
+
"adj_factor", params, "trade_date,adj_factor", "tushare returned no adjustment factors"
|
|
684
|
+
)
|
|
685
|
+
factors = pd.DataFrame(items, columns=columns)
|
|
683
686
|
factors["adj_factor"] = pd.to_numeric(factors["adj_factor"], errors="coerce")
|
|
684
687
|
if not (factors["adj_factor"].gt(0) & factors["adj_factor"].lt(float("inf"))).all():
|
|
685
688
|
raise ValueError("tushare returned invalid adjustment factors")
|
|
@@ -713,30 +716,10 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
|
|
|
713
716
|
|
|
714
717
|
def _quote_tushare(symbol: str) -> dict:
|
|
715
718
|
"""Tushare realtime quote via HTTP API."""
|
|
716
|
-
import os
|
|
717
|
-
|
|
718
|
-
import requests
|
|
719
|
-
|
|
720
|
-
token = os.environ.get("TUSHARE_TOKEN")
|
|
721
|
-
if not token:
|
|
722
|
-
raise ValueError("TUSHARE_TOKEN not set")
|
|
723
|
-
|
|
724
719
|
ts_code = f"{symbol}.SH" if symbol.startswith(("6", "9", "5")) else f"{symbol}.SZ"
|
|
725
720
|
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
json={
|
|
729
|
-
"api_name": "realtime_quote",
|
|
730
|
-
"token": token,
|
|
731
|
-
"params": {"ts_code": ts_code},
|
|
732
|
-
},
|
|
733
|
-
timeout=15,
|
|
734
|
-
)
|
|
735
|
-
data = resp.json()
|
|
736
|
-
if data.get("code") != 0 or not data.get("data", {}).get("items"):
|
|
737
|
-
raise ValueError(f"tushare quote failed: {data.get('msg', '')}")
|
|
738
|
-
|
|
739
|
-
row = dict(zip(data["data"]["fields"], data["data"]["items"][0]))
|
|
721
|
+
columns, items = _tushare("realtime_quote", {"ts_code": ts_code}, error="tushare quote failed")
|
|
722
|
+
row = dict(zip(columns, items[0]))
|
|
740
723
|
return _clean_row(
|
|
741
724
|
{
|
|
742
725
|
"symbol": symbol,
|
|
@@ -1521,16 +1504,21 @@ def _fund_nav_date(stamp) -> str:
|
|
|
1521
1504
|
return datetime.fromtimestamp(stamp / 1000, timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
1522
1505
|
|
|
1523
1506
|
|
|
1507
|
+
def fund_pingzhong_js(symbol: str) -> str:
|
|
1508
|
+
"""Eastmoney's per-fund JS bundle (NAV, scale, holdings series)."""
|
|
1509
|
+
import requests
|
|
1510
|
+
|
|
1511
|
+
response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15)
|
|
1512
|
+
response.raise_for_status()
|
|
1513
|
+
return response.text
|
|
1514
|
+
|
|
1515
|
+
|
|
1524
1516
|
def cmd_fund_quote(args):
|
|
1525
1517
|
symbol = args.symbol
|
|
1526
1518
|
if not re.fullmatch(r"\d{6}", symbol):
|
|
1527
1519
|
return {"error": "open-end fund symbol must be exactly 6 digits"}
|
|
1528
1520
|
try:
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15)
|
|
1532
|
-
response.raise_for_status()
|
|
1533
|
-
text = response.text
|
|
1521
|
+
text = fund_pingzhong_js(symbol)
|
|
1534
1522
|
if _fund_js_value(text, "fS_code") != symbol:
|
|
1535
1523
|
raise ValueError(f"eastmoney returned a different fund for {symbol}")
|
|
1536
1524
|
name = _fund_js_value(text, "fS_name")
|
|
@@ -2262,6 +2250,45 @@ def _snapshot_clist(market: str, floor: float):
|
|
|
2262
2250
|
return total, rows
|
|
2263
2251
|
|
|
2264
2252
|
|
|
2253
|
+
# Non-eastmoney HK/US leg: TradingView's public scanner, same columns as _CLIST_SNAPSHOT_COLUMNS.
|
|
2254
|
+
_TV_BASE = ["name", "description", "close", "change", "volume", "Value.Traded", "price_earnings_ttm"]
|
|
2255
|
+
_TV_SNAPSHOT_COLUMNS = {
|
|
2256
|
+
"HK": ("hongkong", [*_TV_BASE, "price_book_fq", "market_cap_basic"]),
|
|
2257
|
+
"US": ("america", [*_TV_BASE, "market_cap_basic"]),
|
|
2258
|
+
}
|
|
2259
|
+
_TV_KEYS = {"close": "price", "change": "change_pct", "Value.Traded": "turnover"}
|
|
2260
|
+
_TV_KEYS |= {"price_earnings_ttm": "pe", "price_book_fq": "pb", "market_cap_basic": "market_cap"}
|
|
2261
|
+
|
|
2262
|
+
|
|
2263
|
+
def _snapshot_tradingview(market: str, floor: float):
|
|
2264
|
+
import requests
|
|
2265
|
+
|
|
2266
|
+
region, columns = _TV_SNAPSHOT_COLUMNS[market]
|
|
2267
|
+
filters = [{"left": "type", "operation": "equal", "right": "stock"}]
|
|
2268
|
+
filters += [{"left": "is_primary", "operation": "equal", "right": True}]
|
|
2269
|
+
rows, total = [], None
|
|
2270
|
+
while len(rows) < _SNAPSHOT_MAX_ROWS:
|
|
2271
|
+
body = {"columns": columns, "filter": filters, "range": [len(rows), len(rows) + 1000]}
|
|
2272
|
+
body["sort"] = {"sortBy": "market_cap_basic", "sortOrder": "desc"}
|
|
2273
|
+
resp = requests.post(f"https://scanner.tradingview.com/{region}/scan", json=body, timeout=15)
|
|
2274
|
+
resp.raise_for_status()
|
|
2275
|
+
payload = resp.json()
|
|
2276
|
+
total, data = payload.get("totalCount"), payload.get("data") or []
|
|
2277
|
+
for item in data:
|
|
2278
|
+
values = dict(zip(columns, item.get("d") or []))
|
|
2279
|
+
cap = _parse_float(values.get("market_cap_basic"))
|
|
2280
|
+
if cap is None or cap < floor:
|
|
2281
|
+
return total, rows
|
|
2282
|
+
row = {_TV_KEYS.get(col, col): _parse_float(values.get(col)) for col in columns[2:]}
|
|
2283
|
+
row.update(symbol=_clist_symbol(market, values.get("name")), name=values.get("description"))
|
|
2284
|
+
rows.append(_clean_row(row | {"pe_basis": "ttm"}))
|
|
2285
|
+
if len(data) < 1000:
|
|
2286
|
+
break
|
|
2287
|
+
if not rows:
|
|
2288
|
+
raise ValueError("tradingview scanner returned empty data")
|
|
2289
|
+
return total, rows
|
|
2290
|
+
|
|
2291
|
+
|
|
2265
2292
|
def normalize_us_symbol(value) -> str:
|
|
2266
2293
|
symbol = str(value).strip().upper()
|
|
2267
2294
|
symbol = re.sub(r"^(?:105|106|107)[.]", "", symbol)
|
|
@@ -2280,7 +2307,10 @@ def cmd_market_snapshot(args):
|
|
|
2280
2307
|
if market == "A":
|
|
2281
2308
|
legs = [("eastmoney", lambda: _snapshot_xuangu(filters)), ("tencent", lambda: _snapshot_tencent(filters))]
|
|
2282
2309
|
elif market in _CLIST_SNAPSHOT_COLUMNS:
|
|
2283
|
-
legs = [
|
|
2310
|
+
legs = [
|
|
2311
|
+
("eastmoney", lambda: _snapshot_clist(market, floor)),
|
|
2312
|
+
("tradingview", lambda: _snapshot_tradingview(market, floor)),
|
|
2313
|
+
]
|
|
2284
2314
|
else:
|
|
2285
2315
|
return {"error": f"Unknown market: {market}"}
|
|
2286
2316
|
with socket_timeout(25):
|
|
@@ -2308,11 +2338,7 @@ _REGION_INDEX_SYMBOLS = {
|
|
|
2308
2338
|
def _quote_tencent_hk_index(symbol: str) -> dict:
|
|
2309
2339
|
"""Tencent r_hk index quote, using the same `~` field positions as _tencent_payload_row.
|
|
2310
2340
|
Volume is omitted: the index feed's volume field has no confirmed unit."""
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
resp = requests.get(f"https://qt.gtimg.cn/q=r_{_TENCENT_HK_INDEX[symbol]}", timeout=10)
|
|
2314
|
-
resp.raise_for_status()
|
|
2315
|
-
f = _gbk_var_payload(resp.content).split("~")
|
|
2341
|
+
f = _tencent_fields(f"r_{_TENCENT_HK_INDEX[symbol]}")
|
|
2316
2342
|
price = _parse_float(f[3]) if len(f) > 34 else None
|
|
2317
2343
|
if price is None or price <= 0:
|
|
2318
2344
|
raise ValueError(f"tencent returned no quote for {symbol}")
|
|
@@ -2365,12 +2391,9 @@ def _cn_indices_eastmoney() -> dict:
|
|
|
2365
2391
|
|
|
2366
2392
|
def _cn_indices_tencent() -> dict:
|
|
2367
2393
|
"""One qt.gtimg.cn batch request for every CN index (eastmoney refuses some datacenter IPs)."""
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
resp = requests.get(f"https://qt.gtimg.cn/q={','.join(code for code, _ in _CN_INDICES)}", timeout=10)
|
|
2371
|
-
resp.raise_for_status()
|
|
2394
|
+
content = _tencent_raw(",".join(code for code, _ in _CN_INDICES))
|
|
2372
2395
|
quotes = {}
|
|
2373
|
-
for part in
|
|
2396
|
+
for part in content.decode("gbk", errors="replace").split(";"):
|
|
2374
2397
|
name, _, payload = part.strip().partition('="')
|
|
2375
2398
|
fields = payload.rstrip('"').split("~")
|
|
2376
2399
|
if len(fields) > 37 and _parse_float(fields[3]):
|
package/tools/value_data.py
CHANGED
|
@@ -26,6 +26,7 @@ from stock_data import (
|
|
|
26
26
|
_em_datacenter,
|
|
27
27
|
_yf_hk_symbol,
|
|
28
28
|
detect_market,
|
|
29
|
+
fund_pingzhong_js,
|
|
29
30
|
normalize_stock_code,
|
|
30
31
|
)
|
|
31
32
|
from trading_calendar import _MARKET_TZ, market_now
|
|
@@ -1129,12 +1130,8 @@ def tracking_error(nav, benchmark):
|
|
|
1129
1130
|
|
|
1130
1131
|
|
|
1131
1132
|
def fund_size_history(symbol):
|
|
1132
|
-
import requests
|
|
1133
|
-
|
|
1134
1133
|
def fetch():
|
|
1135
|
-
|
|
1136
|
-
response.raise_for_status()
|
|
1137
|
-
match = re.search(r"\bData_fluctuationScale\s*=\s*(.*?);", response.text, re.S)
|
|
1134
|
+
match = re.search(r"\bData_fluctuationScale\s*=\s*(.*?);", fund_pingzhong_js(symbol), re.S)
|
|
1138
1135
|
if not match:
|
|
1139
1136
|
raise ValueError("fund scale history unavailable")
|
|
1140
1137
|
data = json.loads(match.group(1))
|