@weaxs/openclaw-stock-analysis 0.2.10 → 0.2.12

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.
Files changed (41) hide show
  1. package/README.md +11 -51
  2. package/dist/index.js +3693 -1971
  3. package/index.ts +74 -1636
  4. package/openclaw.plugin.json +3 -0
  5. package/package.json +3 -3
  6. package/scripts/cli-json.mjs +23 -0
  7. package/scripts/exec-process.mjs +89 -0
  8. package/scripts/setup-python.mjs +37 -4
  9. package/scripts/tool-calls.mjs +489 -0
  10. package/skills/event-driven/SKILL.md +2 -2
  11. package/skills/growth-quality/SKILL.md +1 -1
  12. package/skills/stock-analysis/SKILL.md +12 -7
  13. package/skills/stock-analysis/references/stateless-analysis.md +9 -1
  14. package/tools/_cache.py +13 -0
  15. package/tools/_subproc.py +46 -0
  16. package/tools/alert_rules.py +65 -16
  17. package/tools/backtest.py +3 -3
  18. package/tools/capabilities.py +32 -9
  19. package/tools/cli_budgets.json +2 -0
  20. package/tools/diagnostics.py +3 -4
  21. package/tools/gather.py +2 -6
  22. package/tools/import_parser.py +3 -4
  23. package/tools/lixinger.py +119 -27
  24. package/tools/market_regime.py +5 -2
  25. package/tools/market_review.py +5 -6
  26. package/tools/name_resolver.py +82 -21
  27. package/tools/report_renderer.py +3 -3
  28. package/tools/requirements.txt +6 -5
  29. package/tools/risk_screening.py +3 -2
  30. package/tools/screener.py +6 -4
  31. package/tools/search_intel.py +81 -12
  32. package/tools/sec_edgar.py +266 -0
  33. package/tools/sec_holders.py +6 -0
  34. package/tools/signal_tracker.py +11 -10
  35. package/tools/stateless_analysis.py +115 -0
  36. package/tools/stock_data.py +707 -222
  37. package/tools/tiaa_disclosures.py +267 -0
  38. package/tools/tool_schemas.json +2704 -0
  39. package/tools/trading_calendar.py +65 -30
  40. package/tools/value_data.py +366 -134
  41. package/tools/watchlist.py +43 -5
@@ -0,0 +1,489 @@
1
+ import TOOL_SCHEMAS from "../tools/tool_schemas.json" with { type: "json" };
2
+ import { withJsonInput } from "./json-input.mjs";
3
+
4
+ export { TOOL_SCHEMAS };
5
+
6
+ // Shared host -> CLI mapping for the Pi, OpenClaw and dsh adapters; parameter
7
+ // schemas live in tools/tool_schemas.json and Hermes keeps its Python twin
8
+ // (hermes/tools.py). tests/test_adapter_parity.ts pins all of them together.
9
+ // `input` tools ship their JSON through a temp file (argv limits on Windows).
10
+ export const TOOL_CALLS = {
11
+ get_announcements: {
12
+ script: "value_data.py",
13
+ argv: (p) => ["announcements", p.symbol, "--category", p.category ?? "all", "--start-date", p.start_date ?? "", "--end-date", p.end_date ?? "", "--top", String(p.top ?? 50)],
14
+ },
15
+ get_us_holdings: {
16
+ script: "sec_edgar.py",
17
+ argv: (p) => ["holdings", p.cik, ...(p.mode ? ["--mode", p.mode] : [])],
18
+ },
19
+ get_insider_trades: {
20
+ script: "sec_edgar.py",
21
+ argv: (p) => ["insider_trades", p.symbol, "--days", String(p.days ?? 90), "--top", String(p.top ?? 10)],
22
+ },
23
+ get_valuation_history: {
24
+ script: "value_data.py",
25
+ argv: (p) => ["valuation_history", p.symbol, "--years", String(p.years ?? 5)],
26
+ },
27
+ get_index_valuation: {
28
+ script: "value_data.py",
29
+ argv: (p) => ["index_valuation", p.symbol, "--years", String(p.years ?? 5)],
30
+ },
31
+ get_earnings_calendar: {
32
+ script: "value_data.py",
33
+ argv: (p) => ["earnings_calendar", "--report-date", p.report_date ?? "", "--symbol", p.symbol ?? "", "--top", String(p.top ?? 50)],
34
+ },
35
+ get_shareholder_structure: {
36
+ script: "value_data.py",
37
+ argv: (p) => ["shareholder_structure", p.symbol, "--report-date", p.report_date ?? ""],
38
+ },
39
+ get_etf_details: {
40
+ script: "value_data.py",
41
+ argv: (p) => ["etf_details", p.symbol, "--benchmark", p.benchmark ?? "", "--days", String(p.days ?? 60), ...(p.include_full_holdings ? ["--include-full-holdings"] : [])],
42
+ },
43
+ get_dividends: {
44
+ script: "value_data.py",
45
+ argv: (p) => ["dividends", "--market", p.market ?? "A", "--symbol", p.symbol ?? "", "--mode", p.mode ?? "history", "--report-date", p.report_date ?? "", "--years", String(p.years ?? 10), "--top", String(p.top ?? 20)],
46
+ },
47
+ get_kline: {
48
+ script: "stock_data.py",
49
+ argv: (p) => [
50
+ "kline",
51
+ p.symbol,
52
+ "--period",
53
+ p.period ?? "daily",
54
+ "--count",
55
+ String(p.count ?? 60),
56
+ ],
57
+ },
58
+ get_quote: {
59
+ script: "stock_data.py",
60
+ argv: (p) => ["quote", p.symbol],
61
+ },
62
+ get_fund_quote: {
63
+ script: "stock_data.py",
64
+ argv: (p) => ["fund_quote", p.symbol],
65
+ },
66
+ get_capital_flow: {
67
+ script: "stock_data.py",
68
+ argv: (p) => {
69
+ const args = ["capital_flow"];
70
+ if (p.symbol) args.push(p.symbol);
71
+ args.push("--mode", p.mode ?? "detail");
72
+ return args;
73
+ },
74
+ },
75
+ get_news: {
76
+ script: "stock_data.py",
77
+ argv: (p) => ["news", p.symbol, "--days", String(p.days ?? 3)],
78
+ },
79
+ get_financials: {
80
+ script: "stock_data.py",
81
+ argv: (p) => {
82
+ const args = ["financials", p.symbol];
83
+ if (p.periods !== undefined && p.periods !== 1) args.push("--periods", String(p.periods));
84
+ if (p.annual) args.push("--annual");
85
+ if (p.include_dcf_inputs) args.push("--include-dcf-inputs");
86
+ return args;
87
+ },
88
+ },
89
+ get_technical_analysis: {
90
+ script: "technical.py",
91
+ argv: (p) => {
92
+ const args = [
93
+ "analyze",
94
+ p.symbol,
95
+ "--period",
96
+ p.period ?? "daily",
97
+ "--count",
98
+ String(p.count ?? 120),
99
+ ];
100
+ if (p.periods) args.push("--periods", p.periods);
101
+ return args;
102
+ },
103
+ },
104
+ analyze_pattern: {
105
+ script: "pattern.py",
106
+ argv: (p) => [
107
+ "analyze",
108
+ p.symbol,
109
+ "--period",
110
+ p.period ?? "daily",
111
+ "--days",
112
+ String(p.days ?? 60),
113
+ ],
114
+ },
115
+ get_market_indices: {
116
+ script: "stock_data.py",
117
+ argv: (p) => ["market_indices", "--region", p.region ?? "cn"],
118
+ },
119
+ get_sector_rankings: {
120
+ script: "stock_data.py",
121
+ argv: (p) => [
122
+ "sector_rankings",
123
+ "--top",
124
+ String(p.top ?? 10),
125
+ "--direction",
126
+ p.direction ?? "top",
127
+ "--board-type",
128
+ p.board_type ?? "industry",
129
+ "--market",
130
+ p.market ?? "A",
131
+ ],
132
+ },
133
+ get_sector_constituents: {
134
+ script: "stock_data.py",
135
+ argv: (p) => [
136
+ "sector_constituents",
137
+ p.sector,
138
+ "--board-type",
139
+ p.board_type ?? "auto",
140
+ ],
141
+ },
142
+ resolve_stock_sectors: {
143
+ script: "stock_data.py",
144
+ argv: (p) => ["resolve_stock_sectors", p.symbol],
145
+ },
146
+ get_stock_info: {
147
+ script: "stock_data.py",
148
+ argv: (p) => ["stock_info", p.symbol],
149
+ },
150
+ get_chip_distribution: {
151
+ script: "stock_data.py",
152
+ argv: (p) => ["chip_distribution", p.symbol],
153
+ },
154
+ get_market_stats: {
155
+ script: "stock_data.py",
156
+ argv: (p) => ["market_stats", "--market", p.market ?? "A"],
157
+ },
158
+ get_limit_up_pool: {
159
+ script: "stock_data.py",
160
+ argv: (p) => {
161
+ const args = ["limit_up_pool"];
162
+ if (p.date) args.push("--date", p.date);
163
+ return args;
164
+ },
165
+ },
166
+ get_dragon_tiger: {
167
+ script: "stock_data.py",
168
+ argv: (p) => {
169
+ const args = ["dragon_tiger"];
170
+ if (p.date) args.push("--date", p.date);
171
+ if (p.symbol) args.push("--symbol", p.symbol);
172
+ args.push("--top", String(p.top ?? 20));
173
+ return args;
174
+ },
175
+ },
176
+ get_hot_stocks: {
177
+ script: "stock_data.py",
178
+ argv: (p) => ["hot_stocks", "--top", String(p.top ?? 20)],
179
+ },
180
+ get_margin_trading: {
181
+ script: "stock_data.py",
182
+ argv: (p) => ["margin_trading", p.symbol, "--days", String(p.days ?? 10), ...(p.include_ratio ? ["--include-ratio"] : [])],
183
+ },
184
+ get_northbound_flow: {
185
+ script: "stock_data.py",
186
+ argv: (p) => ["northbound_flow", "--days", String(p.days ?? 10)],
187
+ },
188
+ get_fundamental_context: {
189
+ script: "stock_data.py",
190
+ argv: (p) => ["fundamental_context", p.symbol],
191
+ },
192
+ screen_stocks: {
193
+ script: "screener.py",
194
+ argv: (p) => {
195
+ const args = ["screen", "--market", p.market ?? "A", "--top", String(p.top ?? 20)];
196
+ if (p.config) args.push("--config", p.config);
197
+ if (p.l2) args.push("--l2");
198
+ return args;
199
+ },
200
+ },
201
+ calculate_rotation_metrics: {
202
+ script: "sector_rotation.py",
203
+ input: (p) => p,
204
+ argv: (p, path) => ["analyze", "--input", path],
205
+ },
206
+ backtest_rotation_allocation: {
207
+ script: "sector_rotation.py",
208
+ input: (p) => p,
209
+ argv: (p, path) => ["backtest", "--input", path],
210
+ },
211
+ analyze_trend_strategy: {
212
+ script: "trend_strategy.py",
213
+ input: (p) => p,
214
+ argv: (p, path) => ["fetch", "--input", path],
215
+ },
216
+ run_backtest: {
217
+ script: "backtest.py",
218
+ argv: (p) => {
219
+ const args = ["run", p.strategy, p.symbol];
220
+ if (p.start) args.push("--start", p.start);
221
+ if (p.end) args.push("--end", p.end);
222
+ args.push("--capital", String(p.capital ?? 1000000));
223
+ return args;
224
+ },
225
+ },
226
+ evaluate_signal: {
227
+ script: "backtest.py",
228
+ argv: (p) => [
229
+ "evaluate_signal",
230
+ p.symbol,
231
+ p.signal,
232
+ "--forward",
233
+ p.forward_days ?? "3,5,10",
234
+ "--lookback",
235
+ String(p.lookback ?? 250),
236
+ ],
237
+ },
238
+ resolve_stock_name: {
239
+ script: "name_resolver.py",
240
+ argv: (p) => ["resolve", p.query, "--top", String(p.top ?? 5)],
241
+ },
242
+ check_trading_day: {
243
+ script: "trading_calendar.py",
244
+ argv: (p) => {
245
+ const args = ["check", p.market];
246
+ if (p.date) args.push("--date", p.date);
247
+ return args;
248
+ },
249
+ },
250
+ get_trading_days: {
251
+ script: "trading_calendar.py",
252
+ argv: (p) => {
253
+ const args = [p.direction ?? "next", p.market, "--count", String(p.count ?? 5)];
254
+ if (p.date) args.push("--date", p.date);
255
+ return args;
256
+ },
257
+ },
258
+ get_trading_phase: {
259
+ script: "trading_calendar.py",
260
+ argv: (p) => ["phase", p.market],
261
+ },
262
+ calculate_ma: {
263
+ script: "technical.py",
264
+ argv: (p) => [
265
+ "calculate_ma",
266
+ p.symbol,
267
+ "--periods",
268
+ p.periods ?? "5,10,20,30,60,120,250",
269
+ "--period",
270
+ p.kline_period ?? "daily",
271
+ "--count",
272
+ "300",
273
+ ],
274
+ },
275
+ get_volume_analysis: {
276
+ script: "volume_analysis.py",
277
+ argv: (p) => [
278
+ "analyze",
279
+ p.symbol,
280
+ "--period",
281
+ p.period ?? "daily",
282
+ "--count",
283
+ String(p.count ?? 60),
284
+ ],
285
+ },
286
+ search_stock_news: {
287
+ script: "search_intel.py",
288
+ argv: (p) => ["search", p.query, "--count", String(p.count ?? 10)],
289
+ },
290
+ search_comprehensive_intel: {
291
+ script: "search_intel.py",
292
+ argv: (p) => {
293
+ const args = ["comprehensive", p.symbol];
294
+ if (p.name) args.push("--name", p.name);
295
+ return args;
296
+ },
297
+ },
298
+ get_social_sentiment: {
299
+ script: "search_intel.py",
300
+ argv: (p) => ["sentiment", p.symbol],
301
+ },
302
+ get_trending_sentiment: {
303
+ script: "search_intel.py",
304
+ argv: () => ["trending"],
305
+ },
306
+ extract_article: {
307
+ script: "search_intel.py",
308
+ argv: (p) => ["extract", p.url, "--max-chars", String(p.max_chars ?? 3000)],
309
+ },
310
+ screen_risk: {
311
+ script: "risk_screening.py",
312
+ argv: (p) => {
313
+ const args = ["screen", p.symbol];
314
+ if (p.name) args.push("--name", p.name);
315
+ return args;
316
+ },
317
+ },
318
+ detect_market_regime: {
319
+ script: "market_regime.py",
320
+ argv: (p) => ["detect", p.market ?? "A"],
321
+ },
322
+ get_market_review: {
323
+ script: "market_review.py",
324
+ argv: (p) => ["review", "--market", p.market ?? "A"],
325
+ },
326
+ get_watchlist: {
327
+ script: "watchlist.py",
328
+ argv: () => ["list"],
329
+ },
330
+ run_watchlist_analysis: {
331
+ script: "watchlist.py",
332
+ argv: (p) => ["analyze", p.symbols, "--workers", String(p.workers ?? 3)],
333
+ },
334
+ detect_anomaly: {
335
+ script: "anomaly_detect.py",
336
+ argv: (p) => ["detect", p.symbol],
337
+ },
338
+ diagnose_data_sources: {
339
+ script: "diagnostics.py",
340
+ argv: (p) => ["check", "--market", p.market ?? "all"],
341
+ },
342
+ get_market_capabilities: {
343
+ script: "capabilities.py",
344
+ argv: (p) =>
345
+ p.symbol
346
+ ? ["get", "--symbol", p.symbol]
347
+ : ["get", "--market", p.market ?? "A"],
348
+ },
349
+ render_stock_report: {
350
+ script: "report_renderer.py",
351
+ input: (p) => p.report,
352
+ argv: (p, path) => ["stock", "--template", p.template ?? "full", "--input", path, ...(p.final ? ["--final"] : [])],
353
+ },
354
+ render_market_report: {
355
+ script: "report_renderer.py",
356
+ input: (p) => p.report,
357
+ argv: (p, path) => ["market", "--input", path, ...(p.final ? ["--final"] : []), ...(p.save ? ["--save"] : [])],
358
+ },
359
+ get_review_history: {
360
+ script: "market_review.py",
361
+ argv: (p) => ["history", "--limit", String(p.limit ?? 10)],
362
+ },
363
+ build_watchlist_context: {
364
+ script: "watchlist_context.py",
365
+ argv: (p) => {
366
+ const args = ["build", p.symbols, "--workers", String(p.workers ?? 3)];
367
+ if (p.include_market_review) args.push("--include-market-review");
368
+ return args;
369
+ },
370
+ },
371
+ analyze_position_context: {
372
+ script: "position_context.py",
373
+ argv: (p) => {
374
+ const args = [
375
+ "analyze",
376
+ p.symbol,
377
+ "--cost",
378
+ String(p.cost),
379
+ "--quantity",
380
+ String(p.quantity),
381
+ ];
382
+ if (p.stop_loss !== undefined) args.push("--stop-loss", String(p.stop_loss));
383
+ if (p.take_profit !== undefined) args.push("--take-profit", String(p.take_profit));
384
+ return args;
385
+ },
386
+ },
387
+ check_alert_rules: {
388
+ script: "alert_rules.py",
389
+ argv: (p) => {
390
+ const b64 = Buffer.from(JSON.stringify(p.rules), "utf-8").toString("base64");
391
+ return ["check", p.symbol, "--rules-b64", b64];
392
+ },
393
+ },
394
+ record_signal: {
395
+ script: "signal_tracker.py",
396
+ argv: (p) => {
397
+ const args = [
398
+ "record",
399
+ p.symbol,
400
+ "--direction",
401
+ p.direction,
402
+ "--horizon-days",
403
+ String(p.horizon_days ?? 10),
404
+ ];
405
+ if (p.entry_price !== undefined) args.push("--entry-price", String(p.entry_price));
406
+ if (p.target_price !== undefined) args.push("--target-price", String(p.target_price));
407
+ if (p.stop_price !== undefined) args.push("--stop-price", String(p.stop_price));
408
+ if (p.source) args.push("--source", p.source);
409
+ if (p.note) args.push("--note", p.note);
410
+ return args;
411
+ },
412
+ },
413
+ evaluate_signals: {
414
+ script: "signal_tracker.py",
415
+ argv: (p) => {
416
+ const args = ["evaluate"];
417
+ if (p.symbol) args.push("--symbol", p.symbol);
418
+ return args;
419
+ },
420
+ },
421
+ get_signal_summary: {
422
+ script: "signal_tracker.py",
423
+ argv: (p) => {
424
+ const args = ["summary"];
425
+ if (p.source) args.push("--source", p.source);
426
+ if (p.symbol) args.push("--symbol", p.symbol);
427
+ args.push("--status", p.status ?? "all");
428
+ return args;
429
+ },
430
+ },
431
+ parse_stock_list: {
432
+ script: "import_parser.py",
433
+ argv: (p) => {
434
+ const b64 = Buffer.from(String(p.text), "utf-8").toString("base64");
435
+ return ["parse", "--text-b64", b64];
436
+ },
437
+ },
438
+ compare_stocks: {
439
+ script: "stateless_analysis.py",
440
+ input: (p) => p,
441
+ argv: (p, path) => ["peers", "--input", path],
442
+ },
443
+ analyze_disclosure_changes: {
444
+ script: "stateless_analysis.py",
445
+ input: (p) => p,
446
+ argv: (p, path) => ["disclosure", "--input", path],
447
+ },
448
+ analyze_portfolio_risk: {
449
+ script: "stateless_analysis.py",
450
+ input: (p) => p,
451
+ argv: (p, path) => ["portfolio", "--input", path],
452
+ },
453
+ plan_portfolio_rebalance: {
454
+ script: "stateless_analysis.py",
455
+ input: (p) => p,
456
+ argv: (p, path) => ["rebalance", "--input", path],
457
+ },
458
+ calculate_position_size: {
459
+ script: "stateless_analysis.py",
460
+ input: (p) => p,
461
+ argv: (p, path) => ["position_size", "--input", path],
462
+ },
463
+ calculate_dcf_valuation: {
464
+ script: "stateless_analysis.py",
465
+ input: (p) => p,
466
+ argv: (p, path) => ["dcf", "--input", path],
467
+ },
468
+ analyze_event_study: {
469
+ script: "stateless_analysis.py",
470
+ input: (p) => p,
471
+ argv: (p, path) => ["event_study", "--input", path],
472
+ },
473
+ validate_backtest: {
474
+ script: "stateless_analysis.py",
475
+ input: (p) => p,
476
+ argv: (p, path) => ["robustness", "--input", path],
477
+ },
478
+ compare_analysis_snapshots: {
479
+ script: "stateless_analysis.py",
480
+ input: (p) => p,
481
+ argv: (p, path) => ["snapshot", "--input", path],
482
+ },
483
+ };
484
+
485
+ /** Run one tool call; `run(script, argv)` resolves to the CLI's JSON text. */
486
+ export function callTool(name, args, run) {
487
+ const { script, argv, input } = TOOL_CALLS[name];
488
+ return input ? withJsonInput(input(args), path => run(script, argv(args, path))) : run(script, argv(args));
489
+ }
@@ -28,7 +28,7 @@ gather 工具返回:
28
28
  - `stock_info` — 公司基本信息
29
29
  - `sector_rankings` — 板块排名
30
30
 
31
- A 股事件原文先调用 `get_announcements`:业绩预告用 `forecast`、快报用 `express`、减持用 `reduction`、增发用 `issuance`、问询及回复用 `inquiry`、分红用 `dividend`,指定 `start_date/end_date`。返回 PDF 链接而非正文;读取原文后再量化,`truncated=true` 时缩小日期范围。
31
+ 事件原文先调用 `get_announcements`:A 股业绩预告用 `forecast`、快报用 `express`、减持用 `reduction`、增发用 `issuance`、问询及回复用 `inquiry`、分红用 `dividend`;港股用 HKEXnews,支持 `all/forecast/annual/interim/quarterly/issuance/dividend`;美股用 SEC 申报(`all` 含 8-K/6-K/DEF 14A,需 SEC_USER_AGENT),不支持的类别会报错。指定 `start_date/end_date`;PDF/HTML 原文用 `extract_article` 提取并检查 `truncated`,读取后再量化,列表截断时缩小日期范围。
32
32
 
33
33
  新闻摘要只用于发现事件。金额、期限、合同对手、业绩变化或政策原文必须由公告/原文确认;只有摘要时不做精确量化。
34
34
 
@@ -100,4 +100,4 @@ A 股事件原文先调用 `get_announcements`:业绩预告用 `forecast`、
100
100
 
101
101
  ### 补充数据覆盖
102
102
 
103
- get_earnings_calendar 查询 A 股仍需 report_date;HK 提供 symbol,可选财政期末 report_date;优先 HKEX 已公告业绩审批董事会排期 confirmation=official_board_meeting_notice、date_kind=scheduled_board_meeting,不能称实际披露日。供应商备选日期为 provider_only,未知期次在请求特定报告期时另列 unverified_schedules,不能强行匹配。
103
+ get_earnings_calendar 查询 A 股仍需 report_date;HK 提供 symbol,可选财政期末 report_date;优先 HKEX 已公告业绩审批董事会排期 confirmation=official_board_meeting_notice、date_kind=scheduled_board_meeting,不能称实际披露日。US/JP 提供 symbol,日期来自 yfinance、confirmation=provider_only,非官方确认;KR/TW 不可用。未知期次在请求特定报告期时另列 unverified_schedules,不能强行匹配。
@@ -26,7 +26,7 @@ gather 工具返回:
26
26
  - `stock_info` — 公司基本信息(行业、板块)
27
27
  - `sector_rankings` — 板块排名
28
28
 
29
- 需要财务趋势时调用 `get_financials(symbol, annual=true, periods=10)`。港股配置 `LIXINGER_TOKEN` 后优先理杏仁非金融公司财报,按真实 `report_type` 判断年报,保留实际财年末、披露日期、币种;历史 ROE/毛利率/净利率为百分数,顶层 `roe/profit_margin` 延续小数比例。读取 `available_periods/warnings`,缺期不补造。有效 Yahoo 顶层快照与历史行分开读:`currency` 为快照财报币种、`market_cap_currency` 为市值币种,历史币种在 `periods` 每行,`snapshot_source` 标记快照来源;null 不用历史值补成跨期或跨币种数字;顶层 `report_date` 未知时读取 `periods` 的历史日期,不当作当前快照报告期。
29
+ 需要财务趋势时调用 `get_financials(symbol, annual=true, periods=10)`。港股配置 `LIXINGER_TOKEN` 后优先理杏仁非金融公司财报,按真实 `report_type` 判断年报,保留实际财年末、披露日期、币种;历史 ROE/毛利率/净利率为百分数,顶层 `roe/profit_margin` 延续小数比例。读取 `available_periods/warnings`,缺期不补造。A/港/美股需要 DCF 输入时追加 `include_dcf_inputs=true`,读取 `dcf_inputs.source/periods/warnings`,每行 `field_sources` 标明字段来源、`missing_fields` 列出仍缺字段;`total_debt` 不含租赁,`lease_liabilities` 单列,按估值口径决定是否计入债务。有效 Yahoo 顶层快照与历史行分开读:`currency` 为快照财报币种、`market_cap_currency` 为市值币种,历史币种在 `periods` 每行,`snapshot_source` 标记快照来源;null 不用历史值补成跨期或跨币种数字;顶层 `report_date` 未知时读取 `periods` 的历史日期,不当作当前快照报告期。
30
30
 
31
31
  Yahoo 顶层快照单位以 `snapshot_units` 为准:`roe/profit_margin/dividend_yield=ratio`,`debt_to_equity=percent`,例如 150 表示 150%,不是 150 倍;`pe=trailing`,不与 dynamic PE 直接比较。
32
32
 
@@ -17,7 +17,7 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
17
17
 
18
18
  ## 无状态分析扩展
19
19
 
20
- 当用户要求同行比较、组合风险/压力测试、目标权重调仓、仓位预算或新旧分析比较时,MUST 读取[无状态研究工具](references/stateless-analysis.md),分别使用 compare_stocks、analyze_portfolio_risk、plan_portfolio_rebalance、calculate_position_size、compare_analysis_snapshots。所有用户状态均由本次输入提供;调仓计划数量不等于成交,现金不足或整手差额必须读取 unfilled 说明。
20
+ 当用户要求同行比较、组合风险/压力测试、目标权重调仓、仓位预算、DCF 估值或新旧分析比较时,MUST 读取[无状态研究工具](references/stateless-analysis.md),分别使用 compare_stocks、analyze_portfolio_risk、plan_portfolio_rebalance、calculate_position_size、calculate_dcf_valuation、compare_analysis_snapshots。所有用户状态均由本次输入提供;调仓计划数量不等于成交,现金不足或整手差额必须读取 unfilled 说明。
21
21
 
22
22
  ## 意图路由表
23
23
 
@@ -29,8 +29,9 @@ 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
- | 大盘择时 | `detect_market_regime`;A 股可补充 `get_market_stats` |
34
+ | 大盘择时 | `detect_market_regime`;可补充 `get_market_stats(market)` 看涨跌家数,美股行业强弱用 `get_sector_rankings(market=US)`(ETF 代理) |
34
35
 
35
36
  ## 执行流程
36
37
 
@@ -42,11 +43,13 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
42
43
  python3 scripts/gather.py <symbol>
43
44
  ```
44
45
 
45
- 解析返回的 JSON 数据。如果某个字段为 `null` 或包含 `error`,表示该数据不可用,基于可用数据继续分析。大盘状态按股票所属市场查询;日/韩/台市场暂不支持,标明缺失,不能套用 A 股状态。
46
+ 解析返回的 JSON 数据。如果某个字段为 `null` 或包含 `error`,表示该数据不可用,基于可用数据继续分析。大盘状态按股票所属市场查询,A/HK/US/JP/KR/TW 均使用各自指数;非 A 股板块热点不可用时 sector_heat=false,不能套用 A 股状态或把 false 解读成无热点。
46
47
 
47
48
  解读实时行情前先调 `get_trading_phase` 确认该市场当前盘中阶段(盘前/早盘/午间休市/午盘/交易中/盘后/休市),避免把休市时的静态快照当作盘中信号解读。
48
49
 
49
- 港股 `get_quote` 自动按 yfinance → 腾讯 → finnhub → longbridge 容灾,腾讯无需 API key,使用 `r_hk` 实时报价通道(`hk` 通道延迟约 15 分钟)。腾讯港股成交量为股,成交额及市值为港元;PB、换手率、量比为 null 时按缺失处理。该备用源只覆盖报价,K 线仍走原链路。
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
+
52
+ 港股 `get_quote` 自动按 yfinance → 腾讯 → finnhub → longbridge 容灾,腾讯无需 API key,使用 `r_hk` 实时报价通道(`hk` 通道延迟约 15 分钟)。腾讯港股成交量为股,成交额及市值为港元;PB、换手率、量比为 null 时按缺失处理。腾讯也是港股 `get_kline` 的第二个源,以及美股报价和 K 线在 finnhub / longbridge 之后、alphavantage 之前的备用源;腾讯 K 线为前复权(`adjusted: "qfq"`),与 yfinance 的全收益口径不同。
50
53
 
51
54
  ### 第二步:综合研判
52
55
 
@@ -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
 
@@ -117,13 +120,13 @@ python3 scripts/gather.py <symbol>
117
120
 
118
121
  按用户问题选择数据,完整说明口径、采样覆盖和缺失项:
119
122
 
120
- - 判断估值贵贱:`get_valuation_history(symbol, years=5)` 的 PE-TTM/PB 历史正值分位与 Band;亏损 PE 不计算分位,实际采样不足五年必须说明。
123
+ - 判断估值贵贱:`get_valuation_history(symbol, years=5)` 的 PE-TTM/PB 历史正值分位与 Band;亏损 PE 不计算分位,实际采样不足五年必须说明;美股为 SEC 申报派生的周采样,读取 `share_basis/warnings`。
121
124
  - 读多年财报:`get_financials(symbol, periods=10, annual=true)`;A 股按年报筛选,港股按源实际可得年度数返回。财报期不等于公告日,年报历史不能用于假定当时已知信息的回测。
122
125
  - 财报季排期:`get_earnings_calendar(report_date="YYYY-MM-DD", symbol=...)`,区分最新预约日期、实际披露日期和已公告业绩预告,不把预告当业绩实绩。
123
126
  - 股东变化:`get_shareholder_structure`。A 股北向值是财报十大流通股东中的 HKSCC 名义持股,缺席不等于零,不能当成日度北向买卖;港股南向值按港交所披露日期使用。
124
127
  - 大盘估值:`get_index_valuation(symbol="000300", years=5)`;中证近期 PE1 不冒充 PE-TTM、PB 或多年分位。
125
128
  - ETF:`get_etf_details(symbol="510300", benchmark="sh000300")`。折溢价须看净值/行情日期;披露持仓不是完整实时申赎篮子,指数成分与基金持仓分别呈现。跟踪误差必须给出用户认可的基准。
126
- - 股息:`get_dividends` 区分历史、未来已公布除息日历和 A 股报告期排行;预案不计入已实现 TTM 股息。名义每股现金未重算送转股口径,遇送转股时不得据此精确比较持有收益。
129
+ - 股息:`get_dividends` 区分历史、未来已公布除息日历和排行;history/calendar 支持 A/HK/US/JP/KR/TW,排行仍仅 A/HK。预案不计入已实现 TTM 股息。名义每股现金未重算送转股口径,遇送转股时不得据此精确比较持有收益。
127
130
  - 两融:`get_margin_trading(include_ratio=true)` 的 `margin_buy_ratio_pct` 只使用同日成交额;null 表示不可计算。
128
131
 
129
132
  慢变数据存于 `~/.stock-analysis/cache`:财报、基本信息及新历史数据按天,板块映射按周;行情仍实时查询。输出中的报告期/数据日期决定能否用于判断,缓存命中不代表数据已更新。
@@ -136,4 +139,6 @@ get_shareholder_structure 的 northbound 优先使用沪深官方季度总量;
136
139
 
137
140
  信号价格使用原始报价口径,自动记录的默认 `record_date` 与 `price_date` 均按标的市场时区确定(显式 `date` 不变),并保存原始 `price_as_of`;`price_date` 晚于 `record_date` 时拒绝记录与结算。多头 target 必须高于 entry、stop 必须低于 entry,空头相反,否则拒绝记录。开盘先触 stop 按 open 结算,先触 target 按 target 保守结算;日内顺序未知的双触发仍 stop 优先。复权 K 线需有该报价日的可核实 adjustment_factor,才能换算入场/目标/止损及收益;缺失时 skipped_price_basis 并保持未结算,不得猜测拆股或除权比例,重复日期返回 skipped_no_data。记录日无 K 线时仅在前后因子一致(或已有明确报价日)时使用最近锚点;旧信号缺少报价时点且记录日因子发生变化时必须保持未结算。evaluate_signals 返回 complete/deferred/warnings;预算耗尽时已完成结果保存,未处理记录下次重试。当前仅日线 Tushare、Alpha Vantage 提供可验证换算系数,其余复权来源可能跳过结算。
138
141
 
142
+ 用户说“我的自选股”且未提供代码时,先调用 get_watchlist 读取 dsh 侧栏列表,再把 symbols 传给 run_watchlist_analysis 或 build_watchlist_context;空列表要如实说明,不自行补股票池。
143
+
139
144
  自选股上下文异动检查失败时 anomaly_status=unavailable、anomaly_count=null,并提供 anomaly_error/warnings;summary.partial 不得写成无异常或完整成功。
@@ -13,7 +13,7 @@
13
13
 
14
14
  传 `previous/current`,每项 `{text, source, period, metrics}`;正文上限200000字符,metrics 形状同上(可为空),`max_changes` 默认30、上限100。
15
15
 
16
- 先查询原始公告;HTML 可用 extract_article,但它默认截断正文,不能将其结果自动视为全文。PDF/OCR 由宿主文档读取能力或用户提供,MUST NOT 把标题、链接或搜索摘要冒充全文。缺少正文时仍可分析已核实的财务指标,但不要调用要求正文的比较工具。
16
+ 先查询原始公告;HTML/PDF 可用 extract_article,默认3000字符。用于披露比较时按所需正文设置 max_chars(上限200000)并检查 truncated;truncated=true 不能当作全文。无文本层的 PDF 仍需宿主 OCR 或用户提供,MUST NOT 把标题、链接或搜索摘要冒充全文。缺少正文时仍可分析已核实的财务指标,但不要调用要求正文的比较工具。
17
17
 
18
18
  工具输出精确到传入文本行号的变化片段、来源、截断标志和指标差异。文本差异本身不等于经营变化;Agent 要阅读上下文,说明发生了什么、与原预期的关系和可能反证,并引用原文。金额单位和 basis 一致才计算 delta;前期值大于0才计算普通增长率,亏损转盈另述。报告期可不同,但必须核实是可比同长期间(年度/同比单季等),累计季度不能直接当单季。
19
19
 
@@ -49,6 +49,14 @@
49
49
 
50
50
  lot_size 来自用户或可核实交易规则,尤其港股不能统一猜100股。工具不覆盖券商最低收费、未提供税费、跳空和流动性风险。quantity=0 表示当前约束下不足一个交易单位,MUST NOT 向上凑整。
51
51
 
52
+ ## DCF 估值:calculate_dcf_valuation
53
+
54
+ A/港/美股可先调用 `get_financials(symbol, annual=true, periods=5, include_dcf_inputs=true)` 取年度收入、营业利润、税、现金流、资本开支、现金、债务、少数股东权益和股本。美股优先 SEC companyfacts,A 股和港股配置 `LIXINGER_TOKEN` 时优先理杏仁;主源缺失字段按同财年同币种用 Yahoo 补齐(租赁口径不同,不跨源补),并在 `field_sources` 标注。A 股 `operating_income` 是营业利润(含投资收益和公允价值变动),不等于 EBIT,用作经营利润率前需剔除。仍缺的字段列在 `missing_fields` 且为 null,MUST 向用户索取或另行核实,不能补默认值。`total_debt` 不含租赁;租赁负债在 `lease_liabilities`,是否计入 `debt` 由调用方明确。传给 `calculate_dcf_valuation` 时 `minority_interest` 对应 `minority_interests`,`total_debt`(加上选定的租赁)对应 `debt`。
55
+
56
+ 必需 `currency,units,base_revenue,revenue_growth,operating_margin,tax_rate,sales_to_capital,wacc,terminal_growth,terminal_wacc,terminal_roic,diluted_shares`。逐年数组长度相同且为1..10年;比例均为小数。可选 `cash,debt,minority_interests,nonoperating_assets,other_claims,current_price`。所有金额和股数口径一致。
57
+
58
+ 工具按达摩达兰 FCFF 口径计算:税后营业利润减去收入增量/销售资本比得到FCFF,终值再投资率为 `terminal_growth/terminal_roic`。输出企业价值、股权价值、每股价值、终值占比和 3x3 终值 WACC/增长敏感性。它不估计 WACC、ERP、国家风险、β或行业销售资本比,也不处理期权、租赁、金融企业和失败概率。结果是假设驱动估值,MUST NOT 当作买卖信号。
59
+
52
60
  ## 事件研究:analyze_event_study
53
61
 
54
62
  通常直接传 `symbol,benchmark,start_date,end_date,event_dates`,由共享 Python 核心取数,避免模型复述整段K线。股票与基准应属于同一市场;代码模式输出实际覆盖区间和提供方复权标记,没有标记时明确未指定,不用调用方猜测覆盖。开始日期须覆盖事件前一交易日、结束日期须覆盖最长事件窗口。也可使用下面的显式价格模式,两种模式互斥。
package/tools/_cache.py CHANGED
@@ -36,6 +36,16 @@ def cached_values(namespace, ttl):
36
36
  yield entry.get("data")
37
37
 
38
38
 
39
+ def _prune(path, ttl):
40
+ """Drop expired siblings of a fresh entry so date-scoped keys cannot grow the cache forever."""
41
+ cutoff = time.time() - ttl
42
+ for old in CACHE_DIR.glob(f"{path.name.split('-', 1)[0]}-*"):
43
+ if old.stem != path.stem and old.suffix in (".json", ".lock"):
44
+ with contextlib.suppress(OSError):
45
+ if old.stat().st_mtime < cutoff:
46
+ old.unlink()
47
+
48
+
39
49
  @contextlib.contextmanager
40
50
  def file_lock(path, timeout=5):
41
51
  """Coordinate processes using a stable lock inode, with bounded waiting."""
@@ -116,6 +126,8 @@ def cached(key: str, ttl: int, fetch):
116
126
  # shortcut: slow fetches may outlast lock wait; prefer duplicate work to blocking callers indefinitely.
117
127
  with contextlib.suppress(OSError):
118
128
  stack.enter_context(file_lock(path.with_suffix(".lock")))
129
+ # A held lock must look fresh so another key's prune never unlinks it mid-fetch.
130
+ os.utime(path.with_suffix(".lock"))
119
131
  entry = _read(path, ttl)
120
132
  if entry and "data" in entry:
121
133
  return entry["data"]
@@ -128,6 +140,7 @@ def cached(key: str, ttl: int, fetch):
128
140
  json.dump(
129
141
  {"key": key, "fetched_at": time.time(), "data": result}, stream, ensure_ascii=False, allow_nan=False
130
142
  )
143
+ _prune(path, ttl)
131
144
  except (OSError, ValueError, TypeError):
132
145
  pass
133
146
  return result