def onBars(self, bars): bar = bars[self.__instrument] close = bar.getClose() closeDs = self.getFeed().getDataSeries(self.__instrument).getCloseDataSeries() qty = 1 mom_long = talib.MOM(closeDs, count=self.__long_period+1, timeperiod=self.__long_period) mom_short = talib.MOM(closeDs, count=self.__short_period+1, timeperiod=self.__short_period) # Wait for enough bars to be available to calculate indicators. if (len(mom_long) < 1) or math.isnan(mom_long[-1]): return buy_condition = (mom_long[-1] > 0) and (mom_short[-1] > 0) sell_condition = (mom_long[-1] < 0) or (mom_short[-1] < 0) # If a position was not opened, check if we should enter a long position. if self.__position is None: if buy_condition: # Enter a buy market order for 10 shares. The order is good till canceled. self.__position = self.enterLong(self.__instrument, qty) # Else, Check for Stop-loss or Exit. elif not self.__position.exitActive(): if sell_condition: self.__position.exitMarket()
def testMOM(self): barDs = self.__loadBarDS() self.assertAmountsAreEqual( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[14], -0.50) self.assertAmountsAreEqual( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[15], -2.00) self.assertAmountsAreEqual( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[16], -5.22) self.assertAmountsAreEqual( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[-1], -1.13)
def testMOM(self): barDs = self.__loadBarDS() self.assertTrue( compare( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[14], -0.50)) self.assertTrue( compare( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[15], -2.00)) self.assertTrue( compare( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[16], -5.22)) self.assertTrue( compare( indicator.MOM(barDs.getCloseDataSeries(), 252, 14)[-1], -1.13))