Below is the function that you can use directly for calculation of Average True Value using python DataFrame.
def wwma(values, n):
"""
J. Welles Wilder's EMA
"""
return values.ewm(alpha=1/n, adjust=False).mean()
def atr(df, n=14):
data = df.copy()
high = data['High']
low = data['Low']
close = data['Close']
data['tr0'] = abs(high - low)
data['tr1'] = abs(high - close.shift())
data['tr2'] = abs(low - close.shift())
tr = data[['tr0', 'tr1', 'tr2']].max(axis=1)
atr = wwma(tr, n)
return round(atr,2)
Explanation to the Code
A function can take input and provide you output. In the above code, the function atr is defined by "def" keyword in python. For more details on functions in python refer to post made on functions in python.
The ATR function as above can take two inputs for calculation. One input is the dataframe denoted by df and another is lookback period denoted by n , which in the instant case is set to 14 by default.
df.copy() function creates copy of the supplied dataframe and save the same in the variable "data".
The data series high and low are saved in variable high and low by assigning them series values from the dataframe. The high column of the dataframe is accessed using data['High'] and the low series of data is accessed using data['Low'].
All the calculations are done on entire series and not on the individual variables. For example for calculating high-low (data['tr0'] = abs(high - low)), calculation is done as under :
Index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
High |
14.5 |
14.7 |
15.0 |
15.5 |
14.3 |
15.1 |
15.6 |
16.2 |
15.4 |
Low |
13.5 |
13.7 |
13.9 |
14.2 |
14.1 |
14.3 |
14.9 |
15.3 |
14.8 |
tr0 |
1.0 |
1.0 |
1.1 |
1.3 |
0.2 |
0.8 |
0.7 |
0.9 |
0.6 |
A single instruction on dataframe calculation calculates on entire series and not on the recent values.
Using the above two functions, ATR can be calculated using dataframe.