Introduction
The Average Directional Movement Index (ADX) is a technical analysis indicator used by traders to quantify the strength of a trend. It’s derived from the Directional Movement Indicator (DMI). It does not indicate the direction of the trend, a rise or fall, but rather its strength. The higher the ADX, the stronger the trend, and vice versa. The indicator is a well known one in trading as it helps traders identify whether the market is trending or moving sideways, thereby informing their trading strategies.
History and Origin
The ADX indicator was developed by J. Welles Wilder Jr., a mechanical engineer turned real estate developer, who later became a technical analyst. Wilder introduced it in his book “New Concepts in Technical Trading Systems” in 1978. It was developed to objectively quantify trend strength by aggregating price movement in a single direction. Over time, the ADX has become a staple in many trading platforms and is widely used by traders across various financial markets.
ADX Indicator Formula
Understanding the mathematical construction of the indicator is essential to appreciate its functionality. Here’s a step-by-step guide:
1. Calculate True Range (TR)
The True Range is the maximum of the following:
- Current High minus the Current Low
- Absolute value of the Current High minus the Previous Close
- Absolute value of the Current Low minus the Previous Close
TR = max(High – Low, |High – Close_prev|, |Low – Close_prev|)
which is the same as a prettier:
\text{{TR}} = \max \left( \text{{High}} - \text{{Low}}, \left| \text{{High}} - \text{{Close}}_{\text{{prev}}} \right|, \left| \text{{Low}} - \text{{Close}}_{\text{{prev}}} \right| \right)
2. Calculate Positive and Negative Directional Movement +DM and -DM
- If Current High − Previous High > Previous Low − Current Low then
+DM = Current High − Previous High, otherwise +DM=0 - If Previous Low − Current Low > Current High − Previous High, then
-DM = Previous Low − Current Low, otherwise -DM=0
3. Calculate Smoothed Averages
To calculate the ADX, we need smoothed averages for the True Range (TR), Positive Directional Movement (+DM), and Negative Directional Movement (-DM). These are typically calculated over N periods, often 14, using Wilder’s Smoothing method.
\text{{Wilder's Smoothed Value}} = \frac{{\left( \text{{Previous Smoothed Value}} \times (N - 1) \right) + \text{{Current Value}}}}{N}
Smoothed True Range (ATR)
The Average True Range (ATR) is a smoothed average of the True Range (TR), calculated using Wilder’s Smoothing:
ATR = (Previous ATR * (N – 1) + Current TR) / N
which is the same as:
\text{{ATR}} = \left( \frac{{\text{{Previous ATR}} \times (N - 1) + \text{{Current TR}}}}{N} \right)
Smoothed +DM and -DM
Similarly, the smoothed +DM and -DM are calculated using Wilder’s Smoothing technique:
Smoothed +DM = (Previous +DM * (N – 1) + Current +DM) / N
Smoothed -DM = (Previous -DM * (N – 1) + Current -DM) / N
which can also be represented as:
\text{{Smoothed +DM}} = \left( \frac{{\text{{Previous +DM}} \times (N - 1) + \text{{Current +DM}}}}{N} \right)
\text{{Smoothed -DM}} = \left( \frac{{\text{{Previous -DM}} \times (N - 1) + \text{{Current -DM}}}}{N} \right)
These smoothed averages provide the basis for calculating the +DI, -DI, and ultimately the ADX. By using Wilder’s Smoothing, these values provide a more responsive measure of trend strength.
4. Calculate Positive and Negative Directional Indicators (+DI and -DI)
+DI = (Smoothed +DM / ATR) * 100
-DI = (Smoothed -DM / ATR) * 100
which is the same as:
+DI = \left( \frac{\text{Smoothed +DM}}{ATR} \right) \times 100
-DI = \left( \frac{\text{Smoothed -DM}}{ATR} \right) \times 100
5. Calculate the Directional Movement Index (DX)
The DX is calculated as part of the process to find the ADX. The DX is a snapshot of the directional movement and is calculated using the +DI and -DI values:
DX = (|+DI – (-DI)| / (+DI + (-DI))) * 100
which is the same as:
DX = \left( \frac{|+DI - (-DI)|}{+DI + (-DI)} \right) \times 100
6. Calculate the ADX
The ADX is then calculated as a smoothed moving average of the DX over a specific period (usually 14 periods), using Wilder’s smoothing method. This smoothing process turns the DX, which can be quite volatile, into a more stable and interpretable indicator:
ADX = (Previous ADX * (N – 1) + Current DX) / N
Which is the same as:
\text{{ADX}} = \left( \frac{{\text{{Previous ADX}} \times (N - 1) + \text{{Current DX}}}}{N} \right)
Here, “MA” represents the moving average and “N” is the number of periods used in the calculation.
Inclusion of ADXATR
The ADXATR value is not the same as the ADX. The ADXATR value is the same as the ATR (Average True Range). The term “ADXATR” is a little confusing but is used in some contexts or trading platforms to refer to the ATR value when it is reported alongside the ADX indicator. Let’s break down the differences:
Metric | Description | Focus | Calculation |
---|---|---|---|
ADX | Average Directional Movement Index; measures the strength of a trend in the market | Trend Strength | Derived from +DI and -DI; calculated as a smoothed average of the DX (Directional Movement Index) |
ADXATR | Average True Range of the price bars; calculated as a smoothed average of the true ranges | Market Volatility | Calculated by taking a smoothed average of the ATR (Average True Range) of the price bars; same value as the ATR study alone would report |
Some traders might find the ADXATR useful as a complementary metric to the ADX, as it can give context to the market’s behaviour (i.e., how volatile the market is) in conjunction with the trend’s strength.
Trading an ADX Indicator Strategy
As we’ve said, the ADX is designed to measure the strength of a market trend, not its direction. It helps traders identify strong trends and potential opportunities for profit. There are several common approaches to an ADX indicator strategy:
- Breakout Indicator: It can indicate breakouts which is generally considered to occur when the value passes 20 or 25. This rise indicates a strong trend, and traders may choose to enter the market in the direction of the trend.
- Trend Exhaustion It can also be used to identify trends running out of steam, often when the value is above 45 and has a downturn from there. Traders might consider this as a signal to exit trades in line with the current trend and potentially prepare for a counter-trend trade.
- Acceleration If the ADX rises in value by more than 3 between the current and prior bars this is a sign of acceleration. Traders might consider this as a signal that the trend is gaining momentum and consider entering or adding to positions in the direction of the trend.
- Alongside DMI: It can also be used with the DMI (Directional Movement Indicator), when the ADX crosses above the higher valued DMI line. The DMI consists of two lines, +DI (Positive Directional Indicator) and -DI (Negative Directional Indicator), representing upward and downward trends, respectively. This crossing may be interpreted as a confirmation of the prevailing trend’s strength. If the ADX crosses above the +DI, it might be seen as a strong bullish trend, while crossing above the -DI might indicate a strong bearish trend.
When considering your ADX strategy bear in mind that if there is a sudden reversal in trend, the indicator won’t pick it up as it only considers trend strength, not direction. You may wish to engage a range bound strategy on securities identified with falling ADX values then disable it once trending strength occurs on a rising value.
Pros and Cons
The ADX has its strengths and weaknesses.
Advantages:
- Trend Strength Assessment: it excels in quantifying the strength of a trend, helping traders identify when a trend is strong or weak.
- Direction Agnostic: Unlike many indicators, it does not attempt to predict the direction of the trend but focuses solely on its strength. This can reduce false signals related to directional changes.
- Filtering Noise: By smoothing data over time, this indicator can filter out market noise, providing a clearer picture of long-term trend strength.
- Combination with Other Indicators: It is often used in conjunction with other indicators like +DI and -DI or with price patterns, enhancing its utility in a trading system.
- Applicable to Various Markets: It can be used in various financial markets, including stocks, commodities, and forex.
Limitations:
- Lagging Indicator: The ADX is a smoothed average, so it inherently lags behind the current market. This delay can sometimes lead to late signals, missing optimal entry or exit points.
- Not Directional: While its direction agnosticism is a strength, it can also be a limitation. It does not provide information on whether the trend is upward or downward, having said that you can use other indicators with it to determine direction.
- Complexity: For beginners, understanding and interpreting it may be challenging due to its mathematical construction and the need to combine it with other directional indicators.
- False Signals During Ranging Markets: In a sideways or ranging market, it might provide misleading signals as it’s primarily designed to measure trend strength.
- Sensitivity to Parameter Choice: The choice of the period (e.g., 14 days) for calculating the ADX can significantly affect its responsiveness. A poorly chosen parameter may lead to too many false signals or make the indicator too slow to be useful.
Coding the ADX Indicator with Python
So let’s suppose we want to take the formulas from above and code this into Python, download some free data for a ticker and then plot it on a chart. We could use a technical analysis library in Python like talib to shortcut the work but let’s plug it in manually so we can see what’s happening. (It took me a while to get the code to produce the chart I wanted due to some limitations with mplfinance and matplotlib handling axes and labels etc so it might not look very elegant but it works).
I’ll assume you have Python installed and have downloaded a copy of VSCode which Microsoft offer free. We will then use Yahoo Finance to get some free stock data and work on creating the calculations from that. Once you have VSCode open and Python set up make sure you have the relevant modules installed (also free) to work with, which can be done by adding the following command into the Terminal tab at the base of VSCode
pip install pandas yfinance numpy matplotlib mplfinance
Then open a new file and save it as something like adx.py. Then you want to add in the following blocks of code into it in the same order:
Step 1. Importing Necessary Libraries and Defining the Wilder Smoothing Function
import pandas as pd
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ohlc
# Function for Wilder Smoothing
def wilder_smoothing(series, window=14):
smoothed = series.copy()
smoothed.iloc[:window] = series.iloc[:window].mean() # Initialize with simple average for the first value
for i in range(window, len(series)):
smoothed.iloc[i] = (smoothed.iloc[i - 1] * (window - 1) + series.iloc[i]) / window
return smoothed
In this step, we import the necessary libraries that will be used for data manipulation, financial data retrieval, numerical computations, and plotting. We also define the Wilder Smoothing function, which is a specific type of exponential smoothing as mentioned in our formula section earlier in this post.
Step 2: Defining the ADX Calculation Function
# Function to calculate the Average Directional Index (ADX), including +DI, -DI
# 'data' is the DataFrame containing stock data, 'window' is the smoothing window for calculations
def calculate_adx(data, window=14):
# Calculate TR, +DM, -DM
data['prev_Close'] = data['Close'].shift(1)
data['TR'] = data[['High', 'Low', 'Close', 'prev_Close']].apply(lambda x: max(x['High'] - x['Low'], abs(x['High'] - x['prev_Close']), abs(x['Low'] - x['prev_Close'])), axis=1)
data['+DM'] = np.where((data['High'] - data['High'].shift(1)) > (data['Low'].shift(1) - data['Low']), data['High'] - data['High'].shift(1), 0)
data['-DM'] = np.where((data['Low'].shift(1) - data['Low']) > (data['High'] - data['High'].shift(1)), data['Low'].shift(1) - data['Low'], 0)
# Smooth TR, +DM, -DM
data['ATR'] = wilder_smoothing(data['TR'], window=window)
data['+DM_smooth'] = wilder_smoothing(data['+DM'], window=window)
data['-DM_smooth'] = wilder_smoothing(data['-DM'], window=window)
# Calculate +DI, -DI
data['+DI'] = (data['+DM_smooth'] / data['ATR']) * 100
data['-DI'] = (data['-DM_smooth'] / data['ATR']) * 100
# Calculate DX (Directional Movement Index)
data['DX'] = (abs(data['+DI'] - data['-DI']) / (data['+DI'] + data['-DI'])) * 100
# Calculate ADX (Average Directional Movement Index) by smoothing DX
data['ADX'] = data['DX'].rolling(window=window).mean()
return data
In this step, we define the function to calculate the Average Directional Index (ADX), it first calculates the necessary components, such as True Range (TR), Positive Directional Movement (+DM), and Negative Directional Movement (-DM), then applies the Wilder Smoothing function to these components and calculates the Directional Indicators (+DI and -DI) and the Directional Movement Index (DX). Finally, the ADX is calculated by smoothing the DX values over the specified window, and the result is added to the original DataFrame.
Step 3 Downloading Data and Calculating ADX
# Download historical data for desired time period and symbol.
start_date = '2022-08-06'
end_date = '2023-08-06'
ticker = 'AMZN'
data = yf.download(ticker, start=start_date, end=end_date)
# Calculate ADX by calling the earlier function
data = calculate_adx(data)
# Drop rows with NaN values in 'ADX', '+DI', and '-DI'
data = data.dropna(subset=['ADX', '+DI', '-DI'])
This block specifies the ticker symbol, start date, and end date, and then downloads the historical stock data using yfinance. It then calls the previously defined calculate_adx
function to calculate the ADX, +DI, and -DI values, and drops any rows with NaN values.
Step 4 Creating Subplots and Preparing Data for the Candlestick Chart
# Create a figure and subplots
fig, (ax1, ax2, ax3) = plt.subplots(3, figsize=(12, 8), gridspec_kw={'height_ratios': [3, 1, 1]})
# Prepare the data for the candlestick chart (using index instead of dates)
ohlc_data = data.reset_index()
ohlc_data['Date_Num'] = ohlc_data.index
ohlc_values = ohlc_data[['Date_Num', 'Open', 'High', 'Low', 'Close']].values
This block creates three subplots for the candlestick chart, volume chart, and ADX indicators. It also prepares the data required for the candlestick chart by resetting the index and selecting the necessary columns.
Step 5 Plotting the Candlestick Chart, Volume, and Indicators
# Plot candlestick chart
candlestick_ohlc(ax1, ohlc_values, width=0.6, colorup='g', colordown='r')
ax1.set_ylabel('Price ($)')
# Remove x-axis tick labels from the candlestick chart
ax1.set_xticklabels([])
# Determine volume bar colors based on price movement
volume_colors = np.where(data['Close'] >= data['Open'], 'g', 'r')
# Plot volume with color-coded bars
ax2.bar(range(len(data)), data['Volume'], color=volume_colors, width=0.5)
ax2.set_ylabel('Volume')
# Remove x-axis tick labels from the volume chart
ax2.set_xticklabels([])
# Plot ADX, +DI, and -DI
ax3.plot(range(len(data)), data['ADX'], color='b', label='ADX')
ax3.plot(range(len(data)), data['+DI'], color='g', label='+DI')
ax3.plot(range(len(data)), data['-DI'], color='r', label='-DI')
ax3.set_ylabel('+DI / -DI / ADX')
ax3.legend(loc='upper left')
# Set x-axis tick labels to corresponding dates for the indicator panel
plt.xticks(range(0, len(data), 15), data.index[::15].strftime('%Y-%m-%d'), rotation=45)
This block handles the actual plotting of the candlestick chart, volume bars, and ADX indicators. It also sets the x-axis tick labels to display corresponding dates for the indicator panel.
Step 6 Finalizing and Displaying the Plot
# Add a title to the overall plot
plt.suptitle('Amazon Stock Price with ADX Indicator')
# Adjust the spacing between subplots to stack the panels together
plt.subplots_adjust(hspace=0)
# Show the plot
plt.show()
This final block adds a title to the overall plot, adjusts the spacing between the subplots to ensure that they are stacked together, and then displays the plot.
Save your file and press the play icon in the top right of VSCode to generate the chart and you should end up with something looking like mine here:
Note how the very strong down trend gets the first peak before it retreats back from over 45. On the right of the chart the uptrend was running out of steam and looked good for a patient short. However earnings then came out above expectations (final candle) scuppering that idea, which is why it’s important to be aware of fundamentals and not lose money on releases you weren’t aware were coming out. Never only rely on charts and technical indicators.
If you want to check this chart against something like Yahoo Finance’s own chart with the same settings for ADX and the same data you will find it looks identical which is always reassuring that we coded it from scratch correctly.
How to use ADX indicator for Day Trading
When adapting the ADX indicator for day trading, several unique considerations come into play. Unlike longer timeframes, day trading requires a keen eye on intraday price movements, and the standard settings might need tweaking:
- Adjusting Windows: Traditional ADX calculations often use a 14-period window for smoothing. However, in the fast-paced environment of day trading, a shorter window might be more responsive. Experimenting with a window size that aligns with your specific trading strategy and market conditions can be beneficial.
- Alternative Smoothing Techniques: While Wilder’s smoothing is commonly used, experimenting with other smoothing techniques like the Exponential Hull Moving Average (HMA) or TRIX could offer a more tailored fit for intraday trading. This could potentially enhance the responsiveness of the ADX to sudden price changes.
- Scalping Signals: In day trading, some traders might use it as part of a scalping strategy. Monitoring small ADX fluctuations within tight ranges could provide subtle cues for quick entry and exit points.
- Combination with Short-term Indicators: Pairing itwith other short-term indicators that align with intraday trends could enhance its effectiveness for day trading.
Here are some specific short-term indicators that can be used in conjunction with the ADX:
- Stochastic Oscillator: Often used on intraday timeframes to identify overbought and oversold conditions.
- Moving Average Convergence Divergence (MACD): The MACD can be adjusted to a shorter period to provide quicker signals for short-term trends.
- Relative Strength Index (RSI): When set to a shorter timeframe like 5 or 10 periods, it can be a powerful tool for identifying short-term overbought or oversold conditions.
- Bollinger Bands: By narrowing the bands or using shorter periods for the moving average, these can be adapted to a shorter timeframe.
- Momentum Oscillators: Various momentum indicators, such as the Rate of Change (ROC) or the Momentum Oscillator itself, provide insights into the speed of price movement and can be effective for short-term trading.
- Exponential Moving Averages (EMAs): Short period EMAs (like 5, 10, or 20 periods) respond more quickly to price changes and can be used for short-term trend identification.
- Parabolic SAR: This can be used to identify potential stop and reversal points in a fast-moving market, suitable for day trading.
- Volume-Based Indicators: Indicators like On-Balance Volume (OBV) or Volume Rate of Change can be useful for understanding short-term volume trends.
The effectiveness of these indicators in a short-term context often depends on how they are configured. Shorter settings will make them more responsive to recent price changes, aligning them more closely with a short-term trading strategy.
While the core principles of the indicator remain the same as for longer term trading, fine-tuning the settings and considering alternative techniques might make it a more precise tool for day trading. Experimentation and back-testing with different window sizes, smoothing methods, and complementary indicators are essential to find the optimal setup for your custom ADX indicator strategy.
Comparing the Average Directional Movement Index (ADX) with Other Indicators
The ADX is a unique indicator that measures the strength of a trend, but it’s not the only tool traders have at their disposal. Let’s compare it with a couple of other popular technical indicators:
- Relative Strength Index (RSI): While the ADX measures the strength of a trend, the RSI is used to identify overbought or oversold conditions. The RSI can provide signals for potential reversals, while the ADX can help confirm if the market is trending or ranging.
- Moving Average Convergence Divergence (MACD): The MACD is a trend-following momentum indicator. It can provide signals for potential buy and sell points, while the ADX can help determine the strength of the trend. Using these two indicators together can provide a more comprehensive picture of the market.
When to use the ADX over others largely depends on your trading strategy. If your strategy relies on identifying strong trends, the ADX could be a valuable addition to your screens.
Frequently Asked Questions about the Average Directional Movement Index (ADX)
- What does a rising ADX indicate? It indicates that the strength of the trend is increasing. However, it does not indicate the direction of the trend.
- What does an ADX value above 25 signify? An value above 25 generally indicates a strong trend. This can be an uptrend or a downtrend.
- Can the ADX be used for all types of trading? Yes, the use of an ADX indicator strategy is applicable for various types of trading, including swing trading, day trading, and even long-term investing. It’s a versatile tool that can be adapted to different trading styles and timeframes.
Key Takeaways
- Understanding Trend Strength: The indicator is valuable for quantifying the strength of a trend, but not its direction. The higher the value, the stronger the trend, helping traders identify market opportunities.
- Historical Significance: Developed by J. Welles Wilder Jr. in 1978, this tool has become a staple in many trading platforms, used across various financial markets.
- Mathematical Construction: The calculation involves several steps, including True Range, Positive and Negative Directional Movement, Wilder’s Smoothing method, and directional indicators.
- Day Trading Considerations: When using the indicator for day trading, unique considerations such as adjusting windows, experimenting with alternative smoothing techniques, and pairing with short-term indicators can be valuable.
- Strategies and Signals: It can be employed to indicate breakouts, trend exhaustion, acceleration, and in conjunction with the DMI. Its rise and fall can signify different trading opportunities.
- Pros and Cons: While excelling in trend strength assessment and noise filtering, it may present challenges such as being a lagging indicator, complexity for beginners, and sensitivity to parameter choice.
- Python Coding: The post provides a step-by-step guide to coding the indicator with Python, demonstrating how to download data, define calculations, and plot charts.
- Comparisons with Other Indicators: It can be compared with other indicators like RSI and MACD for a comprehensive market analysis, depending on the trader’s strategy.
- Versatility: This tool is applicable for various types of trading, including swing trading, day trading, and long-term investing, making it a versatile and adaptable part of a trading system.
- Holistic Approach: It should be used as part of a comprehensive trading strategy, including risk management, and never solely relied upon.
Further Reading
“New Concepts in Technical Trading Systems” J. Welles Wilder (1978)
“Technical Analysis of the Financial Markets: A Comprehensive Guide to Trading Methods and Applications” John J Murphy (1999)
“Technical Analysis Explained, Fifth Edition: The Successful Investor’s Guide to Spotting Investment Trends and Turning Points” Pring Martin J (2014)
Leave a Reply