没有返回历史数据,请检查资产和时间范围,该怎么修改?帮帮孩子吧
由bqh35n1p创建,最终由bqh35n1p 被浏览 3 用户
from bigmodule import M
from bigquant import *
import dai
import pandas as pd
import numpy as np
# 交易引擎:初始化函数,只执行一次
def initialize(context):
from bigtrader.finance.commission import PerOrder
# 设置手续费
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
context.ins = context.instruments
def handle_data(context, data):
from datetime import datetime
dt = data.current_dt.strftime('%Y-%m-%d')
# 获取历史数据(以 DataFrame 形式)
historical_data = data.history(context.ins[0], ['close'], 50, '1m')
# 检查历史数据
if historical_data is None or len(historical_data) == 0:
raise ValueError("没有返回历史数据,请检查资产和时间范围")
# 确保有足够的数据
if len(historical_data) >= 68: # 68日最高价需要的最小数据量
# 计算最近50日最低价
historical_data['lowest_50'] = historical_data['close'].rolling(window=50).min()
# 计算最近68日最高价
historical_data['highest_68'] = historical_data['close'].rolling(window=68).max()
# 计算自定义5日EMA
historical_data['custom_ema'] = ((historical_data['close'] - historical_data['lowest_50']) /
(4 * (historical_data['highest_68'] - historical_data['lowest_50']))).ewm(span=5, adjust=False).mean()
# 处理可能的 NaN 值
historical_data['custom_ema'].fillna(method='bfill', inplace=True)
# 获取当前收盘价和最后计算的QS值
close_price = historical_data['close'].iloc[-1]
qs = historical_data['custom_ema'].iloc[-1]
# 调试输出
print(dt, '当前QS值:', qs)
print(historical_data[['close', 'lowest_50', 'highest_68', 'custom_ema']].tail())
# 获取当前持仓情况
positions = context.get_account_positions()
print(dt, '当前持仓:', positions)
# 根据QS指标进行交易
if qs < 0.3 and context.ins[0] not in positions: # QS指标低于0.3时买入
stock = context.ins[0]
context.order_target_percent(stock, 1.0) # 全仓买入
print(dt, '买入信号,QS:', qs, '持仓百分比为100%')
elif qs > 3.5 and context.ins[0] in positions: # QS指标高于3.5时卖出
if positions[context.ins[0]].avail_qty > 0:
stock = context.ins[0]
context.order_target_percent(stock, 0) # 卖出所有持仓
print(dt, '卖出信号,QS:', qs, '持仓百分比为0%')
else:
print(dt, '数据不足,无法计算指标。')
# 回测配置
data = {
"start_date": '2024-01-01',
'end_date': '2024-5-08',
'market': 'cn_stock',
'instruments': ['600839.SH'] # 请替换为您的股票代码
}
m3 = M.bigtrader.v30(
data=data,
initialize=initialize,
handle_data=handle_data,
capital_base=500000,
frequency="""1m""",
product_type="""股票""",
rebalance_period_type="""交易日""",
rebalance_period_days="""1""",
rebalance_period_roll_forward=True,
backtest_engine_mode="""标准模式""",
before_start_days=0,
volume_limit=1,
order_price_field_buy="""open""",
order_price_field_sell="""open""",
benchmark="""沪深300指数""",
plot_charts=True
)
ValueError: 没有返回历史数据,请检查资产和时间范围
\