Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
NonWindowSafeInput Error - Custom Factor within another Custom Factor

I got a NonWindowSafeInput error and resolved it by simply setting window_safe=True. But I don't understand why I got the error and how forcing window_safe to true fixes it. Hoping someone may explain further? Please see the code below for reference:

from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import CustomFactor  
import numpy as np

class Momentum(CustomFactor):  
    # Compute momentum  
    def compute(self, today, assets, out, close):  
        out[:] = close[-1] / close[0]

def MeanMom(mwl, wl, mom_input):  
    class MeanMomFact(CustomFactor):  
        mom = Momentum(window_length=wl, inputs=[mom_input])  
        # Fix NonWindowSafeInput error  
        mom.window_safe = True  
        inputs = [mom]  
        window_length = mwl  
        def compute(self, today, asset_ids, out, mom):  
            # Calculates the mean momentum over window length mwl  
            out[:] = np.nanmean(mom, axis=0)  
    return MeanMomFact()

def make_pipeline():  
    MM = MeanMom(mwl=5, wl=5, mom_input=USEquityPricing.close)  
    return Pipeline(columns={'MeanMom': MM})

result = run_pipeline(make_pipeline(), start_date = '2015-01-01', end_date = '2016-01-01')  
result.head(10)  

Thanks ahead.

5 responses
class NonWindowSafeInput(ZiplineError):  
    """  
    Raised when a Pipeline API term that is not deemed window safe is specified  
    as an input to another windowed term.  
    This is an error because it's generally not safe to compose windowed  
    functions on split/dividend adjusted data.  
    """  
    msg = (  
        "Can't compute windowed expression {parent} with "  
        "windowed input {child}."  
    )  

I see the above error explained in github but I'm still confused as to how it works. With reference to my custom factors above, what issues could potentially arise? and why is NotWindowSafeInput not a warning instead of an error?

Hi Jean-Michel,

I recently gave an explanation of window safety here which I think you might find helpful. It comes down to the idea that factors which are not normalized will have their values affected by splits and dividends. If you ask for a history of something like momentum, it's value could change dramatically if you ask for a historical window over a period where a split occurred. If you normalize the momentum factor, it will be unaffected by corporate actions and you can be sure that any changes in value are meaningful.

Let me know if this 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.

This does help, thank you.

You mentioned that returns are normalised, are you referring to the Returns() function? The reason why I'm asking is that I'm currently working on a user-defined returns function as shown below:

def tRet(offset=0, nbars=2, r_input=USEquityPricing.close):  
    class tRetFact(CustomFactor):  
        window_length = nbars + offset  
        inputs = [r_input]  
        def compute(self, today, assets, out, close):  
            df = pd.DataFrame(index=assets, data={  
                    "returns": ((close[-1 - offset] / close[(-1 - offset) - (nbars - 1)]) - 1) * 100  
                                 }  
                             )  
            out[:] = df['returns'].values  
    return tRetFact()  

I would like to use the above function as input into other custom factors. In this case, is it window_safe? If not, please may you suggest how it can be amended/normalized to be window_safe. Thanks

Hi Jean-Michel,

Yes, I was referring to the built-in Returns() factor, but any returns factor should be window safe. Yours looks window safe, but CustomFactors are not window safe by default. Out of curiosity, is there a reason why you aren't using the built-in factor? From what I can tell, it's doing the same thing as your CustomFactor. Note that nbars in your version is the same as window_length in the built-in.

Jamie

Hi Jamie

Its the offset parameter that's slightly different. The offset parameter allows one to choose a date that precedes the current date whilst maintaining the current date index. Here, I recently posted something similar - in this case it would be nice to remove the offset parameter altogether and somehow find a way to play with the "today" parameter in compute. If you could suggest something then that would be great!

I thought the NonWindowSafeInput error came from detecting window safety - are you saying that it justs picks up that window_safe is False by default. Put another way, when you say CustomFactors are not window safe by default does that mean we always have to manually force the window_safe variable to be true?