## Introduction

The Triple Exponential Moving Average (TRIX) has been an interesting development for technical analysis, as it offers traders a unique perspective on market trends and momentum. This indicator is designed to filter out insignificant price movements, providing a clearer picture of the market’s direction.

The TRIX indicator is essentially a momentum oscillator that displays the percentage rate of change of a triple exponentially smoothed moving average. It’s a tool that combines trend and momentum, helping traders identify overbought and oversold conditions, and even anticipate potential trend reversals through bullish and bearish divergences.

It is calculated through a series of exponential smoothing passes on the data, which helps to reduce the impact of random market fluctuations or “noise.” This makes the it particularly useful in identifying the underlying trend in a market.

This indicator is not just about identifying trends though; it’s also about understanding the momentum behind these trends. By displaying the rate of change of a triple exponentially smoothed moving average, it provides insights into the strength or weakness of a trend, which can be crucial information for traders looking to time their trades effectively.

In this post we will be exploring its origins, mathematical construction, and purpose. We will also discuss how to use the TRIX in trading, its pros and cons, and how to code it into Python.

## History and Origin of the TRIX Indicator

The indicator was first introduced in the 1980s. Its creator, Jack Hutson, was an influential figure in the field, serving as the editor of the magazine “Technical Analysis of Stocks & Commodities.” Hutson’s work on the TRIX was considered ground-breaking, offering traders a new way to filter out market noise and focus on the underlying trend.

## Mathematical Construction

The **TRIX indicator** is calculated using a series of exponential moving averages (EMAs). The process involves three rounds of smoothing, which helps to reduce market noise and highlight the underlying trend. Here’s a step-by-step breakdown of the calculation:

**First Exponential Moving Average (EMA1):**The first step is to calculate an EMA of the closing prices. The formula for an EMA is:

EMA1 = (\text{{Close}} - EMA1(\text{{previous day}})) \times \alpha + EMA1(\text{{previous day}})

Here, ‘Close’ refers to the closing price, and ‘EMA1(previous day)’ is the EMA value from the previous day.

2. **Second Exponential Moving Average (EMA2):**

The second step is to calculate an EMA of the EMA1 values:

EMA2 = (EMA1 - EMA2(\text{{previous day}})) \times \alpha + EMA2(\text{{previous day}})

3. **Third Exponential Moving Average (EMA3):**

The third step is to calculate an EMA of the EMA2 values:

EMA3 = (EMA2 - EMA3(\text{{previous day}})) \times \alpha + EMA3(\text{{previous day}})

4. **Calculate the TRIX:**

The final step is to calculate the 1-day percent change of the EMA3 values, which gives the TRIX indicator:

TRIX = \frac{{EMA3(\text{{today}}) - EMA3(\text{{previous day}})}}{{EMA3(\text{{previous day}})}} \times 100

Step | Calculation | Description |
---|---|---|

1 | EMA1 = (Close â€“ EMA1(previous day)) * Alpha + EMA1(previous day) | Calculate the first EMA from the closing prices |

2 | EMA2 = (EMA1 â€“ EMA2(previous day)) * Alpha + EMA2(previous day) | Calculate the second EMA from the first EMA values |

3 | EMA3 = (EMA2 â€“ EMA3(previous day)) * Alpha + EMA3(previous day) | Calculate the third EMA from the second EMA values |

4 | TRIX = (EMA3(today) â€“ EMA3(previous day)) / EMA3(previous day) * 100 | Calculate the TRIX indicator as the one-day percent change in EMA3 |

The term ‘Alpha’ with regards to this indicator refers to the smoothing factor used in the calculation of the exponential moving averages. It is used to give different weights to the data points, with more recent data receiving more weight. The ‘Alpha’ is calculated using the following formula: **Alpha** = 2 / (N + 1) which can be represented as:

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

Here, ‘N’ refers to the period chosen for the TRIX calculation. For example, if you’re using a 14-day period, ‘N’ would be 14. The ‘Alpha’ value determines the degree of weighting decrease, a key component of the exponential moving average calculation.

The triple exponential moving average indicator oscillates around a zero line, with positive values indicating upward price momentum and negative values indicating downward price momentum. The TRIX can be used to generate trading signals, identify overbought and oversold conditions, and spot potential price reversals.

## Purpose and Design

The triple exponential moving average indicator was designed with a specific purpose in mind: to filter out insignificant price movements and provide a clearer picture of the market’s direction. By smoothing out price fluctuations, the indicator helps traders distinguish between genuine trends and random noise.

The indicator combines trend analysis with momentum measurement. It not only identifies overbought and oversold conditions in the market but also detects bullish and bearish divergences. These divergences can signal potential trend reversals, providing traders with valuable insights for their trading decisions.

## How to Use it for Trading

Here’s how you can leverage it:

**Zero-Line Crossovers:**The TRIX indicator oscillates around a zero line, and when it crosses this line, it can signal a potential market trend. A positive crossover (when the TRIX line crosses from below to above the zero line) indicates a bullish trend, suggesting a good time to buy. Conversely, a negative crossover (when the TRIX line crosses from above to below the zero line) signals a bearish trend, indicating a potential selling opportunity.**Signal Line Crossovers:**Traders often add a signal line to the indicator, which is a moving average of the TRIX values. A bullish signal is generated when the TRIX line crosses above the signal line, and a bearish signal is generated when the TRIX line crosses below the signal line. The signal line is usually a 9-day EMA (Exponential Moving Average) of the TRIX line.**Divergences:**Divergences between the indicator and price action can signal significant market turning points. A bullish divergence occurs when the TRIX forms a higher low while the price forms a lower low, indicating potential upward price movement. A bearish divergence occurs when the TRIX forms a lower high while the price forms a higher high, suggesting potential downward price movement.

Signal | Meaning | Action |
---|---|---|

Positive zero-line crossover | Bullish trend | Potential buying opportunity |

Negative zero-line crossover | Bearish trend | Potential selling opportunity |

TRIX crosses above signal line | Bullish signal | Potential buying opportunity |

TRIX crosses below signal line | Bearish signal | Potential selling opportunity |

Bullish divergence | Potential upward price movement | Watch for buying opportunity |

Bearish divergence | Potential downward price movement | Watch for selling opportunity |

## Best TRIX indicator Setting

### The Lookback Period

The lookback period, often denoted as *N*, is the number of days used to compute the Triple Exponential Moving Average. While 14 days is a commonly recommended starting point, the best lookback period can vary depending on:

**Trading Style**:**Short-term traders**may prefer a shorter lookback period (e.g., 7 to 10 days) to capture short-term market movements.**Long-term investors**might opt for a longer period (e.g., 20 to 28 days) to focus on the broader market trend and avoid being influenced by short-term volatility.

**Market Volatility**:- In highly volatile markets, a longer lookback period can help filter out noise and focus on the underlying trend.
- In more stable or sideways markets, a shorter period might be more responsive to genuine trend shifts.

**Asset Type**:- Different assets have different volatilities and behaviors. For instance, cryptocurrencies might need a different lookback period than traditional stocks.

### Signal Line Setting

Typically, the signal line is a 9-day EMA of the TRIX. However, traders can adjust this based on their objectives:

**Shortening the Signal Line**: This makes it more reactive to TRIX changes, potentially leading to earlier signals. This might result in more false signals but quicker entries and exits.**Lengthening the Signal Line**: This will delay signals, potentially filtering out short-lived price moves but might also result in entering or exiting a position late.

(You can change both the lookback period and the Signal line setting in Part 4 of the Python tutorial code later in this post.)

### Optimization Techniques

To determine the best settings for the TRIX indicator, traders might employ:

**Backtesting**: By applying different settings to past data, traders can evaluate which would have been the most profitable in historical scenarios.**Walk-forward Analysis**: This method involves optimizing on a historical dataset and then testing on a more recent dataset. It helps to confirm if the optimized settings are robust and not just curve-fitted to past data.**Sensitivity Analysis**: By slightly altering the lookback and signal line periods, traders can evaluate how sensitive their strategies are to changes in these settings.

### Complementary Indicators

Considering the integration of other technical indicators can also play a role in setting adjustments. For instance, if using the TRIX indicator in conjunction with the Relative Strength Index (RSI), the settings for both indicators should be harmonized to ensure they provide complementary signals.

## Pros and Cons

Like any technical analysis tool, the this indicator has its strengths and weaknesses. On the plus side, it’s excellent at filtering out market noise and identifying the underlying trend. It also provides valuable insights into market momentum and potential trend reversals.

However, the TRIX indicator is not infallible. It can produce false signals, particularly in volatile markets. The selection of the lookback period is subjective and can impact the indicator’s responsiveness. A shorter lookback period will make the TRIX more responsive to recent price changes, but it might also increase the chance of false signals. Whereas, a longer lookback period will smooth out the fluctuations more, but it could lead to a delay in signalling trend changes.

Like all technical indicators, it should not be used in isolation but in conjunction with other tools and analysis methods to bring about more confidence in its signals.

## Coding it in Python and Plotting it on a Chart

This guide assumes that you have Python installed on your computer. If not, you can download it from the official Python website.

**Step 1: Install Visual Studio Code and Python Extension**

- Download and install Visual Studio Code from the official website (free from Microsoft).
- Open Visual Studio Code.
- Click on the Extensions view icon on the Sidebar (or press

).**Ctrl+Shift+X** - Search for

.**Python** - Click on the Install button to install the Python extension for Visual Studio Code.

**Step 2: Install Required Python Libraries**

Before we start coding, we need to install some Python libraries that our script will use. Open a new terminal in VSCode by clicking on

from the menu bar. Then, type the following commands and press Enter after each one to install the necessary libraries:**Terminal > New Terminal**

```
pip install yfinance
pip install pandas
pip install mplfinance
pip install matplotlib
```

**Step 3: Create a New Python File**

- Click on the Explorer view icon on the Sidebar (or press

).**Ctrl+Shift+E** - Click on the New File button.
- Name the file

.**trix_indicator.py**

**Step 4: Write the Python Script**

Now, we’ll write our Python script. We’ll break it down into smaller parts and explain what each part does.

**Part 1: Import Libraries**

First, we need to import the libraries that we’ll use in our script. Copy the following code into your

file:**trix_indicator.py**

```
import yfinance as yf
import pandas as pd
import mplfinance as mpf
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
```

Here’s what each line does:

: This imports the**import yfinance as yf**library, which we’ll use to download financial data from Yahoo Finance.`yfinance`

: This imports the**import pandas as pd**`pandas`

library, which we’ll use for data manipulation and analysis.

: This imports the**import mplfinance as mpf**

library, which we’ll use to create financial plots.**mplfinance**

: This imports the**import matplotlib.pyplot as plt**

module from the**pyplot**`matplotlib`

library, which we’ll use to create plots.

: This imports the**from matplotlib.lines import Line2D**`Line2D`

class from the

module, which we’ll use to create custom legend lines for our plot.**matplotlib.lines**

: This imports the**import numpy as np**

library, which we’ll use for numerical operations.**numpy**

**Part 2: Define the TRIX Calculation Function**

Next, we’ll define a function to calculate the TRIX indicator. Copy the following code into your

file beneath the imports from above:**trix_indicator.py**

```
def calculate_trix(data, lookback):
ex1 = data['Close'].ewm(span=lookback, adjust=False).mean()
ex2 = ex1.ewm(span=lookback, adjust=False).mean()
ex3 = ex2.ewm(span=lookback, adjust=False).mean()
trix = 100 * (ex3.diff() / ex3)
return trix
```

If you refer back to the *Mathematical Construction* section of this post, this is how the above code caters to it:

**First Exponential Moving Average (EMA1):**This is calculated with the line

. The**ex1 = data['Close'].ewm(span=lookback, adjust=False).mean()**

function in pandas calculates an exponential weighted function, which is used here to calculate the EMA of the closing prices. The**ewm**

parameter is equivalent to the ‘N’ in your Alpha formula, and**span**

makes it an exponentially decreasing weight.**adjust=False****Second Exponential Moving Average (EMA2):**This is calculated with the line

. It’s the same as the first EMA, but it’s calculated on the first EMA values (EMA1).**ex2 = ex1.ewm(span=lookback, adjust=False).mean()****Third Exponential Moving Average (EMA3):**This is calculated with the line

. It’s the same as the first and second EMAs, but it’s calculated on the second EMA values (EMA2).**ex3 = ex2.ewm(span=lookback, adjust=False).mean()****Calculate the TRIX:**This is calculated with the line

. The**trix = 100 * (ex3.diff() / ex3)**`diff`

function calculates the difference between the current and a prior element, which corresponds to

. This difference is then divided by**(EMA3(today) â€“ EMA3(previous day))**

and multiplied by 100 to get the TRIX.**EMA3(previous day)**

**Part 3: Fetch the Data**

Next, we’ll fetch the financial data that we’ll use to calculate the TRIX indicator. Copy the code once again into your

file:**trix_indicator.py**

```
# Fetch the data
data = yf.download('^RUT', start='2022-07-01', end='2023-07-01')
```

This line of code uses the

function from the **download**

library to download the historical market data for the Russell 2000 index (**yfinance**

) from Yahoo Finance. The **^RUT**

and **start**

parameters specify the date range for the data.**end**

**Part 4: Calculate the TRIX and Signal Line**

Now, we’ll calculate TRIX and its signal line. You know to add it into the file again by now:

```
# Calculate the TRIX
data['TRIX'] = calculate_trix(data, 14)
# Calculate the Signal line
data['Signal'] = data['TRIX'].ewm(span=9, adjust=False).mean()
```

The first line calculates the TRIX indicator using the

function we defined earlier and adds it as a new column to our DataFrame. The signal line, which is a 9-day EMA of the TRIX, is calculated with the line **calculate_trix**

. This is not part of the TRIX calculation itself, but it’s often used in conjunction with the TRIX for generating trading signals. This is also added to the DataFrame as a new column.**data['Signal'] = data['TRIX'].ewm(span=9, adjust=False).mean()**

**Part 5: Add the 0 Line**

Next, we’ll add a 0 line, which the TRIX oscillates around:

```
# Add 0 line
data['0 Line'] = 0
```

This line adds a new column to our DataFrame filled with the value 0.

**Part 6: Define the Additional Plots**

Now, we’ll define the additional plots for our chart.

```
# Define the additional plots as a list of dictionaries
apd = [
mpf.make_addplot(data['TRIX'], panel=2, color='b', secondary_y=False, ylabel='TRIX'),
mpf.make_addplot(data['Signal'], panel=2, color='r', secondary_y=False),
mpf.make_addplot(data['0 Line'], panel=2, color='black', secondary_y=False, linestyle='dashed')
]
```

This code defines three additional plots for our chart: the TRIX line, the signal line, and the 0 line. The

function from the **make_addplot**

library is used to create each plot.**mplfinance**

**Part 7: Create the Chart**

Finally, we’ll create the chart. As with the blocks of code above copy it into your

file:**trix_indicator.py**

```
# Create a subplot for the TRIX and add the additional plot
fig, axes = mpf.plot(data, type='candle', style='yahoo', addplot=apd, volume=True, panel_ratios=(5, 1, 3), title='Russell 2000 and TRIX', returnfig=True)
# Create legend using dummy lines
legend_lines = [Line2D([0], [0], color=c, lw=1.5, linestyle=ls) for c, ls in zip(['b', 'r', 'black'], ['solid', 'solid', 'dashed'])]
axes[2].legend(legend_lines, ['TRIX', 'Signal', '0 Line'], loc='lower left')
# Show the plot
mpf.show()
```

This code creates a candlestick chart of the Russell 2000 index with the TRIX.

**Part 8: Run the Python Script**

Now that we’ve written our Python script, it’s time to run it. Here’s how:

- Save your

file by clicking on**trix_indicator.py**

from the menu bar or by pressing**File > Save**

. At this point you can likely just click the play icon in the top right of VSCode to run it, otherwise read on.**Ctrl+S** - Open a new terminal in VSCode by clicking on

from the menu bar.**Terminal > New Terminal** - In the terminal, navigate to the directory where you saved your

file using the**trix_indicator.py**

command. For example, if you saved your file in a directory named**cd**

on your desktop, you would type**python_scripts**

and press Enter.**cd Desktop/python_scripts** - Once you’re in the correct directory, type

and press Enter to run your script.**python trix_indicator.py**

If everything goes well, you should see a chart of the Russell 2000 index with the TRIX, signal line, and 0 line plotted on the third panel.

It ought to look like mine shown here:

**Customizing the Script**

You can customize this script to suit your needs. Here are a few things you might want to change:

- To change the index or stock that the script analyzes, replace
`'`

with the ticker symbol of your choice.**^RUT**' - To change the date range that the script analyzes, modify the

and**start**

parameters in the**end**

function.**yf.download** - To change the lookback period used to calculate the TRIX, replace

in the**14**

line with the number of periods you want to use.**calculate_trix(data, 14)** - To change the period used to calculate the signal line, replace

in the**9**

line with the number of periods you want to use. It is the span or the number of periods over which the Exponential Moving Average (EMA) for the signal line is calculated.**data['Signal'].ewm(span=9, adjust=False).mean()**

Remember to save your changes and rerun the script to see the updated chart.

## TRIX Indicator vs. Other Indicators

Lets’ take a look at the similarities and differences of this indicator with the Moving Average Convergence Divergence (MACD), another popular momentum oscillator.

**TRIX:**

As we have already explored in this post, this indicator is a momentum oscillator that applies triple exponential smoothing to filter out market noise and highlight the underlying trend. It oscillates around a zero line, with positive values indicating upward momentum and negative values indicating downward momentum. Traders often add a signal line, typically a 9-day EMA of the TRIX line, to generate trading signals based on crossovers. It’s particularly useful for identifying overbought and oversold conditions and spotting potential price reversals through bullish and bearish divergences.

**MACD:**

The MACD is also a momentum oscillator, but it operates differently from the triple exponential moving average oscillator. The MACD is calculated by subtracting a long-term exponential moving average (EMA) from a short-term EMA. This results in the MACD line. A signal line, which is an EMA of the MACD line, is then plotted on top of the MACD line. Traders look for crossovers between the MACD line and the signal line as potential trading signals.

**Key Differences:**

**Smoothing Mechanism:**The TRIX uses triple exponential smoothing, which helps to reduce market noise more effectively than the MACD’s dual EMA calculation. This makes the the triple exponential moving average indicator potentially more reliable in volatile markets.**Signal Generation:**While both indicators generate signals based on crossovers with their respective signal lines, the TRIX indicator also generates signals when it crosses the zero line.**Trend Identification:**The TRIX, with its triple smoothing, is particularly adept at identifying the underlying trend in the market. While the MACD can also identify trends, it may be more susceptible to false signals due to market noise.**Divergence Detection:**Both the TRIX and MACD can be used to spot bullish and bearish divergences, which can signal potential trend reversals. However, the TRIX’s triple smoothing may make it more effective at filtering out false divergence signals.

In conclusion, while both the TRIX indicator and the MACD have their uses, the choice between them depends on your trading style, risk tolerance, and the specific market conditions. It’s always a good idea to use these indicators in conjunction with other technical analysis tools and methods to confirm their signals.

Indicator | Smoothing Mechanism | Signal Generation | Trend Identification | Divergence Detection |
---|---|---|---|---|

TRIX | Triple exponential smoothing | Zero-line and signal line crossovers | Excellent, particularly effective in reducing market noise | Possible through bullish and bearish divergences |

MACD | Dual EMA calculation | Signal line crossovers | Good, but may be more susceptible to false signals due to market noise | Possible through bullish and bearish divergences |

## Key Takeaways

- The TRIX Indicator is a momentum oscillator that applies triple exponential smoothing to filter out market noise and highlight the underlying trend. It is particularly useful in volatile markets.
- It is calculated using a series of exponential moving averages (EMAs). The process involves three rounds of smoothing, which helps to reduce market noise and highlight the underlying trend.
- The indicator is not just about identifying trends; it’s also about understanding the momentum behind these trends. By displaying the rate of change of a triple exponentially smoothed moving average, it provides insights into the strength or weakness of a trend.
- it can be used in trading to identify potential buying and selling opportunities. It is particularly useful for spotting bullish and bearish divergences, which can signal potential trend reversals.
- It should not be used in isolation but in conjunction with other tools and analysis methods to confirm its signals.
- The Python implementation provided in the article allows you to calculate the TRIX and plot it on a chart. You can customize this code to suit your needs, such as changing the index or stock that the script analyzes, modifying the date range, or adjusting the lookback period used to calculate the TRIX. You could then go on to develop a screener for your strategy with this insight.
- The TRIX indicator and the MACD both are momentum oscillators, but they operate differently. The choice between them depends on your trading style, risk tolerance, and the specific market conditions.

## Further Reading

“*Technical Analysis from A to Z*” by Steven B. Achelis**:** Published by McGraw Hill; 2nd edition (January 13, 2001). This book covers a wide range of technical analysis tools, including the TRIX indicator.

If interested in other technical indicators in general, you should look at something like, “*Technical Analysis: The Complete Resource for Financial Market Technicians*” by Charles D. Kirkpatrick II and Julie R. Dahlquist: Published by FT Press; 3rd edition (October 22, 2015). Although it doesn’t cover TRIX.

## Leave a Reply