Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Why can't a function see a variable that I declared global in a previous function
def initialize(context):  
    global preEMA10

    preEMA10=0  
    global preEMA15

    preEMA15=0  
    global preEMA20

    preEMA20=0  
    global preEMA30

    preEMA30=0  
    global preEMA50

    preEMA50=0  
    global preEMA80

    preEMA80=0  
    global preEMA100

    preEMA100=0  
    global preEMA150

    preEMA150=0  
    global preEMA200

    preEMA200=0  
    global preEMA250

    preEMA250=0  
# Will be called on every trade event for the securities you specify.

def handle_data(context, data):  
    for stock in data:  
        exchange_time=get_datetime()  
        if exchange_time.hour == 4:  
           price = history(bar_count = 2, frequency = '1d', field='price').iloc[0]  
           prices_10 = history(bar_count=10, frequency='1d', field='price')  
           SMA_p10 = prices_10.mean()  
           q10 = 2 / (10 + 1)  
           if preEMA10 == 0:  
              preEMA10 = SMA_p10  
           else:  
                pass  
           EMA_p10 = (price * q10) + (preEMA10 * (1 - q10))  
           preEMA10 = EMA_p10  

the problem I run into is that in the
if loop, I get a warning that preEMA10 has not been declared yet, when I have clearly declared it and globally as well.

6 responses

to specify the if loop:

if preEMA10 == 0:  
   preEMA10 = SMA_p10  
else:  
      pass  

Hi Jason,

Is there a specific reason why you're using global instead of context? In this case, if you use context.preEMA10, it would prevent the error messages from occurring any further. If you wanted to use globals in this case, you'd need to surround your preEMA10 statements with try/except.

Like so:



def initialize(context):  
    context.stock = sid(24)  
    global preEMA10  
    preEMA10 = 10

# Will be called on every trade event for the securities you specify.

def handle_data(context, data):  
    try:  
        print preEMA10  
    except:  
        pass  
    for stock in data:  
        exchange_time=get_datetime()  
        if exchange_time.hour == 4:  
           price = history(bar_count = 2, frequency = '1d', field='price').iloc[0]  
           prices_10 = history(bar_count=10, frequency='1d', field='price')  
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.

Hey Seong,

Thanks! Im pretty sure that fixes everything, but just to clarify.

it would be written as so:

def initialize(context):  
      preEMA10 = 10  
def handle_data(context, data):  
      preEMA10 = context.preEMA10  

The better way would be to have context.preEMA10 in intialize() first

def initialize(context):  
    context.preEMA10 = 10

def handle_data(context, data):  
    preEMA10 = context.preEMA10  

Can I alter that variable in def handle_data(), using context.preEMA10 like so:

def initialize(context):  
      context.preEMA10 = 0  
def handle_data(context, data):  
      context.preEMA10 = 10  
      print context.preEMA10  

would this print 10?

the purpose behind all of this is that I am calculated Exponential Moving Average, and that formula requires the result from its self on the previous day.
this is fine, the problem is the algorithm, on the first day, it would have nothing to compare the current price to. So, in order to lay the foundation that is needed for the algorithm, I want that algorithm to be able to reference the previous days simple moving avg, if it cannot find a EMA from the previous day, which it wont on day 1. so I need to be able to reference that variable that is in replace of the previous days moving avg, in the algorithm, as the SMA of yesterday, after that the algorithm can reference back to the previous EMA and can ignore that SMA for the rest of the backtest.

That's exactly right, it will print 10 because the value gets updated. "context" is used to save states between functions and between bars of the backtest. If you need functions to share variables, or to have variables update between bars, you should create the variable with "context". Here's a more detailed description in the help docs: https://www.quantopian.com/help#ide-api

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.