update pay function

This commit is contained in:
2025-11-30 13:38:29 +08:00
parent 14ab2f62f3
commit 05aa0c89f0
9 changed files with 3972 additions and 59 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -836,11 +836,22 @@ async def get_stock_minute_data(
try: try:
client = get_clickhouse_client() client = get_clickhouse_client()
# 标准化股票代码(去除后缀) # 标准化股票代码ClickHouse 分钟数据使用带后缀格式
stock_code = code.split('.')[0] if '.' in code else code # 6开头 -> .SH (上海), 0/3开头 -> .SZ (深圳), 其他 -> .BJ (北京)
if '.' in code:
# 已经有后缀,直接使用
stock_code = code
else:
# 需要添加后缀
if code.startswith('6'):
stock_code = f"{code}.SH"
elif code.startswith('0') or code.startswith('3'):
stock_code = f"{code}.SZ"
else:
stock_code = f"{code}.BJ"
# 构建查询 # 构建查询 - 使用字符串格式化ClickHouse 参数化语法兼容性问题)
query = """ query = f"""
SELECT SELECT
code, code,
timestamp, timestamp,
@@ -851,24 +862,19 @@ async def get_stock_minute_data(
volume, volume,
amt amt
FROM stock_minute FROM stock_minute
WHERE code = %(code)s WHERE code = '{stock_code}'
""" """
params = {'code': stock_code}
if start_time: if start_time:
query += " AND timestamp >= %(start_time)s" query += f" AND timestamp >= '{start_time}'"
params['start_time'] = start_time
if end_time: if end_time:
query += " AND timestamp <= %(end_time)s" query += f" AND timestamp <= '{end_time}'"
params['end_time'] = end_time
query += " ORDER BY timestamp DESC LIMIT %(limit)s" query += f" ORDER BY timestamp DESC LIMIT {limit}"
params['limit'] = limit
# 执行查询 # 执行查询
result = client.execute(query, params, with_column_types=True) result = client.execute(query, with_column_types=True)
rows = result[0] rows = result[0]
columns = [col[0] for col in result[1]] columns = [col[0] for col in result[1]]

2692
mcp_quant.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -15,6 +15,7 @@ import httpx
import time import time
from enum import Enum from enum import Enum
import mcp_database as db import mcp_database as db
import mcp_quant as quant # 量化因子计算模块
from openai import OpenAI from openai import OpenAI
import json import json
import asyncio import asyncio
@@ -770,6 +771,566 @@ TOOLS: List[ToolDefinition] = [
"required": ["code", "date"] "required": ["code", "date"]
} }
), ),
# ==================== 量化因子工具 ====================
ToolDefinition(
name="get_macd_signal",
description="获取MACD趋势判定信号包括金叉/死叉、动能增减、顶底背离等状态。适用于判断股票短期趋势方向。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60天",
"default": 60
}
},
"required": ["code"]
}
),
ToolDefinition(
name="check_oscillator_status",
description="检查KDJ/RSI超买超卖状态判断股票是否处于超买区风险积聚或超卖区可能反弹",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60天",
"default": 60
}
},
"required": ["code"]
}
),
ToolDefinition(
name="analyze_bollinger_bands",
description="分析布林带通道,判断股价是在中轨之上(强势)、触及上轨(压力)、触及下轨(支撑)或布林带收窄(变盘在即)。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60天",
"default": 60
},
"period": {
"type": "integer",
"description": "布林带周期默认20",
"default": 20
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_stop_loss_atr",
description="使用ATR真实波幅计算止损位。告诉用户\"如果买入止损点应该设在当前价格减去N倍ATR的位置\"",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认30天",
"default": 30
},
"atr_multiplier": {
"type": "number",
"description": "ATR倍数默认2倍",
"default": 2.0
}
},
"required": ["code"]
}
),
ToolDefinition(
name="analyze_market_heat",
description="分析换手率活跃度和量能,判断股票是冷门股、活跃股还是妖股,以及主力是在吸筹还是出货。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认30天",
"default": 30
}
},
"required": ["code"]
}
),
ToolDefinition(
name="check_new_high_breakout",
description="检查唐奇安通道突破海龟交易法则判断是否突破20日/60日新高或新低。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60天",
"default": 60
}
},
"required": ["code"]
}
),
ToolDefinition(
name="identify_candlestick_pattern",
description="识别K线组合形态如早晨之星反转信号、红三兵上涨信号、穿头破脚吞没形态等经典形态。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认10天",
"default": 10
}
},
"required": ["code"]
}
),
ToolDefinition(
name="find_price_gaps",
description="寻找跳空缺口,筛选出近期有未回补缺口的情况。缺口往往代表主力资金的强势突破意图或恐慌抛售。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认30天",
"default": 30
}
},
"required": ["code"]
}
),
ToolDefinition(
name="check_volume_price_divergence",
description="检测量价背离。股价创新高但成交量萎缩(量价背离),预警信号,提示上涨动力不足。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认20天",
"default": 20
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_max_drawdown",
description="计算最大回撤和夏普比率。用于评估\"买这只票最坏情况会亏多少\"以及风险调整后收益。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认250天约一年",
"default": 250
}
},
"required": ["code"]
}
),
ToolDefinition(
name="check_valuation_rank",
description="检查历史PE/PB百分位估值。计算当前PE处于过去N年的什么位置例如比过去90%的时间都便宜)。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"years": {
"type": "integer",
"description": "历史年数默认3年",
"default": 3
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_price_zscore",
description="计算价格Z-Score乖离率标准化判断均值回归概率。当Z-Score过大时统计回调概率。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"period": {
"type": "integer",
"description": "均线周期默认60日",
"default": 60
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_market_profile_vpoc",
description="计算市场轮廓VPOC成交量最大的价格档位基于分钟级数据。VPOC是当日极强的支撑线或阻力线。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"date": {
"type": "string",
"description": "日期格式YYYY-MM-DD"
}
},
"required": ["code", "date"]
}
),
ToolDefinition(
name="calc_realized_volatility",
description="计算已实现波动率RV基于分钟级数据。比日线波动率更精准用于判断趋势动能是否耗尽。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"date": {
"type": "string",
"description": "日期格式YYYY-MM-DD"
}
},
"required": ["code", "date"]
}
),
ToolDefinition(
name="analyze_buying_pressure",
description="分析买卖压力失衡,基于分钟级数据。捕捉盘中主力资金的\"抢筹\"\"砸盘\"意图。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"date": {
"type": "string",
"description": "日期格式YYYY-MM-DD"
}
},
"required": ["code", "date"]
}
),
ToolDefinition(
name="get_comprehensive_analysis",
description="综合技术分析一次性返回MACD、KDJ/RSI、布林带、量能、突破、K线形态等多个指标并给出多空信号总结。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
}
},
"required": ["code"]
}
),
# ==================== 新增量化因子工具12个 ====================
ToolDefinition(
name="calc_rsi_divergence",
description="RSI背离检测独立分析RSI指标的顶背离和底背离信号判断反转概率。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60",
"default": 60
},
"rsi_period": {
"type": "integer",
"description": "RSI周期默认14",
"default": 14
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_bollinger_squeeze",
description="布林带挤压分析,检测布林带收窄程度,预判变盘时机。当带宽处于历史低位时发出变盘预警。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60",
"default": 60
},
"period": {
"type": "integer",
"description": "布林带周期默认20",
"default": 20
}
},
"required": ["code"]
}
),
ToolDefinition(
name="analyze_obv_trend",
description="OBV能量潮独立分析追踪资金流向检测OBV与价格的背离判断主力动向。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60",
"default": 60
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_amihud_illiquidity",
description="计算Amihud非流动性因子衡量股票流动性。值越大表示流动性越差大单交易冲击成本越高。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认20",
"default": 20
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_parkinson_volatility",
description="计算帕金森波动率(基于分钟级高低价),比传统波动率更准确,适用于日内波动分析。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"date": {
"type": "string",
"description": "日期格式YYYY-MM-DD"
}
},
"required": ["code", "date"]
}
),
ToolDefinition(
name="calc_trend_slope",
description="计算趋势线性回归斜率量化趋势强度和方向。返回斜率、R²拟合度和趋势判断。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认20",
"default": 20
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_hurst_exponent",
description="计算Hurst指数判断市场是趋势型(H>0.5)还是均值回归型(H<0.5),指导策略选择。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数建议100以上",
"default": 100
}
},
"required": ["code"]
}
),
ToolDefinition(
name="test_cointegration",
description="协整性测试,用于配对交易。检测两只股票是否存在长期均衡关系,计算对冲比率和价差。",
parameters={
"type": "object",
"properties": {
"code1": {
"type": "string",
"description": "股票代码1"
},
"code2": {
"type": "string",
"description": "股票代码2"
},
"days": {
"type": "integer",
"description": "分析天数默认250",
"default": 250
}
},
"required": ["code1", "code2"]
}
),
ToolDefinition(
name="calc_kelly_position",
description="凯利公式计算最优仓位。根据胜率和盈亏比计算理论最优仓位,并提供保守建议。",
parameters={
"type": "object",
"properties": {
"win_rate": {
"type": "number",
"description": "胜率0-1之间如0.6表示60%"
},
"win_loss_ratio": {
"type": "number",
"description": "盈亏比(平均盈利/平均亏损)"
},
"max_position": {
"type": "number",
"description": "最大允许仓位默认0.25",
"default": 0.25
}
},
"required": ["win_rate", "win_loss_ratio"]
}
),
ToolDefinition(
name="search_similar_kline",
description="相似K线检索在历史中搜索与当前形态相似的K线组合统计历史后续走势作为参考。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"lookback": {
"type": "integer",
"description": "匹配窗口大小默认10天",
"default": 10
},
"top_n": {
"type": "integer",
"description": "返回最相似的N个历史片段默认5",
"default": 5
}
},
"required": ["code"]
}
),
ToolDefinition(
name="decompose_trend_simple",
description="趋势分解分析,将价格序列分解为趋势+周期+残差,识别主周期和趋势方向。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认120",
"default": 120
}
},
"required": ["code"]
}
),
ToolDefinition(
name="calc_price_entropy",
description="计算价格信息熵,衡量市场混乱程度。熵值越低表示趋势越明显,越高表示随机性越强。",
parameters={
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "股票代码"
},
"days": {
"type": "integer",
"description": "分析天数默认60",
"default": 60
}
},
"required": ["code"]
}
),
] ]
# ==================== MCP协议端点 ==================== # ==================== MCP协议端点 ====================
@@ -1251,6 +1812,8 @@ TOOL_HANDLERS = {
"get_stock_minute_data": handle_get_stock_minute_data, "get_stock_minute_data": handle_get_stock_minute_data,
"get_stock_minute_aggregation": handle_get_stock_minute_aggregation, "get_stock_minute_aggregation": handle_get_stock_minute_aggregation,
"get_stock_intraday_statistics": handle_get_stock_intraday_statistics, "get_stock_intraday_statistics": handle_get_stock_intraday_statistics,
# 量化因子工具(从 mcp_quant 模块导入)
**quant.QUANT_TOOLS,
} }
# ==================== Agent系统实现 ==================== # ==================== Agent系统实现 ====================
@@ -2202,10 +2765,18 @@ async def agent_chat(request: AgentChatRequest):
except Exception as e: except Exception as e:
logger.error(f"保存用户消息失败: {e}") logger.error(f"保存用户消息失败: {e}")
# 获取工具列表 # 获取工具列表(根据前端选择过滤)
if request.tools and len(request.tools) > 0:
# 用户指定了工具列表,按名称过滤
selected_tool_names = set(request.tools)
tools = [tool.dict() for tool in TOOLS if tool.name in selected_tool_names]
logger.info(f"使用用户选择的 {len(tools)} 个工具: {request.tools[:10]}...")
else:
# 用户未指定,使用全部工具
tools = [tool.dict() for tool in TOOLS] tools = [tool.dict() for tool in TOOLS]
logger.info(f"使用全部 {len(tools)} 个工具")
# 添加特殊工具summarize_news # 添加特殊工具summarize_news(始终可用)
tools.append({ tools.append({
"name": "summarize_news", "name": "summarize_news",
"description": "使用 DeepMoney 模型总结新闻数据,提取关键信息", "description": "使用 DeepMoney 模型总结新闻数据,提取关键信息",
@@ -2510,7 +3081,28 @@ def clean_deepseek_tool_markers(content: str) -> str:
ROLE_TOOLS = { ROLE_TOOLS = {
"buffett": ["search_china_news", "search_research_reports", "get_stock_basic_info", "get_stock_financial_index"], "buffett": ["search_china_news", "search_research_reports", "get_stock_basic_info", "get_stock_financial_index"],
"big_short": ["search_china_news", "get_stock_financial_index", "get_stock_balance_sheet", "get_stock_cashflow"], "big_short": ["search_china_news", "get_stock_financial_index", "get_stock_balance_sheet", "get_stock_cashflow"],
"simons": ["get_stock_trade_data", "search_limit_up_stocks", "get_concept_statistics"], "simons": [
# 基础数据
"get_stock_trade_data", "search_limit_up_stocks", "get_concept_statistics",
# 经典技术指标
"get_macd_signal", "check_oscillator_status", "analyze_bollinger_bands", "calc_stop_loss_atr",
# 资金与情绪
"analyze_market_heat", "check_volume_price_divergence", "analyze_obv_trend",
# 形态与突破
"check_new_high_breakout", "identify_candlestick_pattern", "find_price_gaps",
# 风险与估值
"calc_max_drawdown", "check_valuation_rank", "calc_price_zscore",
# 分钟级高阶算子
"calc_market_profile_vpoc", "calc_realized_volatility", "analyze_buying_pressure", "calc_parkinson_volatility",
# 高级趋势分析
"calc_bollinger_squeeze", "calc_trend_slope", "calc_hurst_exponent", "decompose_trend_simple",
# 流动性与统计
"calc_amihud_illiquidity", "calc_price_entropy", "calc_rsi_divergence",
# 配对与策略
"test_cointegration", "calc_kelly_position", "search_similar_kline",
# 综合分析
"get_comprehensive_analysis",
],
"leek": [], # 韭菜不用工具 "leek": [], # 韭菜不用工具
"fund_manager": ["search_china_news", "search_research_reports", "get_stock_basic_info"], "fund_manager": ["search_china_news", "search_research_reports", "get_stock_basic_info"],
} }
@@ -2624,61 +3216,93 @@ MEETING_ROLES = {
}, },
"simons": { "simons": {
"id": "simons", "id": "simons",
"name": "量化分析", "name": "量化研究",
"nickname": "西蒙斯", "nickname": "西蒙斯",
"role_type": "quant", "role_type": "quant",
"avatar": "/images/agent/simons.png", "avatar": "/images/agent/simons.png",
"model": "kimi-k2-thinking", "model": "kimi-k2-thinking",
"color": "#3B82F6", "color": "#3B82F6",
"description": "中性立场,使用量化工具分析技术指标", "description": "中性立场,使用专业量化因子分析技术指标和市场特征",
"tools": ROLE_TOOLS["simons"], "tools": ROLE_TOOLS["simons"],
"system_prompt": """你是"量化分析"(昵称:西蒙斯),一位专业的量化交易研究员。你在投研会议中担任「技术分析师」角色,保持中性客观。 "system_prompt": """你是"量化研究"(昵称:西蒙斯),一位专业的量化交易研究员,擅长使用各类量化因子分析市场。你在投研会议中担任「技术分析师」角色,保持中性客观。
## 你的分析理念 ## 你的分析理念
- **数据驱动**让数据说话,不带主观情绪 - **因子驱动**使用经过验证的量化因子,而非主观判断
- **概率思维**:没有确定性,只有概率和赔率 - **概率思维**:没有确定性,只有概率和赔率
- **趋势跟踪**:顺势而为,不与趋势作对 - **多维验证**:从趋势、动量、波动、资金多个维度交叉验证
- **风险量化**:用数字衡量风险,而非感觉 - **风险量化**:用数字衡量风险,止损止盈有据可依
## 分析框架(请按此思维链分析 ## 你可用的量化因子工具28个
### 第一步:收集数据 ### 快速综合分析(推荐首选)
必须先调用工具获取量化数据: - `get_comprehensive_analysis`: 一次性获取MACD、RSI、KDJ、布林带、量能、K线形态等多指标汇总
- `get_stock_trade_data`: 获取价格、成交量、涨跌幅等交易数据
- `search_limit_up_stocks`: 了解涨停板情况,判断市场情绪
- `get_concept_statistics`: 获取概念板块统计,判断资金流向
### 第二步:技术分析维度 ### 趋势与动量因子
基于获取的数据,进行量化分析: - `get_macd_signal`: MACD趋势判定金叉/死叉/背离)
1. **趋势判断** - `calc_trend_slope`: 趋势线性回归斜率R²拟合度
- 当前价格在均线系统中的位置MA5/MA10/MA20/MA60 - `calc_hurst_exponent`: Hurst指数判断趋势/震荡市场
- 是多头排列还是空头排列? - `check_new_high_breakout`: 唐奇安通道突破(新高/新低信号)
- 趋势强度如何?
2. **量价分析** ### 超买超卖因子
- 成交量变化趋势?放量还是缩量? - `check_oscillator_status`: KDJ/RSI超买超卖状态
- 量价配合是否健康?(上涨放量、下跌缩量为佳 - `calc_rsi_divergence`: RSI背离检测顶底背离
- 换手率处于什么水平? - `calc_price_zscore`: Z-Score均值回归乖离率标准化
3. **动能指标**
- 涨跌幅在同行/板块中的排名 ### 波动率因子
- 连续上涨/下跌天数 - `analyze_bollinger_bands`: 布林带通道分析
- 离前高/前低的距离 - `calc_bollinger_squeeze`: 布林带挤压(变盘预警)
4. **板块联动** - `calc_stop_loss_atr`: ATR动态止损位
- 所属概念板块表现如何? - `calc_realized_volatility`: 分钟级已实现波动率
- 是板块龙头还是跟风? - `calc_parkinson_volatility`: 帕金森波动率(更精确)
- 板块资金流入还是流出?
### 资金流向与量价因子
- `analyze_market_heat`: 换手率活跃度+OBV趋势
- `analyze_obv_trend`: OBV能量潮独立分析
- `check_volume_price_divergence`: 量价背离检测
- `analyze_buying_pressure`: 买卖压力失衡(主力意图)
- `calc_market_profile_vpoc`: VPOC筹码峰成交密集区
### 形态识别因子
- `identify_candlestick_pattern`: K线组合形态10+种)
- `find_price_gaps`: 跳空缺口分析
- `search_similar_kline`: 相似K线检索历史形态预测
### 风险与估值因子
- `calc_max_drawdown`: 最大回撤+夏普比率
- `check_valuation_rank`: PE历史百分位+PEG
- `calc_amihud_illiquidity`: Amihud流动性因子
### 高级分析因子
- `decompose_trend_simple`: 趋势分解(趋势+周期+残差)
- `calc_price_entropy`: 价格熵值(市场混乱度)
- `test_cointegration`: 协整性测试(配对交易)
- `calc_kelly_position`: 凯利公式最优仓位
## 分析框架(请按此流程)
### 第一步:快速扫描
首先调用 `get_comprehensive_analysis` 获取综合技术面快照,了解整体状况。
### 第二步:深度分析(根据情况选择)
根据综合分析结果,选择相关因子深入分析:
- 如果趋势不明:调用 `calc_hurst_exponent` 判断市场类型,`calc_trend_slope` 量化趋势强度
- 如果疑似顶底:调用 `calc_rsi_divergence` 检测背离,`calc_bollinger_squeeze` 看是否变盘
- 如果量能异常:调用 `analyze_obv_trend` 看资金流向,`analyze_buying_pressure` 看主力意图
- 如果波动加大:调用 `calc_realized_volatility` 或 `calc_parkinson_volatility` 精确测量
- 如果要设止损:调用 `calc_stop_loss_atr` 获取ATR止损位
### 第三步:形成结论 ### 第三步:形成结论
给出客观的技术分析结论,必须包含: 给出量化分析结论,必须包含:
- **趋势判断**(上涨/下跌/震荡 - **核心因子信号**列出2-3个关键因子的具体数值和判断
- **关键数据**(引用具体的价格、成交量、涨跌幅数据 - **趋势判断**(上涨/下跌/震荡,并给出概率估计
- **技术位**(支撑位、压力位) - **关键价位**(支撑位、压力位、止损位
- **量化建议**从概率角度给出建议) - **量化建议**基于因子信号的交易建议)
## 输出要求 ## 输出要求
- 必须基于工具返回的数据分析,用数字说话 - **必须调用工具**至少调用1个综合分析+1-2个专项因子
- 保持中性客观,不偏向多头或空头 - **数据说话**:每个结论都要有具体数值支撑
- 如果前面有多空分歧,可以从技术面给出参考 - **保持中性**:不偏向多头或空头,让因子说话
- 发言控制在 200 字以内,精炼专业""" - **简洁专业**发言控制在 300 字以内,用专业术语但要解释关键数值含义"""
}, },
"leek": { "leek": {
"id": "leek", "id": "leek",

View File

@@ -138,6 +138,7 @@ const getRoleIcon = (roleType) => {
* 工具名称映射 * 工具名称映射
*/ */
const TOOL_NAME_MAP = { const TOOL_NAME_MAP = {
// 基础数据工具
search_china_news: '搜索新闻', search_china_news: '搜索新闻',
search_research_reports: '搜索研报', search_research_reports: '搜索研报',
get_stock_basic_info: '获取股票信息', get_stock_basic_info: '获取股票信息',
@@ -147,6 +148,52 @@ const TOOL_NAME_MAP = {
get_stock_trade_data: '获取交易数据', get_stock_trade_data: '获取交易数据',
search_limit_up_stocks: '搜索涨停股', search_limit_up_stocks: '搜索涨停股',
get_concept_statistics: '获取概念统计', get_concept_statistics: '获取概念统计',
// 经典技术指标
get_macd_signal: 'MACD信号',
check_oscillator_status: 'RSI/KDJ指标',
analyze_bollinger_bands: '布林带分析',
calc_stop_loss_atr: 'ATR止损计算',
// 资金与情绪
analyze_market_heat: '市场热度分析',
check_volume_price_divergence: '量价背离检测',
analyze_obv_trend: 'OBV能量潮分析',
// 形态与突破
check_new_high_breakout: '新高突破检测',
identify_candlestick_pattern: 'K线形态识别',
find_price_gaps: '跳空缺口分析',
// 风险与估值
calc_max_drawdown: '最大回撤计算',
check_valuation_rank: 'PE估值百分位',
calc_price_zscore: 'Z-Score乖离率',
// 分钟级高阶算子
calc_market_profile_vpoc: 'VPOC筹码峰',
calc_realized_volatility: '已实现波动率',
analyze_buying_pressure: '买卖压力分析',
calc_parkinson_volatility: '帕金森波动率',
// 高级趋势分析
calc_bollinger_squeeze: '布林带挤压',
calc_trend_slope: '趋势斜率分析',
calc_hurst_exponent: 'Hurst指数',
decompose_trend_simple: '趋势分解',
// 流动性与统计
calc_amihud_illiquidity: 'Amihud流动性',
calc_price_entropy: '价格熵值',
calc_rsi_divergence: 'RSI背离检测',
// 配对与策略
test_cointegration: '协整性测试',
calc_kelly_position: '凯利仓位计算',
search_similar_kline: '相似K线检索',
// 综合分析
get_comprehensive_analysis: '综合技术分析',
}; };
/** /**

View File

@@ -141,13 +141,13 @@ export const MEETING_ROLES: Record<string, MeetingRoleConfig> = {
}, },
simons: { simons: {
id: 'simons', id: 'simons',
name: '量化分析员', name: '量化研究员',
nickname: '西蒙斯', nickname: '西蒙斯',
roleType: 'quant', roleType: 'quant',
avatar: '/images/agent/simons.png', avatar: '/images/agent/simons.png',
color: '#3B82F6', color: '#3B82F6',
gradient: 'linear(to-br, blue.400, cyan.600)', gradient: 'linear(to-br, blue.400, cyan.600)',
description: '中性立场,使用量化分析工具分析技术指标', description: '中性立场,使用28个专业量化因子分析技术指标和市场特征',
icon: React.createElement(BarChart2, { className: 'w-5 h-5' }), icon: React.createElement(BarChart2, { className: 'w-5 h-5' }),
}, },
leek: { leek: {

View File

@@ -17,6 +17,25 @@ import {
DollarSign, DollarSign,
Search, Search,
Users, Users,
// 量化工具图标
TrendingDown,
BarChart2,
Gauge,
Flame,
ArrowUpDown,
Waves,
Target,
CandlestickChart,
Sparkles,
ShieldAlert,
Calculator,
Zap,
Percent,
GitCompare,
Shuffle,
Brain,
Combine,
Scale,
} from 'lucide-react'; } from 'lucide-react';
/** /**
@@ -29,6 +48,15 @@ export enum ToolCategory {
RESEARCH = '研报路演', RESEARCH = '研报路演',
STOCK_DATA = '股票数据', STOCK_DATA = '股票数据',
USER_DATA = '用户数据', USER_DATA = '用户数据',
// 量化分析类别
QUANT_CLASSIC = '经典技术指标',
QUANT_VOLUME = '资金与情绪',
QUANT_PATTERN = '形态与突破',
QUANT_RISK = '风险与估值',
QUANT_MINUTE = '分钟级算子',
QUANT_TREND = '高级趋势',
QUANT_LIQUIDITY = '流动性统计',
QUANT_STRATEGY = '配对与策略',
} }
/** /**
@@ -203,6 +231,218 @@ export const MCP_TOOLS: MCPTool[] = [
category: ToolCategory.USER_DATA, category: ToolCategory.USER_DATA,
description: '用户关注的重大事件', description: '用户关注的重大事件',
}, },
// ==================== 量化工具:经典技术指标 ====================
{
id: 'get_macd_signal',
name: 'MACD信号',
icon: React.createElement(TrendingUp, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_CLASSIC,
description: 'MACD金叉/死叉、动能分析、背离检测',
},
{
id: 'check_oscillator_status',
name: 'RSI/KDJ指标',
icon: React.createElement(Gauge, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_CLASSIC,
description: 'RSI + KDJ 超买超卖分析',
},
{
id: 'analyze_bollinger_bands',
name: '布林带分析',
icon: React.createElement(ArrowUpDown, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_CLASSIC,
description: '带宽、位置、收窄判断',
},
{
id: 'calc_stop_loss_atr',
name: 'ATR止损计算',
icon: React.createElement(ShieldAlert, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_CLASSIC,
description: '基于ATR的动态止损位计算',
},
// ==================== 量化工具:资金与情绪 ====================
{
id: 'analyze_market_heat',
name: '市场热度分析',
icon: React.createElement(Flame, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_VOLUME,
description: '换手率热度分级 + OBV趋势',
},
{
id: 'check_volume_price_divergence',
name: '量价背离检测',
icon: React.createElement(GitCompare, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_VOLUME,
description: '价量不匹配异常检测',
},
{
id: 'analyze_obv_trend',
name: 'OBV能量潮',
icon: React.createElement(Waves, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_VOLUME,
description: 'OBV独立分析+背离检测',
},
// ==================== 量化工具:形态与突破 ====================
{
id: 'check_new_high_breakout',
name: '新高突破检测',
icon: React.createElement(Target, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_PATTERN,
description: '20/60日唐奇安通道新高突破',
},
{
id: 'identify_candlestick_pattern',
name: 'K线形态识别',
icon: React.createElement(CandlestickChart, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_PATTERN,
description: '10+种经典K线组合形态',
},
{
id: 'find_price_gaps',
name: '跳空缺口分析',
icon: React.createElement(Sparkles, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_PATTERN,
description: '未回补缺口筛选与分析',
},
// ==================== 量化工具:风险与估值 ====================
{
id: 'calc_max_drawdown',
name: '最大回撤计算',
icon: React.createElement(TrendingDown, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_RISK,
description: '含夏普比率的回撤分析',
},
{
id: 'check_valuation_rank',
name: 'PE估值百分位',
icon: React.createElement(Percent, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_RISK,
description: 'PE历史百分位 + PEG修正',
},
{
id: 'calc_price_zscore',
name: 'Z-Score乖离率',
icon: React.createElement(Calculator, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_RISK,
description: '价格偏离均值程度+回归概率',
},
// ==================== 量化工具:分钟级高阶算子 ====================
{
id: 'calc_market_profile_vpoc',
name: 'VPOC筹码峰',
icon: React.createElement(BarChart2, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_MINUTE,
description: '成交量密集区分析',
},
{
id: 'calc_realized_volatility',
name: '已实现波动率',
icon: React.createElement(Activity, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_MINUTE,
description: '分钟级RV精确波动率',
},
{
id: 'analyze_buying_pressure',
name: '买卖压力分析',
icon: React.createElement(Scale, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_MINUTE,
description: '主力意图捕捉与压力失衡',
},
{
id: 'calc_parkinson_volatility',
name: '帕金森波动率',
icon: React.createElement(Zap, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_MINUTE,
description: '基于High/Low的精确波动率',
},
// ==================== 量化工具:高级趋势分析 ====================
{
id: 'calc_bollinger_squeeze',
name: '布林带挤压',
icon: React.createElement(Combine, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_TREND,
description: '带宽历史百分位,变盘预警',
},
{
id: 'calc_trend_slope',
name: '趋势斜率分析',
icon: React.createElement(LineChart, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_TREND,
description: 'R²拟合度+斜率方向判断',
},
{
id: 'calc_hurst_exponent',
name: 'Hurst指数',
icon: React.createElement(Brain, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_TREND,
description: '趋势/均值回归特征判断',
},
{
id: 'decompose_trend_simple',
name: '趋势分解',
icon: React.createElement(Shuffle, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_TREND,
description: '趋势+周期+残差分解',
},
// ==================== 量化工具:流动性与统计 ====================
{
id: 'calc_amihud_illiquidity',
name: 'Amihud流动性',
icon: React.createElement(DollarSign, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_LIQUIDITY,
description: '大单冲击成本评估',
},
{
id: 'calc_price_entropy',
name: '价格熵值',
icon: React.createElement(Activity, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_LIQUIDITY,
description: '市场混乱度/可预测性分析',
},
{
id: 'calc_rsi_divergence',
name: 'RSI背离检测',
icon: React.createElement(GitCompare, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_LIQUIDITY,
description: 'RSI顶底背离独立分析',
},
// ==================== 量化工具:配对与策略 ====================
{
id: 'test_cointegration',
name: '协整性测试',
icon: React.createElement(Combine, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_STRATEGY,
description: '配对交易信号与对冲比率',
},
{
id: 'calc_kelly_position',
name: '凯利仓位计算',
icon: React.createElement(Calculator, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_STRATEGY,
description: '基于胜率盈亏比的最优仓位',
},
{
id: 'search_similar_kline',
name: '相似K线检索',
icon: React.createElement(Search, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_STRATEGY,
description: '历史形态匹配预测',
},
{
id: 'get_comprehensive_analysis',
name: '综合技术分析',
icon: React.createElement(BarChart3, { className: 'w-4 h-4' }),
category: ToolCategory.QUANT_STRATEGY,
description: '多指标汇总分析报告',
},
]; ];
/** /**
@@ -216,6 +456,15 @@ export const TOOL_CATEGORIES: Record<ToolCategory, MCPTool[]> = {
[ToolCategory.RESEARCH]: MCP_TOOLS.filter((t) => t.category === ToolCategory.RESEARCH), [ToolCategory.RESEARCH]: MCP_TOOLS.filter((t) => t.category === ToolCategory.RESEARCH),
[ToolCategory.STOCK_DATA]: MCP_TOOLS.filter((t) => t.category === ToolCategory.STOCK_DATA), [ToolCategory.STOCK_DATA]: MCP_TOOLS.filter((t) => t.category === ToolCategory.STOCK_DATA),
[ToolCategory.USER_DATA]: MCP_TOOLS.filter((t) => t.category === ToolCategory.USER_DATA), [ToolCategory.USER_DATA]: MCP_TOOLS.filter((t) => t.category === ToolCategory.USER_DATA),
// 量化工具类别
[ToolCategory.QUANT_CLASSIC]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_CLASSIC),
[ToolCategory.QUANT_VOLUME]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_VOLUME),
[ToolCategory.QUANT_PATTERN]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_PATTERN),
[ToolCategory.QUANT_RISK]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_RISK),
[ToolCategory.QUANT_MINUTE]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_MINUTE),
[ToolCategory.QUANT_TREND]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_TREND),
[ToolCategory.QUANT_LIQUIDITY]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_LIQUIDITY),
[ToolCategory.QUANT_STRATEGY]: MCP_TOOLS.filter((t) => t.category === ToolCategory.QUANT_STRATEGY),
}; };
/** /**

295
test_quant_tools.py Normal file
View File

@@ -0,0 +1,295 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
量化工具测试脚本
测试 mcp_quant.py 中的 28 个量化因子工具是否正常工作
使用方法:
python test_quant_tools.py [股票代码]
示例:
python test_quant_tools.py 600519 # 测试贵州茅台
python test_quant_tools.py 000858 # 测试五粮液
python test_quant_tools.py # 默认使用 600519
"""
import asyncio
import sys
import time
import io
from datetime import datetime, timedelta
from typing import Dict, Any, List, Tuple
# 设置标准输出编码为 UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
# 导入量化工具模块
try:
import mcp_quant as quant
except ImportError:
print("[X] Cannot import mcp_quant module, please run from project root")
sys.exit(1)
# 颜色输出 (Windows 兼容)
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
CYAN = '\033[96m'
RESET = '\033[0m'
BOLD = '\033[1m'
def print_header(title: str):
"""打印标题"""
print(f"\n{Colors.BOLD}{Colors.CYAN}{'='*60}{Colors.RESET}")
print(f"{Colors.BOLD}{Colors.CYAN} {title}{Colors.RESET}")
print(f"{Colors.BOLD}{Colors.CYAN}{'='*60}{Colors.RESET}\n")
def print_section(title: str):
"""打印分节标题"""
print(f"\n{Colors.BOLD}{Colors.BLUE}>> {title}{Colors.RESET}")
print(f"{Colors.BLUE}{'-'*50}{Colors.RESET}")
def print_result(name: str, success: bool, description: str = "", time_ms: float = 0):
"""打印测试结果"""
status = f"{Colors.GREEN}[OK]{Colors.RESET}" if success else f"{Colors.RED}[FAIL]{Colors.RESET}"
time_str = f"{Colors.YELLOW}({time_ms:.0f}ms){Colors.RESET}" if time_ms > 0 else ""
print(f" {status} {name} {time_str}")
if description:
# 截断过长的描述
desc = description[:80] + "..." if len(description) > 80 else description
print(f" {Colors.CYAN}-> {desc}{Colors.RESET}")
async def test_tool(func, *args, **kwargs) -> Tuple[bool, str, float]:
"""
测试单个工具
返回: (是否成功, 描述信息, 耗时ms)
"""
start = time.time()
try:
result = await func(*args, **kwargs)
elapsed = (time.time() - start) * 1000
if result.get("success"):
desc = result.get("data", {}).get("description", "")
return True, desc, elapsed
else:
return False, result.get("error", "未知错误"), elapsed
except Exception as e:
elapsed = (time.time() - start) * 1000
return False, str(e), elapsed
async def run_tests(stock_code: str = "600519"):
"""运行所有量化工具测试"""
print_header(f"量化工具测试 - 股票代码: {stock_code}")
results: List[Tuple[str, bool, str, float]] = []
# ==================== 一、经典技术指标 ====================
print_section("一、经典技术指标 (4个)")
# 1. MACD信号
success, desc, ms = await test_tool(quant.get_macd_signal, stock_code)
print_result("get_macd_signal (MACD信号)", success, desc, ms)
results.append(("get_macd_signal", success, desc, ms))
# 2. RSI/KDJ指标
success, desc, ms = await test_tool(quant.check_oscillator_status, stock_code)
print_result("check_oscillator_status (RSI/KDJ)", success, desc, ms)
results.append(("check_oscillator_status", success, desc, ms))
# 3. 布林带分析
success, desc, ms = await test_tool(quant.analyze_bollinger_bands, stock_code)
print_result("analyze_bollinger_bands (布林带)", success, desc, ms)
results.append(("analyze_bollinger_bands", success, desc, ms))
# 4. ATR止损
success, desc, ms = await test_tool(quant.calc_stop_loss_atr, stock_code)
print_result("calc_stop_loss_atr (ATR止损)", success, desc, ms)
results.append(("calc_stop_loss_atr", success, desc, ms))
# ==================== 二、资金与情绪 ====================
print_section("二、资金与情绪 (3个)")
# 5. 市场热度
success, desc, ms = await test_tool(quant.analyze_market_heat, stock_code)
print_result("analyze_market_heat (市场热度)", success, desc, ms)
results.append(("analyze_market_heat", success, desc, ms))
# 6. 量价背离
success, desc, ms = await test_tool(quant.check_volume_price_divergence, stock_code)
print_result("check_volume_price_divergence (量价背离)", success, desc, ms)
results.append(("check_volume_price_divergence", success, desc, ms))
# 7. OBV能量潮
success, desc, ms = await test_tool(quant.analyze_obv_trend, stock_code)
print_result("analyze_obv_trend (OBV能量潮)", success, desc, ms)
results.append(("analyze_obv_trend", success, desc, ms))
# ==================== 三、形态与突破 ====================
print_section("三、形态与突破 (3个)")
# 8. 新高突破
success, desc, ms = await test_tool(quant.check_new_high_breakout, stock_code)
print_result("check_new_high_breakout (新高突破)", success, desc, ms)
results.append(("check_new_high_breakout", success, desc, ms))
# 9. K线形态
success, desc, ms = await test_tool(quant.identify_candlestick_pattern, stock_code)
print_result("identify_candlestick_pattern (K线形态)", success, desc, ms)
results.append(("identify_candlestick_pattern", success, desc, ms))
# 10. 跳空缺口
success, desc, ms = await test_tool(quant.find_price_gaps, stock_code)
print_result("find_price_gaps (跳空缺口)", success, desc, ms)
results.append(("find_price_gaps", success, desc, ms))
# ==================== 四、风险与估值 ====================
print_section("四、风险与估值 (3个)")
# 11. 最大回撤
success, desc, ms = await test_tool(quant.calc_max_drawdown, stock_code)
print_result("calc_max_drawdown (最大回撤)", success, desc, ms)
results.append(("calc_max_drawdown", success, desc, ms))
# 12. PE估值百分位
success, desc, ms = await test_tool(quant.check_valuation_rank, stock_code)
print_result("check_valuation_rank (PE估值)", success, desc, ms)
results.append(("check_valuation_rank", success, desc, ms))
# 13. Z-Score乖离率
success, desc, ms = await test_tool(quant.calc_price_zscore, stock_code)
print_result("calc_price_zscore (Z-Score)", success, desc, ms)
results.append(("calc_price_zscore", success, desc, ms))
# ==================== 五、分钟级高阶算子 ====================
print_section("五、分钟级高阶算子 (4个)")
print(f" (自动使用最近交易日数据)")
# 14. VPOC筹码峰
success, desc, ms = await test_tool(quant.calc_market_profile_vpoc, stock_code)
print_result("calc_market_profile_vpoc (VPOC)", success, desc, ms)
results.append(("calc_market_profile_vpoc", success, desc, ms))
# 15. 已实现波动率
success, desc, ms = await test_tool(quant.calc_realized_volatility, stock_code)
print_result("calc_realized_volatility (RV波动率)", success, desc, ms)
results.append(("calc_realized_volatility", success, desc, ms))
# 16. 买卖压力
success, desc, ms = await test_tool(quant.analyze_buying_pressure, stock_code)
print_result("analyze_buying_pressure (买卖压力)", success, desc, ms)
results.append(("analyze_buying_pressure", success, desc, ms))
# 17. 帕金森波动率
success, desc, ms = await test_tool(quant.calc_parkinson_volatility, stock_code)
print_result("calc_parkinson_volatility (帕金森波动率)", success, desc, ms)
results.append(("calc_parkinson_volatility", success, desc, ms))
# ==================== 六、高级趋势分析 ====================
print_section("六、高级趋势分析 (4个)")
# 18. 布林带挤压
success, desc, ms = await test_tool(quant.calc_bollinger_squeeze, stock_code)
print_result("calc_bollinger_squeeze (布林带挤压)", success, desc, ms)
results.append(("calc_bollinger_squeeze", success, desc, ms))
# 19. 趋势斜率
success, desc, ms = await test_tool(quant.calc_trend_slope, stock_code)
print_result("calc_trend_slope (趋势斜率)", success, desc, ms)
results.append(("calc_trend_slope", success, desc, ms))
# 20. Hurst指数
success, desc, ms = await test_tool(quant.calc_hurst_exponent, stock_code)
print_result("calc_hurst_exponent (Hurst指数)", success, desc, ms)
results.append(("calc_hurst_exponent", success, desc, ms))
# 21. 趋势分解
success, desc, ms = await test_tool(quant.decompose_trend_simple, stock_code)
print_result("decompose_trend_simple (趋势分解)", success, desc, ms)
results.append(("decompose_trend_simple", success, desc, ms))
# ==================== 七、流动性与统计 ====================
print_section("七、流动性与统计 (3个)")
# 22. Amihud流动性
success, desc, ms = await test_tool(quant.calc_amihud_illiquidity, stock_code)
print_result("calc_amihud_illiquidity (Amihud)", success, desc, ms)
results.append(("calc_amihud_illiquidity", success, desc, ms))
# 23. 价格熵值
success, desc, ms = await test_tool(quant.calc_price_entropy, stock_code)
print_result("calc_price_entropy (价格熵值)", success, desc, ms)
results.append(("calc_price_entropy", success, desc, ms))
# 24. RSI背离
success, desc, ms = await test_tool(quant.calc_rsi_divergence, stock_code)
print_result("calc_rsi_divergence (RSI背离)", success, desc, ms)
results.append(("calc_rsi_divergence", success, desc, ms))
# ==================== 八、配对与策略 ====================
print_section("八、配对与策略 (4个)")
# 25. 协整性测试 (需要两只股票)
success, desc, ms = await test_tool(quant.test_cointegration, stock_code, "000858")
print_result("test_cointegration (协整性测试)", success, desc, ms)
results.append(("test_cointegration", success, desc, ms))
# 26. 凯利仓位 (纯计算,不需要股票代码)
success, desc, ms = await test_tool(quant.calc_kelly_position, 0.55, 2.0)
print_result("calc_kelly_position (凯利仓位)", success, desc, ms)
results.append(("calc_kelly_position", success, desc, ms))
# 27. 相似K线检索
success, desc, ms = await test_tool(quant.search_similar_kline, stock_code)
print_result("search_similar_kline (相似K线)", success, desc, ms)
results.append(("search_similar_kline", success, desc, ms))
# 28. 综合技术分析
success, desc, ms = await test_tool(quant.get_comprehensive_analysis, stock_code)
print_result("get_comprehensive_analysis (综合分析)", success, desc, ms)
results.append(("get_comprehensive_analysis", success, desc, ms))
# ==================== 统计结果 ====================
print_header("测试结果统计")
passed = sum(1 for r in results if r[1])
failed = sum(1 for r in results if not r[1])
total = len(results)
total_time = sum(r[3] for r in results)
print(f" 总计: {total} 个工具")
print(f" {Colors.GREEN}通过: {passed}{Colors.RESET}")
print(f" {Colors.RED}失败: {failed}{Colors.RESET}")
print(f" 成功率: {passed/total*100:.1f}%")
print(f" 总耗时: {total_time/1000:.2f}")
print(f" 平均耗时: {total_time/total:.0f} ms/工具")
# 打印失败的工具
if failed > 0:
print(f"\n{Colors.RED}失败的工具:{Colors.RESET}")
for name, success, desc, ms in results:
if not success:
print(f" - {name}: {desc}")
print()
return passed == total
if __name__ == "__main__":
# 获取股票代码参数
stock_code = sys.argv[1] if len(sys.argv) > 1 else "600519"
# 运行测试
success = asyncio.run(run_tests(stock_code))
# 返回退出码
sys.exit(0 if success else 1)