276 lines
10 KiB
Python
276 lines
10 KiB
Python
"""
|
||
真实数据库回测脚本
|
||
|
||
使用真实数据库数据对601398.SH(工商银行)进行回测
|
||
回测期间:2024年1月1日 - 2024年12月31日
|
||
"""
|
||
|
||
import sys
|
||
import os
|
||
import logging
|
||
from datetime import datetime
|
||
|
||
# 添加项目路径
|
||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||
src_dir = os.path.dirname(current_dir)
|
||
sys.path.insert(0, src_dir)
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format='%(asctime)s - %(levelname)s - %(message)s',
|
||
handlers=[
|
||
logging.StreamHandler(),
|
||
logging.FileHandler('real_backtest.log', encoding='utf-8')
|
||
]
|
||
)
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
def progress_callback(current, total, message):
|
||
"""进度回调函数"""
|
||
progress = (current / total) * 100
|
||
print(f"\r进度: {progress:.1f}% - {message}", end="", flush=True)
|
||
if current == total:
|
||
print()
|
||
|
||
|
||
def run_real_backtest():
|
||
"""运行真实数据库回测"""
|
||
try:
|
||
print("🚀 启动真实数据库回测")
|
||
print("="*60)
|
||
print("📊 测试股票: 601398.SH (工商银行)")
|
||
print("📅 回测期间: 2024-01-01 ~ 2024-12-31")
|
||
print("="*60)
|
||
|
||
# 1. 检查数据库连接
|
||
print("\n1️⃣ 检查数据库连接...")
|
||
try:
|
||
from data_process_model.database_config import init_database, close_database
|
||
if not init_database():
|
||
print("❌ 数据库连接失败,请检查配置")
|
||
return False
|
||
print("✅ 数据库连接成功")
|
||
except Exception as e:
|
||
print(f"❌ 数据库模块导入失败: {e}")
|
||
return False
|
||
|
||
# 2. 导入回测引擎
|
||
print("\n2️⃣ 导入回测引擎...")
|
||
try:
|
||
# 添加当前目录到Python路径
|
||
current_back_trader_dir = os.path.dirname(os.path.abspath(__file__))
|
||
sys.path.insert(0, current_back_trader_dir)
|
||
|
||
from backtest_engine import BacktestEngine
|
||
from ma_cross_strategy import MACrossStrategy
|
||
print("✅ 回测引擎导入成功")
|
||
except Exception as e:
|
||
print(f"❌ 回测引擎导入失败: {e}")
|
||
return False
|
||
|
||
# 3. 创建回测引擎
|
||
print("\n3️⃣ 创建回测引擎...")
|
||
engine = BacktestEngine(initial_capital=1000000.0)
|
||
print(f"✅ 回测引擎创建成功,初始资金: {engine.initial_capital:,.2f} 元")
|
||
|
||
# 4. 设置回测参数
|
||
print("\n4️⃣ 设置回测参数...")
|
||
stock_codes = ["601398.SH"] # 工商银行
|
||
engine.set_universe(stock_codes)
|
||
engine.set_period("2024-01-01", "2024-12-31", "1m")
|
||
print(f"✅ 股票池: {stock_codes}")
|
||
print("✅ 回测期间: 2024-01-01 ~ 2024-12-31")
|
||
print("✅ 数据周期: 分钟线(1m)")
|
||
|
||
# 5. 创建均线交叉策略
|
||
print("\n5️⃣ 创建交易策略...")
|
||
strategy_params = {
|
||
'short_period': 20, # 20分钟均线(相当于日线的短期)
|
||
'long_period': 60, # 60分钟均线(相当于日线的长期)
|
||
'stop_loss': 0.02, # 2%止损(分钟级别风险控制更严)
|
||
'take_profit': 0.05, # 5%止盈(分钟级别目标更小)
|
||
'position_size': 0.3, # 30%仓位(分钟级别更保守)
|
||
'min_volume': 1000000 # 最小成交量过滤
|
||
}
|
||
strategy = MACrossStrategy(strategy_params)
|
||
engine.set_strategy(strategy)
|
||
|
||
print("✅ 策略配置:")
|
||
print(f" - 短期均线: {strategy_params['short_period']}分钟")
|
||
print(f" - 长期均线: {strategy_params['long_period']}分钟")
|
||
print(f" - 止损比例: {strategy_params['stop_loss']*100:.1f}%")
|
||
print(f" - 止盈比例: {strategy_params['take_profit']*100:.1f}%")
|
||
print(f" - 仓位比例: {strategy_params['position_size']*100:.1f}%")
|
||
|
||
# 6. 加载历史数据
|
||
print("\n6️⃣ 从数据库加载历史数据...")
|
||
if not engine.load_data_from_database():
|
||
print("❌ 历史数据加载失败")
|
||
print(" 请确认:")
|
||
print(" - 数据库中存在对应的股票数据表")
|
||
print(" - 数据时间范围覆盖回测期间")
|
||
print(" - 股票代码格式正确(601398.SH)")
|
||
return False
|
||
|
||
print("✅ 历史数据加载成功")
|
||
|
||
# 7. 执行回测
|
||
print("\n7️⃣ 开始执行回测...")
|
||
print(" (这可能需要几分钟时间,请耐心等待)")
|
||
|
||
start_time = datetime.now()
|
||
success = engine.run_backtest(progress_callback)
|
||
end_time = datetime.now()
|
||
|
||
duration = (end_time - start_time).total_seconds()
|
||
|
||
if success:
|
||
print(f"\n✅ 回测执行成功 (耗时: {duration:.1f}秒)")
|
||
|
||
# 8. 显示回测结果
|
||
print("\n8️⃣ 回测结果分析:")
|
||
print("="*60)
|
||
engine.print_summary()
|
||
|
||
# 9. 保存详细结果
|
||
print("\n9️⃣ 保存回测结果...")
|
||
result_file = f"backtest_601398_SH_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
||
if engine.save_results(result_file):
|
||
print(f"✅ 详细结果已保存到: {result_file}")
|
||
|
||
# 10. 显示投资组合最终状态
|
||
print("\n🔟 投资组合最终状态:")
|
||
print(f" 现金余额: {engine.portfolio.cash:,.2f} 元")
|
||
print(f" 总资产: {engine.portfolio.total_value:,.2f} 元")
|
||
print(f" 持仓情况:")
|
||
|
||
if engine.portfolio.positions:
|
||
for stock_code, position in engine.portfolio.positions.items():
|
||
print(f" {stock_code}: {position.shares}股, 市值: {position.market_value:,.2f}元")
|
||
else:
|
||
print(" 无持仓")
|
||
|
||
# 交易记录统计
|
||
trades = engine.portfolio.trades
|
||
if trades:
|
||
buy_trades = [t for t in trades if t.action == 'BUY']
|
||
sell_trades = [t for t in trades if t.action == 'SELL']
|
||
print(f"\n📈 交易记录统计:")
|
||
print(f" 总交易次数: {len(trades)}笔")
|
||
print(f" 买入交易: {len(buy_trades)}笔")
|
||
print(f" 卖出交易: {len(sell_trades)}笔")
|
||
|
||
if trades:
|
||
total_commission = sum(t.commission for t in trades)
|
||
print(f" 总手续费: {total_commission:,.2f}元")
|
||
|
||
return True
|
||
|
||
else:
|
||
print(f"\n❌ 回测执行失败 (耗时: {duration:.1f}秒)")
|
||
return False
|
||
|
||
except Exception as e:
|
||
print(f"\n❌ 回测过程出错: {e}")
|
||
logger.error(f"回测异常: {e}", exc_info=True)
|
||
import traceback
|
||
traceback.print_exc()
|
||
return False
|
||
finally:
|
||
# 确保关闭数据库连接
|
||
try:
|
||
close_database()
|
||
print("\n🔚 数据库连接已关闭")
|
||
except:
|
||
pass
|
||
|
||
|
||
def check_data_availability():
|
||
"""检查数据可用性"""
|
||
try:
|
||
print("🔍 检查数据可用性...")
|
||
|
||
from data_process_model.database_config import init_database, close_database
|
||
from data_process_model.stock_models import create_stock_kline_model
|
||
|
||
if not init_database():
|
||
print("❌ 无法连接数据库")
|
||
return False
|
||
|
||
# 检查是否存在601398.SH的分钟数据
|
||
try:
|
||
model_class = create_stock_kline_model("601398.SH", "1m")
|
||
|
||
# 检查表是否存在数据
|
||
count = model_class.select().count()
|
||
print(f"✅ 找到 601398.SH 分钟数据: {count} 条记录")
|
||
|
||
if count == 0:
|
||
print("⚠️ 数据表为空,请先运行数据下载脚本")
|
||
return False
|
||
|
||
# 对分钟数据,检查是否有足够的数据进行回测
|
||
if count < 10000: # 至少需要1万条分钟数据
|
||
print("⚠️ 分钟数据不足,请检查数据")
|
||
return False
|
||
|
||
# 检查时间范围
|
||
first_record = model_class.select().order_by(model_class.timestamp).first()
|
||
last_record = model_class.select().order_by(model_class.timestamp.desc()).first()
|
||
|
||
if first_record and last_record:
|
||
print(f"📅 数据时间范围: {first_record.timestamp} ~ {last_record.timestamp}")
|
||
|
||
# 检查是否覆盖回测期间
|
||
from datetime import datetime
|
||
backtest_start = datetime(2024, 1, 1)
|
||
backtest_end = datetime(2024, 12, 31)
|
||
|
||
if first_record.timestamp <= backtest_start and last_record.timestamp >= backtest_end:
|
||
print("✅ 数据时间范围覆盖回测期间")
|
||
return True
|
||
else:
|
||
print("⚠️ 数据时间范围不完全覆盖回测期间")
|
||
print(" 但分钟数据量充足,继续进行回测")
|
||
return True # 对于分钟数据,即使不完全覆盖也可以回测
|
||
|
||
except Exception as e:
|
||
print(f"❌ 检查数据时出错: {e}")
|
||
return False
|
||
finally:
|
||
close_database()
|
||
|
||
except Exception as e:
|
||
print(f"❌ 数据检查失败: {e}")
|
||
return False
|
||
|
||
|
||
def main():
|
||
"""主函数"""
|
||
print("🏦 工商银行(601398.SH)真实数据回测")
|
||
print("="*60)
|
||
|
||
# 首先检查数据可用性
|
||
if not check_data_availability():
|
||
print("\n💡 建议操作:")
|
||
print("1. 确认已运行数据下载脚本 (data_process_model/main.py)")
|
||
print("2. 确认数据库中存在 601398.SH 的历史数据")
|
||
print("3. 确认数据时间范围覆盖 2024年")
|
||
return
|
||
|
||
# 执行回测
|
||
success = run_real_backtest()
|
||
|
||
if success:
|
||
print("\n🎉 回测完成!")
|
||
print(" 可以查看生成的 JSON 文件获取详细结果")
|
||
else:
|
||
print("\n😞 回测失败,请检查错误信息")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|