stock-analysis-plugin 0.1.10 → 0.1.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 CHANGED
@@ -42,6 +42,17 @@ A 股 / 港股 / 美股 / 日股 / 韩股 / 台股综合分析、多因子选股
42
42
 
43
43
  > 所有 npm 包同时以 scoped(`@weaxs/*`)和非 scoped 同名两种名字发布,内容一致,任选其一即可。
44
44
 
45
+ 插件包地址:
46
+
47
+ | 平台 | 包名 | 地址 | 安装命令 |
48
+ |------|------|------|----------|
49
+ | Pi Agent | `@weaxs/stock-analysis-plugin`(或 `stock-analysis-plugin`) | [npm](https://www.npmjs.com/package/@weaxs/stock-analysis-plugin) | `npm install @weaxs/stock-analysis-plugin` |
50
+ | Hermes Agent | `stock-analysis-plugin` | [PyPI](https://pypi.org/project/stock-analysis-plugin/) | `pip install stock-analysis-plugin` |
51
+ | OpenClaw | `@weaxs/openclaw-stock-analysis`(或 `openclaw-stock-analysis`) | [npm](https://www.npmjs.com/package/@weaxs/openclaw-stock-analysis) | `openclaw plugins install clawhub:@weaxs/openclaw-stock-analysis` |
52
+ | DeepSeek Harness (dsh) | `@weaxs/dsh-stock-analysis`(或 `dsh-stock-analysis`) | [npm](https://www.npmjs.com/package/@weaxs/dsh-stock-analysis) | `dsh plugin --profile <profile> add @weaxs/dsh-stock-analysis` |
53
+
54
+ 各平台的详细安装步骤见下方对应小节。
55
+
45
56
  ### Pi Agent Extension
46
57
 
47
58
  ```bash
@@ -190,7 +201,7 @@ Agent 会自动调用行情 → 技术面 → 基本面 → 资金面 → 消息
190
201
  | Skill | 调用方式 | 功能 |
191
202
  |-------|----------|------|
192
203
  | 综合分析 | `/skill:stock-analysis` | 技术面 + 基本面 + 资金面 + 消息面多维研判,输出结构化研报 |
193
- | 全市场选股 | `/skill:stock-screener` | L1 多因子硬筛 → L2 LLM 智能排序 → 输出推荐列表 |
204
+ | 全市场选股 | `/skill:stock-screener` | L1 多因子硬筛(市场情绪调节,可选 `--l2` 量化增强)→ L2 LLM 智能排序 → 输出推荐列表 |
194
205
  | 策略回测 | `/skill:strategy-backtest` | YAML 策略定义 → 回测 → 诊断 → LLM 变异优化 → 迭代 |
195
206
 
196
207
  ### 策略方法论(12 个)
@@ -242,7 +253,7 @@ Agent 会自动调用行情 → 技术面 → 基本面 → 资金面 → 消息
242
253
 
243
254
  | 工具 | 说明 |
244
255
  |------|------|
245
- | `screen_stocks` | 全市场多因子筛选 |
256
+ | `screen_stocks` | 全市场多因子筛选(市场情绪调节,可选 L2 量化增强) |
246
257
  | `screen_risk` | 风险因子筛查 |
247
258
  | `run_backtest` | YAML 策略回测 |
248
259
  | `detect_market_regime` | 市场状态检测(牛/熊/震荡) |
@@ -359,6 +370,7 @@ python tools/technical.py analyze AAPL --period weekly
359
370
 
360
371
  # 全市场筛选
361
372
  python tools/screener.py screen --market A --top 20
373
+ python tools/screener.py screen --market A --top 20 --l2
362
374
  python tools/screener.py screen --market A --config my_filter.yaml
363
375
 
364
376
  # 策略回测
@@ -403,7 +415,7 @@ stock-analysis/
403
415
  │ ├── stock_data.py # 行情 / 资金流 / 新闻 / 财务
404
416
  │ ├── technical.py # 技术指标分析
405
417
  │ ├── pattern.py # K 线形态识别
406
- │ ├── screener.py # 全市场多因子筛选
418
+ │ ├── screener.py # 全市场多因子筛选(含市场情绪调节,--l2 量化增强)
407
419
  │ ├── backtest.py # 策略回测引擎
408
420
  │ ├── volume_analysis.py # 量价分析
409
421
  │ ├── search_intel.py # 搜索 / 舆情 / 正文提取
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stock-analysis-plugin",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Pi Agent extension for stock analysis, screening, and strategy backtesting across A/HK/US markets",
5
5
  "type": "module",
6
6
  "main": "./pi/index.ts",
package/pi/index.ts CHANGED
@@ -27,7 +27,7 @@ export default (pi: ExtensionAPI) => {
27
27
  pi.registerTool({
28
28
  name: "get_kline",
29
29
  description:
30
- "获取股票K线数据(OHLCV)。支持A股(如600519)、港股(如00700.HK)、美股(如AAPL)、日股(如7203.T)、韩股(如005930.KS)、台股(如2330.TW)及A股ETF",
30
+ "获取股票K线数据(OHLCV)。支持A股(如600519)、港股(如00700.HK)、美股(如AAPL)、日股(如7203.T)、韩股(如005930.KS)、台股(如2330.TW)及A股ETF。需要原始历史价格自行计算或画图时用;只问指标用 get_technical_analysis,只问现价用 get_quote",
31
31
  parameters: {
32
32
  type: "object",
33
33
  properties: {
@@ -63,7 +63,7 @@ export default (pi: ExtensionAPI) => {
63
63
  pi.registerTool({
64
64
  name: "get_quote",
65
65
  description:
66
- "获取股票实时行情报价。支持A股、港股、美股、日股、韩股、台股",
66
+ "获取股票实时行情报价(现价、涨跌幅、量比等)。支持A股、港股、美股、日股、韩股、台股",
67
67
  parameters: {
68
68
  type: "object",
69
69
  properties: {
@@ -83,7 +83,7 @@ export default (pi: ExtensionAPI) => {
83
83
  pi.registerTool({
84
84
  name: "get_capital_flow",
85
85
  description:
86
- "获取A股资金流向数据。detail=个股每日明细,summary=多日汇总+趋势,sector_flow=板块资金流排行",
86
+ "获取A股资金流向(主力/超大单/大单/中单/小单净流入)。detail=个股每日明细,summary=多日汇总+趋势,sector_flow=板块资金流排行。可配合 get_chip_distribution 验证主力行为",
87
87
  parameters: {
88
88
  type: "object",
89
89
  properties: {
@@ -111,7 +111,7 @@ export default (pi: ExtensionAPI) => {
111
111
 
112
112
  pi.registerTool({
113
113
  name: "get_news",
114
- description: "获取股票相关财经新闻",
114
+ description: "获取个股最近N天财经新闻快讯(轻量、无需配置)。需要深度全网情报用 search_comprehensive_intel,按主题搜索用 search_stock_news,读文章全文用 extract_article",
115
115
  parameters: {
116
116
  type: "object",
117
117
  properties: {
@@ -135,7 +135,7 @@ export default (pi: ExtensionAPI) => {
135
135
  pi.registerTool({
136
136
  name: "get_financials",
137
137
  description:
138
- "获取股票关键财务指标(PE/PB/市值/营收/净利润/ROE等)",
138
+ "获取股票关键财务指标(PE/PB/市值/营收/净利润/ROE等),适合快速估值快查。A股深度基本面(成长性/盈利能力/分红)用 get_fundamental_context",
139
139
  parameters: {
140
140
  type: "object",
141
141
  properties: {
@@ -157,7 +157,7 @@ export default (pi: ExtensionAPI) => {
157
157
  pi.registerTool({
158
158
  name: "get_technical_analysis",
159
159
  description:
160
- "获取股票技术面分析(MA/MACD/RSI/BOLL/KDJ/成交量等指标 + 100分综合评分 + 6级买卖信号 + 趋势/偏离度/支撑压力位)",
160
+ "获取股票技术面分析(MA/MACD/RSI/BOLL/KDJ/成交量等指标 + 100分综合评分 + 6级买卖信号 + 趋势/偏离度/支撑压力位)。个股技术面综合判断与买卖时机分析的首选;只要均线数值或自定义周期用 calculate_ma,专问量价用 get_volume_analysis,扫当日异动用 detect_anomaly",
161
161
  parameters: {
162
162
  type: "object",
163
163
  properties: {
@@ -193,7 +193,7 @@ export default (pi: ExtensionAPI) => {
193
193
  pi.registerTool({
194
194
  name: "analyze_pattern",
195
195
  description:
196
- "K线形态识别 — 检测十字星、锤子线、吞没、启明星、黄昏星、双底、20日突破等12+种经典形态",
196
+ "K线形态识别 — 检测十字星、锤子线、吞没、启明星、黄昏星、双底、20日突破等12+种经典形态。综合技术面判断用 get_technical_analysis",
197
197
  parameters: {
198
198
  type: "object",
199
199
  properties: {
@@ -231,7 +231,7 @@ export default (pi: ExtensionAPI) => {
231
231
  pi.registerTool({
232
232
  name: "get_market_indices",
233
233
  description:
234
- "获取主要市场指数行情。CN: 上证/深证/创业板/科创50/沪深300;HK: 恒生/国企/科技;US: 道琼斯/纳斯达克/标普500;JP: 日经225/东证;KR: KOSPI/KOSDAQ;TW: 台湾加权",
234
+ "获取主要市场指数行情。CN: 上证/深证/创业板/科创50/沪深300;HK: 恒生/国企/科技;US: 道琼斯/纳斯达克/标普500;JP: 日经225/东证;KR: KOSPI/KOSDAQ;TW: 台湾加权。大盘复盘用 get_market_review 一站式获取",
235
235
  parameters: {
236
236
  type: "object",
237
237
  properties: {
@@ -304,7 +304,7 @@ export default (pi: ExtensionAPI) => {
304
304
  pi.registerTool({
305
305
  name: "get_chip_distribution",
306
306
  description:
307
- "获取A股筹码分布数据(获利比例、平均成本、90%/70%成本集中度)。仅支持A股",
307
+ "获取A股筹码分布数据(获利比例、平均成本、90%/70%成本集中度)。仅支持A股。与 get_capital_flow 配合验证主力行为",
308
308
  parameters: {
309
309
  type: "object",
310
310
  properties: {
@@ -324,7 +324,7 @@ export default (pi: ExtensionAPI) => {
324
324
  pi.registerTool({
325
325
  name: "get_market_stats",
326
326
  description:
327
- "获取A股市场整体统计(涨跌家数、涨停跌停数、平均涨幅、涨跌Top5、总成交额)",
327
+ "获取A股市场整体统计(涨跌家数、涨停跌停数、平均涨幅、涨跌Top5、总成交额)。用于衡量市场整体情绪与温度",
328
328
  parameters: {
329
329
  type: "object",
330
330
  properties: {
@@ -344,7 +344,7 @@ export default (pi: ExtensionAPI) => {
344
344
  pi.registerTool({
345
345
  name: "get_fundamental_context",
346
346
  description:
347
- "获取A股深度基本面(估值PE/PB/PS + 成长性营收/净利增速 + 盈利能力ROE/毛利率 + 分红历史)",
347
+ "获取A股深度基本面(估值PE/PB/PS + 成长性营收/净利增速 + 盈利能力ROE/毛利率 + 分红历史)。用于评估公司质地与长期持有价值;快速查PE/PB用 get_financials",
348
348
  parameters: {
349
349
  type: "object",
350
350
  properties: {
@@ -366,7 +366,7 @@ export default (pi: ExtensionAPI) => {
366
366
  pi.registerTool({
367
367
  name: "screen_stocks",
368
368
  description:
369
- "全市场股票筛选(AlphaSift L1 多因子硬筛)。按PE/PB/市值/换手率/涨跌幅/量比等因子过滤和评分",
369
+ "全市场股票筛选(AlphaSift L1 多因子硬筛 + 市场情绪调节)。按PE/PB/市值/换手率/涨跌幅/量比等因子过滤和评分,可用 l2 开启质量/成长/动量/波动率/资金流增强",
370
370
  parameters: {
371
371
  type: "object",
372
372
  properties: {
@@ -383,9 +383,13 @@ export default (pi: ExtensionAPI) => {
383
383
  type: "string",
384
384
  description: "自定义筛选配置YAML文件路径(可选)",
385
385
  },
386
+ l2: {
387
+ type: "boolean",
388
+ description: "开启L2量化增强(质量/成长/真实动量/波动率/资金流因子,逐股抓取数据较慢),默认关闭",
389
+ },
386
390
  },
387
391
  },
388
- async execute(_id, { market = "A", top = 20, config }) {
392
+ async execute(_id, { market = "A", top = 20, config, l2 = false }) {
389
393
  const result = await py("screener.py", [
390
394
  "screen",
391
395
  "--market",
@@ -393,6 +397,7 @@ export default (pi: ExtensionAPI) => {
393
397
  "--top",
394
398
  String(top),
395
399
  ...(config ? ["--config", config] : []),
400
+ ...(l2 ? ["--l2"] : []),
396
401
  ]);
397
402
  return asText(result.stdout);
398
403
  },
@@ -401,7 +406,7 @@ export default (pi: ExtensionAPI) => {
401
406
  pi.registerTool({
402
407
  name: "run_backtest",
403
408
  description:
404
- "策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标",
409
+ "策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal",
405
410
  parameters: {
406
411
  type: "object",
407
412
  properties: {
@@ -445,7 +450,7 @@ export default (pi: ExtensionAPI) => {
445
450
  pi.registerTool({
446
451
  name: "evaluate_signal",
447
452
  description:
448
- "技术信号历史准确率评估 — 回溯历史数据,统计某个技术信号触发后N日的胜率和平均收益。支持9种信号:macd_golden_cross/macd_death_cross/rsi_oversold/rsi_overbought/breakout_20d/breakdown_20d/volume_surge/ma_golden_cross/ma_death_cross",
453
+ "技术信号历史准确率评估 — 回溯历史数据,统计某个技术信号触发后N日的胜率和平均收益。支持9种信号:macd_golden_cross/macd_death_cross/rsi_oversold/rsi_overbought/breakout_20d/breakdown_20d/volume_surge/ma_golden_cross/ma_death_cross。要完整模拟交易过程用 run_backtest",
449
454
  parameters: {
450
455
  type: "object",
451
456
  properties: {
@@ -498,7 +503,7 @@ export default (pi: ExtensionAPI) => {
498
503
  pi.registerTool({
499
504
  name: "resolve_stock_name",
500
505
  description:
501
- "股票名称智能解析 — 输入中文名(贵州茅台)、拼音(guizhou maotai/gzmt)、部分代码,返回匹配的股票代码。仅支持A股",
506
+ "股票名称智能解析 — 输入中文名(贵州茅台)、拼音(guizhou maotai/gzmt)、部分代码,返回匹配的股票代码。仅支持A股。用户给出中文名/拼音/部分代码时先调本工具换成代码再调其他工具",
502
507
  parameters: {
503
508
  type: "object",
504
509
  properties: {
@@ -600,7 +605,7 @@ export default (pi: ExtensionAPI) => {
600
605
  pi.registerTool({
601
606
  name: "calculate_ma",
602
607
  description:
603
- "独立均线计算器 — 支持任意周期MA(5/10/20/30/60/120/250或自定义)+ 偏离度 + 均线排列 + 金叉死叉检测",
608
+ "独立均线计算器 — 支持任意周期MA(5/10/20/30/60/120/250或自定义)+ 偏离度 + 均线排列 + 金叉死叉检测。只要均线数值或需要30/120/250等非默认周期时用本工具;综合技术面分析用 get_technical_analysis",
604
609
  parameters: {
605
610
  type: "object",
606
611
  properties: {
@@ -640,7 +645,7 @@ export default (pi: ExtensionAPI) => {
640
645
  pi.registerTool({
641
646
  name: "get_volume_analysis",
642
647
  description:
643
- "独立量价分析 — 量价相关性、上涨/下跌日成交量对比、量能趋势、量价模式解读(放量上涨/缩量回调等)",
648
+ "独立量价分析 — 量价相关性、上涨/下跌日成交量对比、量能趋势、量价模式解读(放量上涨/缩量回调等)。综合技术面判断用 get_technical_analysis,扫当日异动用 detect_anomaly",
644
649
  parameters: {
645
650
  type: "object",
646
651
  properties: {
@@ -678,7 +683,7 @@ export default (pi: ExtensionAPI) => {
678
683
  pi.registerTool({
679
684
  name: "search_stock_news",
680
685
  description:
681
- "多引擎股票新闻搜索(支持 Tavily/Brave/SerpAPI)。需配置对应 API Key 环境变量",
686
+ "多引擎股票新闻搜索(支持 Tavily/Brave/SerpAPI)。需配置对应 API Key 环境变量。get_news 快讯不够或要按主题搜索时用本工具;深度6维情报用 search_comprehensive_intel",
682
687
  parameters: {
683
688
  type: "object",
684
689
  properties: {
@@ -707,7 +712,7 @@ export default (pi: ExtensionAPI) => {
707
712
  pi.registerTool({
708
713
  name: "search_comprehensive_intel",
709
714
  description:
710
- "股票综合情报搜索 — 从6个维度(新闻/公告/行情分析/风险/业绩/行业)搜索综合信息",
715
+ "股票综合情报搜索 — 从6个维度(新闻/公告/行情分析/风险/业绩/行业)搜索综合信息。用于个股的深入研究/全面调研;快速看新闻用 get_news",
711
716
  parameters: {
712
717
  type: "object",
713
718
  properties: {
@@ -735,7 +740,7 @@ export default (pi: ExtensionAPI) => {
735
740
  pi.registerTool({
736
741
  name: "get_social_sentiment",
737
742
  description:
738
- "获取股票社交媒体情绪数据(Reddit/X/Polymarket)。主要支持美股。需配置 SENTIMENT_API_KEY",
743
+ "获取股票社交媒体情绪数据。A股:东方财富股吧热度+雪球讨论热度(无需配置);美股/港股:Reddit/X/Polymarket情绪(需 SENTIMENT_API_KEY)。自动按市场选数据源。面向个股维度;全市场热门讨论用 get_trending_sentiment",
739
744
  parameters: {
740
745
  type: "object",
741
746
  properties: {
@@ -755,7 +760,7 @@ export default (pi: ExtensionAPI) => {
755
760
  pi.registerTool({
756
761
  name: "get_trending_sentiment",
757
762
  description:
758
- "获取社交媒体热门趋势(Reddit/X/Polymarket热门股票讨论)。数据缓存10分钟。适用于发现市场热点",
763
+ "获取社交媒体热门趋势(Reddit/X/Polymarket热门股票讨论)。数据缓存10分钟。适用于发现市场热点;查个股情绪用 get_social_sentiment",
759
764
  parameters: {
760
765
  type: "object",
761
766
  properties: {},
@@ -769,7 +774,7 @@ export default (pi: ExtensionAPI) => {
769
774
  pi.registerTool({
770
775
  name: "extract_article",
771
776
  description:
772
- "网页文章全文提取 — 输入URL,提取文章标题、正文(最多3000字)、作者、发布日期等。适用于深度阅读搜索结果中的新闻/研报",
777
+ "网页文章全文提取 — 输入URL,提取文章标题、正文(最多3000字)、作者、发布日期等。配合 get_news/search_stock_news 的搜索结果做深度阅读",
773
778
  parameters: {
774
779
  type: "object",
775
780
  properties: {
@@ -789,7 +794,7 @@ export default (pi: ExtensionAPI) => {
789
794
  pi.registerTool({
790
795
  name: "screen_risk",
791
796
  description:
792
- "风险专项筛查 — 7维度风险检测(估值极端/技术预警/解禁到期/内部人减持/业绩预警/监管处罚/行业政策),返回风险评级和一票否决标记",
797
+ "风险专项筛查 — 7维度风险检测(估值极端/技术预警/解禁到期/内部人减持/业绩预警/监管处罚/行业政策),返回风险评级和一票否决标记。入场决策前的排雷必调本工具",
793
798
  parameters: {
794
799
  type: "object",
795
800
  properties: {
@@ -838,7 +843,7 @@ export default (pi: ExtensionAPI) => {
838
843
  pi.registerTool({
839
844
  name: "get_market_review",
840
845
  description:
841
- "大盘复盘 — 获取市场日度复盘数据,包含指数、涨跌统计、板块排名、新闻、市场温度与策略建议",
846
+ "大盘复盘 — 获取市场日度复盘数据,包含指数、涨跌统计、板块排名、新闻、市场温度与策略建议。复盘类需求的首选,无需再分别调指数/统计/板块工具",
842
847
  parameters: {
843
848
  type: "object",
844
849
  properties: {
@@ -888,7 +893,7 @@ export default (pi: ExtensionAPI) => {
888
893
  pi.registerTool({
889
894
  name: "detect_anomaly",
890
895
  description:
891
- "异常/事件检测 — 一键扫描股票当前所有异动信号(MACD金叉死叉、RSI超买超卖、20日突破、放量异动、涨跌停、布林突破、KDJ极值、资金异动等),返回结构化异常列表",
896
+ "异常/事件检测 — 一键扫描股票当前所有异动信号(MACD金叉死叉、RSI超买超卖、20日突破、放量异动、涨跌停、布林突破、KDJ极值、资金异动等),返回结构化异常列表。当日异动归因的首选;综合技术面判断用 get_technical_analysis",
892
897
  parameters: {
893
898
  type: "object",
894
899
  properties: {
@@ -910,7 +915,7 @@ export default (pi: ExtensionAPI) => {
910
915
  pi.registerTool({
911
916
  name: "diagnose_data_sources",
912
917
  description:
913
- "数据源诊断 — 检查当前环境可用的数据 provider(akshare/tushare/yfinance/finnhub/longbridge/alphavantage),输出每个市场的可用链路、缺失 env、warnings。用于让 agent 自解释为何拿不到数据",
918
+ "数据源诊断 — 检查当前环境可用的数据 provider(akshare/tushare/yfinance/finnhub/longbridge/alphavantage),输出每个市场的可用链路、缺失 env、warnings。工具拿不到数据或报错时调用排查",
914
919
  parameters: {
915
920
  type: "object",
916
921
  properties: {
@@ -930,7 +935,7 @@ export default (pi: ExtensionAPI) => {
930
935
  pi.registerTool({
931
936
  name: "get_market_capabilities",
932
937
  description:
933
- "市场能力边界 — 返回指定市场支持/不支持的工具列表,避免 agent 对港股调 get_chip_distribution 或对美股调 get_capital_flow 后编造数据",
938
+ "市场能力边界 — 返回指定市场支持/不支持的工具列表。不确定某市场能否用某工具(如港股的筹码分布、美股的资金流)时先调本工具,避免调用不支持的工具后编造数据",
934
939
  parameters: {
935
940
  type: "object",
936
941
  properties: {
@@ -952,7 +957,7 @@ export default (pi: ExtensionAPI) => {
952
957
  pi.registerTool({
953
958
  name: "render_stock_report",
954
959
  description:
955
- "股票分析报告渲染 — 将结构化 JSON(符合 schemas/report_schema.json)通过 j2 模板渲染为 Markdown。style: brief|full。仅渲染,不保存不推送",
960
+ "股票分析报告渲染 — 将结构化 JSON(符合 schemas/report_schema.json)通过 j2 模板渲染为 Markdown。template: brief|full。全部分析完成后的最后一步调用。仅渲染,不保存不推送",
956
961
  parameters: {
957
962
  type: "object",
958
963
  properties: {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: stock-analysis
3
- description: 综合股票分析 — 技术面+基本面+资金面+消息面+风险筛查多维研判。当用户要求分析个股时使用。
3
+ description: 综合股票分析 — 技术面+基本面+资金面+消息面+风险筛查多维研判。用于个股综合研判类问题:走势判断、买卖时机、风险排雷、持仓处理。
4
4
  allowed-tools: Bash(python3:*) Read
5
5
  ---
6
6
 
@@ -8,6 +8,17 @@ allowed-tools: Bash(python3:*) Read
8
8
 
9
9
  你是一位专业的股票分析师。用户提供股票代码后,你需要进行全面的多维度分析并输出结构化研报。
10
10
 
11
+ ## 意图路由表
12
+
13
+ 快速问答先判断意图,按下表走最短调用链;完整综合研判走下方执行流程(gather 采集管线),不受此表限制。单工具可答的问题按各工具描述中的适用场景选择,本表不再重复。
14
+
15
+ | 意图 | 调用序列 |
16
+ |------|---------|
17
+ | 个股买卖时机 | `get_technical_analysis` → `get_capital_flow`(summary, 仅A股) → `screen_risk` → `detect_market_regime`。合成规则:screen_risk 有一票否决则不入场(无视评分);BUY/STRONG_BUY + 主力净流入 + 大盘非下跌 → 可入场;大盘下跌趋势中个股 BUY 降级为轻仓试错或等待;HOLD/WAIT 则给出具体触发条件(如回踩 MA10 不破、放量突破 20 日高点) |
18
+ | 个股状态速览 | `get_quote` + `get_technical_analysis` |
19
+ | 异动归因 | `detect_anomaly` + `get_news` |
20
+ | 大盘择时 | `detect_market_regime` + `get_market_stats` |
21
+
11
22
  ## 执行流程
12
23
 
13
24
  ### 第一步:采集数据
@@ -25,11 +25,17 @@ allowed-tools: Bash(python3:*) Read
25
25
  python3 scripts/gather.py --market A --top 20
26
26
  ```
27
27
 
28
- 可选参数:`--market`(A/HK/US)、`--top`(返回数量)、`--config`(自定义 YAML 配置路径)。
28
+ 可选参数:`--market`(A/HK/US)、`--top`(返回数量)、`--config`(自定义 YAML 配置路径)、`--l2`(L2 量化增强开关,默认关闭)。
29
+
30
+ **何时开启 `--l2`**:需要对候选股做量化因子精排时开启。开启后逐股补算质量/成长/真实动量/波动率/资金流五类因子,结果更精细,但逐股抓取数据较慢,日常快速筛选保持关闭即可。开启 `--l2` 后候选按 `scores.final` 重新排序,config 里的 `sort_by`/`sort_order` 不生效;且 l2 模式下 `scores.momentum` 仍是 L1 参考值,不参与 final 综合分(final 用的是真实动量组)。
31
+
32
+ **`market_sentiment` 输出字段**:无论是否开 `--l2`,输出始终带 `market_sentiment`(市场情绪温度 0-100、level、multiplier 0.8-1.2 的 regime 调节器)。`multiplier < 1` 表示市场情绪偏弱,排序和推荐应更保守(收紧入选数量、降低激进度);`multiplier > 1` 表示情绪偏暖,可适度放宽。
29
33
 
30
34
  ### 第三步:L2 智能排序
31
35
 
32
- 对 L1 筛选出的候选股,基于返回的各项数据进行 LLM 智能排序:
36
+ 对 L1 筛选出的候选股,基于返回的各项数据进行 LLM 智能排序。
37
+
38
+ 注意区分两层"增强":`--l2` 是工具内的量化因子增强(在 L1 结果上补算因子,发生在排序之前);本步的 LLM 排序是 skill 流程的最后一环,在量化结果之上综合形态/量价/安全边际做最终排序。两者可叠加使用:先 `--l2` 拿精细因子,再做 LLM 排序。
33
39
 
34
40
  排序考虑因素:
35
41
  1. **技术形态质量**:趋势明确 > 震荡 > 趋势不明
@@ -22,7 +22,7 @@ def _run_tool(script: str, args: str, timeout: int = 30):
22
22
  return None
23
23
 
24
24
 
25
- def _calc_temperature(stats: dict, indices: list) -> dict:
25
+ def calc_temperature(stats: dict, indices: list) -> dict:
26
26
  """Calculate market temperature score from breadth, index change, and limit data."""
27
27
  scores = []
28
28
  weights = []
@@ -105,7 +105,7 @@ def review_market(market: str = "A") -> dict:
105
105
  except Exception:
106
106
  results[key] = None
107
107
 
108
- temperature = _calc_temperature(results.get("stats"), results.get("indices"))
108
+ temperature = calc_temperature(results.get("stats"), results.get("indices"))
109
109
 
110
110
  output = {
111
111
  "market": market,
package/tools/screener.py CHANGED
@@ -1,16 +1,28 @@
1
1
  #!/usr/bin/env python3
2
- """AlphaSift L1 — multi-factor stock screener with hard filter + scoring."""
2
+ """AlphaSift L1 — multi-factor stock screener with hard filter + scoring.
3
+
4
+ L1: snapshot → hard filters → value/momentum/liquidity composite.
5
+ Regime gate: market sentiment temperature scales the final score (multiplier in [0.8, 1.2]).
6
+ L2 (opt-in via --l2 / config l2: true): per-candidate quality/growth/momentum/volatility/moneyflow factors.
7
+ """
3
8
 
4
9
  import argparse
5
10
  import json
6
11
  import os
7
12
  import subprocess
8
13
  import sys
14
+ from concurrent.futures import ThreadPoolExecutor
15
+ from pathlib import Path
9
16
 
10
17
  import numpy as np
11
18
  import pandas as pd
12
19
  import yaml
13
20
 
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+
23
+ from market_review import calc_temperature
24
+ from stock_data import compute_market_stats
25
+
14
26
  DEFAULT_FILTERS = {
15
27
  "pe_min": 0,
16
28
  "pe_max": 100,
@@ -24,16 +36,40 @@ DEFAULT_FILTERS = {
24
36
  "volume_ratio_min": 0.5,
25
37
  }
26
38
 
39
+ L2_WEIGHTS = {
40
+ "value": 0.15,
41
+ "quality": 0.20,
42
+ "growth": 0.15,
43
+ "momentum": 0.20,
44
+ "liquidity": 0.10,
45
+ "moneyflow": 0.15,
46
+ "low_volatility": 0.05,
47
+ }
27
48
 
28
- def fetch_snapshot(market: str) -> list:
49
+ _INDEX_REGION = {"A": "cn", "HK": "hk", "US": "us"}
50
+
51
+
52
+ def _fetch_json(args: list[str], timeout: int = 30) -> dict | list | None:
53
+ """Run a stock_data.py CLI command and parse its JSON stdout; None on any failure."""
29
54
  script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "stock_data.py")
30
- r = subprocess.run(
31
- [sys.executable, script, "market_snapshot", "--market", market],
32
- capture_output=True,
33
- text=True,
34
- encoding="utf-8",
35
- )
36
- return json.loads(r.stdout)
55
+ try:
56
+ r = subprocess.run(
57
+ [sys.executable, script, *args],
58
+ capture_output=True,
59
+ text=True,
60
+ encoding="utf-8",
61
+ timeout=timeout,
62
+ )
63
+ if r.returncode == 0 and r.stdout.strip():
64
+ return json.loads(r.stdout)
65
+ except Exception:
66
+ pass
67
+ return None
68
+
69
+
70
+ def fetch_snapshot(market: str) -> list:
71
+ # a cold full-market snapshot can exceed 30s (CI runners) — allow longer
72
+ return _fetch_json(["market_snapshot", "--market", market], timeout=120)
37
73
 
38
74
 
39
75
  def load_config(path: str) -> dict:
@@ -111,10 +147,175 @@ def compute_scores(df: pd.DataFrame) -> pd.DataFrame:
111
147
  return df
112
148
 
113
149
 
114
- def screen(market: str, top: int, config: dict | None) -> dict:
150
+ def sentiment_multiplier(score: float) -> float:
151
+ return round(0.8 + score / 100 * 0.4, 3) # linear map to [0.8, 1.2]
152
+
153
+
154
+ def compute_sentiment(market: str, snapshot: list | None = None) -> dict:
155
+ """Market sentiment gate; degrades to a neutral multiplier of 1.0 on any failure."""
156
+ fallback = {"score": None, "level": "unknown", "signal": None, "multiplier": 1.0}
157
+ region = _INDEX_REGION.get(market)
158
+ if region is None:
159
+ return fallback
160
+ try:
161
+ stats = None
162
+ if isinstance(snapshot, list) and snapshot:
163
+ try:
164
+ stats = compute_market_stats(snapshot)
165
+ except Exception:
166
+ stats = None
167
+ indices = _fetch_json(["market_indices", "--region", region])
168
+ if not isinstance(indices, list) or not indices:
169
+ return fallback
170
+ temp = calc_temperature(stats, indices)
171
+ score = temp.get("score")
172
+ if not isinstance(score, (int, float)):
173
+ return fallback
174
+ return {
175
+ "score": score,
176
+ "level": temp.get("level", "unknown"),
177
+ "signal": temp.get("signal"),
178
+ "multiplier": sentiment_multiplier(float(score)),
179
+ }
180
+ except Exception:
181
+ return fallback
182
+
183
+
184
+ def _enrich_one(symbol: str, market: str) -> dict:
185
+ """Fetch raw L2 indicators for one candidate; missing factor sources just yield missing keys."""
186
+ result: dict = {}
187
+ try:
188
+ kline = _fetch_json(["kline", symbol, "--period", "daily", "--count", "250"])
189
+ if isinstance(kline, list) and len(kline) >= 2:
190
+ closes = pd.Series([float(k["close"]) for k in kline if k.get("close") is not None])
191
+ highs = [float(k["high"]) for k in kline if k.get("high") is not None]
192
+ if len(closes) >= 21:
193
+ result["ret_20d"] = round(float(closes.iloc[-1] / closes.iloc[-21] - 1) * 100, 2)
194
+ if len(closes) >= 61:
195
+ result["ret_60d"] = round(float(closes.iloc[-1] / closes.iloc[-61] - 1) * 100, 2)
196
+ if len(closes) and highs:
197
+ peak = max(highs)
198
+ if peak > 0:
199
+ result["high_250_proximity"] = round(float(closes.iloc[-1]) / peak, 4)
200
+ rets = closes.pct_change().dropna().tail(20)
201
+ if len(rets) >= 2:
202
+ result["vol20"] = round(float(rets.std()) * float(np.sqrt(252)), 4)
203
+ except Exception:
204
+ pass
205
+
206
+ if market == "A":
207
+ fund = _fetch_json(["fundamental_context", symbol])
208
+ if isinstance(fund, dict) and "error" not in fund:
209
+ prof = fund.get("profitability") or {}
210
+ for key in ("roe", "gross_margin", "net_margin"):
211
+ if prof.get(key) is not None:
212
+ result[key] = prof[key]
213
+ growth = fund.get("growth") or {}
214
+ for key in ("revenue_yoy", "net_income_yoy"):
215
+ if growth.get(key) is not None:
216
+ result[key] = growth[key]
217
+ else:
218
+ fin = _fetch_json(["financials", symbol])
219
+ if isinstance(fin, dict) and "error" not in fin:
220
+ for key in ("roe", "profit_margin"):
221
+ if fin.get(key) is not None:
222
+ result[key] = fin[key]
223
+
224
+ if market == "A":
225
+ flow = _fetch_json(["capital_flow", symbol, "--mode", "summary"])
226
+ if isinstance(flow, dict) and "error" not in flow and flow.get("main_net_5d") is not None:
227
+ result["main_net_5d"] = flow["main_net_5d"]
228
+ return result
229
+
230
+
231
+ def _cross_sectional_scores(enrichments: dict) -> dict:
232
+ """Min-max normalize enrichment factors across the candidate set; groups fully missing are skipped."""
233
+ fdf = pd.DataFrame.from_dict(enrichments, orient="index") if enrichments else pd.DataFrame()
234
+ out: dict = {sym: {} for sym in fdf.index}
235
+
236
+ def col(name: str) -> pd.Series | None:
237
+ return pd.to_numeric(fdf[name], errors="coerce") if name in fdf.columns else None
238
+
239
+ def add_group(group: str, parts: list):
240
+ valid = [p for p in parts if p is not None and p.notna().any()]
241
+ if not valid:
242
+ return
243
+ combined = pd.concat(valid, axis=1).mean(axis=1)
244
+ for sym, v in combined.items():
245
+ if not pd.isna(v):
246
+ out[sym][group] = float(v)
247
+
248
+ margin = col("gross_margin")
249
+ profit_margin = col("profit_margin")
250
+ if margin is None:
251
+ margin = profit_margin
252
+ elif profit_margin is not None:
253
+ margin = margin.combine_first(profit_margin)
254
+ add_group("quality", [_minmax(s) for s in (col("roe"), margin, col("net_margin")) if s is not None])
255
+ add_group(
256
+ "growth", [_minmax(s.clip(-50, 100)) for s in (col("revenue_yoy"), col("net_income_yoy")) if s is not None]
257
+ )
258
+ add_group(
259
+ "momentum",
260
+ [_minmax(s) for s in (col("ret_20d"), col("ret_60d"), col("high_250_proximity")) if s is not None],
261
+ )
262
+
263
+ flow = col("main_net_5d")
264
+ if flow is not None:
265
+ add_group("moneyflow", [_minmax(flow)])
266
+
267
+ vol = col("vol20")
268
+ if vol is not None:
269
+ add_group("low_volatility", [100 - _minmax(vol)])
270
+
271
+ return out
272
+
273
+
274
+ def _apply_l2(candidates: list, market: str, multiplier: float) -> None:
275
+ """Enrich candidates with L2 factors and rewrite each scores['final'] as composite_l2 × multiplier."""
276
+ symbols = [c.get("symbol") for c in candidates]
277
+ enrichments: dict = {}
278
+ with ThreadPoolExecutor(max_workers=6) as executor:
279
+ futures = {executor.submit(_enrich_one, sym, market): sym for sym in symbols if sym}
280
+ for future, sym in futures.items():
281
+ try:
282
+ enrichments[sym] = future.result() or {}
283
+ except Exception:
284
+ enrichments[sym] = {}
285
+
286
+ factor_scores = _cross_sectional_scores(enrichments)
287
+
288
+ for c in candidates:
289
+ sym = c.get("symbol")
290
+ groups = factor_scores.get(sym, {})
291
+ c["enriched"] = bool(enrichments.get(sym))
292
+ scores = c["scores"]
293
+ components = {
294
+ "value": scores["value"],
295
+ "liquidity": scores["liquidity"],
296
+ }
297
+ # momentum is L2-only: candidates without kline factors drop the group and renormalize weights.
298
+ components.update(
299
+ {g: groups[g] for g in ("momentum", "quality", "growth", "moneyflow", "low_volatility") if g in groups}
300
+ )
301
+ scores.update(
302
+ {g: round(groups[g], 1) for g in ("quality", "growth", "moneyflow", "low_volatility") if g in groups}
303
+ )
304
+ total_weight = sum(L2_WEIGHTS[g] for g in components)
305
+ composite_l2 = sum(L2_WEIGHTS[g] * components[g] for g in components) / total_weight
306
+ scores["final"] = round(composite_l2 * multiplier, 1)
307
+
308
+
309
+ def screen(market: str, top: int, config: dict | None, l2: bool = False) -> dict:
115
310
  raw = fetch_snapshot(market)
116
311
  if isinstance(raw, dict) and "error" in raw:
117
312
  return raw
313
+ if raw is None:
314
+ return {"error": "failed to fetch market snapshot", "market": market}
315
+
316
+ l2_enabled = bool(l2 or (config or {}).get("l2"))
317
+ sentiment = compute_sentiment(market, raw if isinstance(raw, list) else None)
318
+ multiplier = sentiment["multiplier"]
118
319
 
119
320
  df = pd.DataFrame(raw)
120
321
  total = len(df)
@@ -140,18 +341,21 @@ def screen(market: str, top: int, config: dict | None) -> dict:
140
341
  "returned_count": 0,
141
342
  "filters_applied": filters,
142
343
  "candidates": [],
344
+ "market_sentiment": sentiment,
345
+ "l2_enabled": l2_enabled,
143
346
  }
144
347
 
145
348
  df = compute_scores(df)
146
349
 
147
- sort_by = config.get("sort_by", "composite_score") if config else "composite_score"
148
- sort_order = config.get("sort_order", "desc") if config else "desc"
149
- ascending = sort_order == "asc"
150
-
151
- if sort_by in df.columns:
152
- df = df.sort_values(sort_by, ascending=ascending)
350
+ # L2 re-scores by final afterwards; config sort_by/sort_order only apply to the non-L2 path.
351
+ if l2_enabled or not config:
352
+ sort_by, ascending = "composite_score", False
153
353
  else:
154
- df = df.sort_values("composite_score", ascending=False)
354
+ sort_by = config.get("sort_by", "composite_score")
355
+ ascending = config.get("sort_order", "desc") == "asc"
356
+ if sort_by not in df.columns:
357
+ sort_by, ascending = "composite_score", False
358
+ df = df.sort_values(sort_by, ascending=ascending)
155
359
 
156
360
  df = df.head(top)
157
361
 
@@ -173,14 +377,22 @@ def screen(market: str, top: int, config: dict | None) -> dict:
173
377
  v = row.get(field)
174
378
  if v is not None and not (isinstance(v, float) and np.isnan(v)):
175
379
  entry[field] = round(float(v), 2) if isinstance(v, (float, np.floating)) else v
380
+ composite = float(row.get("composite_score", 0))
176
381
  entry["scores"] = {
177
382
  "value": round(float(row.get("value_score", 0)), 1),
178
383
  "momentum": round(float(row.get("momentum_score", 0)), 1),
179
384
  "liquidity": round(float(row.get("liquidity_score", 0)), 1),
180
- "composite": round(float(row.get("composite_score", 0)), 1),
385
+ "composite": round(composite, 1),
386
+ "final": round(composite * multiplier, 1),
181
387
  }
182
388
  candidates.append(entry)
183
389
 
390
+ if l2_enabled:
391
+ _apply_l2(candidates, market, multiplier)
392
+ candidates.sort(key=lambda c: c["scores"]["final"], reverse=True)
393
+ for rank, entry in enumerate(candidates, 1):
394
+ entry["rank"] = rank
395
+
184
396
  return {
185
397
  "market": market,
186
398
  "total_stocks": total,
@@ -188,6 +400,8 @@ def screen(market: str, top: int, config: dict | None) -> dict:
188
400
  "returned_count": len(candidates),
189
401
  "filters_applied": filters,
190
402
  "candidates": candidates,
403
+ "market_sentiment": sentiment,
404
+ "l2_enabled": l2_enabled,
191
405
  }
192
406
 
193
407
 
@@ -199,6 +413,9 @@ def main():
199
413
  p.add_argument("--market", default="A", choices=["A", "HK", "US"])
200
414
  p.add_argument("--top", type=int, default=20)
201
415
  p.add_argument("--config", help="Path to YAML config file")
416
+ p.add_argument(
417
+ "--l2", action="store_true", help="Enable L2 factor enrichment (quality/growth/momentum/volatility/moneyflow)"
418
+ )
202
419
 
203
420
  args = parser.parse_args()
204
421
  if not args.command:
@@ -206,7 +423,7 @@ def main():
206
423
  sys.exit(1)
207
424
 
208
425
  config = load_config(args.config) if args.config else None
209
- result = screen(args.market, args.top, config)
426
+ result = screen(args.market, args.top, config, l2=args.l2)
210
427
  print(json.dumps(result, ensure_ascii=False, default=str))
211
428
 
212
429
 
@@ -27,123 +27,130 @@ def _cache_set(key: str, data):
27
27
 
28
28
  # --------------- Web Search ---------------
29
29
 
30
+ _SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
31
+
32
+
33
+ def _scrub_secrets(msg: str) -> str:
34
+ """Error text may embed request URLs (requests connection errors) — never leak keys to stdout JSON."""
35
+ return _SECRET_PARAM_RE.sub(r"\1***", msg)
36
+
30
37
 
31
38
  def _tavily_search(query: str, max_results: int = 5) -> list[dict]:
32
39
  api_key = os.environ.get("TAVILY_API_KEY")
33
40
  if not api_key:
34
41
  return []
35
- try:
36
- import requests
42
+ import requests
37
43
 
38
- resp = requests.post(
39
- "https://api.tavily.com/search",
40
- json={
41
- "api_key": api_key,
42
- "query": query,
43
- "max_results": max_results,
44
- "search_depth": "basic",
45
- },
46
- timeout=15,
47
- )
48
- data = resp.json()
49
- return [
50
- {
51
- "title": r.get("title", ""),
52
- "url": r.get("url", ""),
53
- "snippet": r.get("content", "")[:200],
54
- "source": "tavily",
55
- }
56
- for r in data.get("results", [])
57
- ]
58
- except Exception:
59
- return []
44
+ resp = requests.post(
45
+ "https://api.tavily.com/search",
46
+ json={
47
+ "api_key": api_key,
48
+ "query": query,
49
+ "max_results": max_results,
50
+ "search_depth": "basic",
51
+ },
52
+ timeout=15,
53
+ )
54
+ if not resp.ok:
55
+ raise RuntimeError(f"tavily HTTP {resp.status_code}")
56
+ data = resp.json()
57
+ return [
58
+ {
59
+ "title": r.get("title", ""),
60
+ "url": r.get("url", ""),
61
+ "snippet": r.get("content", "")[:200],
62
+ "source": "tavily",
63
+ }
64
+ for r in data.get("results", [])
65
+ ]
60
66
 
61
67
 
62
68
  def _brave_search(query: str, count: int = 5) -> list[dict]:
63
69
  api_key = os.environ.get("BRAVE_API_KEY")
64
70
  if not api_key:
65
71
  return []
66
- try:
67
- import requests
68
-
69
- resp = requests.get(
70
- "https://api.search.brave.com/res/v1/web/search",
71
- headers={"X-Subscription-Token": api_key, "Accept": "application/json"},
72
- params={"q": query, "count": count},
73
- timeout=15,
74
- )
75
- data = resp.json()
76
- return [
77
- {
78
- "title": r.get("title", ""),
79
- "url": r.get("url", ""),
80
- "snippet": r.get("description", "")[:200],
81
- "source": "brave",
82
- }
83
- for r in data.get("web", {}).get("results", [])
84
- ]
85
- except Exception:
86
- return []
72
+ import requests
73
+
74
+ resp = requests.get(
75
+ "https://api.search.brave.com/res/v1/web/search",
76
+ headers={"X-Subscription-Token": api_key, "Accept": "application/json"},
77
+ params={"q": query, "count": count},
78
+ timeout=15,
79
+ )
80
+ if not resp.ok:
81
+ raise RuntimeError(f"brave HTTP {resp.status_code}")
82
+ data = resp.json()
83
+ return [
84
+ {
85
+ "title": r.get("title", ""),
86
+ "url": r.get("url", ""),
87
+ "snippet": r.get("description", "")[:200],
88
+ "source": "brave",
89
+ }
90
+ for r in data.get("web", {}).get("results", [])
91
+ ]
87
92
 
88
93
 
89
94
  def _serpapi_search(query: str, num: int = 5) -> list[dict]:
90
95
  api_key = os.environ.get("SERPAPI_KEY")
91
96
  if not api_key:
92
97
  return []
93
- try:
94
- import requests
95
-
96
- resp = requests.get(
97
- "https://serpapi.com/search",
98
- params={
99
- "api_key": api_key,
100
- "q": query,
101
- "num": num,
102
- "engine": "google",
103
- },
104
- timeout=15,
105
- )
106
- data = resp.json()
107
- return [
108
- {
109
- "title": r.get("title", ""),
110
- "url": r.get("link", ""),
111
- "snippet": r.get("snippet", "")[:200],
112
- "source": "serpapi",
113
- }
114
- for r in data.get("organic_results", [])
115
- ]
116
- except Exception:
117
- return []
98
+ import requests
99
+
100
+ resp = requests.get(
101
+ "https://serpapi.com/search",
102
+ params={
103
+ "api_key": api_key,
104
+ "q": query,
105
+ "num": num,
106
+ "engine": "google",
107
+ },
108
+ timeout=15,
109
+ )
110
+ if not resp.ok:
111
+ raise RuntimeError(f"serpapi HTTP {resp.status_code}")
112
+ data = resp.json()
113
+ return [
114
+ {
115
+ "title": r.get("title", ""),
116
+ "url": r.get("link", ""),
117
+ "snippet": r.get("snippet", "")[:200],
118
+ "source": "serpapi",
119
+ }
120
+ for r in data.get("organic_results", [])
121
+ ]
118
122
 
119
123
 
120
124
  def _bocha_search(query: str, max_results: int = 5) -> list[dict]:
121
125
  api_key = os.environ.get("BOCHA_API_KEY")
122
126
  if not api_key:
123
127
  return []
124
- try:
125
- import requests
126
-
127
- resp = requests.post(
128
- "https://api.bochaai.com/v1/web-search",
129
- headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
130
- json={"query": query, "count": max_results},
131
- timeout=15,
132
- )
133
- data = resp.json()
134
- results = []
135
- for item in data.get("web", {}).get("results", []):
136
- results.append(
137
- {
138
- "title": item.get("name", ""),
139
- "url": item.get("url", ""),
140
- "snippet": item.get("snippet", "")[:200],
141
- "source": "bocha",
142
- }
143
- )
144
- return results
145
- except Exception:
146
- return []
128
+ import requests
129
+
130
+ resp = requests.post(
131
+ "https://api.bochaai.com/v1/web-search",
132
+ headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
133
+ json={"query": query, "count": max_results},
134
+ timeout=15,
135
+ )
136
+ if not resp.ok:
137
+ raise RuntimeError(f"bocha HTTP {resp.status_code}")
138
+ data = resp.json()
139
+ code = data.get("code")
140
+ if code is not None and str(code) != "200":
141
+ # Bocha can signal quota/auth failure via HTTP 200 + non-200 envelope code
142
+ raise RuntimeError(f"bocha code {code}: {data.get('msg') or data.get('message') or 'unknown'}")
143
+ # Bocha web-search returns Bing-style data.webPages.value[] (issue #13)
144
+ items = ((data.get("data") or {}).get("webPages") or {}).get("value") or []
145
+ return [
146
+ {
147
+ "title": item.get("name", ""),
148
+ "url": item.get("url", ""),
149
+ "snippet": (item.get("snippet") or "")[:200],
150
+ "source": "bocha",
151
+ }
152
+ for item in items
153
+ ]
147
154
 
148
155
 
149
156
  def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
@@ -155,10 +162,10 @@ def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
155
162
  base_urls = [u.strip().rstrip("/") for u in os.environ.get("SEARXNG_BASE_URLS", "").split(",") if u.strip()]
156
163
  if not base_urls:
157
164
  return []
158
- try:
159
- import requests
160
- except ImportError:
161
- return []
165
+ import requests
166
+
167
+ last_error = None
168
+ responded = False
162
169
  for base in base_urls:
163
170
  try:
164
171
  resp = requests.get(
@@ -168,7 +175,9 @@ def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
168
175
  timeout=15,
169
176
  )
170
177
  if not resp.ok:
178
+ last_error = f"searxng {base} HTTP {resp.status_code}"
171
179
  continue
180
+ responded = True
172
181
  data = resp.json()
173
182
  results = [
174
183
  {
@@ -181,8 +190,10 @@ def _searxng_search(query: str, max_results: int = 5) -> list[dict]:
181
190
  ]
182
191
  if results:
183
192
  return results
184
- except Exception:
185
- continue
193
+ except Exception as e:
194
+ last_error = f"searxng {base}: {e}"
195
+ if last_error and not responded:
196
+ raise RuntimeError(last_error)
186
197
  return []
187
198
 
188
199
 
@@ -190,6 +201,7 @@ def search_news(query: str, max_results: int = 10) -> dict:
190
201
  results = []
191
202
  engines_tried = []
192
203
  engines_available = []
204
+ engines_errors = {}
193
205
 
194
206
  for name, fn in [
195
207
  ("tavily", _tavily_search),
@@ -199,7 +211,11 @@ def search_news(query: str, max_results: int = 10) -> dict:
199
211
  ("searxng", _searxng_search),
200
212
  ]:
201
213
  engines_tried.append(name)
202
- items = fn(query, max_results)
214
+ try:
215
+ items = fn(query, max_results)
216
+ except Exception as e:
217
+ engines_errors[name] = _scrub_secrets(str(e))
218
+ continue
203
219
  if items:
204
220
  engines_available.append(name)
205
221
  results.extend(items)
@@ -207,14 +223,19 @@ def search_news(query: str, max_results: int = 10) -> dict:
207
223
  break
208
224
 
209
225
  if not results:
226
+ if engines_errors:
227
+ note = "All configured search engines failed; see engines_errors for per-engine reasons."
228
+ else:
229
+ note = (
230
+ "No search engines configured. Set TAVILY_API_KEY, BRAVE_API_KEY, BOCHA_API_KEY, "
231
+ "SERPAPI_KEY, or SEARXNG_BASE_URLS in environment."
232
+ )
210
233
  return {
211
234
  "query": query,
212
235
  "results": [],
213
236
  "engines_tried": engines_tried,
214
- "note": (
215
- "No search engines configured. Set TAVILY_API_KEY, BRAVE_API_KEY, BOCHA_API_KEY, "
216
- "SERPAPI_KEY, or SEARXNG_BASE_URLS in environment."
217
- ),
237
+ "engines_errors": engines_errors,
238
+ "note": note,
218
239
  }
219
240
 
220
241
  seen_urls = set()
@@ -228,6 +249,7 @@ def search_news(query: str, max_results: int = 10) -> dict:
228
249
  "query": query,
229
250
  "results": deduped[:max_results],
230
251
  "engines_used": engines_available,
252
+ "engines_errors": engines_errors,
231
253
  "total": len(deduped),
232
254
  }
233
255
 
@@ -244,11 +266,13 @@ def search_comprehensive(symbol: str, name: str = None) -> dict:
244
266
  }
245
267
 
246
268
  results = {}
269
+ engines_errors = {}
247
270
  for dim, query in dimensions.items():
248
271
  data = search_news(query, max_results=3)
249
272
  results[dim] = data.get("results", [])
273
+ engines_errors.update(data.get("engines_errors") or {})
250
274
 
251
- return {"symbol": symbol, "name": label, "dimensions": results}
275
+ return {"symbol": symbol, "name": label, "dimensions": results, "engines_errors": engines_errors}
252
276
 
253
277
 
254
278
  # --------------- A-share Sentiment Sources ---------------
@@ -1248,7 +1248,11 @@ def cmd_market_indices(args):
1248
1248
  ("sh000016", "上证50"),
1249
1249
  ]
1250
1250
  results = []
1251
- df = _akshare_retry(ak.stock_zh_index_spot_em)
1251
+ try:
1252
+ df = _akshare_retry(ak.stock_zh_index_spot_em)
1253
+ except Exception:
1254
+ # eastmoney refuses datacenter/proxy IPs (RemoteDisconnected) — sina is the fallback
1255
+ df = _akshare_retry(ak.stock_zh_index_spot_sina)
1252
1256
  for code, name in indices:
1253
1257
  clean_code = code[2:] if code[:2] in ("sh", "sz") else code
1254
1258
  row = df[df["代码"] == clean_code]
@@ -1497,76 +1501,80 @@ def cmd_chip_distribution(args):
1497
1501
  # --------------- market_stats ---------------
1498
1502
 
1499
1503
 
1504
+ def compute_market_stats(data: list) -> dict:
1505
+ """Compute breadth/limit/turnover statistics from a market snapshot list."""
1506
+ import numpy as np
1507
+
1508
+ changes = []
1509
+ turnovers = []
1510
+ limit_ups = []
1511
+ limit_downs = []
1512
+ up_count = down_count = flat_count = 0
1513
+
1514
+ for s in data:
1515
+ chg = s.get("change_pct")
1516
+ if chg is not None:
1517
+ changes.append(float(chg))
1518
+ if chg > 0:
1519
+ up_count += 1
1520
+ elif chg < 0:
1521
+ down_count += 1
1522
+ else:
1523
+ flat_count += 1
1524
+ t = s.get("turnover")
1525
+ if t is not None:
1526
+ turnovers.append(float(t))
1527
+
1528
+ price = s.get("price")
1529
+ prev = s.get("prev_close")
1530
+ sym = s.get("symbol", "")
1531
+ if price and prev and prev > 0:
1532
+ code_info = normalize_stock_code(sym)
1533
+ lp = code_info.get("limit_pct")
1534
+ if lp:
1535
+ limit_up = calc_limit_price(float(prev), lp, "up")
1536
+ limit_down = calc_limit_price(float(prev), lp, "down")
1537
+ if abs(float(price) - limit_up) < 0.01:
1538
+ limit_ups.append({"symbol": sym, "name": s.get("name"), "change_pct": chg})
1539
+ elif abs(float(price) - limit_down) < 0.01:
1540
+ limit_downs.append({"symbol": sym, "name": s.get("name"), "change_pct": chg})
1541
+
1542
+ changes_arr = np.array(changes) if changes else np.array([0])
1543
+ sorted_data = sorted(data, key=lambda x: x.get("change_pct") or 0, reverse=True)
1544
+
1545
+ return _clean_row(
1546
+ {
1547
+ "total_stocks": len(data),
1548
+ "up_count": up_count,
1549
+ "down_count": down_count,
1550
+ "flat_count": flat_count,
1551
+ "limit_up_count": len(limit_ups),
1552
+ "limit_down_count": len(limit_downs),
1553
+ "avg_change_pct": round(float(changes_arr.mean()), 2),
1554
+ "median_change_pct": round(float(np.median(changes_arr)), 2),
1555
+ "total_turnover": round(sum(turnovers), 0) if turnovers else None,
1556
+ "top5_gainers": [
1557
+ {"symbol": s.get("symbol"), "name": s.get("name"), "change_pct": s.get("change_pct")}
1558
+ for s in sorted_data[:5]
1559
+ ],
1560
+ "top5_losers": [
1561
+ {"symbol": s.get("symbol"), "name": s.get("name"), "change_pct": s.get("change_pct")}
1562
+ for s in sorted_data[-5:]
1563
+ ],
1564
+ "limit_up_samples": limit_ups[:5],
1565
+ "limit_down_samples": limit_downs[:5],
1566
+ }
1567
+ )
1568
+
1569
+
1500
1570
  def cmd_market_stats(args):
1501
1571
  try:
1502
- import numpy as np
1503
-
1504
1572
  data = snapshot_a()
1505
1573
  if isinstance(data, dict) and "error" in data:
1506
1574
  return data
1507
1575
  if not data:
1508
1576
  return {"error": "No market data"}
1509
-
1510
- changes = []
1511
- turnovers = []
1512
- limit_ups = []
1513
- limit_downs = []
1514
- up_count = down_count = flat_count = 0
1515
-
1516
- for s in data:
1517
- chg = s.get("change_pct")
1518
- if chg is not None:
1519
- changes.append(float(chg))
1520
- if chg > 0:
1521
- up_count += 1
1522
- elif chg < 0:
1523
- down_count += 1
1524
- else:
1525
- flat_count += 1
1526
- t = s.get("turnover")
1527
- if t is not None:
1528
- turnovers.append(float(t))
1529
-
1530
- price = s.get("price")
1531
- prev = s.get("prev_close")
1532
- sym = s.get("symbol", "")
1533
- if price and prev and prev > 0:
1534
- code_info = normalize_stock_code(sym)
1535
- lp = code_info.get("limit_pct")
1536
- if lp:
1537
- limit_up = calc_limit_price(float(prev), lp, "up")
1538
- limit_down = calc_limit_price(float(prev), lp, "down")
1539
- if abs(float(price) - limit_up) < 0.01:
1540
- limit_ups.append({"symbol": sym, "name": s.get("name"), "change_pct": chg})
1541
- elif abs(float(price) - limit_down) < 0.01:
1542
- limit_downs.append({"symbol": sym, "name": s.get("name"), "change_pct": chg})
1543
-
1544
- changes_arr = np.array(changes) if changes else np.array([0])
1545
- sorted_data = sorted(data, key=lambda x: x.get("change_pct") or 0, reverse=True)
1546
-
1547
- return _clean_row(
1548
- {
1549
- "total_stocks": len(data),
1550
- "up_count": up_count,
1551
- "down_count": down_count,
1552
- "flat_count": flat_count,
1553
- "limit_up_count": len(limit_ups),
1554
- "limit_down_count": len(limit_downs),
1555
- "avg_change_pct": round(float(changes_arr.mean()), 2),
1556
- "median_change_pct": round(float(np.median(changes_arr)), 2),
1557
- "total_turnover": round(sum(turnovers), 0) if turnovers else None,
1558
- "top5_gainers": [
1559
- {"symbol": s.get("symbol"), "name": s.get("name"), "change_pct": s.get("change_pct")}
1560
- for s in sorted_data[:5]
1561
- ],
1562
- "top5_losers": [
1563
- {"symbol": s.get("symbol"), "name": s.get("name"), "change_pct": s.get("change_pct")}
1564
- for s in sorted_data[-5:]
1565
- ],
1566
- "limit_up_samples": limit_ups[:5],
1567
- "limit_down_samples": limit_downs[:5],
1568
- }
1569
- )
1577
+ return compute_market_stats(data)
1570
1578
  except Exception as e:
1571
1579
  return {"error": str(e)}
1572
1580
 
@@ -1708,7 +1716,10 @@ def main():
1708
1716
  "market_stats": cmd_market_stats,
1709
1717
  "fundamental_context": cmd_fundamental_context,
1710
1718
  }
1711
- result = dispatch[args.command](args)
1719
+ # Provider libraries (baostock etc.) print prose to stdout on failure,
1720
+ # which would corrupt the JSON-only contract — divert that noise to stderr.
1721
+ with contextlib.redirect_stdout(sys.stderr):
1722
+ result = dispatch[args.command](args)
1712
1723
  output(result)
1713
1724
 
1714
1725