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

Highlight

  • Article Difficulty:★★☆☆☆
  • This article is adapted from KD Indicator, utilizing TQuant Lab for strategy optimization and adjustment.
  • The built-in factors in TQuant Lab were used to calculate the KD indicator and determine 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.

Source Code

Extended Reading

About

想看更多內容?快來【登入會員】,享受更多閱讀文章的權限喔!
Back