Table of Contents
The SuperTrend Indicator is a technical analysis tool used to identify trends in financial markets. It assists investors in determining relative high and low points during market swings, helping them make buy and sell decisions. This makes the SuperTrend Indicator especially suitable for investors who need help discerning market directions or frequently exit trades too early, missing out on potential gains. However, one drawback of the SuperTrend Indicator is its tendency to be less effective during consolidation phases. To address this, we will use the Average Directional Index ( ADX ) to optimize the SuperTrend strategy in this article.
The ADX indicator, developed by J. Welles Wilder in 1978, measures the strength of a trend and ranges from 0 to 100, with higher values indicating more robust trends. By combining the SuperTrend Indicator with the ADX, we can more effectively differentiate between trending and consolidating phases. This allows us to construct a SuperTrend strategy, which we will backtest using TQuant Lab to evaluate its performance in capturing market swings.
The diagram above illustrates the SuperTrend Indicator applied to a price chart. We can observe that the SuperTrend Indicator effectively identifies upward trending phases; however, it produces noise during consolidation phases, leading to less reliable signals. To mitigate this, we pair the SuperTrend Indicator with the ADX, which helps us determine the trend’s strength. This combination allows us to construct a more robust SuperTrend strategy. Below, we will explain the formulas behind the SuperTrend and ADX indicators to provide insight into their inner workings.
Although the SuperTrend Indicator appears as a single line in the chart, it comprises two bands—an upper and a lower band. When the closing price breaks above the upper band, it signals a potential upward trend, with the lower band becoming the new support level. Conversely, if the closing price falls below the lower band, it indicates a possible downward trend, with the upper band becoming the new resistance. The SuperTrend Indicator we see is formed by the support level ( the lower band ) during an uptrend and the resistance level ( the upper band ) during a downtrend.
To calculate the upper and lower bands of the SuperTrend Indicator, we need to follow three steps:
Step1: Calculate ATR
The ATR ( Average True Range ) is based on the TR ( True Range ), which represents the maximum price movement within a specific period. The TR is usually determined by the greatest absolute value among the following three differences:
The ATR is obtained by applying a moving average to the TR over a specified period, typically 14 days.
p.s. For more applications of ATR, you can refer to: TQuant Lab Loss Aversion Strategy — Average True Range.
Step2: Calculate Basic Upper and Lower Bands
The formulas for the basic upper and lower bands are as follows:
The Multiplier is a factor used to adjust the distance of the bands, commonly set to 2 or 3.
Step3: Calculate Final Upper and Lower Bands
The ADX indicator ranges from 0 to 100, with the following interpretations:
The ADX calculation involves four steps:
Step1: Calculate ATR
The ATR is calculated in the same manner as in the SuperTrend Indicator.
Step2: Calculate +DM, -DM ( Directional Movement )
Step3: Calculate +DI, -DI ( Directional Indicator )
Step4: Calculate ADX
DX = 100 × ( |+DI – (-DI)| / |+DI + (-DI)| )
The ADX is obtained by applying a moving average to the DX over a specified period.
The following demonstrates how we will generate the trading signals required for the SuperTrend strategy using TQuant Lab.
This article is written using Windows 11 and Jupyter Lab as the editor.
import os
import numpy as np
import pandas as pd
# tej_key
tej_key = 'your key'
api_base = 'https://api.tej.com.tw'
os.environ['TEJAPI_KEY'] = tej_key
os.environ['TEJAPI_BASE'] = api_base
Given the characteristics of the SuperTrend Indicator, we aim to select stocks with growth potential and a tendency to trend. Therefore, we use the get_universe
function to obtain the electronics industry stocks which had been listed at the end of 2018 and filter for the top 10 by market capitalization using the TEJ Tool API
.
from zipline.sources.TEJ_Api_Data import get_universe
pool = get_universe(start = '2018-12-28',
end = '2018-12-28',
mkt_bd_e = 'TSE', # Listed stock in Taiwan
stktp_e = 'Common Stock',
main_ind_c = 'M2300 電子工業' # Electronics Industry
) # or use `main_ind_e = M2300 Electronics`
import TejToolAPI
mktcap_data = TejToolAPI.get_history_data(start = '2018-12-28',
end = '2018-12-28',
ticker = pool,
columns = ['Market_Cap_Dollars']
)
tickers = mktcap_data.nlargest(10, 'Market_Cap_Dollars')['coid'].tolist()
With the backtest period set from Jan 1, 2019, to Jul 1, 2024, we import the price and volume data of the 10 selected stocks and the TAIEX-Total Return Index ( IR0001 ) as the performance benchmark.
start = '2019-01-01'
end = '2024-07-01'
os.environ['mdate'] = start + ' ' + end
os.environ['ticker'] = ' '.join(tickers) + ' ' + 'IR0001'
!zipline ingest -b tquant
With the price and volume data in hand, we can use the CustomFactor
function to construct the upper and lower bands of the SuperTrend Indicator and the ADX indicator. Additionally, to optimize trend detection and reduce short-term noise, we set the ATR calculation period for the SuperTrend Indicator to 50 days and the Multiplier to 4. The ADX calculation period is 14 days to allow timely trend strength assessment.
The detailed construction of the CustomFactor
function can be found in the GitHub source code: TQuant Lab SuperTrend Strategy.
Furthermore, with the Pipeline
function, we can quickly integrate quantitative indicators and price-volume data of multiple stocks. In this case, we use it to handle:
Start Building Portfolios That Outperform the Market!
As mentioned at the beginning of the article, we aim to use the ADX indicator to identify sufficiently strong trends before entering trades to mitigate the disadvantage of the SuperTrend Indicator in recognizing consolidation phases. However, when constructing the buy signal, we do not avoid consolidation phases because these can be viewed as periods of rest in the market, where energy is accumulated, making them an ideal time to enter positions. On the other hand, when constructing the sell signal, we incorporate the ADX indicator to ensure that a downtrend has begun before selling holdings to avoid missing out on previous uptrend gains.
The entry and exit rules for the SuperTrend strategy are as follows:
From the zipline
functions provided in TQuant Lab, we can:
We use run_algorithm()
function to execute the configured SuperTrend Strategy with the trading period from 2019-01-01 to 2024-07-01 and with the initial capital of 1,000,000 NTD. The output, or results, will represent the daily performance and detailed transaction records.
As shown in the table above, the SuperTrend strategy achieved an annualized return of 25.88%, with a relatively low annualized volatility of around 13%. When further examining the performance metrics, the Sharpe ratio is 1.84, and the Sortino ratio is 2.82, indicating that the SuperTrend strategy effectively avoids downside risks while earning excess returns with relatively lower risk. Observing the performance curve, although the SuperTrend strategy did not significantly outperform the market, we can see that after reaching a peak at the beginning of 2021, the returns leveled off until mid-2022, successfully avoiding the significant downturn of the 2022 bear market. Moreover, there was a good recovery trend after 2023, demonstrating the SuperTrend strategy’s ability to lock in profits during uptrends and preemptively avoid downside risks.
The underwater plot chart shows that the two most significant drawdowns occurred during the pandemic in early 2020 and the bear market in 2022. However, compared to the 30% drawdown experienced by the broader market during these periods, the SuperTrend strategy’s 16% and 14% drawdowns were relatively minor.
Using the Pipeline result table and the transaction details generated by run_algorithm()
, we created an additional function, graph()
, to help us understand the performance of individual stocks under the SuperTrend strategy.
The construction method of graph()
can be referenced from the GitHub source code: TQuant Lab SuperTrend Strategy.
In the chart above, red dots represent entry points, and green dots represent exit points. We can see that the SuperTrend strategy successfully profited during the uptrend from 2019 to 2020. However, during the consolidation phase in 2021 and the downtrend in 2022, there were some cases where it bought at relatively high points, indicating a failure. Fortunately, the sell points optimized by the ADX indicator limited some of the losses, and the buy point in 2023 successfully captured the profits up to July 2024.
This strategy was inspired by the SuperTrend indicator. Given the indicator’s failure during consolidation phases, we used the ADX indicator to optimize the strategy and reduce short-term trading noise. From the performance analysis charts generated by Pyfolio, we observed that the SuperTrend strategy effectively avoids downside risks. We also examined TSMC’s performance under this strategy and found that it effectively captured trend gains.
It is important to remind investors that the strategy construction in this article involves selecting a stock pool and parameter settings for indicator calculations. Different stock pools and parameter settings may affect performance. Investors interested in this strategy are encouraged to experiment with different settings to construct the most effective investment strategy.
Please note that the strategy and target discussed in this article are for reference only and do not constitute any recommendation for specific commodities or investments. In the future, we will also introduce using the TEJ database to construct various indicators and backtest their performance. Therefore, we welcome readers interested in various trading strategies to consider purchasing relevant solutions from Quantitative Finance Solution. With our high-quality databases, you can construct a trading strategy that suits your needs.
“Taiwan stock market data, TEJ collect it all.”
The characteristics of the Taiwan stock market differ from those of other European and American markets. Especially in the first quarter of 2024, with the Taiwan Stock Exchange reaching a new high of 20,000 points due to the rise in TSMC’s stock price, global institutional investors are paying more attention to the performance of the Taiwan stock market.
Taiwan Economical Journal (TEJ), a financial database established in Taiwan for over 30 years, serves local financial institutions and academic institutions, and has long-term cooperation with internationally renowned data providers, providing high-quality financial data for five financial markets in Asia.
With TEJ’s assistance, you can access relevant information about major stock markets in Asia, such as securities market, financials data, enterprise operations, board of directors, sustainability data, etc., providing investors with timely and high-quality content. Additionally, TEJ offers advisory services to help solve problems in theoretical practice and financial management!
Subscribe to newsletter