,

Understanding the Directional Movement Index, Strategy and Python

Posted by

Directional Movement Index Strategy
As well as interpreting the DMI signals, this article also includes a step by step tutorial to create your own DMI and DDif chart using Python from free software and data
Table of Contents

    Introduction

    The Directional Movement Index (DMI) is a powerful tool that traders use to gauge the strength of a market trend. It’s a component of the Average Directional Index (ADX) and was developed by J. Welles Wilder. The DMI is particularly useful in determining whether a security is trending and the strength of that trend.

    The DMI consists of two lines, the +DI (often referred to as DMI+) and -DI (often referred to as DMI-), which represent positive and negative movement respectively. The crossing of these lines can provide valuable buy and sell signals for traders. The DMI is best used in conjunction with other indicators and is particularly effective in long-term trading situations.

    Origins

    The DMI was developed by technical analyst J. Welles Wilder. The DMI was introduced by him in his 1978 book, “New Concepts in Technical Trading Systems,” where he presented several of his innovative technical indicators.

    Wilder developed the DMI as a tool to help traders identify the strength of a trend. He believed that understanding the direction of the market was crucial for successful trading. Over time, the DMI has become a familiar feature on many traders’ charts including my own and is appreciated for its ability to provide a clear picture of the impetus of market trends.

    DMI Calculation

    The DMI breaks down trend strength through a sequence of computations. The process starts by determining the True Range (TR), which represents the largest difference among the current high-low, current high-previous close, and current low-previous close. With TR in hand, the Directional Movement (DM) is ascertained, either indicating upward (+DM), downward (-DM), or no movement. This DM captures the most significant segment of the current trading range that surpasses the previous one. Based on these values, the Directional Indicators (+DI and -DI) are derived, reflecting the percentage of the average true range for both upward and downward trading intervals. The process culminates in the Directional Movement Index (DX), a ratio of the absolute difference to the sum of +DI and -DI, multiplied by 100.

    1. Calculate True Range (TR) The True Range provides a measure of price volatility and is the largest of the following three values:
    • 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(\text{High} - \text{Low}, |\text{High} - \text{Close}_{\text{prev}}|, |\text{Low} - \text{Close}_{\text{prev}}|)

    2. Calculate Directional Movement (+DM and -DM) The Directional Movement is a measure of the upward or downward movement in price compared to the previous period. The calculations are as follows:

    • If Current High minus Previous High is greater than Previous Low minus Current Low, then:
    +DM = \text{Current High} - \text{Previous High}

    otherwise, +DM = 0

    • If Previous Low minus Current Low is greater than Current High minus Previous High, then:
    -DM = \text{Previous Low} - \text{Current Low}

    otherwise, -DM = 0

    3. Calculate Smoothed Averages Using Wilder’s Smoothing method, calculate smoothed averages for TR, +DM, and -DM. Typically, this is done over 14 periods.

    \text{Wilder’s Smoothed Value} = \left( \text{Previous Smoothed Value} \times (N - 1) \right) + \text{Current Value} \div N

    Smoothed True Range (ATR) The Average True Range is a smoothed version of the TR:

    ATR = \frac{\text{Previous ATR} \times (N - 1) + \text{Current TR}}{N}

    Smoothed +DM and -DM Similarly, calculate the smoothed +DM and -DM:

    \text{Smoothed +DM} = \frac{\text{Previous +DM} \times (N - 1) + \text{Current +DM}}{N}
    \text{Smoothed -DM} = \frac{\text{Previous -DM} \times (N - 1) + \text{Current -DM}}{N}

    4. Calculate Positive and Negative Directional Indicators (+DI and -DI) These indicators provide a measure of the direction of movement:

    +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 provides a measure of the strength and direction of movement:

    DX = \left( \frac{|+DI - (-DI)|}{+DI + (-DI)} \right) \times 100

    Purpose and Design

    The primary purpose of the DMI is to measure the strength of a trend. It does this by comparing the differences in the highs and lows of consecutive periods. The DMI is designed to help traders identify whether a security is trending and the strength of that trend.

    The DMI is unique in its ability to provide a clear picture of both the direction and strength of a trend. This dual functionality sets it apart from many other technical indicators. It’s particularly useful in trending markets, where it can help traders identify potential entry and exit points.

    Interpreting Directional Movement Index (DMI) Signals

    Interpreting the DMI involves understanding the relationship between the +DI and -DI lines. When the +DI line crosses above the -DI line, it’s generally seen as a buy signal. This suggests that upward price movement is dominating. Conversely, when the +DI line crosses below the -DI line, it’s considered a sell signal, indicating that downward price movement is prevailing.

    However, Wilder himself cautioned against using these two lines in isolation. He recommended looking at the ADX line for confirmation. For a strong sell signal, the +DI should be greater than -DI and both should be greater than ADX (+DI > -DI > ADX). For a strong buy signal, +DI should be lower than -DI and both should be lower than ADX (+DI < -DI < ADX).

    Pros and Cons

    Like any technical indicator, the DMI has its strengths and weaknesses. One of the main advantages of the DMI is its ability to provide a clear picture of both the direction and strength of a trend. This can help traders make more informed decisions about when to enter or exit a trade.

    However, the DMI also has its limitations. It’s less effective in markets that lack a clear trend, and it can produce false signals during periods of price consolidation. Additionally, the DMI can become very volatile during periods of extreme price movement, which can make it harder to interpret.

    Despite these potential pitfalls, the DMI remains a valuable tool in the trader’s toolkit. It’s particularly useful when used in conjunction with other technical indicators, as it can help confirm their signals and provide a more complete picture of market conditions.

    Coding the DMI: Python & R

    The DMI can be coded in various trading languages such as Python and R. Here, we’ll provide a basic outline of how you might approach this task in Python using the pandas library for data manipulation and the ta (Technical Analysis) library for calculating the DMI.

    Python
    import pandas as pd
    import ta
    
    # Assume df is a pandas DataFrame with 'High', 'Low', and 'Close' columns
    df['DMI+'] = ta.trend.adx_pos(df['High'], df['Low'], df['Close'], window=14)
    df['DMI-'] = ta.trend.adx_neg(df['High'], df['Low'], df['Close'], window=14)
    df['ADX'] = ta.trend.adx(df['High'], df['Low'], df['Close'], window=14)

    In the above Python code, we first import the necessary libraries. We then calculate the +DI and -DI lines (interchangeably called DMI+ and DMI-), as well as the ADX line, using the adx_pos, adx_neg, and adx functions from the ta library. The window parameter is set to 14, which is the default period used by Wilder.

    If you want to see a more detailed step by step guide on how to get the +DI and -DI plotted on a chart with Python using free software and data, we include that over in our ADX post.

    Here’s how you might code the DMI in R using the TTR (Technical Trading Rules) package:

    R
    # Install and load the necessary package
    install.packages("TTR")
    library(TTR)
    
    # Assume 'data' is a data frame with 'High', 'Low', and 'Close' columns
    data$DMIplus <- DMI(data[, c("High", "Low", "Close")], n=14)$DIp
    data$DMIminus <- DMI(data[, c("High", "Low", "Close")], n=14)$DIn
    data$ADX <- ADX(data[, c("High", "Low", "Close")], n=14)$ADX
    

    In the above R code, we first install and load the TTR package. We then calculate the DMI+ and DMI- lines, as well as the ADX line, using the DMI and ADX functions from the TTR package. The ‘n’ parameter is set to 14, which is the default period used by Wilder.

    Understanding the Directional Movement Index Difference (DDif)

    The Directional Movement Index Difference (DDif) is a derivative of the DMI study. It’s calculated by subtracting the -DI line (representing downward movement) from the +DI line (representing upward movement). The resulting value can provide additional insights into market trends.

    \text{DDif} = +DI - (-DI)

    or more simply:

    \text{DDif} = +DI + DI

    Positive DDif values indicate an uptrend, suggesting that upward price movement is dominating. Negative DDif values, on the other hand, indicate a downtrend, suggesting that downward price movement is prevailing. When the DDif values oscillate around zero, it indicates the absence of a clear trend.

    Just like the DMI, the DDif is best used in trending markets. It can help traders identify the strength and direction of a trend, providing valuable insights for making trading decisions.

    Here’s how you might calculate the DDif in Python:

    Python
    # Assume df is a pandas DataFrame with 'High', 'Low', and 'Close' columns, and DMI+ and DMI- have been calculated
    df['DDif'] = df['DMI+'] - df['DMI-']
    

    Tutorial: Plotting DMI and DDif using Python in VSCode

    Step 1: Setup

    1. Install Visual Studio Code (VSCode) from the official website (it’s free).
    2. Launch VSCode and install the Python extension for improved Python support.
    3. Create a new Python file, say “plot_dmi_ddif.py“.
    4. Before diving into the code, ensure you have the necessary Python packages installed. Open your terminal or command prompt and enter the following commands:
    Bash
    pip install pandas yfinance numpy matplotlib mplfinance

    This will install pandas, yfinance (for fetching stock data), numpy, matplotlib (for plotting), and mplfinance (for specialized financial plots).

    Step 2: Import Required Libraries

    In your Python file, begin by importing the necessary libraries:

    Python
    import pandas as pd
    import yfinance as yf
    import numpy as np
    import matplotlib.pyplot as plt
    from mplfinance.original_flavor import candlestick_ohlc

    Step 3: Define Helper Functions

    These functions will assist in calculating the True Range, +DM, -DM, +DI, -DI, DX, Average Directional Index (ADX), DDif and smoothing the data:

    Python
    # 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
        
    # 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()
    
        # Calculate DDif
        data['DDif'] = data['+DI'] - data['-DI']
    
        return data

    Step 4: Download Data and Process

    Now, fetch the data for the desired stock/index and calculate the ADX:

    Python
    # Download historical data for desired time period and symbol.
    start_date = '2022-08-18'
    end_date = '2023-08-18'
    ticker = '^RUT'
    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'])

    Step 5: Plotting the Data

    In this step, you’ll set up the chart and plot the data:

    Python
    # 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
    # ... [rest of the plotting code]
    
    # 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)
    
    # Add a title to the overall plot
    plt.suptitle('Russell 2000 Stock Index with DMI and DDif')
    
    # Adjust the spacing between subplots to stack the panels together
    plt.subplots_adjust(hspace=0)
    
    # Show the plot
    plt.show()

    Step 6: Running the Code

    1. Save the plot_dmi_ddif.py file.
    2. Open the terminal in VSCode.
    3. Navigate to the directory containing your Python file.
    4. Run the code using the command: python plot_dmi_ddif.py or just press the play button in top right of VSCode
    5. Observe the generated chart showing the stock’s candlestick data, ADX, +DI, -DI, and DDif which should look the same as mine shown below:
    Directional Movement Index Strategy
    Note when +DI and -DI are both falling around April 2023 the market is tight and choppy, DDif flatlines. This usually indicates a good time to stay out. It’s the same principle when scalping just a few ticks intraday using DMI.

    Conclusion

    The Directional Movement Index (DMI) is a tool that can help traders identify the strength and direction of a trend. Developed by J. Welles Wilder, the DMI has become a staple on many traders’ chart. Despite its potential limitations, such as its reduced effectiveness in range-bound markets and potential for volatility during periods of extreme price movement, the DMI can provide valuable insights when used correctly.

    Remember, the DMI is just one tool in your trading toolkit. It should not be used in isolation, but rather as part of a comprehensive trading strategy that takes into account other technical indicators, fundamental analysis, and risk management principles. As with any trading tool, it’s important to practice and experiment with the DMI in a risk-free environment before using it in live trading.

    Editor’s Note

    I have used the DMI indicator for over 20 years, mainly because when I started on the electronic trading floor in 2002, the technical analysis screens I was sharing happened to have it left there by the prior trader who had left London to trade in sunny, low-tax Gibraltar. Although initially I wasn’t aware of it’s construction or that it even was the DMI at the time, after watching it 12 hours a day for the first few months, I got a pretty good idea of what was going to happen when it behaved in certain ways. The point I want to get across is that although indicators are designed with certain ‘rules’ that should be applied to them, in reality they can be useful through your own unique interpretations. So keep openminded when looking for a directional movement index strategy and see what works for you.

    Personally I tend to only use both DMI and MACD on my charts. Here’s why:

    Complementary Indicators: While both the DMI and MACD are momentum indicators, they measure different aspects of the market.

    • DMI focuses on trend strength and direction. The ADX component of DMI indicates the strength of a trend, while the +DI and -DI components indicate its direction.
    • MACD measures the relationship between two moving averages of a security’s price. It can help traders identify potential buy and sell signals based on crossovers of its MACD line and signal line.

    I find the +DI and -DI lines’ movements tend to identify market turns before the MACD and it also works well to tell you when not to be in the market. If both the +DI and -DI are dropping together it shows there is no conviction in the market, it’s getting thin and choppy and it’s highly likely I’ll lose money entering the market under when I see this. No trade is very often the best trade.

    References and Further Reading

    For those interested in learning more about the DMI and its applications in trading, the following resources are recommended:

    1. Wilder, J. Welles. “New Concepts in Technical Trading Systems.” Trend Research, 1978. This is the original book where Wilder introduced the DMI and several other technical indicators.

    Leave a Reply

    Your email address will not be published. Required fields are marked *