Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
MACD-Mean-Reversion Strategy encountering KeyErrors with specific securities

Hi, this is my first algorithm on Quantopian, so I wanted to learn as much as possible from working with the fundamental data API as well as the quantitative indicators provided by talib. Thus, I coded a simple MACD algorithm that opens a long position when MACD is positive and a short position when MACD is negative and the current share price is above the 5-day moving average. Unfortunately, during testing I ran into a number of KeyErrors regarding specific securities (which I have stored in the list 'error_stocks') that I was unable to workaround (despite attempts at debugging). What causes these KeyErrors? I initially assumed that perhaps it had to do with how order_target_percent was implemented, but after playing around with the function I realized that was probably not the case.

3 responses

@Muthu C. You can either use:

for stock in data:  

or include a test to ensure that the stock under test is actually in the data collection at the time of order submission:

for stock in context.fundamental_df:  
    if stock not in data:  
        continue  

Also, ensure you clean up your history data...

prices = history(50, '1d', 'price').dropna()  

Thank you for the help!

I recently modified the original algorithm to exit positions no longer in the list of securities to invest in, so here are the new results: