How to get slope of moving average in pipeline?

I want to screen stocks by slope of moving average, let's say for 200 days moving average, take 50 days data of 200sma and do linear regression:

def make_pipeline():
pipe = Pipeline()
sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200)
slp = Slope(inputs=[sma], window_length=50)
filter_slp = slp > 0
pipe.set_screen(filter_slp
)
return pipe

class Slope(CustomFactor):
inputs = [USEquityPricing.close]
def compute(self, today, assets, out, closes):
out[:] = slope(closes)
def slope(df):
return smx.OLS(df, smx.add_constant(range(-len(df) + 1, 1))).fit().params[-1]


2 responses

You ever get to the bottom of this?

The main issue with the above custom factor is the smx.OLS method only calculates regressions for one asset at a time. One needs to iterate over each asset to then output all the values. Take a look at this post for a little more explanation https://www.quantopian.com/posts/fixing-linear-regression-custom-factor.

However, a second issue will be passing the SimpleMovingAverage as an input to another factor (ie the slope factor). This isn't 'window_safe' which means the values will change depending upon the timeframe (ie 'window') one looks at it. For example, if there is a 2:1 split, the value of the SMA will be halved. Getting the slope of these values will be problematic. Unless there is a big need to find the slope of the averages, I'd go with just finding the slope of the actual prices. That can be done like this. It uses stats.linregress rather than smx.OLS but pretty much the same.

class Slope(CustomFactor):
inputs = [USEquityPricing.close]
window_length = 200

def compute(self, today, assets, out, close_prices):
# Get the log prices
log_close_prices = np.log(close_prices)

# Create 1D array like [1, 2, 3,...] to regress against
# Length is the number of days (ie window_length)
x = np.arange(close_prices.shape)

def annualized_slope(column):
slope, intercept, r_value, p_value, std_err = stats.linregress(x, column)
return_value = (np.power(np.exp(slope), 252)-1) * 100
return return_value

# Iterate over the columns of data (ie the assets)
# Use the numpy apply_along_axis method in place of a for loop
out[:] = np.apply_along_axis(annualized_slope, axis=0, arr=log_close_prices)


Attached is notebook with this custom factor in action.

5