,

Adaptive Moving Average (AMA): Origins, Uses and Coding Examples

Posted by

Adaptive Moving Average
“If you learn to be fluid, to adapt, you’ll always be unbeatable” – Fist of Legend
Table of Contents

    Introduction

    The Adaptive Moving Average (AMA), also known as the Kaufman’s Adaptive Moving Average (KAMA), is an indicator that adapts to market volatility and can be used in both trending and sideways markets. In this guide, we’ll explore the origins, mathematical construction, and purpose of the AMA, as well as how to use it to find trading signals.

    Origins of the Adaptive Moving Average (AMA)

    The AMA was developed by Perry Kaufman and first introduced in his book “New Trading Systems and Methods” – now in its sixth edition. Kaufman sought to create an indicator that could adjust itself to the market’s changing volatility. Traditional moving averages, such as the Simple Moving Average (SMA) and the Exponential Moving Average (EMA), use a fixed length of time to calculate the average, which can be less effective during periods of market volatility. Kaufman’s AMA, on the other hand, adapts its sensitivity based on market conditions, making it a more responsive and dynamic tool for traders.

    Purpose and Design

    The primary purpose of the Adaptive Moving Average (AMA) is to help traders identify the start of trends and the direction of the current trend. The AMA is designed to be more responsive to price changes when the price is trending and less responsive when the price is moving sideways. This is achieved by adjusting the smoothing constant based on the Efficiency Ratio (ER), which measures the market’s volatility.

    As such the AMA is unique in its ability to adapt to market conditions. Unlike the fixed period which is used to calculate the Simple Moving Average (SMA) and the Exponential Moving Average (EMA), AMA’s is variable meaning lagging signals are less common during periods of high volatility as are false signals during periods of low volatility. It adjusts its sensitivity based on the market’s volatility, ultimately providing for more timely and accurate signals.

    How to Find Trading Signals with Adaptive Moving Average (AMA)

    Using the AMA to find trading signals is relatively straightforward. Here are some common strategies:

    1. Trend Identification: When the AMA is rising, it indicates an uptrend, and when it’s falling, it indicates a downtrend. Traders can use this information to align their trades with the current trend.
    2. Price Crossovers: Price crossovers happen when the price of an asset moves across the AMA line. If the price moves from below the AMA line to above it, that’s a positive or ‘buy’ signal. If the price moves from above the AMA line to below it, that’s a negative or ‘sell’ signal. This strategy works best in trending markets.
    3. AMA Crossovers: Some traders use two AMAs, one with a shorter period and one with a longer period, i.e. fast and slow respectively. A buy signal is generated when the shorter-period AMA crosses above the longer-period AMA, and a sell signal is generated when the shorter-period AMA crosses below the longer-period AMA.
    4. Divergences: If the price is making new highs but the AMA is not, it could indicate a bearish divergence. Conversely, if the price is making new lows but the AMA is not, it could indicate a bullish divergence.

    Remember, no indicator is perfect, and the AMA should be used in conjunction with other technical analysis tools to confirm signals and avoid false positives.

    Mathematical Construction

    The Adaptive Moving Average (AMA) is a type of moving average that adjusts based on changes in market conditions. Unlike the Exponential Moving Average (EMA), which uses a fixed constant for smoothing the data, the AMA uses a scalable constant that adjusts itself. Let’s break down how it works:

    1. Exponential Moving Average (EMA): The EMA is calculated using the formula:

    EMA(today)=C×(price(today)−EMA(yesterday))+EMA(yesterday)

    C is known as the smoothing constant. It is calculated as:

    C = \frac{2}{{N+1}}
    


    N is a number used to approximate a simple moving average.
    C varies between 0 and 1.

    2. Adaptive Moving Average (AMA): The AMA calculation is similar to the EMA, but it uses a different constant (SC), known as the Scalable Constant.
    The formula is:

    \text{{AMA(today)}} = SC \times (\text{{price(today)}} - \text{{AMA(yesterday)}}) + \text{{AMA(yesterday)}}

    3. Scalable Constant (SC): The AMA uses the Scalable Constant to adjust the weight between two EMAs – a fast EMA (short look back period) and a slow EMA (long look back period).The Scalable Constant varies between 0 and 1, and is used to adjust the weight based on the market direction relative to market volatility.

    4. Efficiency Ratio (ER): The Scalable Constant uses the Efficiency Ratio to determine the market trend’s degree. The ratio is the direction relative to volatility.
    The formula is:

    \text{{ER}} = \text{{Abs}}\left(\frac{{\text{{Direction}}}}{{\text{{Volatility}}}}\right)
    

    In this formula:
    Direction is calculated as:

    \text{{Price(today)}} - \text{{Price(N bars back)}}

    Volatility is the sum of the absolute value of the one bar difference in closes over the look back period N. By default, N is 10 bars.

    5. Weighting or Scaling the Constant: The formula for weighting or scaling the constant is:

    SC = \left(ER \times (\text{{Fast}} - \text{{Slow}}) + \text{{Slow}}\right)^2

    In this formula:
    Fast is calculated as:

    \frac{2}{{2+1}}

    Slow is calculated as:

    \frac{2}{{30+1}}

    These are the default values for the fast and slow EMAs, respectively.

    Overall this formulation allows the AMA to adapt to market conditions. The Efficiency Ratio (ER) is a measure of how efficiently the market is moving. A high ER (closer to 1) means the price is moving up or down with little noise, while a low ER (closer to 0) means there is a lot of noise, or sideways movement, in the price. When the market is trending, the ER approaches 1 and the scalable constant is weighted towards the Fast constant. If the market is in congestion, then ER will approach 0 and the scalable constant is weighted towards the Slow constant.

    The result from the formula above is squared, causing the AMA to go flat when the market is in congestion because the ER approaches zero and the resulting smoothing constant is a very small number.

    Coding the Adaptive Moving Average

    Step 1: Open Visual Studio Code and Create a New Python File

    Start by opening Visual Studio Code (VSCode) which is free software from Microsoft and install Python, it has step by step instructions to do that if I remember correctly. Click on “File” -> “New File” or use the shortcut Ctrl+N to create a new file. Once the new file is open, save it with a “.py” extension to specify that it’s a Python file. For example, you might name it “ama_chart.py“.

    Now we’ll start writing our Python code. We’ll break it down into five sections.

    Step 2: Import the Necessary Libraries

    Python
    import pandas as pd
    import numpy as np
    import yfinance as yf
    import mplfinance as mpf
    import matplotlib.lines as mlines
    import matplotlib.pyplot as plt

    This section imports all the Python libraries we’ll need. If you don’t already have these libraries installed, you can install them using pip, Python’s package manager. You can open a new terminal in VSCode by clicking on “Terminal” -> “New Terminal”, and then use the following commands to install the libraries:

    Bash
    pip install pandas
    pip install numpy
    pip install yfinance
    pip install mplfinance
    pip install matplotlib

    Step 3: Define the AMA Calculation Function

    Python
    def calculate_ama(price, fast_period=2, slow_period=30, ER_period=10):
        direction = price - price.shift(ER_period)
        volatility = np.abs(price - price.shift(1)).rolling(ER_period).sum()
        ER = np.abs(direction / volatility)
        fast_SC = 2 / (fast_period + 1)
        slow_SC = 2 / (slow_period + 1)
        SC = (ER * (fast_SC - slow_SC) + slow_SC) ** 2
        ama = pd.Series(index=price.index)
        ama.iloc[:ER_period] = price.iloc[0]
        for i in range(ER_period, len(price)):
            ama.iloc[i] = SC.iloc[i] * (price.iloc[i] - ama.iloc[i-1]) + ama.iloc[i-1]
        return ama
    

    This function calculates the Adaptive Moving Average (AMA) for a given price series. It uses the Efficiency Ratio (ER) to adjust the smoothing constant based on market volatility.

    Step 4: Download Data and Calculate the AMAs

    Python
    ticker = 'AAPL'
    df = yf.download(ticker, start='2022-07-19', end='2023-07-19')
    df['Fast AMA'] = calculate_ama(df['Close'], fast_period=2, slow_period=30, ER_period=10)
    df['Slow AMA'] = calculate_ama(df['Close'], fast_period=2, slow_period=30, ER_period=30)

    Here, we’re downloading historical data for Apple Inc. (AAPL) from Yahoo Finance and calculating two AMAs: a “fast” AMA with a short lookback period, and a “slow” AMA with a longer lookback period.

    Step 5: Plot the Data

    Python
    fast_ama_line = mpf.make_addplot(df['Fast AMA'].dropna(), color='b', width=1.5)
    slow_ama_line = mpf.make_addplot(df['Slow AMA'].dropna(), color='r', width=1.5)
    fast_dummy_line = mlines.Line2D([], [], color='blue', linewidth=1.5, label='Fast AMA')
    slow_dummy_line = mlines.Line2D([], [], color='red', linewidth=1.5, label='Slow AMA')
    fig, axes = mpf.plot(df, type='candle', style='yahoo', 
                         title=f'{ticker} Close Prices and AMAs',
                         ylabel='Price ($)',
                         addplot=[fast_ama_line, slow_ama_line],
                         figratio=(10,6),
                         volume=True,
                         returnfig=True)
    axes[0].legend(handles=[fast_dummy_line, slow_dummy_line])
    plt.show()

    Finally, we’re creating the plot. We first create two lines for the fast and slow AMAs, and then we add them to the plot. We also create two dummy lines for the legend. The mpf.plot() function creates the plot, and plt.show() displays it.

    Once you have pasted all five sections into your Python file in VSCode, you can run the file by clicking on the green play button in the top-right corner or by pressing Ctrl+Alt+N. You should see a candlestick chart of AAPL’s closing prices along with the fast and slow AMAs that looks like mine shown here:

    Adaptive Moving Average
    Kaufman’s Adaptive Moving Average fast and slow line on an Apple stock candle chart with volume bars created from our Python script

    Pros and Cons of Adaptive Moving Average (AMA)

    The Adaptive Moving Average (AMA) has its strengths and weaknesses. Understanding these can help you use the AMA more effectively in your trading strategy.

    Pros of AMA

    1. Adapts to Market Volatility: The AMA adjusts its sensitivity based on market volatility, making it more responsive during trending periods and less responsive during sideways markets. This can lead to more timely and accurate signals compared to traditional moving averages.
    2. Versatile: The AMA can be used in both trending and sideways markets, making it a versatile tool for different market conditions.
    3. Easy to Interpret: The AMA is plotted directly on the price chart, making it easy to interpret. Rising AMA indicates an uptrend, falling AMA indicates a downtrend, and flat AMA indicates a sideways market.

    Cons of AMA

    1. Complex Calculation: The AMA involves a complex calculation, which can be difficult to understand and implement, especially for beginners.
    2. Lagging Indicator: Although the AMA is more responsive than traditional moving averages, it is still a lagging indicator. This means it reacts to price changes rather than predicting them.
    3. False Signals: Like all moving averages, even the AMA can generate false signals, especially in choppy or sideways markets. It’s important to use the AMA in conjunction with other technical analysis tools to confirm signals and avoid false positives.

    Application

    The Adaptive Moving Average can be used in several trading strategies for example:

    1. Trend Following: The AMA is an excellent tool for trend following strategies. When the AMA is rising, traders can look for opportunities to go long, and when the AMA is falling, traders can look for opportunities to go short. The AMA’s ability to adapt to market volatility can help traders stay in trends longer and avoid getting whipsawed out of their positions.
    2. Breakout Trading: The AMA can also be used in breakout trading strategies. When the price crosses above the AMA, it could indicate the start of an uptrend and a potential buying opportunity. Conversely, when the price crosses below the AMA, it could indicate the start of a downtrend and a potential selling opportunity.
    3. Divergence Trading: Divergences between the price and the AMA can signal potential reversals. For example, if the price is making new highs but the AMA is not, it could indicate a bearish divergence and a potential selling opportunity. Conversely, if the price is making new lows but the AMA is not, it could indicate a bullish divergence and a potential buying opportunity.

    Remember, while these strategies can be effective, they are not foolproof. It’s important to use the AMA in conjunction with other technical analysis tools and to manage your risk appropriately.

    Key Takeaways

    • The Adaptive Moving Average (AMA) is an indicator that adjusts to market volatility, making it useful in both trending and sideways markets.
    • The AMA was developed by Perry Kaufman and introduced in his book “New Trading Systems and Methods.”
    • Unlike the Simple Moving Average (SMA) and the Exponential Moving Average (EMA), the AMA adapts its sensitivity based on market conditions, providing more timely and accurate signals.
    • The AMA can be used to identify trends, generate buy/sell signals through price crossovers, identify divergences, and generate signals through AMA crossovers with two different periods (fast and slow).
    • The mathematical construction of the AMA involves calculating the Efficiency Ratio (ER), which measures the market’s volatility, and then using it to adjust the smoothing constant.
    • The article provides a step-by-step guide on how to code the AMA in Python using Visual Studio Code.
    • The AMA, like all indicators, has its strengths and weaknesses. It’s versatile and easy to interpret, but also involves complex calculations and, as a lagging indicator, can generate false signals.

    Finally, we’re interested in hearing from you! Share your experiences with using the AMA in the comments below, or let us know if you have any questions. Your input could help guide future content on this topic.

    Further Reading

    Trading Systems and Methods” Perry J Kaufman, (Wiley Trading) 6th Edition, 2019

    Leave a Reply

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