修复代码问题
This commit is contained in:
112
backtest.py
112
backtest.py
@@ -7,12 +7,11 @@
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import os
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pandas as pd
|
||||
from datetime import datetime
|
||||
from backtesting import Backtest
|
||||
|
||||
# 数据库配置(直接硬编码,开发环境)
|
||||
DB_HOST = "81.71.3.24"
|
||||
@@ -47,20 +46,19 @@ def load_data_from_db(code, start_date, end_date):
|
||||
try:
|
||||
# 构建 SQL 查询
|
||||
query = f"""
|
||||
SELECT
|
||||
trade_date,
|
||||
open * factor AS "Open",
|
||||
close * factor AS "Close",
|
||||
high * factor AS "High",
|
||||
low * factor AS "Low",
|
||||
volume AS "Volume",
|
||||
COALESCE(factor, 1.0) AS factor
|
||||
FROM leopard_daily daily
|
||||
LEFT JOIN leopard_stock stock ON stock.id = daily.stock_id
|
||||
WHERE stock.code = '{code}'
|
||||
AND daily.trade_date BETWEEN '{start_date} 00:00:00'
|
||||
AND '{end_date} 23:59:59'
|
||||
ORDER BY daily.trade_date
|
||||
SELECT trade_date,
|
||||
open * factor AS "Open",
|
||||
close * factor AS "Close",
|
||||
high * factor AS "High",
|
||||
low * factor AS "Low",
|
||||
volume AS "Volume",
|
||||
COALESCE(factor, 1.0) AS factor
|
||||
FROM leopard_daily daily
|
||||
LEFT JOIN leopard_stock stock ON stock.id = daily.stock_id
|
||||
WHERE stock.code = '{code}'
|
||||
AND daily.trade_date BETWEEN '{start_date} 00:00:00'
|
||||
AND '{end_date} 23:59:59'
|
||||
ORDER BY daily.trade_date
|
||||
"""
|
||||
|
||||
# 执行查询
|
||||
@@ -175,30 +173,6 @@ def parse_arguments():
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def format_value(value, cn_name, key):
|
||||
"""
|
||||
格式化数值显示
|
||||
"""
|
||||
if isinstance(value, (int, float)):
|
||||
if "%" in cn_name or key in [
|
||||
"Sharpe Ratio",
|
||||
"Sortino Ratio",
|
||||
"Calmar Ratio",
|
||||
"Profit Factor",
|
||||
]:
|
||||
formatted_value = f"{value:.2f}"
|
||||
elif "$" in cn_name:
|
||||
formatted_value = f"{value:.2f}"
|
||||
elif "次数" in cn_name:
|
||||
formatted_value = f"{value:.0f}"
|
||||
else:
|
||||
formatted_value = f"{value:.4f}"
|
||||
else:
|
||||
formatted_value = str(value)
|
||||
|
||||
return formatted_value
|
||||
|
||||
|
||||
def print_stats(stats):
|
||||
"""
|
||||
打印回测统计结果
|
||||
@@ -206,33 +180,32 @@ def print_stats(stats):
|
||||
参数:
|
||||
stats: backtesting 库返回的统计对象
|
||||
"""
|
||||
print("\n" + "=" * 60)
|
||||
print("回测结果")
|
||||
print("=" * 60)
|
||||
print("回测结果")
|
||||
|
||||
indicator_name_mapping = {
|
||||
# 'Start': '回测开始时间',
|
||||
# 'End': '回测结束时间',
|
||||
# 'Duration': '回测持续时长',
|
||||
# 'Exposure Time [%]': '持仓时间占比(%)',
|
||||
'Equity Final [$]': '最终收益',
|
||||
'Equity Peak [$]': '峰值收益',
|
||||
'Return [%]': '总收益率(%)',
|
||||
'Buy & Hold Return [%]': '买入并持有收益率(%)',
|
||||
'Return (Ann.) [%]': '年化收益率(%)',
|
||||
'Volatility (Ann.) [%]': '年化波动率(%)',
|
||||
"Equity Final [$]": "最终收益",
|
||||
"Equity Peak [$]": "峰值收益",
|
||||
"Return [%]": "总收益率(%)",
|
||||
"Buy & Hold Return [%]": "买入并持有收益率(%)",
|
||||
"Return (Ann.) [%]": "年化收益率(%)",
|
||||
"Volatility (Ann.) [%]": "年化波动率(%)",
|
||||
# 'CAGR [%]': '复合年均增长率(%)',
|
||||
# 'Sharpe Ratio': '夏普比率',
|
||||
'Sortino Ratio': '索提诺比率',
|
||||
'Calmar Ratio': '卡尔玛比率',
|
||||
"Sortino Ratio": "索提诺比率",
|
||||
"Calmar Ratio": "卡尔玛比率",
|
||||
# 'Alpha [%]': '阿尔法系数(%)',
|
||||
# 'Beta': '贝塔系数',
|
||||
'Max. Drawdown [%]': '最大回撤(%)',
|
||||
'Avg. Drawdown [%]': '平均回撤(%)',
|
||||
'Max. Drawdown Duration': '最大回撤持续时长',
|
||||
'Avg. Drawdown Duration': '平均回撤持续时长',
|
||||
'# Trades': '总交易次数',
|
||||
'Win Rate [%]': '胜率(%)',
|
||||
"Max. Drawdown [%]": "最大回撤(%)",
|
||||
"Avg. Drawdown [%]": "平均回撤(%)",
|
||||
"Max. Drawdown Duration": "最大回撤持续时长",
|
||||
"Avg. Drawdown Duration": "平均回撤持续时长",
|
||||
"# Trades": "总交易次数",
|
||||
"Win Rate [%]": "胜率(%)",
|
||||
# 'Best Trade [%]': '最佳单笔交易收益率(%)',
|
||||
# 'Worst Trade [%]': '最差单笔交易收益率(%)',
|
||||
# 'Avg. Trade [%]': '平均单笔交易收益率(%)',
|
||||
@@ -240,14 +213,19 @@ def print_stats(stats):
|
||||
# 'Avg. Trade Duration': '单笔交易平均持有时长',
|
||||
# 'Profit Factor': '盈利因子',
|
||||
# 'Expectancy [%]': '期望收益(%)',
|
||||
'SQN': '系统质量数',
|
||||
"SQN": "系统质量数",
|
||||
# 'Kelly Criterion': '凯利准则',
|
||||
}
|
||||
for k, v in stats.items():
|
||||
if k in indicator_name_mapping:
|
||||
cn_name = indicator_name_mapping.get(k, k)
|
||||
if isinstance(v, (int, float)):
|
||||
if "%" in cn_name or k in ['Sharpe Ratio', 'Sortino Ratio', 'Calmar Ratio', 'Profit Factor']:
|
||||
if "%" in cn_name or k in [
|
||||
"Sharpe Ratio",
|
||||
"Sortino Ratio",
|
||||
"Calmar Ratio",
|
||||
"Profit Factor",
|
||||
]:
|
||||
formatted_value = f"{v:.2f}"
|
||||
elif "$" in cn_name:
|
||||
formatted_value = f"{v:.2f}"
|
||||
@@ -257,9 +235,9 @@ def print_stats(stats):
|
||||
formatted_value = f"{v:.4f}"
|
||||
else:
|
||||
formatted_value = str(v)
|
||||
print(f'{cn_name}: {formatted_value}')
|
||||
print(f"{cn_name}: {formatted_value}")
|
||||
|
||||
print("=" * 60 + "\n")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def main():
|
||||
@@ -278,20 +256,16 @@ def main():
|
||||
print(f"数据加载完成,共 {len(data)} 条记录")
|
||||
|
||||
# 截取预热数据
|
||||
warmup_data = data.iloc[-args.warmup_days :]
|
||||
warmup_data = data.iloc[-args.warmup_days:]
|
||||
print(f"使用预热数据范围: {warmup_data.index[0]} ~ {warmup_data.index[-1]}")
|
||||
|
||||
# 加载策略
|
||||
print(f"加载策略: {args.strategy_file}")
|
||||
calculate_indicators, strategy_class = load_strategy(args.strategy_file)
|
||||
|
||||
# 计算指标
|
||||
print("计算指标...")
|
||||
warmup_data = calculate_indicators(warmup_data)
|
||||
print("指标计算完成")
|
||||
|
||||
# 执行回测
|
||||
print("开始回测...")
|
||||
from backtesting import Backtest
|
||||
|
||||
bt = Backtest(
|
||||
@@ -308,12 +282,10 @@ def main():
|
||||
|
||||
# 生成图表
|
||||
if args.output:
|
||||
print(f"\n生成图表: {args.output}")
|
||||
os.makedirs(os.path.dirname(args.output), exist_ok=True)
|
||||
bt.plot(filename=args.output, open_browser=False)
|
||||
print(f"图表已保存到: {args.output}")
|
||||
|
||||
print("\n回测完成!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n错误: {e}")
|
||||
import traceback
|
||||
|
||||
Reference in New Issue
Block a user