Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
help with algorithm using z score and moving averages.

how do you get the average price and total volume within a certain window period, of our portfolio consisting of roughly 30 stocks? we want to use that to calculate the z score of the stocks. This is what we have so far, but there seems to be an error with the pipeline

def initialize(context):  
    schedule_function(my_rebalance,  
                      date_rules.every_day,  
                      time_rules.market_open(hours=1))  
    attach_pipeline(make_pipeline(), 'my_pipeline')  
def make_pipeline():  
    universe = QTradableStocksUS()  

    sma_50 = Factors.SimpleMovingAverage(inputs = [USEquityPricing.close],  
                                        window_length = 50,  
                                        mask = universe)  
    sma_200 = Factors.SimpleMovingAverage(inputs = [USEquityPricing.close],  
                                        window_length = 200,  
                                        mask = universe)  
    mktcap = Fundamentals.market_cap.latest  
    universe &= (Fundamentals.morningstar_sector_code.latest != 103)  
    universe &= (Fundamentals.morningstar_sector_code.latest != 104)  
    universe &= (Fundamentals.morningstar_sector_code.latest != 207)  
    universe &= (Fundamentals.ebit.latest > 0)  
    universe &= (Fundamentals.enterprise_value.latest > 0)  
    universe &= (Fundamentals.net_ppe.latest > 0)  

    mktcap = Fundamentals.market_cap.latest  
    evebit = Fundamentals.enterprise_value.latest / Fundamentals.ebit.latest  
    roc = Fundamentals.ebit.latest / (Fundamentals.net_ppe.latest +  
                                      Fundamentals.working_capital.latest)  

    universe &= (evebit > 0)  
    universe &= (roc > 0)  
    evebit_rank = evebit.rank(ascending=True, mask=universe)  
    roc_rank = roc.rank(ascending=False, mask=universe)  
    mf = evebit_rank + roc_rank  
    mf_rank = mf.rank(ascending=True, mask=universe) #best first  
    mf_rank2 = mf.rank(ascending=False, mask=universe) #worst first  
    universe &= (mf_rank <= 100) | (mf_rank2 <= 100) #top 100 for respective rank  
    universe1 = universe  
    universe1 &= (mf_rank <= 100) #universe for top 100  
    universe2 = universe  
    universe2 &= (mf_rank2 <= 100 #universe for bottom 100  
    return Pipeline(  
        columns = {'sma_50': sma_50,  
                  'sma_200': sma_200,  
                  'mktcap': mktcap,  
                  'evebit': evebit,  
                  'evebit_rank': evebit_rank,  
                  'roc': roc,  
                  'roc_rank': roc_rank,  
                  'mf': mf,  
                 'mf_rank': mf_rank,  
                 'mf_rank2': mf_rank2,  
                  },  
        screen=universe,  
    )  
2 responses

To get the average price over a specific time use the SimpleMovingAverage method. Your code seems to be doing this and gets the average close price over 50 days and 200 days. To get the total volume over a specific time one would need to write a small custom factor. Something like this.

class Volume_Over_Window(CustomFactor):  
    """  
    Sums the volume over the window_length.  
    """  
    inputs = [USEquityPricing.volume]  
    # Default window length of 1 which will simply return the latest volume  
    window_length = 1  
    def compute(self, today, assets, out, inputs):  
        out[:] = np.nansum(inputs, axis=0) 

However, what you really probably want is the 'dollar volume' over a given time. More typically, one doesn't use the total dollar volume but rather the 'average dollar volume'. This often works better than the total because values over different time periods can be compared. The 'average dollar volume' is a built in factor AverageDollarVolume. Check out the docs https://www.quantopian.com/docs/api-reference/pipeline-api-reference#quantopian.pipeline.factors.AverageDollarVolume .

The error you were getting is because of a missed parenthesis. Specifically this line of code from above

    universe2 &= (mf_rank2 <= 100 #universe for bottom 100  

It should be

    universe2 &= (mf_rank2 <= 100) #universe for bottom 100  

It's often easier to debug pipelines in the notebook environment where the output dataframe can be viewed. Attached is the pipeline above with some added volume and dollar volume factors. Hope that helps.

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.

thanks dan :)