@weaxs/openclaw-stock-analysis 0.2.0 → 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.
- package/dist/index.js +3 -3
- package/index.ts +3 -3
- package/package.json +1 -1
- package/skills/dragon-head/SKILL.md +1 -1
- package/skills/emotion-cycle/SKILL.md +1 -1
- package/tools/screener.py +3 -2
- package/tools/stock_data.py +217 -42
- package/tools/trading_calendar.py +20 -4
package/dist/index.js
CHANGED
|
@@ -4486,7 +4486,7 @@ var index_default = definePluginEntry({
|
|
|
4486
4486
|
});
|
|
4487
4487
|
api.registerTool({
|
|
4488
4488
|
name: "get_quote",
|
|
4489
|
-
description: "\u83B7\u53D6\u80A1\u7968\u5B9E\u65F6\u884C\u60C5\u62A5\u4EF7\uFF08\u73B0\u4EF7\u3001\u6DA8\u8DCC\u5E45\u3001\u91CF\u6BD4\u7B49\uFF09\u3002\u652F\u6301A\u80A1\u3001\u6E2F\u80A1\u3001\u7F8E\u80A1\u3001\u65E5\u80A1\u3001\u97E9\u80A1\u3001\u53F0\u80A1",
|
|
4489
|
+
description: "\u83B7\u53D6\u80A1\u7968\u5B9E\u65F6\u884C\u60C5\u62A5\u4EF7\uFF08\u73B0\u4EF7\u3001\u6DA8\u8DCC\u5E45\u3001\u91CF\u6BD4\u7B49\uFF09\u3002\u652F\u6301A\u80A1\u3001\u6E2F\u80A1\u3001\u7F8E\u80A1\u3001\u65E5\u80A1\u3001\u97E9\u80A1\u3001\u53F0\u80A1\uFF1B\u975E\u4EA4\u6613\u65F6\u6BB5\u8FD4\u56DE\u6700\u8FD1\u4EA4\u6613\u65E5\u6536\u76D8\u4EF7\u5E76\u4EE5 as_of/stale \u6807\u6CE8",
|
|
4490
4490
|
parameters: typebox_exports.Object({
|
|
4491
4491
|
symbol: typebox_exports.String({ description: "\u80A1\u7968\u4EE3\u7801\uFF08A\u80A1\u5982600519\uFF0C\u7F8E\u80A1\u5982AAPL\uFF0C\u6E2F\u80A1\u598200700.HK\uFF09" })
|
|
4492
4492
|
}),
|
|
@@ -4733,7 +4733,7 @@ var index_default = definePluginEntry({
|
|
|
4733
4733
|
description: "\u83B7\u53D6A\u80A1\u6DA8\u505C\u6C60/\u6DA8\u505C\u677F\u590D\u76D8\u2014\u2014\u5F53\u65E5\u6DA8\u505C\u4E2A\u80A1\uFF0C\u542B\u8FDE\u677F\u6570\u3001\u5C01\u677F\u8D44\u91D1\u3001\u70B8\u677F\u6B21\u6570\u3001\u9996\u672B\u6B21\u5C01\u677F\u65F6\u95F4\u3001\u6240\u5C5E\u884C\u4E1A\u3002\u77ED\u7EBF\u60C5\u7EEA\u4E0E\u9F99\u5934\u6218\u6CD5\u6838\u5FC3\u6570\u636E",
|
|
4734
4734
|
parameters: typebox_exports.Object({
|
|
4735
4735
|
date: typebox_exports.Optional(
|
|
4736
|
-
typebox_exports.String({ description: "\u65E5\u671F\uFF08YYYYMMDD\uFF09\uFF0C\u9ED8\u8BA4\u5F53\u65E5" })
|
|
4736
|
+
typebox_exports.String({ description: "\u65E5\u671F\uFF08YYYYMMDD\uFF09\uFF0C\u9ED8\u8BA4\u5F53\u65E5\uFF1B\u975E\u4EA4\u6613\u65E5\u6216\u672A\u6765\u65E5\u671F\u81EA\u52A8\u56DE\u9000\u5230\u6700\u8FD1\u4EA4\u6613\u65E5\uFF08\u8FD4\u56DE\u542B requested_date \u4E0E stale \u6807\u6CE8\uFF09" })
|
|
4737
4737
|
)
|
|
4738
4738
|
}),
|
|
4739
4739
|
async execute(_id, params) {
|
|
@@ -4748,7 +4748,7 @@ var index_default = definePluginEntry({
|
|
|
4748
4748
|
description: "\u83B7\u53D6A\u80A1\u9F99\u864E\u699C\u2014\u2014\u4E0A\u699C\u4E2A\u80A1\u51C0\u4E70\u989D/\u4E70\u5165\u989D/\u5356\u51FA\u989D/\u4E0A\u699C\u539F\u56E0/\u89E3\u8BFB\uFF0C\u53EF\u6309\u4E2A\u80A1\u8FC7\u6EE4",
|
|
4749
4749
|
parameters: typebox_exports.Object({
|
|
4750
4750
|
date: typebox_exports.Optional(
|
|
4751
|
-
typebox_exports.String({ description: "\u65E5\u671F\uFF08YYYY-MM-DD\uFF09\uFF0C\u9ED8\u8BA4\u5F53\u65E5" })
|
|
4751
|
+
typebox_exports.String({ description: "\u65E5\u671F\uFF08YYYY-MM-DD\uFF09\uFF0C\u9ED8\u8BA4\u5F53\u65E5\uFF1B\u975E\u4EA4\u6613\u65E5\u6216\u672A\u6765\u65E5\u671F\u81EA\u52A8\u56DE\u9000\u5230\u6700\u8FD1\u4EA4\u6613\u65E5\uFF08\u8FD4\u56DE\u542B requested_date \u4E0E stale \u6807\u6CE8\uFF09" })
|
|
4752
4752
|
),
|
|
4753
4753
|
symbol: typebox_exports.Optional(
|
|
4754
4754
|
typebox_exports.String({ description: "A\u80A1\u80A1\u7968\u4EE3\u7801\uFF08\u53EF\u9009\uFF0C\u6309\u4E2A\u80A1\u8FC7\u6EE4\uFF09\uFF0C\u5982 600519" })
|
package/index.ts
CHANGED
|
@@ -88,7 +88,7 @@ export default definePluginEntry({
|
|
|
88
88
|
|
|
89
89
|
api.registerTool({
|
|
90
90
|
name: "get_quote",
|
|
91
|
-
description: "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A
|
|
91
|
+
description: "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A股、港股、美股、日股、韩股、台股;非交易时段返回最近交易日收盘价并以 as_of/stale 标注",
|
|
92
92
|
parameters: Type.Object({
|
|
93
93
|
symbol: Type.String({ description: "股票代码(A股如600519,美股如AAPL,港股如00700.HK)" }),
|
|
94
94
|
}),
|
|
@@ -363,7 +363,7 @@ export default definePluginEntry({
|
|
|
363
363
|
"获取A股涨停池/涨停板复盘——当日涨停个股,含连板数、封板资金、炸板次数、首末次封板时间、所属行业。短线情绪与龙头战法核心数据",
|
|
364
364
|
parameters: Type.Object({
|
|
365
365
|
date: Type.Optional(
|
|
366
|
-
Type.String({ description: "日期(YYYYMMDD
|
|
366
|
+
Type.String({ description: "日期(YYYYMMDD),默认当日;非交易日或未来日期自动回退到最近交易日(返回含 requested_date 与 stale 标注)" })
|
|
367
367
|
),
|
|
368
368
|
}),
|
|
369
369
|
async execute(_id, params) {
|
|
@@ -380,7 +380,7 @@ export default definePluginEntry({
|
|
|
380
380
|
"获取A股龙虎榜——上榜个股净买额/买入额/卖出额/上榜原因/解读,可按个股过滤",
|
|
381
381
|
parameters: Type.Object({
|
|
382
382
|
date: Type.Optional(
|
|
383
|
-
Type.String({ description: "日期(YYYY-MM-DD
|
|
383
|
+
Type.String({ description: "日期(YYYY-MM-DD),默认当日;非交易日或未来日期自动回退到最近交易日(返回含 requested_date 与 stale 标注)" })
|
|
384
384
|
),
|
|
385
385
|
symbol: Type.Optional(
|
|
386
386
|
Type.String({ description: "A股股票代码(可选,按个股过滤),如 600519" })
|
package/package.json
CHANGED
|
@@ -24,7 +24,7 @@ python3 scripts/gather.py <symbol>
|
|
|
24
24
|
同时用 resolve_stock_sectors 确认个股所属板块,再用 get_sector_constituents 拉取同板块个股列表——后续「龙头 vs 跟风」的强弱对比都在这个板块池内进行。
|
|
25
25
|
获取不到板块池或池内个股同期表现时,只评估候选股的强势特征,不给出“龙头/龙一”结论。
|
|
26
26
|
|
|
27
|
-
短线情绪与资金席位补充:`get_limit_up_pool`(涨停池的连板数、首末次封板时间、封板资金、炸板次数)用于确认板块内个股的高度与封板质量;`get_dragon_tiger
|
|
27
|
+
短线情绪与资金席位补充:`get_limit_up_pool`(涨停池的连板数、首末次封板时间、封板资金、炸板次数)用于确认板块内个股的高度与封板质量;`get_dragon_tiger`(龙虎榜)用于查看上榜个股的席位净买额与上榜原因。两者在非交易日或未来日期会自动回退到最近交易日的数据(返回含 `requested_date` 与 `stale: true` 标注),解读时以 `date` 字段的实际数据日期为准,不得把回退数据当成请求日当日数据。
|
|
28
28
|
|
|
29
29
|
### 2. 相对强弱验证
|
|
30
30
|
|
|
@@ -17,7 +17,7 @@ description: 市场情绪周期:用市场宽度、涨跌停、成交额和热
|
|
|
17
17
|
python3 scripts/gather.py [A|HK|US]
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
A 股情绪另有两个直接数据源:`get_limit_up_pool`(涨停池:连板梯队高度、炸板率、封板资金)与 `get_hot_stocks
|
|
20
|
+
A 股情绪另有两个直接数据源:`get_limit_up_pool`(涨停池:连板梯队高度、炸板率、封板资金)与 `get_hot_stocks`(全市场人气热搜榜)。`get_limit_up_pool` 在非交易日或未来日期会回退到最近交易日数据(返回含 `requested_date` 与 `stale: true`),情绪判断以其 `date` 字段的实际数据日期为准。
|
|
21
21
|
|
|
22
22
|
### 2. 情绪指标
|
|
23
23
|
|
package/tools/screener.py
CHANGED
|
@@ -54,8 +54,9 @@ def _fetch_json(args: list[str], timeout: int = 30) -> dict | list | None:
|
|
|
54
54
|
|
|
55
55
|
|
|
56
56
|
def fetch_snapshot(market: str) -> list:
|
|
57
|
-
# a cold full-market snapshot can exceed 30s (CI runners) — allow longer
|
|
58
|
-
|
|
57
|
+
# a cold full-market snapshot can exceed 30s (CI runners) — allow longer; with
|
|
58
|
+
# all eastmoney/sina legs timing out, the tencent fallback leg needs ~2min more
|
|
59
|
+
return _fetch_json(["market_snapshot", "--market", market], timeout=240)
|
|
59
60
|
|
|
60
61
|
|
|
61
62
|
def load_config(path: str) -> dict:
|
package/tools/stock_data.py
CHANGED
|
@@ -272,21 +272,13 @@ def _gbk_var_payload(content: bytes) -> str:
|
|
|
272
272
|
return content.decode("gbk", errors="replace").split('="', 1)[-1].rsplit('"', 1)[0]
|
|
273
273
|
|
|
274
274
|
|
|
275
|
-
def
|
|
276
|
-
"""
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
both are normalized to 元 to match the rest of the chain."""
|
|
280
|
-
import requests
|
|
281
|
-
|
|
282
|
-
resp = requests.get(f"https://qt.gtimg.cn/q={_cn_code(symbol)}", timeout=10)
|
|
283
|
-
f = _gbk_var_payload(resp.content).split("~")
|
|
284
|
-
if len(f) < 35 or not f[1]:
|
|
285
|
-
raise ValueError(f"tencent returned no quote for {symbol}")
|
|
286
|
-
f += [""] * (47 - len(f)) # pad optional tail fields (pe/pb/market_cap…) on short payloads
|
|
275
|
+
def _tencent_payload_row(f: list, symbol: str) -> dict:
|
|
276
|
+
"""Build the quote row from one Tencent `~`-separated payload (already split).
|
|
277
|
+
Shared by _quote_tencent (single) and _tencent_batch_quotes (snapshot leg)."""
|
|
278
|
+
f += [""] * (50 - len(f)) # pad optional tail fields (pe/pb/market_cap/volume_ratio…) on short payloads
|
|
287
279
|
turnover = _parse_float(f[37])
|
|
288
280
|
market_cap = _parse_float(f[45])
|
|
289
|
-
|
|
281
|
+
return {
|
|
290
282
|
"symbol": symbol,
|
|
291
283
|
"name": f[1],
|
|
292
284
|
"price": _parse_float(f[3]),
|
|
@@ -302,8 +294,23 @@ def _quote_tencent(symbol: str) -> dict:
|
|
|
302
294
|
"pe": _parse_float(f[39]),
|
|
303
295
|
"pb": _parse_float(f[46]),
|
|
304
296
|
"turnover_rate": _parse_float(f[38]),
|
|
297
|
+
"volume_ratio": _parse_float(f[49]),
|
|
305
298
|
"amplitude": _parse_float(f[43]),
|
|
306
299
|
}
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _quote_tencent(symbol: str) -> dict:
|
|
303
|
+
"""Tencent quote via qt.gtimg.cn. GBK-encoded `v_sh600519="1~name~code~..."` fields.
|
|
304
|
+
|
|
305
|
+
Units differ from akshare: turnover arrives in 万元 and market_cap in 亿元 —
|
|
306
|
+
both are normalized to 元 to match the rest of the chain."""
|
|
307
|
+
import requests
|
|
308
|
+
|
|
309
|
+
resp = requests.get(f"https://qt.gtimg.cn/q={_cn_code(symbol)}", timeout=10)
|
|
310
|
+
f = _gbk_var_payload(resp.content).split("~")
|
|
311
|
+
if len(f) < 35 or not f[1]:
|
|
312
|
+
raise ValueError(f"tencent returned no quote for {symbol}")
|
|
313
|
+
row = _tencent_payload_row(f, symbol)
|
|
307
314
|
if normalize_stock_code(symbol)["is_etf"]:
|
|
308
315
|
row["is_etf"] = True
|
|
309
316
|
return _clean_row(row)
|
|
@@ -1120,12 +1127,48 @@ def quote_yf(symbol: str) -> dict:
|
|
|
1120
1127
|
)
|
|
1121
1128
|
|
|
1122
1129
|
|
|
1130
|
+
def _quote_stale_marker(market: str):
|
|
1131
|
+
"""Stale-data annotation for a quote fetched outside the market's live session.
|
|
1132
|
+
|
|
1133
|
+
Quotes carry no date of their own, so a weekend/holiday or pre-market call
|
|
1134
|
+
would otherwise present the last trading day's close as if it were live
|
|
1135
|
+
(issue #31 follow-up). Returns None — no annotation — during live sessions
|
|
1136
|
+
and post-market (today's close), or when the calendar is unavailable.
|
|
1137
|
+
pre_market covers the call-auction window (e.g. CN 09:15-09:29), where the
|
|
1138
|
+
quote is actually auction-indicative — an accepted approximation rather than
|
|
1139
|
+
hand-maintaining per-market auction start times."""
|
|
1140
|
+
from trading_calendar import market_phase, prev_trading_days
|
|
1141
|
+
|
|
1142
|
+
# detect_market labels A-shares "A"; the trading calendar calls the same market "CN"
|
|
1143
|
+
cal_market = "CN" if market == "A" else market
|
|
1144
|
+
try:
|
|
1145
|
+
info = market_phase(cal_market)
|
|
1146
|
+
if info.get("error") or info.get("phase") not in ("closed", "pre_market"):
|
|
1147
|
+
return None
|
|
1148
|
+
prev = prev_trading_days(cal_market, 1, from_date=info["date"])
|
|
1149
|
+
except Exception:
|
|
1150
|
+
return None # calendar unavailable — don't guess
|
|
1151
|
+
if not prev:
|
|
1152
|
+
return None
|
|
1153
|
+
as_of = prev[0]
|
|
1154
|
+
return {
|
|
1155
|
+
"as_of": as_of,
|
|
1156
|
+
"stale": True,
|
|
1157
|
+
"note": f"market is not in a live session; quote is the last completed trading day {as_of}'s close",
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
|
|
1123
1161
|
def cmd_quote(args):
|
|
1124
1162
|
market = detect_market(args.symbol)
|
|
1125
1163
|
try:
|
|
1126
|
-
|
|
1164
|
+
result = quote_a(args.symbol) if market == "A" else quote_yf(args.symbol)
|
|
1127
1165
|
except Exception as e:
|
|
1128
1166
|
return {"error": str(e)}
|
|
1167
|
+
if isinstance(result, dict) and "error" not in result:
|
|
1168
|
+
marker = _quote_stale_marker(market)
|
|
1169
|
+
if marker:
|
|
1170
|
+
result.update(marker)
|
|
1171
|
+
return result
|
|
1129
1172
|
|
|
1130
1173
|
|
|
1131
1174
|
# --------------- capital_flow ---------------
|
|
@@ -1347,17 +1390,29 @@ def cmd_financials(args):
|
|
|
1347
1390
|
|
|
1348
1391
|
|
|
1349
1392
|
def snapshot_a() -> list:
|
|
1393
|
+
import socket
|
|
1394
|
+
|
|
1395
|
+
# akshare/efinance leave requests timeout-less — on a blackholed network a leg
|
|
1396
|
+
# hangs until the kernel TCP timeout (~2min), and the chain would overrun the
|
|
1397
|
+
# caller's subprocess budget before ever reaching the tencent leg. Bound each
|
|
1398
|
+
# blocking socket op for the chain's duration (explicit per-request timeouts,
|
|
1399
|
+
# like the tencent leg's, still win).
|
|
1400
|
+
old_timeout = socket.getdefaulttimeout()
|
|
1401
|
+
socket.setdefaulttimeout(25)
|
|
1350
1402
|
try:
|
|
1351
1403
|
return _failover(
|
|
1352
1404
|
[
|
|
1353
1405
|
("akshare", _snapshot_akshare),
|
|
1354
1406
|
("efinance", _snapshot_efinance),
|
|
1355
1407
|
("sina", _snapshot_sina),
|
|
1408
|
+
("tencent", _snapshot_tencent),
|
|
1356
1409
|
],
|
|
1357
1410
|
label="snapshot_a",
|
|
1358
1411
|
)
|
|
1359
|
-
except Exception:
|
|
1360
|
-
return [{"error": "A-share snapshot unavailable from all sources"}]
|
|
1412
|
+
except Exception as e:
|
|
1413
|
+
return [{"error": f"A-share snapshot unavailable from all sources: {e}"}]
|
|
1414
|
+
finally:
|
|
1415
|
+
socket.setdefaulttimeout(old_timeout)
|
|
1361
1416
|
|
|
1362
1417
|
|
|
1363
1418
|
def _snapshot_efinance() -> list:
|
|
@@ -1413,6 +1468,63 @@ def _snapshot_sina() -> list:
|
|
|
1413
1468
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1414
1469
|
|
|
1415
1470
|
|
|
1471
|
+
# qt.gtimg.cn accepts comma-joined multi-code batches; 60 keeps URLs well short
|
|
1472
|
+
_TENCENT_BATCH = 60
|
|
1473
|
+
|
|
1474
|
+
|
|
1475
|
+
def _tencent_batch_quotes(codes: list) -> list:
|
|
1476
|
+
"""Batch quotes from qt.gtimg.cn for exchange-prefixed codes, a few requests in
|
|
1477
|
+
flight (this leg fires only when the eastmoney/sina legs are all dead, and ~15k
|
|
1478
|
+
enumerated codes serialized would take minutes). Unknown codes are simply absent
|
|
1479
|
+
from the response; delisted/suspended ones come back frozen with volume=0 and
|
|
1480
|
+
are dropped here."""
|
|
1481
|
+
import concurrent.futures
|
|
1482
|
+
|
|
1483
|
+
import requests
|
|
1484
|
+
|
|
1485
|
+
def fetch(batch):
|
|
1486
|
+
try:
|
|
1487
|
+
resp = requests.get(f"https://qt.gtimg.cn/q={','.join(batch)}", timeout=10)
|
|
1488
|
+
except Exception:
|
|
1489
|
+
return [] # a lost batch loses 60 codes — a partial snapshot still beats none
|
|
1490
|
+
rows = []
|
|
1491
|
+
for part in resp.content.decode("gbk", errors="replace").split(";"):
|
|
1492
|
+
vname, _, payload = part.strip().partition('="')
|
|
1493
|
+
f = payload.rstrip('"').split("~")
|
|
1494
|
+
if len(f) < 35 or not f[1]:
|
|
1495
|
+
continue
|
|
1496
|
+
if not _parse_float(f[6]): # volume 0/empty → frozen payload (delisted/suspended)
|
|
1497
|
+
continue
|
|
1498
|
+
prefixed = vname[2:] # strip the leading "v_"
|
|
1499
|
+
bare = prefixed[2:] if prefixed[:2] in ("sh", "sz", "bj") else prefixed
|
|
1500
|
+
rows.append(_clean_row(_tencent_payload_row(f, bare)))
|
|
1501
|
+
return rows
|
|
1502
|
+
|
|
1503
|
+
batches = [codes[i : i + _TENCENT_BATCH] for i in range(0, len(codes), _TENCENT_BATCH)]
|
|
1504
|
+
rows = []
|
|
1505
|
+
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
|
|
1506
|
+
for batch_rows in pool.map(fetch, batches):
|
|
1507
|
+
rows.extend(batch_rows)
|
|
1508
|
+
return rows
|
|
1509
|
+
|
|
1510
|
+
|
|
1511
|
+
def _snapshot_tencent() -> list:
|
|
1512
|
+
"""Tencent full-market snapshot — the plain-HTTPS last-resort leg for when the
|
|
1513
|
+
eastmoney/sina legs are all blocked (datacenter IPs, issue #25).
|
|
1514
|
+
|
|
1515
|
+
Codes are enumerated over the known SH (600-605, 688-689) and SZ (000-003,
|
|
1516
|
+
300-302) ranges and validated by the batch quotes themselves — no list API is
|
|
1517
|
+
reliable from blocked networks (www.szse.cn resets datacenter connections,
|
|
1518
|
+
query.sse.com.cn flaps, akshare's wrapper has no timeout). BSE and suspended
|
|
1519
|
+
stocks stay uncovered by this leg."""
|
|
1520
|
+
codes = [f"sh{i:06d}" for lo, hi in ((600000, 605999), (688000, 689999)) for i in range(lo, hi + 1)]
|
|
1521
|
+
codes += [f"sz{i:06d}" for lo, hi in ((1, 3999), (300000, 302999)) for i in range(lo, hi + 1)]
|
|
1522
|
+
rows = _tencent_batch_quotes(codes)
|
|
1523
|
+
if not rows:
|
|
1524
|
+
raise ValueError("tencent snapshot returned empty data")
|
|
1525
|
+
return rows
|
|
1526
|
+
|
|
1527
|
+
|
|
1416
1528
|
def _snapshot_akshare() -> list:
|
|
1417
1529
|
import akshare as ak
|
|
1418
1530
|
|
|
@@ -2321,21 +2433,66 @@ def cmd_fundamental_context(args):
|
|
|
2321
2433
|
# --------------- short-term sentiment: limit_up_pool / dragon_tiger / hot_stocks (A-share only) ---------------
|
|
2322
2434
|
|
|
2323
2435
|
|
|
2436
|
+
def _resolve_cn_data_date(raw: str) -> tuple[datetime, datetime]:
|
|
2437
|
+
"""Resolve a requested date (YYYYMMDD) to the CN trading day its data belongs to.
|
|
2438
|
+
|
|
2439
|
+
eastmoney's zt-pool/LHB endpoints silently clamp any date later than the latest
|
|
2440
|
+
trading day to that day and answer EMPTY for past non-trading days, so the
|
|
2441
|
+
requested date never proves the data's date (issue #31). Returns
|
|
2442
|
+
(requested, data_date) as datetimes — data_date is the last trading day at or
|
|
2443
|
+
before min(requested, today): weekends, holidays and future dates all resolve
|
|
2444
|
+
backward. Raises ValueError on malformed input."""
|
|
2445
|
+
from trading_calendar import cn_trade_dates # flat sibling import
|
|
2446
|
+
|
|
2447
|
+
req = datetime.strptime(raw, "%Y%m%d")
|
|
2448
|
+
d = min(req, datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))
|
|
2449
|
+
trade_dates = cn_trade_dates(d.year)
|
|
2450
|
+
if d.month == 1: # the walk-back can cross into December of the previous year
|
|
2451
|
+
trade_dates |= cn_trade_dates(d.year - 1)
|
|
2452
|
+
for _ in range(20): # 春节/国庆 plus adjoining weekends fit well within 20 days
|
|
2453
|
+
# empty trade-date set (calendar fetch failed) → weekday-only approximation
|
|
2454
|
+
if d.weekday() < 5 and (not trade_dates or d.strftime("%Y-%m-%d") in trade_dates):
|
|
2455
|
+
break
|
|
2456
|
+
d -= timedelta(days=1)
|
|
2457
|
+
return req, d
|
|
2458
|
+
|
|
2459
|
+
|
|
2324
2460
|
def cmd_limit_up_pool(args):
|
|
2325
|
-
"""A-share limit-up pool (涨停池) for one trading day via eastmoney.
|
|
2326
|
-
|
|
2461
|
+
"""A-share limit-up pool (涨停池) for one trading day via eastmoney.
|
|
2462
|
+
|
|
2463
|
+
The requested date is first resolved to the trading day the data belongs to
|
|
2464
|
+
(_resolve_cn_data_date); when they differ the payload carries requested_date
|
|
2465
|
+
and stale=True so a weekend/future request can't be misread as that day's pool.
|
|
2466
|
+
Known limitation: on a trading day before that day's pool is published, the
|
|
2467
|
+
request resolves to itself and no stale label is emitted (the zt-pool payload
|
|
2468
|
+
carries no date column to cross-check against)."""
|
|
2469
|
+
try:
|
|
2470
|
+
req, data_day = _resolve_cn_data_date((args.date or datetime.now().strftime("%Y%m%d")).replace("-", ""))
|
|
2471
|
+
except ValueError:
|
|
2472
|
+
return {"error": f"limit_up_pool: invalid --date {args.date!r} (want YYYYMMDD)"}
|
|
2473
|
+
date = data_day.strftime("%Y%m%d")
|
|
2474
|
+
requested = req.strftime("%Y%m%d")
|
|
2475
|
+
result = {"date": date}
|
|
2476
|
+
if req != data_day:
|
|
2477
|
+
result["requested_date"] = requested
|
|
2478
|
+
result["stale"] = True
|
|
2479
|
+
result["note"] = f"{requested} is not a trading day or has no data yet; showing the last trading day {date}"
|
|
2327
2480
|
try:
|
|
2328
2481
|
import akshare as ak
|
|
2329
2482
|
|
|
2330
2483
|
df = _akshare_retry(ak.stock_zt_pool_em, date=date)
|
|
2331
2484
|
if df is None or df.empty:
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
"
|
|
2337
|
-
|
|
2338
|
-
|
|
2485
|
+
result["count"] = 0
|
|
2486
|
+
result["max_consecutive_boards"] = 0
|
|
2487
|
+
result["pool"] = []
|
|
2488
|
+
if date != requested:
|
|
2489
|
+
result["note"] = (
|
|
2490
|
+
f"{requested} is not a trading day or has no data yet; "
|
|
2491
|
+
f"last trading day {date} has no limit-up pool data"
|
|
2492
|
+
)
|
|
2493
|
+
else:
|
|
2494
|
+
result["note"] = f"no limit-up pool data for {date}"
|
|
2495
|
+
return result
|
|
2339
2496
|
col_map = {
|
|
2340
2497
|
"代码": "code",
|
|
2341
2498
|
"名称": "name",
|
|
@@ -2357,14 +2514,12 @@ def cmd_limit_up_pool(args):
|
|
|
2357
2514
|
keep = [c for c in col_map.values() if c in df.columns]
|
|
2358
2515
|
pool = [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
2359
2516
|
boards = [r["consecutive_boards"] for r in pool if isinstance(r.get("consecutive_boards"), (int, float))]
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
"pool": pool,
|
|
2365
|
-
}
|
|
2517
|
+
result["count"] = len(pool)
|
|
2518
|
+
result["max_consecutive_boards"] = max(boards) if boards else 0
|
|
2519
|
+
result["pool"] = pool
|
|
2520
|
+
return result
|
|
2366
2521
|
except Exception as e:
|
|
2367
|
-
return {"error":
|
|
2522
|
+
return {"error": f"limit_up_pool date={requested}: {e}"}
|
|
2368
2523
|
|
|
2369
2524
|
|
|
2370
2525
|
def _dragon_tiger_em(raw: str) -> list:
|
|
@@ -2423,9 +2578,18 @@ def _dragon_tiger_sina(raw: str) -> list:
|
|
|
2423
2578
|
|
|
2424
2579
|
|
|
2425
2580
|
def cmd_dragon_tiger(args):
|
|
2426
|
-
"""A-share dragon-tiger list (龙虎榜) for one trading day: eastmoney → sina.
|
|
2427
|
-
|
|
2428
|
-
date
|
|
2581
|
+
"""A-share dragon-tiger list (龙虎榜) for one trading day: eastmoney → sina.
|
|
2582
|
+
|
|
2583
|
+
Same date resolution as cmd_limit_up_pool (issue #31): a non-trading or future
|
|
2584
|
+
date is served the last trading day's list, labeled with requested_date and
|
|
2585
|
+
stale=True."""
|
|
2586
|
+
try:
|
|
2587
|
+
req, data_day = _resolve_cn_data_date((args.date or datetime.now().strftime("%Y-%m-%d")).replace("-", ""))
|
|
2588
|
+
except ValueError:
|
|
2589
|
+
return {"error": f"dragon_tiger: invalid --date {args.date!r} (want YYYY-MM-DD)"}
|
|
2590
|
+
raw = data_day.strftime("%Y%m%d")
|
|
2591
|
+
date = data_day.strftime("%Y-%m-%d")
|
|
2592
|
+
requested_iso = req.strftime("%Y-%m-%d")
|
|
2429
2593
|
sources = [
|
|
2430
2594
|
_sourced("eastmoney", lambda: _dragon_tiger_em(raw)),
|
|
2431
2595
|
_sourced("sina", lambda: _dragon_tiger_sina(raw)),
|
|
@@ -2434,13 +2598,19 @@ def cmd_dragon_tiger(args):
|
|
|
2434
2598
|
rows = _failover(sources, label=f"dragon_tiger:{raw}")
|
|
2435
2599
|
except Exception as e:
|
|
2436
2600
|
return {"error": str(e)}
|
|
2601
|
+
stale = req != data_day
|
|
2437
2602
|
if not rows:
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
"
|
|
2441
|
-
"
|
|
2442
|
-
"note"
|
|
2443
|
-
|
|
2603
|
+
result = {"date": date, "count": 0, "items": []}
|
|
2604
|
+
if stale:
|
|
2605
|
+
result["requested_date"] = requested_iso
|
|
2606
|
+
result["stale"] = True
|
|
2607
|
+
result["note"] = (
|
|
2608
|
+
f"{requested_iso} is not a trading day or has no data yet; "
|
|
2609
|
+
f"last trading day {date} has no dragon-tiger data"
|
|
2610
|
+
)
|
|
2611
|
+
else:
|
|
2612
|
+
result["note"] = f"no dragon-tiger data for {date}"
|
|
2613
|
+
return result
|
|
2444
2614
|
source = rows[0]["source"]
|
|
2445
2615
|
if args.symbol:
|
|
2446
2616
|
m = re.fullmatch(r"(?:sh|sz|bj)(\d{6})", str(args.symbol), re.IGNORECASE)
|
|
@@ -2453,7 +2623,12 @@ def cmd_dragon_tiger(args):
|
|
|
2453
2623
|
reverse=True,
|
|
2454
2624
|
)
|
|
2455
2625
|
items = [{k: v for k, v in r.items() if k != "source"} for r in rows[: args.top]]
|
|
2456
|
-
|
|
2626
|
+
result = {"date": date, "count": len(items), "items": items, "source": source}
|
|
2627
|
+
if stale:
|
|
2628
|
+
result["requested_date"] = requested_iso
|
|
2629
|
+
result["stale"] = True
|
|
2630
|
+
result["note"] = f"{requested_iso} is not a trading day or has no data yet; showing the last trading day {date}"
|
|
2631
|
+
return result
|
|
2457
2632
|
|
|
2458
2633
|
|
|
2459
2634
|
def _strip_exchange_prefix(row: dict) -> dict:
|
|
@@ -14,7 +14,21 @@ def _is_weekend(d: datetime) -> bool:
|
|
|
14
14
|
return d.weekday() >= 5
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
|
|
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:
|
|
@@ -52,7 +68,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
|
|
|
52
68
|
return {"date": date_str, "market": market, "is_trading_day": False, "reason": "weekend"}
|
|
53
69
|
|
|
54
70
|
if market == "CN":
|
|
55
|
-
trading_dates =
|
|
71
|
+
trading_dates = cn_trade_dates(d.year)
|
|
56
72
|
if trading_dates:
|
|
57
73
|
is_td = date_str in trading_dates
|
|
58
74
|
return {
|
|
@@ -80,7 +96,7 @@ def is_trading_day(market: str, date_str: str = None) -> dict:
|
|
|
80
96
|
}
|
|
81
97
|
except Exception:
|
|
82
98
|
pass
|
|
83
|
-
trading_dates =
|
|
99
|
+
trading_dates = cn_trade_dates(d.year)
|
|
84
100
|
if trading_dates:
|
|
85
101
|
is_td = date_str in trading_dates
|
|
86
102
|
return {
|