Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Accessing context in a custom factor

I've read that the proper way of defining global variables is to define them in context . Is there a way to pass the context class to a custom factor? The obvious trick of passing context as an argument of the compute function yields Key error: 'window_safe' .

Also, I have seen algorithms defining variables (typically parameters) outside the scope of any function. This may solve my problem. Is that discouraged, and why?

4 responses

It turns out there is an easy and in retrospect obvious solution. Just create the variables you need in the CustomFactor class, refer to them as self.xxx in the compute function, and set them to the desired values after you create the factor when building the pipeline using factor.xxx = context.yyy.

have you been able to fix the window_safe error?

I don't remember getting a window_safe error in this case. But anyway, you can fix it by adding window_safe = True in the custom factor. You have to make sure that your factor is invariant under stock splits. But anyway if it's not, it probably means that you cannot compare it across different equities and that it should be properly normalized .

Thanks for that note! I never took stock splits into consideration. The reason why I asked is because I am getting another error when I was passing context as an input in a custom factor class.