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]:

Clone Algorithm
3
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 59793634073f914df88faf74
There was a runtime error.
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.

Clone Algorithm
0
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 597b937f6b25bb4f39d51962
There was a runtime error.

Awesome, thanks Dan!

Clone Algorithm
0
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 597b973ce3a3894f3b55fbc3
There was a runtime error.