# The Power of the Average True Range Indicator in Trading.

## Coding the ATR in Python and how to use Volatility to your Advantage while Trading.

Volatility is a key concept in finance. Whoever masters it holds a tremendous edge in the markets. Unfortunately, we cannot always measure and predict it with accuracy. Even though the concept is more important in options trading, we need it pretty much everywhere else. Traders cannot trade without volatility nor manage their positions and risk. Quants and risk managers require volatility to be able to do their work. In this article, we will present the basics of volatility, understand the Average True Range and code it, and finally, see how we can use it in trading.

The different types of volatility around us can be summed up in the following:

**Historical volatility**: It is the realized volatility over a certain period of time. Even though it is backward looking, historical volatility is used more often than not as an expectation of future volatility. One example of a historical measure is the standard deviation, which we will see later. Another example is the Average True Range, the protagonist of this article.**Implied volatility**: In its simplest definition, implied volatility is the measure that when inputed into the Black-Scholes equation, gives out the option’s market price. It is considered as the expected future actual volatility by market participants. It has one time scale, the option’s expiration.**Forward volatility**: It is the volatility over a specific period in the future.**Actual volatility**: It is the amount of volatility at any given time. Also known as local volatility, this measure is hard to calculate and has no time scale.

The most basic type of volatility is our old friend “the Standard Deviation”. It is one of the pillars of descriptive statistics and an important element in some technical indicators (such as the Bollinger Bands). But first let’s define what Variance is before we find Standard Deviation:

Variance is the squared deviations from the mean (a dispersion measure), **we take the square deviations so as to force the distance from the mean to be non-negative**, finally we take the square root to make the measure have the same units as the mean, in a way we are comparing apples to apples (mean to standard deviation standard deviation). Variance is calculated through this formula:

Following our logic, standard deviation is therefore:

In technical analysis, an indicator called the **Average True Range -ATR- **can be used as a gauge for historical trailing volatility. Although it is considered as a lagging indicator, it gives some insights as to where volatility is now and where has it been last period (day, week, month, etc.). But first, we should understand how the **True Range** is calculated (the ATR is just the average of that calculation).

The true range is simply the greatest of the three price differences:

**High — Low****High — Previous close****Previous close — Low**

Once we have got the maximum out of the above three, we simply take an average of n periods of the true ranges to get the Average True Range. Generally, since in periods of panic and price depreciation we see volatility go up, the ATR will most likely trend higher during these periods, similarly in times of steady uptrends or downtrends, the ATR will tend to go lower. One should always remember that this indicator is very lagging and therefore has to be used with extreme caution. Below is the function code that calculates a form of the ATR.

`def atr(Data, atr_lookback, high, low, close, whereTR, whereATR):`

# TR

for i in range(len(Data)):

Data[i, whereTR] = max(Data[i, high] - Data[i, low],

abs(Data[i, high] - Data[i - 1, close]),

abs(Data[i, low] - Data[i - 1, close]))

Data[0, whereATR] = Data[0, high] - Data[0, low]

Data[atr_lookback - 1, whereATR] = Data[0:atr_lookback - 1, whereTR].mean()

first_atr = Data[0, whereATR]

for i in range(len(Data)):

Data[0, whereATR] = first_atr

Data[i, whereATR] = (((Data[i - 1, whereATR] * (atr_lookback - 1)) + Data[i, whereTR]) / atr_lookback)

return Data

The below chart shows the EURUSD daily values versus the 14-Day ATR. Notice the slightly negative visual correlation between the two. Also, we notice the spike in the ATR when the EURUSD started plummeting during the 2008 financial crisis.

# A Word on Trailing Stops

A trailing stop-loss order moves in the direction of the presumed profit direction each time a pre-defined number of ticks occur. In other words, if you buy a EURUSD contract at 1.000 and put your trailing stop-loss order at 0.9985 and price goes up to 1.050, your new stop-loss can go up to at least 1.000 which is a breakeven strategy, no matter what happens you will not lose money (unless your broker is dishonest) because you’ll be stopped out at 1.0000 (your buying price) in case the market turns against you. Take-profit orders are fixed levels upon which the ongoing order will be closed automatically by your broker as soon as prices reach those levels. In our previous example, if the take-profit order was set at 1.030, the order would have been closed for a price return of 3%. The take-profit order can be limiting you from further profits, as it cuts you out of every possible upside, while the trailing stop-loss order can be seen as an enhanced version of the typical stop-loss order. Now, we can use the ATR to try to approximate the most recent volatility.

Example: A trader buys 1 lot of EURGBP at 0.8990. He decides that his target will be 3 times the current 14-period ATR while the stop 1.5 times the current 14-period ATR. If we suppose that the ATR is showing a value of 0.0010, then the trade characteristics will be:

**Entry at 0.8990.****Stop at 0.8975.****Target at 0.9020.**

This way, the trader ensures a 2:1 risk reward ratio that respects the basic risk management practices. For more details on Trading & Performance measurement, have a look at this article:

# A quick and easy way to measure the current Volatility state

Subjectively, if the ATR has been above its chosen moving average (for example 20-period or even 300-period), we can consider it as a volatile market and we can probably try widening the stop-loss margin. If the ATR is showing low levels, you can set a stop-loss according to your capital limits. Now, to do this in MetaTrader 5 software, we first display the ATR indicator. In the below graph, we can see the 14-period ATR of the EURUSD daily values.

Then, from the task bar, we open **View → Navigator** which will be displayed on the left. We drag and drop the Moving Average indicator into the ATR’s window.

And finally, we select “**First Indicator’s Data”** from the “**Apply to”** dropdown menu.

Now, we can see the moving average applied to the ATR in the indicator’s panel.

Now, we can use this technique in many ways but the simplest of all is that by assuming a change in volatility when we break the moving average or by assuming we will stay in the same current market state as we approach the moving average. Here’s an example from the above graph: As long as the ATR remains below its moving average, the bullish trend continues.

# What if the trade is good but prices were too volatile and stopped us out before they went in our direction?

That is, we lost money even though we were right. A simple remedy for this is to widen the stop-loss levels even though that makes us take on more risk. But prices are already volatile which is in itself volatility risk that is giving us a risk to be stopped-out early. To conclude this point, when prices are volatile and a profitable trading opportunity is spotted, the trader must account for this volatility by widening the stop-loss orders so as not to get stopped out early since we do not expect the price to move in our favor as soon as we initiate the trade. This technique of course, comes with a risk that you get stopped-out when prices fluctuate much more than anticipated thus providing a bigger loss.

To conclude, managing risk is a huge field and a part of trading. Consider checking the economic calendar for any upcoming possible volatile events. Even if the ATR or any volatility measure has been trending at low levels, a news event can cause extreme spikes in prices. Watch out of inflation, GDP, employment, and interest rate announcements. Remember, the ATR does not predict the future, it merely tells you what has happened on average in the recent past. Generally, any technical strategy does not work around major news event.

Make sure you understand this rule of thumb whenever you are trading. If greed is good, then fear is better in the sense that avoiding unnecessary risk is better. Markets are still mostly random and have a low signal to noise ratio, do not expect to be treated nicely.