#读取基金数据
instruments=['510330.HOF']
df = DataSource('bar1d_CN_FUND').read(instruments)
history_ds = DataSource.write_df(df)
#设置开始日期,结束日期
start_date = '2018-01-04'
end_date = '2018-10-01'
# 策略比较参考标准,以沪深300为例
benchmark = '000300.SHA'
capital_base = 1000000
# 2. 策略主体函数
# 初始化虚拟账户状态,只在第一个交易日运行
def initialize(context):
#记录策略运行天数
context.index = 0
#短均线参数
context.short_period = 5
#长均线参数
context.long_period = 10
# 策略交易逻辑,每个交易日运行一次
def handle_data(context, data):
today = data.current_dt.strftime('%Y-%m-%d')
#更新策略运行天数
context.index += 1
if context.index <= context.long_period:
return
for instr in instruments:
# 将标的转化为equity格式
sid = context.symbol(instr)
# 短周期均线值
short_mavg = data.history(sid, 'price', context.short_period, '1d').mean()
# 长周期均线值
long_mavg = data.history(sid, 'price', context.long_period, '1d').mean()
# 账户持仓
cur_pos = context.portfolio.positions[sid].amount
# 策略逻辑部分
# 空仓状态下,短周期均线上穿(大于)长周期均线形成金叉,买入股票,且该股票可以交易
# 持仓状态下,短周期均线下穿(小于)长周期均线形成死叉,卖出股票,且该股票可以交易
if short_mavg > long_mavg and cur_pos == 0:
context.order_target_percent(sid, 1)
elif short_mavg < long_mavg and cur_pos > 0:
context.order_target_percent(sid, 0)
# 3. 启动回测
# 策略回测接口: https://bigquant.com/docs/module_trade.html
m = M.trade.v4(
instruments=['510330.HOF'],
start_date=start_date,
end_date=end_date,
initialize=initialize,
history_ds = history_ds,
before_trading_start=None,
handle_data=handle_data,
# 买入订单以开盘价成交
order_price_field_buy='open',
m_deps=np.random.randn(),
order_price_field_sell='open',
capital_base=capital_base,
benchmark=benchmark,
volume_limit=0.25,
product_type='stock',
)