|
|
#!/usr/bin/env python3
|
|
|
# 期货分析系统演示脚本
|
|
|
|
|
|
import sys
|
|
|
import json
|
|
|
from datetime import datetime
|
|
|
from qihuo_analyzer.data.data_fetcher import DataFetcher
|
|
|
from qihuo_analyzer.data.data_storage import DataStorage
|
|
|
from qihuo_analyzer.modules.trend_filter import TrendFilter
|
|
|
from qihuo_analyzer.modules.risk_manager import RiskManager
|
|
|
from qihuo_analyzer.modules.fund_flow_monitor import FundFlowMonitor
|
|
|
from qihuo_analyzer.modules.support_resistance import SupportResistance
|
|
|
from qihuo_analyzer.modules.rollover_detector import RolloverDetector
|
|
|
from qihuo_analyzer.modules.deepseek_agent import DeepseekAgent
|
|
|
from qihuo_analyzer.core.models import AnalysisResult
|
|
|
|
|
|
|
|
|
def print_header(title):
|
|
|
"""打印标题"""
|
|
|
print(f"\n{'='*60}")
|
|
|
print(f"{title:^60}")
|
|
|
print(f"{'='*60}")
|
|
|
|
|
|
|
|
|
def print_section(title):
|
|
|
"""打印章节标题"""
|
|
|
print(f"\n{'-'*40}")
|
|
|
print(f"{title:^40}")
|
|
|
print(f"{'-'*40}")
|
|
|
|
|
|
|
|
|
def print_json(data, indent=2):
|
|
|
"""打印JSON格式数据"""
|
|
|
print(json.dumps(data, ensure_ascii=False, indent=indent))
|
|
|
|
|
|
|
|
|
def main():
|
|
|
"""主函数"""
|
|
|
print_header("AI 期货分析系统演示")
|
|
|
print(f"当前时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
|
|
|
# 初始化组件
|
|
|
print_section("初始化系统组件")
|
|
|
data_fetcher = DataFetcher()
|
|
|
data_storage = DataStorage()
|
|
|
trend_filter = TrendFilter()
|
|
|
risk_manager = RiskManager()
|
|
|
fund_flow_monitor = FundFlowMonitor()
|
|
|
support_resistance = SupportResistance()
|
|
|
rollover_detector = RolloverDetector()
|
|
|
deepseek_agent = DeepseekAgent()
|
|
|
|
|
|
print("✅ 系统组件初始化完成")
|
|
|
|
|
|
# 选择合约
|
|
|
symbol = "CU2309" # 铜期货合约
|
|
|
print_section(f"分析合约: {symbol}")
|
|
|
|
|
|
# 获取K线数据
|
|
|
print("📊 获取K线数据...")
|
|
|
kline_data = data_fetcher.get_kline_data(symbol, "1d", 200)
|
|
|
if kline_data.empty:
|
|
|
print("❌ 获取K线数据失败")
|
|
|
return
|
|
|
|
|
|
print(f"✅ 获取K线数据成功,共 {len(kline_data)} 条记录")
|
|
|
print(f"最新价格: {kline_data['close'].iloc[-1]:.2f}")
|
|
|
|
|
|
# 保存K线数据到数据库
|
|
|
data_storage.save_kline_data(symbol, "1d", kline_data)
|
|
|
print("✅ K线数据已保存到数据库")
|
|
|
|
|
|
# 1. 趋势分析
|
|
|
print_section("1. 趋势分析")
|
|
|
trend_analysis = trend_filter.analyze_trend(kline_data)
|
|
|
win_rate = trend_filter.calculate_win_rate(kline_data)
|
|
|
cycle = trend_filter.judge_cycle(kline_data)
|
|
|
|
|
|
print("📈 趋势分析结果:")
|
|
|
print(f"ADX: {trend_analysis['adx']:.2f}")
|
|
|
print(f"趋势强度: {trend_analysis['trend_strength']}")
|
|
|
print(f"趋势方向: {trend_analysis['trend_direction']}")
|
|
|
print(f"综合趋势: {trend_analysis['overall_trend']}")
|
|
|
print(f"胜率: {win_rate:.2f}%")
|
|
|
print(f"推荐周期: {cycle}")
|
|
|
|
|
|
# 2. 资金流向分析
|
|
|
print_section("2. 资金流向分析")
|
|
|
fund_flow_analysis = fund_flow_monitor.analyze_fund_flow(kline_data)
|
|
|
|
|
|
print("💹 资金流向分析结果:")
|
|
|
print(f"资金流向强度: {fund_flow_analysis['fund_flow_strength']:.2f}")
|
|
|
print(f"持仓量趋势: {fund_flow_analysis['oi_trend']}")
|
|
|
print(f"量价配合度: {fund_flow_analysis['volume_price_fit']:.2f}%")
|
|
|
print(f"量价背离: {fund_flow_analysis['divergence']}")
|
|
|
print(f"资金面信号: {fund_flow_analysis['fund_signal']}")
|
|
|
|
|
|
# 3. 压力支撑分析
|
|
|
print_section("3. 压力支撑分析")
|
|
|
sr_analysis = support_resistance.analyze_support_resistance(kline_data)
|
|
|
|
|
|
print("🛡️ 压力支撑分析结果:")
|
|
|
support_levels = sr_analysis['support_resistance_levels']['support_levels']
|
|
|
resistance_levels = sr_analysis['support_resistance_levels']['resistance_levels']
|
|
|
print(f"支撑位: {[f'{level:.2f}' for level in support_levels[:3]]}")
|
|
|
print(f"阻力位: {[f'{level:.2f}' for level in resistance_levels[:3]]}")
|
|
|
|
|
|
# 4. 风险分析
|
|
|
print_section("4. 风险分析")
|
|
|
current_price = kline_data['close'].iloc[-1]
|
|
|
atr = trend_analysis.get('atr', 20)
|
|
|
|
|
|
# 计算止损位
|
|
|
stop_loss_long = risk_manager.calculate_stop_loss(kline_data, current_price, "long")
|
|
|
stop_loss_short = risk_manager.calculate_stop_loss(kline_data, current_price, "short")
|
|
|
|
|
|
# 计算仓位大小
|
|
|
account_balance = 1000000 # 100万账户
|
|
|
position_info = risk_manager.calculate_position_size(account_balance, kline_data, "long", current_price)
|
|
|
|
|
|
print("⚡ 风险分析结果:")
|
|
|
print(f"ATR: {atr:.2f}")
|
|
|
print(f"做多止损: {stop_loss_long:.2f}")
|
|
|
print(f"做空止损: {stop_loss_short:.2f}")
|
|
|
print(f"建议仓位: {position_info['suggested_units']} 手")
|
|
|
print(f"风险比例: {position_info['actual_risk_percent']*100:.2f}%")
|
|
|
print(f"杠杆比例: {position_info['leverage']:.2f}")
|
|
|
|
|
|
# 5. 换月分析
|
|
|
print_section("5. 换月分析")
|
|
|
rollover_analysis = rollover_detector.analyze_rollover(symbol, kline_data)
|
|
|
|
|
|
print("📅 换月分析结果:")
|
|
|
print(f"交割日期: {rollover_analysis['expire_date']}")
|
|
|
print(f"距离交割日: {rollover_analysis['days_to_delivery']} 天")
|
|
|
print(f"预警级别: {rollover_analysis['warning_level']}")
|
|
|
print(f"流动性风险: {rollover_analysis['liquidity_risk']}")
|
|
|
print(f"换月建议: {rollover_analysis['rollover_warning']['warning_message']}")
|
|
|
|
|
|
# 6. AI 智能研判
|
|
|
print_section("6. AI 智能研判")
|
|
|
|
|
|
# 准备数据
|
|
|
market_data = {
|
|
|
'symbol': symbol,
|
|
|
'latest_price': current_price,
|
|
|
'volume': kline_data['volume'].iloc[-1],
|
|
|
'open_interest': kline_data['open_interest'].iloc[-1],
|
|
|
'timeframe': '1d'
|
|
|
}
|
|
|
|
|
|
technical_indicators = {
|
|
|
'macd': {'signal': '金叉'},
|
|
|
'rsi': 55,
|
|
|
'bollinger': {'position': '中轨附近'},
|
|
|
'kdj': {'signal': '金叉'},
|
|
|
'atr': atr
|
|
|
}
|
|
|
|
|
|
trend_data = {
|
|
|
'adx': trend_analysis['adx'],
|
|
|
'trend_strength': trend_analysis['trend_strength'],
|
|
|
'trend_direction': trend_analysis['trend_direction'],
|
|
|
'ma_relationship': trend_analysis['ma_relationship'],
|
|
|
'multi_period_analysis': trend_analysis['multi_period_analysis'],
|
|
|
'overall_trend': trend_analysis['overall_trend'],
|
|
|
'win_rate': win_rate
|
|
|
}
|
|
|
|
|
|
risk_metrics = {
|
|
|
'stop_loss': stop_loss_long,
|
|
|
'target_price': resistance_levels[0] if resistance_levels else current_price * 1.05,
|
|
|
'profit_loss_ratio': 1.8,
|
|
|
'position_size': position_info['suggested_units'],
|
|
|
'risk_ratio': position_info['actual_risk_percent'] * 100
|
|
|
}
|
|
|
|
|
|
# AI 分析
|
|
|
ai_analysis = deepseek_agent.analyze_market(market_data, technical_indicators, trend_data, risk_metrics)
|
|
|
|
|
|
print("🤖 AI 分析结果:")
|
|
|
print(f"趋势判断: {ai_analysis.get('trend_judgment', '未知')}")
|
|
|
print(f"胜率评估: {ai_analysis.get('win_rate_assessment', '未知')}")
|
|
|
print(f"风险预警: {ai_analysis.get('risk_warning', '未知')}")
|
|
|
print(f"交易建议: {ai_analysis.get('trade_recommendation', '未知')}")
|
|
|
print(f"分析逻辑: {ai_analysis.get('analysis_logic', '未知')}")
|
|
|
|
|
|
# 7. 生成交易建议
|
|
|
print_section("7. 交易建议")
|
|
|
recommendation = deepseek_agent.generate_trade_recommendation(ai_analysis)
|
|
|
|
|
|
print("📋 交易建议详情:")
|
|
|
print(f"交易方向: {recommendation.get('direction', '未知')}")
|
|
|
print(f"入场价格: {recommendation.get('entry_price', '未知')}")
|
|
|
print(f"止损价格: {recommendation.get('stop_loss', '未知')}")
|
|
|
print(f"目标价格: {recommendation.get('target_price', '未知')}")
|
|
|
print(f"建议仓位: {recommendation.get('position_size', '未知')} 手")
|
|
|
print(f"执行计划: {recommendation.get('execution_plan', '未知')}")
|
|
|
print(f"风险提示: {recommendation.get('risk_tips', '未知')}")
|
|
|
|
|
|
# 8. 保存分析结果
|
|
|
print_section("8. 保存分析结果")
|
|
|
|
|
|
# 创建分析结果对象
|
|
|
analysis_result = AnalysisResult(symbol)
|
|
|
analysis_result.trend = trend_analysis['overall_trend']
|
|
|
analysis_result.probability = win_rate
|
|
|
analysis_result.direction = recommendation.get('direction', 'wait')
|
|
|
analysis_result.cycle = cycle
|
|
|
analysis_result.atr = atr
|
|
|
analysis_result.adx = trend_analysis['adx']
|
|
|
analysis_result.support = support_levels[0] if support_levels else None
|
|
|
analysis_result.resistance = resistance_levels[0] if resistance_levels else None
|
|
|
analysis_result.stop_loss = recommendation.get('stop_loss')
|
|
|
analysis_result.target_price = recommendation.get('target_price')
|
|
|
analysis_result.position_size = recommendation.get('position_size')
|
|
|
analysis_result.risk_ratio = position_info['actual_risk_percent'] * 100
|
|
|
analysis_result.fund_flow = fund_flow_analysis
|
|
|
analysis_result.signals = {
|
|
|
'trend': trend_analysis['overall_trend'],
|
|
|
'fund': fund_flow_analysis['fund_signal'],
|
|
|
'risk': rollover_analysis['liquidity_risk'],
|
|
|
'ai': recommendation.get('direction', 'wait')
|
|
|
}
|
|
|
|
|
|
# 保存到数据库
|
|
|
result_dict = analysis_result.to_dict()
|
|
|
success = data_storage.save_analysis_result(result_dict)
|
|
|
|
|
|
if success:
|
|
|
print("✅ 分析结果已保存到数据库")
|
|
|
else:
|
|
|
print("❌ 保存分析结果失败")
|
|
|
|
|
|
# 9. 生成综合报告
|
|
|
print_section("9. 综合分析报告")
|
|
|
print_header("AI 期货分析系统 - 综合报告")
|
|
|
print(f"合约: {symbol}")
|
|
|
print(f"分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
print(f"最新价格: {current_price:.2f}")
|
|
|
print(f"趋势判断: {trend_analysis['overall_trend']}")
|
|
|
print(f"胜率评估: {win_rate:.2f}%")
|
|
|
print(f"资金信号: {fund_flow_analysis['fund_signal']}")
|
|
|
print(f"交易方向: {recommendation.get('direction', 'wait')}")
|
|
|
print(f"建议仓位: {recommendation.get('position_size', '未知')} 手")
|
|
|
print(f"止损价格: {recommendation.get('stop_loss', '未知')}")
|
|
|
print(f"目标价格: {recommendation.get('target_price', '未知')}")
|
|
|
print(f"风险等级: {rollover_analysis['liquidity_risk']}")
|
|
|
print(f"换月预警: {rollover_analysis['rollover_warning']['overall_warning']}")
|
|
|
|
|
|
print_header("演示完成")
|
|
|
print("感谢使用 AI 期货分析系统!")
|
|
|
print("系统已完成以下功能:")
|
|
|
print("✅ 数据获取与存储")
|
|
|
print("✅ 趋势分析与胜率计算")
|
|
|
print("✅ 资金流向监控")
|
|
|
print("✅ 压力支撑分析")
|
|
|
print("✅ 风险控制与仓位管理")
|
|
|
print("✅ 换月预警")
|
|
|
print("✅ AI 智能研判")
|
|
|
print("✅ 交易建议生成")
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
main()
|