Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Managing lots of long and short positions

I need to sell stocks only once they are above a certain price for longs and below a certain price for shorts. I am trying to implement this code in my algorithm to determine when to sell for each stock in my list of open orders.

This code starts at line 172 and ends at line 181

    for position in context.portfolio.positions:  
        print(stock)  
        if(context.portfolio.positions[stock].amount > 0):  
            print("    long " + str(context.portfolio.positions[stock].amount))  
            if(data.current(stock, 'price') > context.longprices[stock]+context.threshold):  
                order_target_percent(stock, 0)  
        if(context.portfolio.positions[stock].amount < 0):  
            print("    short " + str(context.portfolio.positions[stock].amount))  
            if(data.current(stock, 'price') < context.shortprices[stock]-context.threshold):  
                order_target_percent(stock, 0)  

context.longprices and context.shortprices are empty Pandas Series I made to store the price when I bought a stock so I can compare the price of when I bought it to it's current price to determine when I should sell

e.x.) If a long position is 0.2 dollars above the price when I bought it, sell
e.x.) If a short position is 0.2 dollars below the price when I bought it, sell

The issue I am experiencing is that it throws an error:

IndexError: index out of bounds

There was a runtime error on line 180.

I don't understand why this is happening, any help would be great,
Thanks!

2 responses

Two things it could be. Should the first line be

for stock in context.portfolio.positions:  

you have 'position' in place of stock.

Also, just because a stock is in positions doesn't mean it is a valid stock. This happens a lot when stocks are de-listed, merge, or change their name (like google did). You may own it (so it shows up in 'context.portfolio.positions' but it's no longer valid. The backtester, will credit your account with the cash value as of the closing price when it was de-listed (see https://www.quantopian.com/posts/delisted-securities-now-removed-from-portfolio) and the stock will disappear on it's own. It's good practice to use the 'data.can_trade' function before referencing a stock in an order, a 'data' index, or other places like a pipeline dataframe index.

Use the debugger. Set a breakpoint at the first line and single step into the code. Put 'stock' in your watchlist. If that's the culprit you will see an equity show up that has a last trade date before the current date.

Thanks! Sorry I asked kind of a dumb question!