Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
slope of sma delta, custom factor?

I am trying to take the difference between the 50 day SMA and the 200 day SMA, and then find the trend line and the slope of that line. This line of code- sma_delta = sma_50 - sma_200 -returns a single float value, not an array. How do I get an array of values for the slope of the trend line on any given day? Do I have to use a "custom factor" to accomplish this? Please see code below, thanks ahead of time for your help!

import talib

def initialize(context):  
    context.spy = sid(8554)  
    schedule_function(signal, date_rules.every_day(), time_rules.market_close())

def signal(context, data):  
    hist_price = data.history(context.spy, 'price', 200, '1d')  
    hist_volume = data.history(context.spy, 'volume', 200, '1d')  
    #----------  
    #SMA  
    sma_200 = hist_price.mean()  
    sma_50 = hist_price[-50].mean()  
    #log.info(sma_200)  
    #log.info(sma_50)  
    #record(SMA_200 = sma_200, SMA_50 = sma_50)  
    sma_delta = sma_50 - sma_200  
    smadelta_slope_wks_3 = talib.LINEARREG_SLOPE(sma_delta, timeperiod=14)[-1]  
1 response

Try this way:

# delta_slop indicator  
import talib  
# ---------------------------------------------------  
stock, fast, slow, slope = symbol('SPY'), 50, 200, 14  
# ---------------------------------------------------  
def initialize(context):  
    schedule_function(signal, date_rules.every_day(), time_rules.market_close())

def signal(context, data):  
    prices = data.history(stock, 'price', slow + slope, '1d')  
    mavg_s = talib.MA(prices, slow)  
    mavg_f = talib.MA(prices, fast)  
    delta = mavg_f[-slope:] - mavg_s[-slope:]  
    delta_slope = talib.LINEARREG_SLOPE(delta, slope)[-1]  

    record(delta_slope = delta_slope, zero = 0)