Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trailing Stop Error - local variable 'cost_basis' referenced before assignment

I am buying stocks on a 500 day high, and using an ATR based trailing stop. The algorithm will run, but it will eventually stop running, and say local variable 'cost_basis' referenced before assignment. I am not sure why it will run for some of the time, but not all the time.Thank you for your help.

3 responses

The problem is when you are trying to sell a stock that can't trade anymore (ie data.can_trade(stock) == False).

The variable 'cost_basis' is defined within the 'sell_signal' method (so it's local to that method) and gets defined within the 'if data.can_trade(stock):' statement. If a stock doesn't pass that if statement (ie it can't trade) then the variable 'cost_basis' won't get defined. You will actually have a problem with all the variables defined in the if statement.

    for stock in context.portfolio.positions :  
            context.exist.append(stock)  
            if data.can_trade(stock):  
                cost_basis=context.portfolio.positions[stock].cost_basis  
                highs = data.history(stock, 'high', 15, '1d')  
                lows = data.history(stock, 'low', 15, '1d')  
                closes = data.history(stock, 'close', 15, '1d')  
                atr = ATR(highs, lows, closes,10)  
                current_price  = data.current(stock, 'price')  
                atr_stop=atr[-1]*2  

I'd remove the if statement BUT add it when you actually try to trade

     for stock in context.portfolio.positions :  
            context.exist.append(stock)  
            cost_basis=context.portfolio.positions[stock].cost_basis  
            highs = data.history(stock, 'high', 15, '1d')  
            lows = data.history(stock, 'low', 15, '1d')  
            closes = data.history(stock, 'close', 15, '1d')  
            atr = ATR(highs, lows, closes,10)  
            current_price  = data.current(stock, 'price')  
            atr_stop=atr[-1]*2

Then add this...

       if data.can_trade(stock) :  
                order_target_percent(stock,0)  
                log.info("Sell: Hit Stop " +str(stock))  

Attached is an updated algo which should work.

Thanks Dan,

Would a stock no longer in data be a delisted stock? How would the algorithm sell a stock if it wasn't in the data because it would not trigger the stop loss?

Eric

Yes, typically a stock 'can't trade' when it's delisted but there are other reasons too. A change of stock class (GOOGL vs GOOG) or a merger or a buyout (eg going private). See https://www.quantopian.com/posts/delisted-securities-now-removed-from-portfolio for how Quantopian handles these. Basically stocks that can't trade are magically liquidated and you see the equivalent cash show up in your account (much the same as it happens in real life with your broker).