【Application】TQuant Lab KD Indicator Strategy: Exploring Stock Price Reversal Timing?

TEJ 台灣經濟新報
TEJ-API Financial Data Analysis
7 min readApr 19, 2024

--

KD Indicator Strategy
Photo by 愚木混株 cdd20 on Unsplash

Highlight

  • Article Difficulty:★★☆☆☆
  • This article is adapted from KD Indicator, utilizing TQuant Lab for strategy optimization and adjustment.
  • Using the built-in factors in TQuant Lab to calculate the KD indicator, and determining stock price reversal timing through the indicator. Comparing the KD Indicator Strategy’s performance from (2020–01–01 to 2024–04–10) to assess if excess returns can be earned.

Preface

The KD Indicator, also known as the Stochastic Oscillator, is a practical and widely used tool in technical analysis. It’s primarily used to determine the short-term strength of stock prices and potential reversal timing. The value of the KD indicator ranges from 0 to 100, with 50 generally serving as the dividing line. When the indicator is above 50, it indicates that the stock price is in a bullish phase; conversely, when the stock price is below 50, it is considered to be in a bearish phase. Additionally, when the KD indicator is below 20, stocks often show signs of being oversold, indicating a potential upward reversal at any time; on the other hand, when the KD indicator is above 80, stocks often exhibit signs of being overbought, suggesting a potential downward reversal at any time. Therefore, this tool is a valuable resource for constructing trading signals for buying and selling stocks, empowering traders with timely and informed decisions.

The calculation process of the KD indicator is as follows:

  • RSV = ( ( Today’s closing price — Lowest price in the past N days ) / ( Highest price in the past N days — Lowest price in the past N days ) ) * 100
  • K value = Yesterday’s K value × (2/3) + Today’s RSV × (1/3)
  • D value = Yesterday’s D value × (2/3) + Today’s K value × (1/3)

From the above formulas, RSV can be interpreted as the strength or weakness of today’s stock price relative to the prices over the past N days. K value, also known as the Fast Stochastic Oscillator, is heavily influenced by the strength or weakness of today’s stock price. On the other hand, the calculation principle of D value is akin to applying another level of smoothing. Hence, it reacts more slowly to current price changes.

Moreover, the value of N in the equations represents the moving window for calculating the indicator. This value can be adjusted according to different investment characteristics, offering a flexible and versatile approach. Setting a larger N value can stabilize the KD values and provide more precise reversal signals based on a more extended historical period, which is suitable for medium- to long-term investors. Conversely, a smaller N value will make the KD indicator more sensitive and suitable for short-term investors. This adaptability allows the KD Indicator to cater to a wide range of investment strategies, making it a valuable tool for all types of traders.

KD Indicator Strategy

In this article, we employ the KD indicator to determine stock price reversal timing and utilize the following entry and exit rules to establish a trading strategy and conduct backtesting:

  • When K ≤ 20: Buy, as it represents a weaker stock price and an oversold market condition.
  • When K ≥ 80: Sell, indicating an overheated market, thus opting for profit-taking.

Additionally, since this strategy involves a longer backtesting period, the value of N is 36 days instead of the more common 14-day window length used in calculating the KD indicator.

Coding Environment and Module Requirements

This article is written using Windows 11 and Jupyter Lab as the editor.

import pandas as pd
import numpy as np
import os

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 and Data Import

  1. Using get_universe to select stocks from the Taiwan 50 Index from 2012-01-01 to 2019-12-31.
  2. Setting the backtesting period from 2020–01–01 to 2024–04–10, and importing price and volume data using !zipline ingest -b tquant.
from zipline.sources.TEJ_Api_Data import get_universe

# get the stock list from Taiwan 50 index
StockList = get_universe('2012-01-01', '2019-12-31', idx_id = 'IX0002')
StockList.append('IR0001')

# set backtest period
start = '2020-01-01'
end = '2024-04-10'

os.environ['ticker'] = ' '.join(StockList)
os.environ['mdate'] = start + ' ' + end

!zipline ingest -b tquant

Construct the KD Indicator Strategy

From the pipeline and zipline function provided in TQuant Lab, we can:

  1. Calculate the K value using the built-in factors from pipeline.
  2. Add liquidity slippage, transaction fees, and set the return of TWSE Weighted Stock Return Index as the benchmark.
  3. Set the KD Indicator Strategy and record the transaction details.
KD Indicator Strategy
Pipeline Calculation Results

Execute the Trading Strategy

We use run_algorithm() function to execute the configured KD Indicator Strategy with the trading period from 2020-01-01 to 2024-04-10 and with the initial capital of 10,000,000 NTD. The output, or results, will represent the daily performance and detailed transaction records.

from zipline import run_algorithm

start_date = pd.Timestamp('2020-01-01',tz='utc')
end_date = pd.Timestamp('2024-04-10',tz='utc')

results = run_algorithm(start = start_date,
end = end_date,
initialize = initialize,
capital_base = 1e7,
handle_data = handle_data,
data_frequency = 'daily',
bundle = 'tquant'
)
results
KD Indicator Strategy
Trading Details

Performance Evaluation Using Pyfolio

import pyfolio as pf

returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(results)
benchmark_rets = results.benchmark_return

# Creating a Full Tear Sheet
pf.create_full_tear_sheet(bt_returns, positions = positions, transactions = transactions,
benchmark_rets = benchmark_rets)
KD Indicator Strategy
Backtesting Performance Compared to Benchmark

Through the above chart, it can be observed that the market has doubled its returns over the past four years. In contrast, the KD Indicator Strategy only achieved a cumulative return of approximately 17.7%. The annualized return rate and annualized volatility were 4% and 17.1% respectively. This has resulted in a performance gap between the KD Indicator Strategy and the market during the backtesting period. The author believes there are three main reasons for this:

  1. Indicator lag: During the early stages of a market rally, as stock prices gradually climb, the KD indicator reaches an overbought signal of ≥ 80, prompting the strategy to liquidate positions. This prevents it from benefiting from subsequent sustained upward price movements.
  2. Missed timing of buying and selling points: We use K values of 20 and 80 as entry and exit points for trades in this implementation. However, some stocks may start to rise before falling below 20, while others may encounter selling pressure before crossing 80. In such cases, the KD Indicator Strategy fails to generate returns.
  3. Generation of false trading signals: False trading signals may occur in highly volatile stocks, where significant price fluctuations lead to incorrect interpretations by the indicator. For example, the KD Indicator Strategy may generate a buy signal, but the stock is actually experiencing sideways volatility.

Regarding the above three points, we can improve the KD Indicator Strategy by combining it with other indicators, such as factors that assist in identifying indicator divergences ( for application of indicator divergences, please refer to TQuant Lab RSI Moving Average Strategy — Identifying Reversals in Oversold Conditions ), or by integrating indicators like MACD. We will leave this for further exploration in the future.

Conclusion

This strategy was inspired by the KD Indicator, utilizing TQuant Lab to incorporate multiple stocks and the built-in factor library of Pipeline to accelerate calculating the K value required for the KD Indicator Strategy. Subsequently, the backtesting of the KD Indicator Strategy was conducted. Although the backtest results were not entirely satisfactory, we observed three drawbacks of the KD Indicator Strategy: indicator lag, missed timing of buying and selling points, and the generation of false trading signals. Investors should also be mindful of these situations when using the KD indicator. Otherwise, combining it with other indicators to assist in entry and exit decisions is preferable.

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 TQuant Lab. With our high-quality databases, you can construct a trading strategy that suits your needs.

[TQuant Lab] Solving Your Quantitative Finance Pain Points Comprehensively providing all the tools needed for trading backtesting.

Register and Start Your Trial

Source Code

Extended Reading

About

--

--

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

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