classDualMovingAverage(TradingAlgorithm):"""Dual Moving Average Crossover algorithm. This algorithm buys apple once its short moving average crosses its long moving average (indicating upwards momentum) and sells its shares once the averages cross again (indicating downwards momentum). """definitialize(self):# Add 2 mavg transforms, one with a long window, one# with a short window.self.add_transform(MovingAverage,'short_mavg',['price'],days=200)self.add_transform(MovingAverage,'long_mavg',['price'],days=400)# To keep track of whether we invested in the stock or notself.invested=Falseself.short_mavg=[]self.long_mavg=[]self.buy_orders=[]self.sell_orders=[]defhandle_data(self,data):if(data['AAPL'].short_mavg['price']>data['AAPL'].long_mavg['price'])andnotself.invested:self.order('AAPL',200)self.invested=Trueself.buy_orders.append(data['AAPL'].datetime)print"{dt}: Buying 100 AAPL shares.".format(dt=data['AAPL'].datetime)elif(data['AAPL'].short_mavg['price']<data['AAPL'].long_mavg['price'])andself.invested:self.order('AAPL',-200)self.invested=Falseself.sell_orders.append(data['AAPL'].datetime)print"{dt}: Selling 100 AAPL shares.".format(dt=data['AAPL'].datetime)# Save mavgs for later analysis.self.short_mavg.append(data['AAPL'].short_mavg['price'])self.long_mavg.append(data['AAPL'].long_mavg['price'])

data['zscores']=np.nandata.zscores[70:]=pairtrade.zscoresax1=plt.subplot(311)data[['PEP','KO']].plot(ax=ax1)plt.ylabel('price')plt.setp(ax1.get_xticklabels(),visible=False)ax2=plt.subplot(312,sharex=ax1)data.zscores.plot(ax=ax2,color='r')plt.plot(pairtrade.buy_orders,data.zscores.ix[pairtrade.buy_orders],'^',c='m',markersize=10,label='buy')plt.plot(pairtrade.sell_orders,data.zscores.ix[pairtrade.sell_orders],'v',c='k',markersize=10,label='sell')plt.ylabel('zscore of spread')plt.setp(ax2.get_xticklabels(),visible=False)plt.legend()ax3=plt.subplot(313,sharex=ax1)stats.portfolio_value.plot()