Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
UnboundLocalError: local variable 'price' referenced before assignment

I am getting the error in my trailing stop. I move the stop up depending on the maximum value for the new stop and the previous stop value. I am getting an error when I test whether the price > context.stop[stock]. It says price is referenced before assignment. I just added the rebalance into it, which rebalances based on the volatility weighting, and the rebalance threshold.

if price < context.stop_price[stock]:

2 responses

I believe you need to indent lines 135-141

            if price < context.stop_price[stock]:  
                order_target(stock, 0)  
                log.info("sell: %s: price, %f, cb %f, stop %f" % (stock.symbol, price, cost_basis, (price-atr_stop)))

You also may want to initialize the variable 'cash_worth' to zero too. Something like this.

    cash_freed = cash_worth = 0.0  

The attached backtest has those changes and doesn't generate the error.

Awesome, thanks Dan!