TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (2024)

TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (1)

Table of Contents

Highlight

  • Article Difficulty:★★☆☆☆
  • This article focuses on developing a trading strategy (RSI Moving Average Strategy) using the Relative Strength Index (RSI) divergence and simple moving averages to determine entry and exit points.
  • Utilizing the TQuant Lab backtesting platform to formulate trading strategies and assess the associated risks and performance.

Preface

The Relative Strength Index (RSI) is a widely popular oscillating technical indicator that calculates the relative strength between buyers and sellers. When the RSI is above 50, it indicates more substantial buying power; when the RSI is below 50, it signals more substantial selling power. In technical analysis, an RSI exceeding 70 is generally considered overbought, while an RSI below 30 is considered oversold. Moreover, RSI is a leading indicator, often anticipating price highs/lows, enabling early detection of market reversals and facilitating contrarian trading strategies.

In addition, since RSI itself lacks directional information, we can complement it with moving averages to determine the market as illustrated bellow:

TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (2)

We can observe that the stock price increases when the moving average declines and the RSI rises above the low point in the oversold zone. Similarly, when the moving average ascends, and the RSI falls below the low point in the overbought zone, the stock price declines shortly afterward. J. W. Wilder, the developer of RSI, once mentioned that displaying divergence is the “greatest strength” of RSI.

The key to identifying the divergence lies in first drawing support/resistance lines on the RSI and then doing the same for the price. Look for the two troughs for the support line and the two peaks for the resistance line. If the direction of the lines is different, it indicates divergence, signaling a potential market reversal in the direction indicated by the RSI.

Coding Environment

This article is composed in MacOS, utilizing Jupyter Notebook as the primary editor.

Data Import

import osos.environ['TEJAPI_KEY'] = "your key" os.environ['TEJAPI_BASE'] = "https://api.tej.com.tw"import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom zipline.data import bundlesfrom zipline.utils.calendar_utils import get_calendarfrom zipline.sources.TEJ_Api_Data import get_Benchmark_Return

Data Period: January 1, 2021, to December 31, 2023

Using the get_universe function, obtain Chemical Biotechnology and Medical Care sectors stock pool. Additionally, the Chemical Biotechnology and Medical Care Return Index (IX0019) was included as a benchmark for market comparison.

from zipline.sources.TEJ_Api_Data import get_universestart = '2021-01-01'end = '2023-12-31'pool = get_universe(start, end, mkt = 'TWSE', stktp_e = 'Common Stock', main_ind_e = 'M1700 Chemical Biotechnology & Medical Care')print(f'total stock: {len(pool)}:\n', pool)start_dt, end_dt = pd.Timestamp(start, tz='utc'), pd.Timestamp(end, tz='utc')tickers = ' '.join(pool)os.environ['ticker'] = tickers+' IX0019'os.environ['mdate'] = start+' '+end!zipline ingest -b tquantbundle = bundles.load('tquant')benchmark_asset = bundle.asset_finder.lookup_symbol('IX0019',as_of_date = None)
TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (3)

Trading Rules for RSI Moving Average Strategy

  1. Buy Signal:
    • When the RSI is below 30, the RSI slope is positive, and the stock’s price moving average is declining, which indicates a strengthening of buyers and a low point in the stock price. In this scenario, initiate a purchase of 1000 shares.
  2. Add-on Buy Signal:
    • When the RSI is between 45 and 55, the RSI slope is positive, and the stock’s price moving average is ascending, suggesting a continued bullish market with expectations of further price increases. In this situation, add 1000 shares to the existing position.
  3. Sell Signal:
    • When the RSI is above 70, the RSI slope is negative, and the stock’s price moving average is ascending, which indicates a strengthening of sellers and a high stock price. We sell all existing shares at this point.

Execute the Trading Strategy

Execute the RSI Moving Average strategy with the run_algorithm() function, setting the trading period from start_time (2021-01-01) to end_time (2023-12-31). Utilize the dataset tquant and initialize the starting_cash to 5,000,000 NTD. The output, or results, will represent the daily performance and detailed transaction records.

from zipline import run_algorithmresults = run_algorithm( start = start_dt, end = end_dt, initialize=initialize, bundle='tquant', analyze=analyze, capital_base=5e6, handle_data = handle_data)results
TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (4)

Using Pyfolio for Performance Evaluation

import pyfolio as pffrom pyfolio.utils import extract_rets_pos_txn_from_ziplinereturns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(results)benchmark_rets = results.benchmark_return# Creating a Full Tear Sheetpf.create_full_tear_sheet(returns, positions = positions, transactions = transactions, benchmark_rets = benchmark_rets, round_trips=False)
TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (5)

With the RSI Moving Average strategy, we observe an annualized return of approximately 12.32% over these 34 months, accumulating a total return close to 40%. The overall performance surpasses the market benchmark. However, the strategy’s reliance on reverse operations based on stock price fluctuations results in higher volatility, reaching around 17%. Regarding the Max Drawdown, it is noticeable that the overall market exhibited poor performance in Q3 and Q4 of 2022 due to factors such as the Fed’s interest rate hikes and the impact of the COVID-19 pandemic. As a consequence, the return rate of the RSI Moving Average strategy experienced a slight decline during this period.

TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (6)

Conclusion

This strategy utilizes RSI Divergence to anticipate stock price lows in advance, combining it with the directional guidance provided by simple moving averages for contrarian operations. Similarly, employing the RSI Moving Average strategy for short positions is also feasible, and investors are welcome to consider these approaches. In the future, we will continue to introduce the construction of various indicators using the TEJ database and backtest indicator performance. Therefore, for readers interested in multiple trading backtests, explore solutions offered by TEJ Databank! Utilize high-quality databases to construct trading strategies tailored to your preferences.

As a friendly reminder, this strategy is provided for reference only and does not refer to any product or investment advice.

Learn More about the High-Quality Investment Database by TEJ!Construct Trading Strategies With Market Data.

Source Code

Click Here to Github

Extended Reading

TQuant Lab 損失規避策略 — 真實波動幅度均值
RSI指標回測實戰
TQuant Lab RSI Moving Average Strategy – Identifying Reversals in Oversold Conditions - TEJ (2024)
Top Articles
Should I Tell My Boss I Have Bed Bugs? | Integrity Pest Solutions
What did the Fed do in response to the COVID-19 crisis?
Knoxville Tennessee White Pages
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Wizard Build Season 28
Readyset Ochsner.org
Apex Rank Leaderboard
Elden Ring Dex/Int Build
Atrium Shift Select
Skip The Games Norfolk Virginia
Oppenheimer & Co. Inc. Buys Shares of 798,472 AST SpaceMobile, Inc. (NASDAQ:ASTS)
Elizabethtown Mesothelioma Legal Question
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Sony E 18-200mm F3.5-6.3 OSS LE Review
Gino Jennings Live Stream Today
Munich residents spend the most online for food
Tamilrockers Movies 2023 Download
Katherine Croan Ewald
Diamond Piers Menards
The Ultimate Style Guide To Casual Dress Code For Women
Site : Storagealamogordo.com Easy Call
Is Windbound Multiplayer
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Integer Division Matlab
Sandals Travel Agent Login
Horn Rank
Ltg Speech Copy Paste
Cognitive Science Cornell
Random Bibleizer
Craigslist Fort Smith Ar Personals
The Clapping Song Lyrics by Belle Stars
Poe T4 Aisling
R/Sandiego
Kempsville Recreation Center Pool Schedule
Rogold Extension
Beaver Saddle Ark
Log in or sign up to view
A Man Called Otto Showtimes Near Amc Muncie 12
Powerspec G512
Saybyebugs At Walmart
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Miami Vice turns 40: A look back at the iconic series
Love Words Starting with P (With Definition)
Tlc Africa Deaths 2021
Youravon Com Mi Cuenta
Nope 123Movies Full
Kushfly Promo Code
Diario Las Americas Rentas Hialeah
Game Akin To Bingo Nyt
Marion City Wide Garage Sale 2023
Latest Posts
Article information

Author: Greg Kuvalis

Last Updated:

Views: 5984

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Greg Kuvalis

Birthday: 1996-12-20

Address: 53157 Trantow Inlet, Townemouth, FL 92564-0267

Phone: +68218650356656

Job: IT Representative

Hobby: Knitting, Amateur radio, Skiing, Running, Mountain biking, Slacklining, Electronics

Introduction: My name is Greg Kuvalis, I am a witty, spotless, beautiful, charming, delightful, thankful, beautiful person who loves writing and wants to share my knowledge and understanding with you.