import numpy as np
from scipy.signal import hilbert
start_date = '2013-01-01'
end_date = '2017-10-23'
benchmark = '000300.INDX' # 基准:HS300
instruments = ['159919.OFA'] # 标的:HS300 ETF
capital_base = 100000
history_data = D.history_data(instruments, '2012-06-01', end_date, fields=['open','close'])
history_data.set_index('date',inplace=True)
history_data['ma_20'] = history_data.close.rolling(20).mean() # 计算MA20
history_data['dsR'] = history_data['ma_20']-history_data['ma_20'].shift(1) # 计算差分
history_data['idsR'] = np.nan
for n in range(120,len(history_data)): # 计算最近100天的Hilbert变换
history_data['idsR'][n] = np.imag(hilbert(history_data['dsR'][n-100:n+1]))[-1]
def initialize(context):
context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0003, min_cost=5))
#print (history_data)
def handle_data(context, data):
instrument = context.symbol(instruments[0])
dataTmp = history_data.ix[data.current_dt.date()]
cur_position = context.portfolio.positions[instrument].amount
if dataTmp['idsR'] > 0 and cur_position == 0: # 虚部大于0,买入
order_target_percent(instrument, 1)
elif dataTmp['idsR'] < 0 and cur_position > 0: # 虚部小于0,卖出
order_target_percent(instrument, 0)
m = M.trade.v2(
instruments=instruments,
start_date=start_date,
end_date=end_date,
initialize=initialize,
handle_data=handle_data,
order_price_field_buy='open',
order_price_field_sell='open',
volume_limit=0,
capital_base=capital_base,
benchmark=benchmark,
)