求助,这个策略回测没有数据,请高人给指点一下毛病在哪儿

用户头像hgh**c
2024-12-20 发布

import talib
import pandas as pd
def init(context):

设置基准收益:沪深300指数

set_benchmark('000300.SH')

打印日志

log.info('策略开始运行,初始化函数全局只运行一次')

设置股票每笔交易的手续费为万分之二(手续费在买卖成交后扣除,不包括税费,税费在卖出成交后扣除)

set_commission(PerShare(type='stock',cost=0.0002))

设置股票交易滑点0.5%,表示买入价为实际价格乘1.005,卖出价为实际价格乘0.995

set_slippage(PriceSlippage(0.005))

设置要操作的股票:同花顺

context.security = '600133.SH'

假设你有一个获取历史数据的函数

def handle_bar(context, bar_dict):

获取股票过去20天的收盘价数据

h = history(context.security, ['close','low','high'], 20, '1d', False, 'pre', is_panel=1)
#talib计算的CCI指标
cci=talib.CCI(h['high'].values, h['low'].values, h['close'].values,timeperiod=15)[-1] # 返回最后一个CCI值

交易策略函数

def trading_strategy(stock_code, end_date):

获取历史数据

df = get_historical_data(stock_code, end_date, period=20)

确保数据足够

if len(df) < 20:
print("数据不足,无法执行交易策略")
return
market_value = context.portfolio.stock_account.market_value

获取账户持仓股票列表

stocklist = list(context.portfolio.stock_account.positions)

计算今日的CCI

today_cci = calculate_cci(df.iloc[1]['high'], df.iloc[1]['low'], df.iloc[1]['close'])

计算昨日的CCI

yesterday_cci = calculate_cci(df.iloc[0]['high'], df.iloc[0]['low'], df.iloc[0]['close'])

执行交易策略

if today_cci < -200 and today_cci > yesterday_cci and len(stocklist) ==0:
order_target_percent(context.security, 1)
# 在这里执行买入操作,例如:order_target(context.security, 100)
elif today_cci > 200 and today_cci < yesterday_cci and market_value > 0:
order_target(context.security, 0)
# 在这里执行卖出操作,例如:order_target(context.security, 0)
else:
print("无交易信号")
def after_trading(context):

获取时间

time = get_datetime().strftime('%Y-%m-%d %H:%M:%S')

打印时间

log.info('{} 盘后运行'.format(time))
log.info('一天结束')

评论