Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
confused by fetcher and rename_col

I'm just trying to understand based on the examples here and in the docs how to implement fetcher and I seem to have encountered an error right out of the gate which I can't quite understand.

This is what I've setup from the examples provided...

def rename_col(df):  
    df = df.rename(columns={'Value': 'value'})  
    df = df.fillna(method='ffill')  
    df = df[['value', 'sid']]                            # really not quite sure what this part is for.  
    log.info(' \n %s '% df.head())  
    return df

def initialize(context):  
    fetch_csv('http://www.quandl.com/api/v1/datasets/BUNDESBANK/BBK01_WT5511.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='gold',  
        usecols=['Value'],  
        post_func=rename_col,  
        date_format='%Y-%m-%d'  
        )

def handle_data(context, data):  
    context.trading_days += 1  
    if data['gold']['sid']:  
        log.debug("--> %s"%data['gold'])

running the above returns what I think I would expect...

DEBUG--> SIDData({'returns': <function _transform at 0x6b2e410>, 'vwap': <function _transform at 0x6b2ea28>, 'stddev': <function _transform at 0x6b2e1b8>, 'sid': 'gold', 'source_id': 'PandasRequestsCSV82c479a46aedae750f001c48634ec100', 'dt': Timestamp('2013-01-04 00:00:00+0000', tz='UTC'), 'mavg': <function _transform at 0x6b2e938>, 'type': 9, 'value': 1632.25, 'datetime': Timestamp('2013-01-04 00:00:00+0000', tz='UTC')})  

and when I check, I see that data['gold']['sid'] == gold

however, I get a Key error if I try and access data['gold']['value'] or data['gold'].value

from the examples I've seen here it seems like this should actually work.

3 responses

I found that for me to get results I actually had to embed my code within a try routine...

def handle_data(context, data):  
    try:  
        log.debug("--> %s"%data['gold']['value'])  
    except:  
        pass  

I'm not totally clear on why this is the case.

Hi Pumplerod,

Thanks for posting about the issue you're facing. The error you are seeing is actually induced during our validation of the algorithm. This involves a few checks, including a unit test suite. The idea with validation is to help protect you from coding pitfalls.

In this case, you're merging external data from fetcher with the trade history. In practice it is quite common for the fetcher data to miss a trading day, or to begin on a date long after the start of your simulation. For example, the quandl pricing on gold that this example uses starts in 2012 - if you were to run a 10 year simulation, the gold data would only be available 80% of the way through the simulation.

The validation tests induce a similar "missing data" problem in the course of testing. While the missing data could happen in practice, the test is set up to always induce a missing data condition. As a result, you do need to add code to check for missing data. The attached backtest does that for the gold data (aside: I also cut out some of the extraneous code in the renaming function).

Sorry for the confusion, and please let us know if you have an idea for better testing/avoiding this case.

thanks,
fawce

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.

Thanks for the clarification. I first did try to test if value existed but I did it the wrong way.

I tried this...

if data['gold']['value']:  
    pass  

which does not work because I get a key error straight away. I see now the correct way for doing this. Thank you very much.