【Application】SuperTrend Strategy: Buy Low, Sell High to Profit from Market Swings

TEJ 台灣經濟新報
TEJ-API Financial Data Analysis
10 min readAug 30, 2024
SuperTrend Strategy
Photo by rc.xyz NFT gallery on Unsplash

Highlight

  • Article Difficulty: ★★★☆☆
  • Introduce the SuperTrend Indicator and the Average Directional Index ( ADX ).
  • Explain the SuperTrend Strategy and how to optimize it using the ADX indicator.
  • Utilize TQuant Lab to backtest the SuperTrend Strategy and observe its effectiveness in capturing market swings.

Preface

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.

SuperTrend Indicator & ADX Indicator

SuperTrend Strategy
SuperTrend Indicator Diagram from TradingView

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.

SuperTrend Indicator Formula

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 difference between the day’s high and low prices.
  • The difference between the previous day’s closing price and the current day’s high price.
  • The difference between the previous day’s closing price and the current day’s low price.

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:

  • Basic upper band = ( High + Low ) / 2 + Multiplier × ATR
  • Basic lower band = ( High + Low ) / 2 — Multiplier × ATR

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

  • Final upper band: If the new basic upper band is lower than the previous final upper band, or if the previous day’s closing price is higher than the previous final upper band, the new basic upper band is used. Otherwise, the previous final upper band is retained.
  • Final lower band: If the new basic lower band is higher than the previous final lower band, or if the previous day’s closing price is lower than the previous final lower band, the new basic lower band is used. Otherwise, the previous final lower band is retained.

ADX Indicator Formula

The ADX indicator ranges from 0 to 100, with the following interpretations:

  1. ADX < 25: Weak market trend, indicating a consolidation phase.
  2. 25 < ADX < 50: The market is forming a moderate trend.
  3. ADX > 50: The market has established a strong trend.

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 )

  • +DM: If ( Today’s High — Yesterday’s High ) > ( Yesterday’s Low — Today’s Low ), then +DM = max ( Today’s High — Yesterday’s High, 0 ). Otherwise, +DM = 0.
  • -DM: If ( Yesterday’s Low — Today’s Low ) > ( Today’s High — Yesterday’s High ), then -DM = max ( Yesterday’s Low — Today’s Low, 0 ). Otherwise, -DM = 0.

Step3: Calculate +DI, -DI ( Directional Indicator )

  • +DI: 100 × ( Moving Average of +DM / ATR )
  • -DI: 100 × ( Moving Average of -DM / ATR )

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.

SuperTrend Strategy

Coding Environment and Module Requirements

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

Selecting Stock Pool

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()

Trading Data Import

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

Trading Data Processing

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:

  • Import daily closing prices.
  • Calculate the final upper and lower bands of the SuperTrend Indicator.
  • Calculate the ADX indicator.
SuperTrend Strategy
Pipeline Results to be Used in Our Strategy

Construct the SuperTrend Strategy

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:

  • Long Entry: If the closing price breaks above the final upper band, this indicates a potential upward trend as the price breaks through resistance, leading to proportionate buying across the stock pool.
  • Short Entry: If the closing price falls below the final lower band, and the ADX > 50, this indicates a potential downward trend as the price breaks through support, leading to selling of holdings.

From the zipline functions provided in TQuant Lab, we can:

  1. Add liquidity slippage and transaction fees, and set the return of the TAIEX-Total Return Index as the benchmark.
  2. Add the calculated pipeline results into the trading proess.
  3. Set the SuperTrend Strategy and record the transaction details.

Execute the Trading Strategy

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.

SuperTrend Strategy
Trading Details

Performance Evaluation Using Pyfolio

SuperTrend Strategy
Backtesting Performance Compared to Benchmark

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.

SuperTrend Strategy
underwater plot

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.

Individual Stock Performance under the SuperTrend Strategy

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.

SuperTrend Strategy
TSMC SuperTrend Strategy Performance Chart

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.

Conclusion

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.

Source Code

Extended Reading

About

--

--

TEJ 台灣經濟新報
TEJ-API Financial Data Analysis

TEJ 為台灣本土第一大財經資訊公司,成立於 1990 年,提供金融市場基本分析所需資訊,以及信用風險、法遵科技、資產評價、量化分析及 ESG 等解決方案及顧問服務。鑒於財務金融領域日趨多元與複雜,TEJ 結合實務與學術界的精英人才,致力於開發機器學習、人工智慧 AI 及自然語言處理 NLP 等新技術,持續提供創新服務