@weaxs/openclaw-stock-analysis 0.2.10 → 0.2.11
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/README.md +3 -2
- package/dist/index.js +313 -435
- package/index.ts +13 -1
- package/openclaw.plugin.json +1 -0
- package/package.json +3 -3
- package/skills/stock-analysis/SKILL.md +4 -1
- package/tools/alert_rules.py +63 -14
- package/tools/name_resolver.py +16 -14
- package/tools/requirements.txt +2 -2
- package/tools/search_intel.py +2 -2
- package/tools/signal_tracker.py +6 -5
- package/tools/stock_data.py +255 -24
- package/tools/tiaa_disclosures.py +263 -0
package/index.ts
CHANGED
|
@@ -482,7 +482,7 @@ export default definePluginEntry({
|
|
|
482
482
|
|
|
483
483
|
api.registerTool({
|
|
484
484
|
name: "get_quote",
|
|
485
|
-
description: "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A股、港股、美股、日股、韩股、台股;非交易时段返回最近交易日收盘价并以 as_of/stale 标注;ETF 的 premium_discount_rate 为正=溢价、负=折价。返回 source、UTC fetched_at 和提供方 data_as_of(未知为null);as_of_basis
|
|
485
|
+
description: "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A股、港股、美股、日股、韩股、台股;非交易时段返回最近交易日收盘价并以 as_of/stale 标注;ETF 的 premium_discount_rate 为正=溢价、负=折价。返回 source、UTC fetched_at 和提供方 data_as_of(未知为null);as_of_basis区分提供方时间与交易日历推断,采集时间不等于行情时间。场外基金用 get_fund_quote;TIAAxxxxxx 返回投顾组合识别、advisor_org 与无统一净值提示;长钱/海外长钱/稳钱另有有知有行 official_disclosures(partial=true,非实时完整持仓);其他组合搜索可用时为 search_partial,否则 unsupported_provider。",
|
|
486
486
|
parameters: Type.Object({
|
|
487
487
|
symbol: Type.String({ description: "股票代码(A股如600519,美股如AAPL,港股如00700.HK)" }),
|
|
488
488
|
}),
|
|
@@ -492,6 +492,18 @@ export default definePluginEntry({
|
|
|
492
492
|
},
|
|
493
493
|
});
|
|
494
494
|
|
|
495
|
+
api.registerTool({
|
|
496
|
+
name: "get_fund_quote",
|
|
497
|
+
description: "获取场外公募基金净值(6位基金代码,如018147)。nav 是已披露日终净值,非实时价;返回 accumulated_nav(累计净值)、change_pct(日涨跌幅)、nav_date(净值日期)。estimated_nav 为估算净值,可能为 null,不能当作实时价;QDII 净值可能滞后 1-2 交易日。",
|
|
498
|
+
parameters: Type.Object({
|
|
499
|
+
symbol: Type.String({ description: "6位场外公募基金代码,如 018147" }),
|
|
500
|
+
}),
|
|
501
|
+
async execute(_id, params) {
|
|
502
|
+
const out = await runPy("stock_data.py", ["fund_quote", params.symbol]);
|
|
503
|
+
return asText(out);
|
|
504
|
+
},
|
|
505
|
+
});
|
|
506
|
+
|
|
495
507
|
api.registerTool({
|
|
496
508
|
name: "get_capital_flow",
|
|
497
509
|
description:
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weaxs/openclaw-stock-analysis",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.11",
|
|
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.
|
|
17
|
-
"pluginSdkVersion": "2026.
|
|
16
|
+
"openclawVersion": "2026.11.3",
|
|
17
|
+
"pluginSdkVersion": "2026.11.3"
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
|
@@ -29,6 +29,7 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
29
29
|
|------|---------|
|
|
30
30
|
| 个股买卖时机 | `get_technical_analysis` → `get_market_capabilities` → 当前市场支持的资金/风险工具 → `detect_market_regime`。A股可加 `get_capital_flow`(summary) 和 `screen_risk`;其他市场不得用缺失的资金或风险数据。veto_buy=true 则不入场;大盘下跌时个股看多信号降级为轻仓试错或等待;HOLD/WAIT 给出可观察触发条件 |
|
|
31
31
|
| 个股状态速览 | `get_quote` + `get_technical_analysis` |
|
|
32
|
+
| 场外公募基金净值 | `get_fund_quote`(6 位基金代码,如 018147) |
|
|
32
33
|
| 异动归因 | `detect_anomaly` + `get_news` |
|
|
33
34
|
| 大盘择时 | `detect_market_regime`;A 股可补充 `get_market_stats` |
|
|
34
35
|
|
|
@@ -46,6 +47,8 @@ python3 scripts/gather.py <symbol>
|
|
|
46
47
|
|
|
47
48
|
解读实时行情前先调 `get_trading_phase` 确认该市场当前盘中阶段(盘前/早盘/午间休市/午盘/交易中/盘后/休市),避免把休市时的静态快照当作盘中信号解读。
|
|
48
49
|
|
|
50
|
+
场外公募基金净值查询使用 `get_fund_quote(symbol="018147")`,不要当作股票实时报价。`nav` 是 `nav_date` 对应的已披露日终净值而非实时价;`accumulated_nav` 为累计净值,`change_pct` 为日涨跌幅。`estimated_nav` 是估算值且可能为 `null`,缺失时不得编造或当作实时成交价;QDII 净值可能滞后 1-2 交易日,须披露实际 `nav_date`。`TIAAxxxxxx` 使用 `get_quote` 获取投顾组合识别与无统一净值提示,不推算组合净值。`advisor_code/advisor_org` 按 TIAA 前三位机构段与资本市场标准网基金投顾业务编码表进行 best-effort 映射,来源和抓取时间随结果返回;投顾机构不等于主理人,查不到时保留 null。`official_disclosures` 目前仅对确认属于有知有行的 `TIAA001001/TIAA001002/TIAA001004` 提供,其他 TIAA 组合不得套用该站文章;有搜索配置时可返回 `disclosure_status=search_partial` 和 `public_search_results`,其中每项均为 `verification=unverified_search_result`,只能作为待核实线索,否则为 `unsupported_provider`。官方披露含发布日期、摘要、正文摘录和 URL;`disclosures_partial=true` 时必须视为不完整历史披露,不能当作实时业绩或完整成分基金清单。示例账户收益不等于用户收益,引用基金代码时必须保留对应文章日期和链接。
|
|
51
|
+
|
|
49
52
|
港股 `get_quote` 自动按 yfinance → 腾讯 → finnhub → longbridge 容灾,腾讯无需 API key,使用 `r_hk` 实时报价通道(`hk` 通道延迟约 15 分钟)。腾讯港股成交量为股,成交额及市值为港元;PB、换手率、量比为 null 时按缺失处理。该备用源只覆盖报价,K 线仍走原链路。
|
|
50
53
|
|
|
51
54
|
### 第二步:综合研判
|
|
@@ -88,7 +91,7 @@ python3 scripts/gather.py <symbol>
|
|
|
88
91
|
- 行情:`get_quote.price`、`get_quote.data_as_of`。
|
|
89
92
|
- 财务:`get_financials.report_date`、`get_financials.roe`,以及历史 `periods` 中实际返回的 `report_date`、`roe`,路径含数字下标。
|
|
90
93
|
- 回测:`run_backtest.metrics.total_trades`、`run_backtest.metrics.win_rate`。
|
|
91
|
-
每项保留原始 value,并按第 2 项填写 source/as_of;正文中的数字及其他证据的 as_of
|
|
94
|
+
每项保留原始 value,并按第 2 项填写 source/as_of;正文中的数字及其他证据的 as_of 元数据不替代独立引用。漏项先补齐再提交。报价过期时保留原始价格与时间作为历史证据;结论与风险说明均以报价的 data_as_of 为行情覆盖截止点,明确该时点至分析日及之后的行情变动未知,等待新报价后再制定当前数值交易计划。
|
|
92
95
|
4. 调用 `render_stock_report`:快速问答用 `brief`,完整研判用 `full`。
|
|
93
96
|
5. 输出渲染后的 Markdown;只在用户要求机器可读数据时附加结构化 JSON。
|
|
94
97
|
|
package/tools/alert_rules.py
CHANGED
|
@@ -140,28 +140,77 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
140
140
|
needs_anom = any(r.get("type") == "anomaly" for r in rules)
|
|
141
141
|
needs_risk = any(r.get("type") in ("risk_veto", "risk_level_at_least") for r in rules)
|
|
142
142
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
jobs
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
143
|
+
needs_quote = (
|
|
144
|
+
needs_anom
|
|
145
|
+
or needs_risk
|
|
146
|
+
or any(r.get("type") in ("price_below", "price_above", "change_pct_above", "change_pct_below") for r in rules)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Share one market snapshot while retaining 60-bar alerts and 120-bar risk analysis.
|
|
150
|
+
with ThreadPoolExecutor(max_workers=4) as pool:
|
|
151
|
+
jobs = {}
|
|
152
|
+
if needs_quote:
|
|
153
|
+
quote_job = pool.submit(_run_json, "stock_data.py", ["quote", symbol])
|
|
154
|
+
jobs["quote"] = quote_job
|
|
155
|
+
if needs_tech or needs_anom or needs_risk:
|
|
156
|
+
from technical import analyze_records
|
|
157
|
+
|
|
158
|
+
kline_job = pool.submit(
|
|
159
|
+
_run_json,
|
|
160
|
+
"stock_data.py",
|
|
161
|
+
["kline", symbol, "--period", "daily", "--count", "120" if needs_risk else "60"],
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
def analyze(count):
|
|
165
|
+
records = kline_job.result()
|
|
166
|
+
try:
|
|
167
|
+
return analyze_records(symbol, records[-count:] if isinstance(records, list) else records)
|
|
168
|
+
except Exception as exc:
|
|
169
|
+
return {"error": f"Technical analysis failed ({type(exc).__name__})"}
|
|
170
|
+
|
|
171
|
+
if needs_risk:
|
|
172
|
+
from risk_screening import screen_risk
|
|
173
|
+
|
|
174
|
+
technical_job = pool.submit(analyze, 120)
|
|
175
|
+
|
|
176
|
+
def collect_risk():
|
|
177
|
+
try:
|
|
178
|
+
return screen_risk(
|
|
179
|
+
symbol, inputs={"quote": quote_job, "technical": technical_job}, run=_run_json
|
|
180
|
+
)
|
|
181
|
+
except Exception as exc:
|
|
182
|
+
return {"error": f"Risk analysis failed ({type(exc).__name__})"}
|
|
183
|
+
|
|
184
|
+
jobs["risk"] = pool.submit(collect_risk)
|
|
185
|
+
if needs_tech:
|
|
186
|
+
jobs["tech"] = pool.submit(analyze, 60)
|
|
187
|
+
if needs_anom:
|
|
188
|
+
from anomaly_detect import detect_anomalies
|
|
189
|
+
|
|
190
|
+
def anomalies():
|
|
191
|
+
records = kline_job.result()
|
|
192
|
+
try:
|
|
193
|
+
return detect_anomalies(
|
|
194
|
+
symbol,
|
|
195
|
+
records=records[-60:] if isinstance(records, list) else records,
|
|
196
|
+
quote=quote_job.result(),
|
|
197
|
+
run=_run_json,
|
|
198
|
+
)
|
|
199
|
+
except Exception as exc:
|
|
200
|
+
return {"error": f"Anomaly analysis failed ({type(exc).__name__})"}
|
|
201
|
+
|
|
202
|
+
jobs["anom"] = pool.submit(anomalies)
|
|
203
|
+
fetched = {key: future.result() for key, future in jobs.items()}
|
|
155
204
|
fetched = {
|
|
156
205
|
key: value if isinstance(value, dict) and "error" not in value else None for key, value in fetched.items()
|
|
157
206
|
}
|
|
158
|
-
quote = fetched
|
|
207
|
+
quote = fetched.get("quote") or {}
|
|
159
208
|
tech = fetched.get("tech")
|
|
160
209
|
anom = fetched.get("anom")
|
|
161
210
|
risk = fetched.get("risk")
|
|
162
211
|
|
|
163
212
|
warnings = []
|
|
164
|
-
if not quote or quote.get("price") is None:
|
|
213
|
+
if needs_quote and (not quote or quote.get("price") is None):
|
|
165
214
|
warnings.append("quote fetch failed or missing price — price/change rules cannot fire")
|
|
166
215
|
if needs_tech and not tech:
|
|
167
216
|
warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
|
package/tools/name_resolver.py
CHANGED
|
@@ -9,30 +9,32 @@ from pathlib import Path
|
|
|
9
9
|
|
|
10
10
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
11
|
|
|
12
|
+
from _cache import DAY, cached # noqa: E402
|
|
12
13
|
from _subproc import utf8_stdio # noqa: E402
|
|
13
14
|
from stock_data import _akshare_retry # noqa: E402
|
|
14
15
|
|
|
15
|
-
_STOCK_MAP_CACHE = None
|
|
16
|
-
|
|
17
16
|
|
|
18
17
|
def _load_stock_map() -> list[dict]:
|
|
19
|
-
|
|
20
|
-
if _STOCK_MAP_CACHE is not None:
|
|
21
|
-
return _STOCK_MAP_CACHE
|
|
22
|
-
try:
|
|
18
|
+
def fetch():
|
|
23
19
|
import akshare as ak
|
|
24
20
|
|
|
25
21
|
df = _akshare_retry(ak.stock_zh_a_spot_em)
|
|
26
22
|
records = []
|
|
27
|
-
for
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
23
|
+
for row in df.to_dict("records"):
|
|
24
|
+
code, name = str(row["代码"]), row["名称"]
|
|
25
|
+
if (
|
|
26
|
+
len(code) != 6
|
|
27
|
+
or not code.isascii()
|
|
28
|
+
or not code.isdigit()
|
|
29
|
+
or not isinstance(name, str)
|
|
30
|
+
or not name.strip()
|
|
31
|
+
):
|
|
32
|
+
raise ValueError("Stock name map contains invalid codes or names")
|
|
33
|
+
records.append({"code": code, "name": name})
|
|
35
34
|
return records
|
|
35
|
+
|
|
36
|
+
try:
|
|
37
|
+
return cached("stock-name-map:v1", DAY, fetch)
|
|
36
38
|
except Exception as e:
|
|
37
39
|
raise RuntimeError(f"Failed to load stock list: {e}") from e
|
|
38
40
|
|
package/tools/requirements.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
akshare>=1.
|
|
1
|
+
akshare>=1.20.24; python_version >= "3.11"
|
|
2
2
|
akshare>=1.14.0; python_version < "3.11"
|
|
3
3
|
yfinance>=0.2.36
|
|
4
4
|
pandas>=2.0.0
|
|
@@ -7,7 +7,7 @@ pyyaml>=6.0
|
|
|
7
7
|
pypinyin>=0.50.0
|
|
8
8
|
requests>=2.33.0
|
|
9
9
|
exchange-calendars>=4.5.0
|
|
10
|
-
newspaper4k>=0.9.
|
|
10
|
+
newspaper4k>=0.9.6.1
|
|
11
11
|
efinance>=0.5.0
|
|
12
12
|
baostock>=0.8.8
|
|
13
13
|
pytdx>=1.72
|
package/tools/search_intel.py
CHANGED
|
@@ -228,13 +228,13 @@ def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
|
|
|
228
228
|
return []
|
|
229
229
|
|
|
230
230
|
|
|
231
|
-
def search_news(query: str, max_results: int = 10) -> dict:
|
|
231
|
+
def search_news(query: str, max_results: int = 10, budget_seconds: int = 45) -> dict:
|
|
232
232
|
results = []
|
|
233
233
|
engines_tried = []
|
|
234
234
|
engines_available = []
|
|
235
235
|
engines_errors = {}
|
|
236
236
|
|
|
237
|
-
with _search_budget(
|
|
237
|
+
with _search_budget(budget_seconds) as state:
|
|
238
238
|
for name, fn in [
|
|
239
239
|
("tavily", _tavily_search),
|
|
240
240
|
("brave", _brave_search),
|
package/tools/signal_tracker.py
CHANGED
|
@@ -136,11 +136,12 @@ def _save_records(store: Path, records: list):
|
|
|
136
136
|
def _append_record(store: Path, record: dict):
|
|
137
137
|
"""Append one complete JSON line; caller holds the store lock."""
|
|
138
138
|
payload = (json.dumps(record, ensure_ascii=False, default=str, allow_nan=False) + "\n").encode("utf-8")
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
139
|
+
previous = store.read_bytes() if store.exists() else b""
|
|
140
|
+
# Publish only complete records; a failed append must not leave a corrupt tail.
|
|
141
|
+
with atomic_write(store, binary=True) as stream:
|
|
142
|
+
stream.write(previous)
|
|
143
|
+
if previous and not previous.endswith(b"\n"):
|
|
144
|
+
stream.write(b"\n")
|
|
144
145
|
stream.write(payload)
|
|
145
146
|
|
|
146
147
|
|
package/tools/stock_data.py
CHANGED
|
@@ -1286,12 +1286,128 @@ def _quote_stale_marker(market: str):
|
|
|
1286
1286
|
}
|
|
1287
1287
|
|
|
1288
1288
|
|
|
1289
|
+
_YOUZHIYOUXING_TIAA = {
|
|
1290
|
+
"TIAA001001": "长钱账户",
|
|
1291
|
+
"TIAA001002": "海外长钱",
|
|
1292
|
+
"TIAA001004": "稳钱账户",
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
|
|
1296
|
+
def _quote_tiaa(symbol: str) -> dict:
|
|
1297
|
+
import requests
|
|
1298
|
+
|
|
1299
|
+
disclosure_name = _YOUZHIYOUXING_TIAA.get(symbol)
|
|
1300
|
+
result = {
|
|
1301
|
+
"symbol": symbol,
|
|
1302
|
+
"name": None,
|
|
1303
|
+
"asset_type": "investment_advisory_portfolio",
|
|
1304
|
+
"type_description": "雪球投顾组合,无统一单位净值",
|
|
1305
|
+
"manager": None,
|
|
1306
|
+
"advisor_code": f"A{symbol[4:7]}",
|
|
1307
|
+
"advisor_org": None,
|
|
1308
|
+
"advisor_mapping_basis": "tiaa_prefix_best_effort",
|
|
1309
|
+
"advisor_source_url": None,
|
|
1310
|
+
"advisor_retrieved_at": None,
|
|
1311
|
+
"nav": None,
|
|
1312
|
+
"example_account_performance": None,
|
|
1313
|
+
"quote_type": None,
|
|
1314
|
+
"exchange": None,
|
|
1315
|
+
"source": None,
|
|
1316
|
+
"source_url": f"https://xueqiu.com/S/{symbol}",
|
|
1317
|
+
"data_as_of": None,
|
|
1318
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
1319
|
+
"official_disclosures": [],
|
|
1320
|
+
"public_search_results": [],
|
|
1321
|
+
"disclosure_provider": "youzhiyouxing" if disclosure_name else None,
|
|
1322
|
+
"disclosure_status": "unavailable" if disclosure_name else "unsupported_provider",
|
|
1323
|
+
"disclosures_partial": True,
|
|
1324
|
+
"disclosures_as_of": None,
|
|
1325
|
+
"note": (
|
|
1326
|
+
"投顾组合无统一净值;主理人及完整业绩/持仓需在对应投顾平台登录后查询;"
|
|
1327
|
+
"官方公开披露仅为部分历史信息,持有人收益随买入时点和调仓跟进不同"
|
|
1328
|
+
),
|
|
1329
|
+
}
|
|
1330
|
+
try:
|
|
1331
|
+
with requests.Session() as session:
|
|
1332
|
+
session.get(
|
|
1333
|
+
"https://xueqiu.com/",
|
|
1334
|
+
headers={"User-Agent": "Mozilla/5.0"},
|
|
1335
|
+
timeout=10,
|
|
1336
|
+
allow_redirects=True,
|
|
1337
|
+
).raise_for_status()
|
|
1338
|
+
response = session.get(
|
|
1339
|
+
"https://stock.xueqiu.com/v5/stock/quote.json",
|
|
1340
|
+
params={"symbol": symbol, "extend": "detail"},
|
|
1341
|
+
headers={"User-Agent": "Mozilla/5.0", "Referer": "https://xueqiu.com/"},
|
|
1342
|
+
timeout=10,
|
|
1343
|
+
)
|
|
1344
|
+
response.raise_for_status()
|
|
1345
|
+
payload = response.json()
|
|
1346
|
+
if payload.get("error_code") not in (None, 0):
|
|
1347
|
+
raise ValueError("xueqiu portfolio metadata unavailable")
|
|
1348
|
+
quote = (payload.get("data") or {}).get("quote") or {}
|
|
1349
|
+
if quote.get("symbol") != symbol:
|
|
1350
|
+
raise ValueError("xueqiu returned different portfolio metadata")
|
|
1351
|
+
result.update(
|
|
1352
|
+
name=quote.get("name"),
|
|
1353
|
+
quote_type=quote.get("type"),
|
|
1354
|
+
exchange=quote.get("exchange"),
|
|
1355
|
+
source="xueqiu",
|
|
1356
|
+
data_as_of=_unix_quote_time(quote.get("timestamp")),
|
|
1357
|
+
)
|
|
1358
|
+
except Exception:
|
|
1359
|
+
result["warnings"] = ["xueqiu portfolio name unavailable; type guidance remains available"]
|
|
1360
|
+
if disclosure_name and result["name"] in (None, disclosure_name):
|
|
1361
|
+
try:
|
|
1362
|
+
from tiaa_disclosures import public_disclosures
|
|
1363
|
+
|
|
1364
|
+
disclosure = public_disclosures(symbol, disclosure_name)
|
|
1365
|
+
result["official_disclosures"] = disclosure["items"]
|
|
1366
|
+
result["disclosures_as_of"] = disclosure["as_of"]
|
|
1367
|
+
if disclosure["items"]:
|
|
1368
|
+
result["disclosure_status"] = "partial_public"
|
|
1369
|
+
except Exception:
|
|
1370
|
+
result.setdefault("warnings", []).append(
|
|
1371
|
+
"official public disclosures unavailable; type guidance remains available"
|
|
1372
|
+
)
|
|
1373
|
+
elif disclosure_name and result["name"]:
|
|
1374
|
+
result["disclosure_status"] = "unsupported_provider"
|
|
1375
|
+
result.setdefault("warnings", []).append("portfolio name does not match the registered disclosure source")
|
|
1376
|
+
else:
|
|
1377
|
+
from tiaa_disclosures import search_public
|
|
1378
|
+
|
|
1379
|
+
result["public_search_results"] = search_public(symbol, result["name"])
|
|
1380
|
+
if result["public_search_results"]:
|
|
1381
|
+
result["disclosure_provider"] = "web_search"
|
|
1382
|
+
result["disclosure_status"] = "search_partial"
|
|
1383
|
+
try:
|
|
1384
|
+
from tiaa_disclosures import advisor_metadata
|
|
1385
|
+
|
|
1386
|
+
result.update(advisor_metadata(symbol))
|
|
1387
|
+
except Exception:
|
|
1388
|
+
result.setdefault("warnings", []).append("advisor organization metadata unavailable")
|
|
1389
|
+
return result
|
|
1390
|
+
|
|
1391
|
+
|
|
1289
1392
|
def cmd_quote(args):
|
|
1393
|
+
if re.fullmatch(r"TIAA\d{6}", args.symbol, re.IGNORECASE):
|
|
1394
|
+
return _quote_tiaa(args.symbol.upper())
|
|
1290
1395
|
market = detect_market(args.symbol)
|
|
1291
1396
|
try:
|
|
1292
1397
|
result = quote_a(args.symbol, evidence=True) if market == "A" else quote_yf(args.symbol, evidence=True)
|
|
1293
1398
|
except Exception as e:
|
|
1294
|
-
|
|
1399
|
+
result = {"error": str(e)}
|
|
1400
|
+
# Exchange quotes cannot see open-end funds. Stock-only prefixes (SH 60/68, ChiNext 30, BSE) keep the bare error.
|
|
1401
|
+
if (
|
|
1402
|
+
isinstance(result, dict)
|
|
1403
|
+
and "error" in result
|
|
1404
|
+
and re.fullmatch(r"\d{6}", args.symbol)
|
|
1405
|
+
and not re.match(r"(?:60|68|30|43|83|87|92)", args.symbol)
|
|
1406
|
+
):
|
|
1407
|
+
result["hint"] = (
|
|
1408
|
+
f"{args.symbol} 若为场外公募基金,请改用 get_fund_quote(stock_data.py fund_quote {args.symbol})"
|
|
1409
|
+
)
|
|
1410
|
+
return result
|
|
1295
1411
|
if isinstance(result, dict) and "error" not in result:
|
|
1296
1412
|
marker = _quote_stale_marker(market)
|
|
1297
1413
|
if marker:
|
|
@@ -1322,6 +1438,109 @@ def cmd_quote(args):
|
|
|
1322
1438
|
return result
|
|
1323
1439
|
|
|
1324
1440
|
|
|
1441
|
+
# --------------- open-end fund quote ---------------
|
|
1442
|
+
|
|
1443
|
+
|
|
1444
|
+
def _fund_js_value(text: str, name: str):
|
|
1445
|
+
match = re.search(rf"\b{re.escape(name)}\s*=\s*", text)
|
|
1446
|
+
if not match:
|
|
1447
|
+
raise ValueError(f"eastmoney fund data missing {name}")
|
|
1448
|
+
try:
|
|
1449
|
+
return json.JSONDecoder().raw_decode(text[match.end() :])[0]
|
|
1450
|
+
except json.JSONDecodeError as exc:
|
|
1451
|
+
raise ValueError(f"eastmoney fund data has invalid {name}") from exc
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
def _fund_nav_date(stamp) -> str:
|
|
1455
|
+
return datetime.fromtimestamp(stamp / 1000, timezone.utc).astimezone(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
1456
|
+
|
|
1457
|
+
|
|
1458
|
+
def _fund_estimate(symbol: str) -> dict:
|
|
1459
|
+
import akshare as ak
|
|
1460
|
+
|
|
1461
|
+
with socket_timeout(25):
|
|
1462
|
+
df = ak.fund_value_estimation_em()
|
|
1463
|
+
if df is None or df.empty or "基金代码" not in df.columns:
|
|
1464
|
+
return {}
|
|
1465
|
+
rows = df[df["基金代码"] == symbol]
|
|
1466
|
+
value_col = next((c for c in df.columns if c.endswith("-估算数据-估算值")), None)
|
|
1467
|
+
change_col = next((c for c in df.columns if c.endswith("-估算数据-估算增长率")), None)
|
|
1468
|
+
if rows.empty or not value_col:
|
|
1469
|
+
return {}
|
|
1470
|
+
row = rows.iloc[0]
|
|
1471
|
+
estimated_nav = _parse_float(row.get(value_col))
|
|
1472
|
+
if estimated_nav is None:
|
|
1473
|
+
return {}
|
|
1474
|
+
return {
|
|
1475
|
+
"estimated_nav": estimated_nav,
|
|
1476
|
+
"estimated_change_pct": _parse_float(str(row.get(change_col)).rstrip("%")) if change_col else None,
|
|
1477
|
+
"estimated_at": value_col.split("-估算数据-", 1)[0],
|
|
1478
|
+
"estimate_status": "available",
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
def cmd_fund_quote(args):
|
|
1483
|
+
symbol = args.symbol
|
|
1484
|
+
if not re.fullmatch(r"\d{6}", symbol):
|
|
1485
|
+
return {"error": "open-end fund symbol must be exactly 6 digits"}
|
|
1486
|
+
try:
|
|
1487
|
+
import requests
|
|
1488
|
+
|
|
1489
|
+
response = requests.get(f"https://fund.eastmoney.com/pingzhongdata/{symbol}.js", timeout=15)
|
|
1490
|
+
response.raise_for_status()
|
|
1491
|
+
text = response.text
|
|
1492
|
+
if _fund_js_value(text, "fS_code") != symbol:
|
|
1493
|
+
raise ValueError(f"eastmoney returned a different fund for {symbol}")
|
|
1494
|
+
name = _fund_js_value(text, "fS_name")
|
|
1495
|
+
nav_rows = _fund_js_value(text, "Data_netWorthTrend")
|
|
1496
|
+
accumulated_rows = _fund_js_value(text, "Data_ACWorthTrend")
|
|
1497
|
+
if not nav_rows:
|
|
1498
|
+
raise ValueError(f"eastmoney returned no NAV for {symbol}")
|
|
1499
|
+
latest = nav_rows[-1]
|
|
1500
|
+
nav_date = _fund_nav_date(latest["x"])
|
|
1501
|
+
accumulated_by_date = {_fund_nav_date(row[0]): row[1] for row in accumulated_rows}
|
|
1502
|
+
today = datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
1503
|
+
estimate = {
|
|
1504
|
+
"estimated_nav": None,
|
|
1505
|
+
"estimated_change_pct": None,
|
|
1506
|
+
"estimated_at": None,
|
|
1507
|
+
"estimate_status": "unavailable",
|
|
1508
|
+
}
|
|
1509
|
+
warnings = []
|
|
1510
|
+
try:
|
|
1511
|
+
estimate.update(_fund_estimate(symbol))
|
|
1512
|
+
except Exception:
|
|
1513
|
+
warnings.append("estimated NAV provider request failed; published NAV remains available")
|
|
1514
|
+
result = _clean_row(
|
|
1515
|
+
{
|
|
1516
|
+
"symbol": symbol,
|
|
1517
|
+
"name": name,
|
|
1518
|
+
"asset_type": "open_end_fund",
|
|
1519
|
+
"nav": latest.get("y"),
|
|
1520
|
+
"accumulated_nav": accumulated_by_date.get(nav_date),
|
|
1521
|
+
"change_pct": latest.get("equityReturn"),
|
|
1522
|
+
"nav_date": nav_date,
|
|
1523
|
+
"data_as_of": nav_date,
|
|
1524
|
+
"as_of": nav_date,
|
|
1525
|
+
"as_of_basis": "provider",
|
|
1526
|
+
"stale": nav_date < today,
|
|
1527
|
+
"source": "eastmoney",
|
|
1528
|
+
"source_url": f"https://fund.eastmoney.com/{symbol}.html",
|
|
1529
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
1530
|
+
"note": (
|
|
1531
|
+
"nav is published end-of-day NAV, not a real-time price; QDII disclosure may lag "
|
|
1532
|
+
"1-2 trading days; estimated_nav is separate and may be unavailable"
|
|
1533
|
+
),
|
|
1534
|
+
**estimate,
|
|
1535
|
+
}
|
|
1536
|
+
)
|
|
1537
|
+
if warnings:
|
|
1538
|
+
result["warnings"] = warnings
|
|
1539
|
+
return result
|
|
1540
|
+
except Exception as e:
|
|
1541
|
+
return {"error": str(e)}
|
|
1542
|
+
|
|
1543
|
+
|
|
1325
1544
|
# --------------- capital_flow ---------------
|
|
1326
1545
|
|
|
1327
1546
|
|
|
@@ -1872,7 +2091,8 @@ def snapshot_hk() -> list:
|
|
|
1872
2091
|
try:
|
|
1873
2092
|
import akshare as ak
|
|
1874
2093
|
|
|
1875
|
-
|
|
2094
|
+
with socket_timeout(25):
|
|
2095
|
+
df = _akshare_retry(ak.stock_hk_spot_em)
|
|
1876
2096
|
col_map = {
|
|
1877
2097
|
"代码": "symbol",
|
|
1878
2098
|
"名称": "name",
|
|
@@ -1900,7 +2120,8 @@ def snapshot_us() -> list:
|
|
|
1900
2120
|
try:
|
|
1901
2121
|
import akshare as ak
|
|
1902
2122
|
|
|
1903
|
-
|
|
2123
|
+
with socket_timeout(25):
|
|
2124
|
+
df = _akshare_retry(ak.stock_us_spot_em)
|
|
1904
2125
|
col_map = {
|
|
1905
2126
|
"代码": "symbol",
|
|
1906
2127
|
"名称": "name",
|
|
@@ -1996,33 +2217,39 @@ def cmd_market_indices(args):
|
|
|
1996
2217
|
)
|
|
1997
2218
|
return results
|
|
1998
2219
|
elif region in _REGION_INDEX_SYMBOLS:
|
|
2220
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
2221
|
+
|
|
1999
2222
|
import yfinance as yf
|
|
2000
2223
|
|
|
2001
2224
|
symbols = _REGION_INDEX_SYMBOLS[region]
|
|
2002
|
-
|
|
2003
|
-
|
|
2225
|
+
|
|
2226
|
+
def fetch_index(item):
|
|
2227
|
+
sym, name = item
|
|
2004
2228
|
try:
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2229
|
+
info = yf.Ticker(sym).info
|
|
2230
|
+
return _clean_row(
|
|
2231
|
+
{
|
|
2232
|
+
"code": sym,
|
|
2233
|
+
"name": name,
|
|
2234
|
+
"price": info.get("regularMarketPrice"),
|
|
2235
|
+
"change": info.get("regularMarketChange"),
|
|
2236
|
+
"change_pct": info.get("regularMarketChangePercent"),
|
|
2237
|
+
"volume": info.get("regularMarketVolume"),
|
|
2238
|
+
"high": info.get("regularMarketDayHigh"),
|
|
2239
|
+
"low": info.get("regularMarketDayLow"),
|
|
2240
|
+
"open": info.get("regularMarketOpen"),
|
|
2241
|
+
"prev_close": info.get("regularMarketPreviousClose"),
|
|
2242
|
+
"source": "yfinance",
|
|
2243
|
+
"data_as_of": _unix_quote_time(info.get("regularMarketTime")),
|
|
2244
|
+
"fetched_at": datetime.now(timezone.utc).isoformat(),
|
|
2245
|
+
}
|
|
2022
2246
|
)
|
|
2023
2247
|
except Exception:
|
|
2024
|
-
|
|
2025
|
-
|
|
2248
|
+
return {"code": sym, "name": name, "note": "data unavailable"}
|
|
2249
|
+
|
|
2250
|
+
# Preserve provider order while overlapping independent quote requests.
|
|
2251
|
+
with ThreadPoolExecutor(max_workers=min(4, len(symbols))) as pool:
|
|
2252
|
+
return list(pool.map(fetch_index, symbols.items()))
|
|
2026
2253
|
return {"error": f"Unknown region: {region}"}
|
|
2027
2254
|
except Exception as e:
|
|
2028
2255
|
return {"error": str(e)}
|
|
@@ -3382,6 +3609,9 @@ def main():
|
|
|
3382
3609
|
p_quote = sub.add_parser("quote")
|
|
3383
3610
|
p_quote.add_argument("symbol")
|
|
3384
3611
|
|
|
3612
|
+
p_fund_quote = sub.add_parser("fund_quote")
|
|
3613
|
+
p_fund_quote.add_argument("symbol")
|
|
3614
|
+
|
|
3385
3615
|
p_cf = sub.add_parser("capital_flow")
|
|
3386
3616
|
p_cf.add_argument("symbol", nargs="?", default="")
|
|
3387
3617
|
p_cf.add_argument("--mode", default="detail", choices=["detail", "summary", "sector_flow"])
|
|
@@ -3451,6 +3681,7 @@ def main():
|
|
|
3451
3681
|
dispatch = {
|
|
3452
3682
|
"kline": cmd_kline,
|
|
3453
3683
|
"quote": cmd_quote,
|
|
3684
|
+
"fund_quote": cmd_fund_quote,
|
|
3454
3685
|
"capital_flow": cmd_capital_flow,
|
|
3455
3686
|
"news": cmd_news,
|
|
3456
3687
|
"financials": cmd_financials,
|