Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Hull Moving Average/Top Percentage Gainers Algo

Hello everyone,
I'm not very fluent in Python, but I'm also very tired and distracted right now so I'm looking for another set of eyes to help me with identifying the issues with this algo. I'm getting two errors... an "Inputs all NaN" Exception from the HMA declaration after 'wmaDiffs' and I'm also getting the error:
"KeyError: Equity(27479, symbol=u'GNK', asset_name=u'GENCO SHIPPING & TRADING LTD', exchange=u'NEW YORK STOCK EXCHANGE', start_date=Timestamp('2005-07-22 00:00:00+0000', tz='UTC'), end_date=Timestamp('2016-08-01 00:00:00+0000', tz='UTC'), first_traded=None, auto_close_date=Timestamp('2016-08-04 00:00:00+0000', tz='UTC'))" I know that the key error is probably from missing data between the data arrays but I'm not exactly sure how to fix it. If anyone can help, I would greatly appreciate it! Btw, if you're wondering why my Algo checks if the moving average is above or below it's last value instead of using a crossover, it's because the Hull moving average has so little lag, that it would be more effective to use turning points as buy/sell signals.

from quantopian.pipeline import Pipeline, CustomFactor  
from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import SimpleMovingAverage, AverageDollarVolume, Latest  
import talib  
import numpy as np  
import pandas as pd  
import math

HMAPeriods   = 42  
PricePeriods = 17

class PercentChanged(CustomFactor):  
inputs = [USEquityPricing.close]  
window_length = 5

def compute(self, today, assets, out, close):  
    out[:] = (close[-1] - close[0]) / close[0]  

class MAType():  
SMA   = 0; EMA   = 1; WMA   = 2; DEMA  = 3; TEMA  = 4;  
TRIMA = 5; KAMA  = 6; MAMA  = 7; T3    = 8  

def initialize(context):  
context.LOW_RSI =50  
changeInterval = 30  


pennyStocksMask = (USEquityPricing.close.latest) > 1.0  
overPricedMask = (USEquityPricing.close.latest) < 20.0

percentageChange = PercentChanged(window_length = changeInterval, mask = pennyStocksMask and overPricedMask)  
price = Latest(inputs=[USEquityPricing.close],window_length=1)  
pipe_screen = ((price > 1.0) & (price < 20.0))

pipe_columns = {'price':price, 'percentageChange':percentageChange}

pipe = Pipeline(columns=pipe_columns,screen=pipe_screen)  
attach_pipeline(pipe, 'example')  

schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())  


def before_trading_start(context, data):  
output = pipeline_output('example')  
context.my_securities = output.sort('percentageChange', ascending=False).iloc[:50]  
print len(context.my_securities)

context.security_list = context.my_securities.index  

log.info("\n" + str(context.my_securities.head(5)))  

def rebalance(context, data):  

# Load historical data for the stocks  
prices = data.history(context.security_list, 'price', 40, '1d')  

rsis = {}  

# Iterate over the list of stocks  
for stock in context.security_list:  
   closes   = data.history(context.security_list, 'price', 40, '1d')  
   closes   = closes.dropna(axis=1)  
   valid   = [sid for sid in closes if sid in data]  
   closes   = closes[valid]  
   wmaA    = closes.apply(talib.MA,   timeperiod = HMAPeriods / 2, matype = MAType.WMA).dropna() * 2.0  
   wmaB     = closes.apply(talib.MA,   timeperiod = HMAPeriods, matype = MAType.WMA).dropna()  
   wmaDiffs = wmaA - wmaB  
   hma      = wmaDiffs.apply(talib.MA, timeperiod = math.sqrt(HMAPeriods), matype = MAType.WMA)

   rsi = talib.RSI(prices[stock], timeperiod=14)[-1]  
   rsis[stock] = rsi  
   current_position = context.portfolio.positions[stock].amount  

   if hma[stock][-1] < hma[stock][-2] and current_position > 0 and data.can_trade(stock):  
        order_target(stock, 0)  

   elif hma[stock][-1] > hma[stock][-2] and rsi < context.LOW_RSI and current_position == 0 and data.can_trade(stock):  
        order_target_percent(stock, 1)