Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
name 'context' is not defined in research notebook

The code works fine in the IDE, but when I move it to the notebook it is saying it can't find 'context'

Anybody know what this could be?

# Import the libraries we will use here.  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import AverageDollarVolume, Returns

#for some reason in research mode this one doesn't work, so use this one below instead  
#from quantopian.algorithm import attach_pipeline, pipeline_output  
from zipline.api import attach_pipeline, pipeline_output  
from quantopian.research import run_pipeline

def initialize(context):  
    """  
    Called once at the start of the program. Any one-time  
    startup logic goes here.  
    """  
    # Define context variables that can be accessed in other methods of  
    # the algorithm.  
    context.long_leverage = 0.5  
    context.short_leverage = -0.5  
    context.returns_lookback = 5

    # Rebalance on the first trading day of each week at 11AM.  
    schedule_function(rebalance,  
                      date_rules.every_day(),  
                      time_rules.market_open(hours=1, minutes=30))

    # Record tracking variables at the end of each day.  
    schedule_function(record_vars,  
                      date_rules.every_day(),  
                      time_rules.market_close(minutes=1))

    # Create and attach our pipeline (dynamic stock selector), defined below.  
    attach_pipeline(make_pipeline(context), 'mean_reversion_example')

def make_pipeline(context):  
    """  
    A function to create our pipeline (dynamic stock selector). The pipeline is used  
    to rank stocks based on different factors, including builtin factors, or custom  
    factors that you can define. Documentation on pipeline can be found here:  
    https://www.quantopian.com/help#pipeline-title  
    """  
    # Create a pipeline object.

    # Create a dollar_volume factor using default inputs and window_length.  
    # This is a builtin factor.  
    dollar_volume = AverageDollarVolume(window_length=1)

    # Define high dollar-volume filter to be the top 2% of stocks by dollar volume.  
    high_dollar_volume = dollar_volume.percentile_between(98, 100)  
    # Create a recent_returns factor with a 5-day returns lookback for all securities  
    # in our high_dollar_volume Filter. This is a custom factor defined below (see  
    # RecentReturns class).  
    recent_returns = Returns(window_length=context.returns_lookback, mask=high_dollar_volume)

    # Define high and low returns filters to be the bottom 1% and top 1% of  
    # securities in the high dollar-volume group.  
    low_returns = recent_returns.percentile_between(0,1)  
    high_returns = recent_returns.percentile_between(99,100)


    # Define a column dictionary that holds all the Factors  
    pipe_columns = {  
            'low_returns':low_returns,  
            'high_returns':high_returns,  
            'recent_returns':recent_returns,  
            'dollar_volume':dollar_volume  
            }

    # Add a filter to the pipeline such that only high-return and low-return  
    # securities are kept.  
    pipe_screen = (low_returns | high_returns)

    # Create a pipeline object with the defined columns and screen.  
    pipe = Pipeline(columns=pipe_columns,screen=pipe_screen)

    return pipe

This is the line that creates the error:

my_pipe = make_pipeline(context)  

The full error:
NameError Traceback (most recent call last)
in ()
----> 1 my_pipe = make_pipeline(context)

NameError: name 'context' is not defined

1 response

Hi Adam, thanks for posting. Would you mind providing a little more information as to what you're trying to do? Algorithm code can't be run directly in Research; you can backtest it using Zipline, or you can run a pipeline alone using the run_pipeline function.

The reason you're getting this error is that make_pipeline is a function that creates a pipeline, given an argument context. For the function to work, you need to pass in an object with a returns_lookback property. If you just want to run the pipeline alone, I would suggest amending make_pipeline to take a returns_lookback argument instead of a context argument, and replacing context.returns_lookback inside the function with returns_lookback.

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.