Back to Community
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[0])

        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.

Loading notebook preview...
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.