ATR Issues

Relatively new here, I was looking into utilizing the ATR indicator in an algorithm and but I can't seem to get the implementation to work. My code looks like this:

import pandas
import talib

def initialize(context):
set_symbol_lookup_date('2015-06-01')
# define the portfolio of stocks to watch:
context.stocks = {symbol('AAPL'),
symbol('GOOG'),
symbol('AMZN')}

# called before the start of each trading day
# calculate the average range for the past 25 days
for stock in context.stocks :
# load historical data for the stock
highs = history(25, '1d', 'high')[stock]
lows = history(25, '1d', 'low')[stock]
closes = history(25, '1d', 'close_price')[stock]
# calculate the ATR for the stock
atr = talib.ATR(highs, lows, closes, timeperiod=25)[-1]
# called on every trade event for the securities you specify.
def handle_data(context, data):
return


For some reason I always receive a line 20 error:

Runtime exception: KeyError: Security(24, symbol='AAPL', security_name='APPLE INC', exchange='NASDAQ GLOBAL SELECT MARKET', start_date=Timestamp('1993-01-04 00:00:00+0000', tz='UTC'), end_date=Timestamp('2015-06-09 00:00:00+0000', tz='UTC'), first_traded=None)

If someone could explain what is going wrong here I would greatly appreciate it.

2 responses

Hi,

I switched to scheduling the function call to be 1ce per day after market open. The ATR function in talib needs a longer history passed into it, so here I'm using 50days of history to calculate 25 day ATR. The ATR is recorded per stock per day.

thanks,
fawce

17
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