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.