Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with simple error?

Hi all,

I new to quantopian and I have made a very simple algorithm that rebalances daily to the 5 securities with the lowest PE given a set of filters. I ran a backtest and I got this error. Can anyone help me understand what is going on?

Thanks.

KeyError: Security(47915, symbol='SRSC_V', security_name='SEARS CANADA INC', exchange='NASDAQ GLOBAL SELECT MARKET', start_date=Timestamp('2014-10-16 00:00:00+0000', tz='UTC'), end_date=Timestamp('2014-11-14 00:00:00+0000', tz='UTC'), first_traded=None)

6 responses

The end_date in the error indicates that Sears Canada stopped trading in November 2014, before the end of your backtest. See this post for more on that problem.

By the way, in your code context.stocks is not a list of stocks as you probably intended. Instead, it's a list that contains only the fundamental_df. This list has length 1. This means that your create_weights function is setting the weight to 1 (100%) for each stock, so with 5 stocks you're using a lot of leverage.

I think I understand what you are saying. How can I change context.stocks to equal my list of 5 stocks?

I've also added some code so that any stock with an end date of less than 30 days from the active date will be removed from the portfolio.

Sorry if these questions are elementary. This is my first algorithm and I am not a computer programmer.

Your stocks are: context.fundamental_df.columns.values. To get the number of stocks, you can use either len(context.fundamental_df.columns) or len(context.fundamental_df.columns.values). Your revision was using len(context.fundamental_df), which is the number of fundamental fields (5), which just happened to be the same as the number of stocks.

Please see the attached backtest for examples. I also added if stock in data: tests and a weight multiplier to match your comment.

Thanks Michael, your help is immensely appreciated!

This is fantastic and I set it to live trading to see how it would perform. The backtest runs perfectly with no errors, but in live trading the algorithm isn't trading any securities. Do you know what is going on? Thanks in advance.

fundamentals are not live in live trading yet.... I cant wait either to do some live algo's with fundamental but for now..... we have to wait