import talib
import numpy as np
def initialize(context):
#设置是否是结算模式
context.set_need_settle(False)
#设置最大杠杆
context.set_max_leverage(1,'fill_amap')
# 设置参数
context.window = 20
def handle_data(context, data):
if context.trading_day_index < context.window : # 在形成均线后才开始交易
return
today= data.current_dt.strftime('%Y-%m-%d') # 当前交易日期
instrument = context.future_symbol(context.instruments[0]) # 交易标的
curr_po = context.portfolio.positions[instrument] # 组合持仓
curr_position = curr_po.amount # 持仓数量
price = data.current(instrument, 'price') # 当前价格
# 计算20天内最高价、最低价
high_price = data.history(instrument, 'price', context.window, '1d').max()
low_price = data.history(instrument, 'price', context.window, '1d').min()
#交易逻辑
if price >= high_price and data.can_trade(instrument):
context.order_target(instrument, 20) # 买入开仓
print(today, curr_position, '买入开仓')
elif price <= low_price and data.can_trade(instrument):
context.order_target(instrument, -20) # 卖出开仓
print(today, curr_position, '卖出开仓')
#启动回测
#策略回测接口:https://bigquant.com/docs/module_trade.htmla
m = .trade.v3(
instaruments=['UR2009.SHF']
start_date='2019-09-01'
end_date='2020-08-01'
initialize=initialize
handle_data=handle_data
#买入定单以开盘价成交
order_price_field_buy='open'
#卖出订单以开盘价成交
order_price_field_sell='open'
capital_base=1000000
benchmark='UR2009.SHF'
m_deps=np.random.rand()
)