Back to Community
fethcher, post_func & Accessing Calculations In handle_data

Hello All,

I've been playing with calculating Bollinger Bands but I don't know how to access my calculations in handle_data

import pandas

def process_df(df):  
    df = df.rename(columns={'Close': 'price'})  
    df = df.fillna(method='ffill')  
    #df = df[['price', 'sid']]' \n %s ' , df.head())  
    df['MA20']=pandas.stats.moments.rolling_mean(df['price'], 20)  
    df['STDDEV']=pandas.stats.moments.rolling_std(df['ABS'], 20)  
    return df  

def initialize(context):  
        post_func = process_df,  
    context.stock = sid(28016)

def handle_data(context, data):  
    #print data['CMG'].datetime  
    if str(data['CMG'].datetime) == "2011-03-31 00:00:00+00:00":  
        print data['CMG']  
    # This is what I would like to do!  
    # current_UPPER = data['CMG']['UPPER']  
    # record(LowerBB=data['CMG'].LOWER)  

I can see that my data is available in data_handler but I'm stuck. Is this completely the wrong approach i.e. should I be using a batch transform?

Also, I don't understand the relationship between 'my' dataframe and the Quantopian dataframe of CMG's prices i.e.


has my extra fields



does not. My data came from the Yahoo a few months ago.



4 responses

Update: this line works but I don't understand why:

if str(data['CMG'].datetime) == "2011-03-31 00:00:00+00:00":  
        print data['CMG']['UPPER']  

But this on its own fails:

print data['CMG']['UPPER']  

with the error:

31  Error   Runtime exception: KeyError: 'UPPER'  



Hi Peter,

I think that what is happening is that your CSV does not have data available for all the days of the backtest. Thus, referring to "data['CMG']['UPPER']" for an event in which Quantopian has data and your CSV dataframe does not will generate a KeyError, as "UPPER" was not generated for that date.

You can check for the existence of a key in a Python array using "in":

if 'UPPER' in data['CMG']:['CMG']['UPPER'])


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.

Hello John,

I'm sure you're in the right area but I've moved to a batch_transform now which I still don't fully understand. This code works but could be improved:

import pandas

def initialize(context):  
    context.stocks = [sid(28016)]

def get_bbands(datapanel):  
    prices['MA20'] = pandas.stats.moments.rolling_mean(prices, 20)  
    prices['ABS'] = prices[28016] - prices['MA20']  
    prices['ABS'] = prices['ABS'].abs()  
    prices['STDDEV']=pandas.stats.moments.rolling_std(prices['ABS'], 20)  
    return prices

def handle_data(context, data):  
    result = get_bbands(data)  
    if result is None:  
    MA20 = result['MA20'][38]  
    STDDEV = result['STDDEV'][38]  
    record(CMG=data[sid(28016)].price, Upper=MA20 + 2.0 * STDDEV, Lower=MA20 - 2.0 * STDDEV, MA20=MA20)  

With the first price available on Day 0 the first MA20 is available on Day 19 and the first Standard Deviation on Day 38 hence window_length = 39.



Hello Peter,

What don't you understand about the batch transform? Perhaps I have some examples.