{"id":1672,"date":"2024-01-25T10:00:00","date_gmt":"2024-01-25T10:00:00","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/rsi-moving-average\/"},"modified":"2026-09-23T18:14:12","modified_gmt":"2026-09-23T18:14:12","slug":"rsi-moving-average","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/rsi-moving-average\/","title":{"rendered":"TQuant Lab RSI Moving Average Strategy \u2013 Identifying Reversals in Oversold Conditions"},"content":{"rendered":"\n<figure class=\"wp-block-image aligncenter size-large caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"rsi moving average\" class=\"wp-image-20364\" height=\"683\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/alex-radelich-2gYsZUmockw-unsplash.jpg\" style=\"aspect-ratio:1.5;object-fit:cover\" width=\"1024\"\/><figcaption class=\"wp-element-caption\">Photo by <a class=\"ek-link\" href=\"https:\/\/unsplash.com\/@alexradelich?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" rel=\"noopener\" target=\"_blank\">Alex Radelich<\/a> on <a class=\"ek-link\" href=\"https:\/\/unsplash.com\/photos\/man-jumping-on-rock-formation-2gYsZUmockw?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash\" rel=\"noopener\" target=\"_blank\">Unsplash<\/a><\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Highlight<\/h2>\n<ul class=\"wp-block-list\">\n<li>Article Difficulty\uff1a\u2605\u2605\u2606\u2606\u2606<\/li>\n<li>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.<\/li>\n<li>Utilizing the TQuant Lab backtesting platform to formulate trading strategies and assess the associated risks and performance.<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\">Preface<\/h2>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<p class=\"wp-block-paragraph\">In addition, since RSI itself lacks directional information, we can complement it with moving averages to determine the market as illustrated bellow:<\/p>\n<figure class=\"wp-block-image size-full caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"rsi moving average\" class=\"wp-image-20376\" height=\"608\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/E688AAE59C96-2024-01-17-E4B88BE58D884.50.04.png\" width=\"684\"\/><figcaption class=\"wp-element-caption\">RSI Divergence<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\">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 \u201cgreatest strength\u201d of RSI.<\/p>\n<p class=\"wp-block-paragraph\">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.<\/p>\n<h2 class=\"wp-block-heading\">Coding Environment<\/h2>\n<p class=\"wp-block-paragraph\">This article is composed in MacOS, utilizing Jupyter Notebook as the primary editor.<\/p>\n<h2 class=\"wp-block-heading\">Data Import<\/h2>\n<pre class=\"wp-block-code\"><code>import os\nos.environ['TEJAPI_KEY'] = \"your key\" \nos.environ['TEJAPI_BASE'] = \"https:\/\/api.tej.com.tw\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom zipline.data import bundles\nfrom zipline.utils.calendar_utils import get_calendar\nfrom zipline.sources.TEJ_Api_Data import get_Benchmark_Return<\/code><\/pre>\n<p class=\"wp-block-paragraph\">Data Period: January 1, 2021, to December 31, 2023<\/p>\n<p class=\"wp-block-paragraph\">Using the <code>get_universe<\/code> function, obtain <mark class=\"has-inline-color has-vivid-cyan-blue-color\" style=\"background-color:rgba(0, 0, 0, 0)\">Chemical Biotechnology and Medical Care sectors stock pool<\/mark>. Additionally, the Chemical Biotechnology and Medical Care Return Index (<em>IX0019<\/em>) was included as a benchmark for market comparison.<\/p>\n<pre class=\"wp-block-code\"><code>from zipline.sources.TEJ_Api_Data import get_universe\nstart = '2021-01-01'\nend = '2023-12-31'\npool = get_universe(start, end, mkt = 'TWSE', stktp_e = 'Common Stock', main_ind_e = 'M1700 Chemical Biotechnology &amp; Medical Care')\nprint(f'total stock: {len(pool)}\uff1a\\n', pool)\n\nstart_dt, end_dt = pd.Timestamp(start, tz='utc'), pd.Timestamp(end, tz='utc')\ntickers = ' '.join(pool)\nos.environ['ticker'] = tickers+' IX0019'\nos.environ['mdate'] = start+' '+end\n!zipline ingest -b tquant\n\nbundle = bundles.load('tquant')\nbenchmark_asset = bundle.asset_finder.lookup_symbol('IX0019',as_of_date = None)<\/code><\/pre>\n<figure class=\"wp-block-image size-full caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"rsi moving average\" class=\"wp-image-20482\" height=\"190\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/E688AAE59C96-2024-01-26-E4B88AE58D889.25.52.png\" width=\"2210\"\/><figcaption class=\"wp-element-caption\">Selected Stock Pool<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Trading Rules for RSI Moving Average Strategy<\/h2>\n<ol class=\"wp-block-list\">\n<li><strong>Buy Signal:<\/strong>\n<ul class=\"wp-block-list\">\n<li>When the RSI is below 30, the RSI slope is positive, and the stock\u2019s 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.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Add-on Buy Signal:<\/strong>\n<ul class=\"wp-block-list\">\n<li>When the RSI is between 45 and 55, the RSI slope is positive, and the stock\u2019s 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.<\/li>\n<\/ul>\n<\/li>\n<li><strong>Sell Signal:<\/strong>\n<ul class=\"wp-block-list\">\n<li>When the RSI is above 70, the RSI slope is negative, and the stock\u2019s price moving average is ascending, which indicates a strengthening of sellers and a high stock price. We sell all existing shares at this point.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<h2 class=\"wp-block-heading\">Execute the Trading Strategy<\/h2>\n<p class=\"wp-block-paragraph\">Execute the RSI Moving Average strategy with the <code>run_algorithm()<\/code> function, setting the trading period from <code>start_time<\/code> (2021-01-01) to <code>end_time<\/code> (2023-12-31). Utilize the dataset <em>tquant<\/em> and initialize the <code>starting_cash<\/code> to 5,000,000 NTD. The output,  or <code>results<\/code>, will represent the daily performance and detailed transaction records.<\/p>\n<pre class=\"wp-block-code\"><code>from zipline import run_algorithm\nresults = run_algorithm(\n    start = start_dt,\n    end = end_dt,\n    initialize=initialize,\n    bundle='tquant',\n    analyze=analyze,\n    capital_base=5e6,\n    handle_data = handle_data\n)\nresults<\/code><\/pre>\n<figure class=\"wp-block-image size-large caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"rsi moving average\" class=\"wp-image-20459\" height=\"487\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/E688AAE59C96-2024-01-24-E4B88AE58D8811.51.45.png\" width=\"1024\"\/><figcaption class=\"wp-element-caption\">Transaction Details<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Using Pyfolio for Performance Evaluation<\/h2>\n<pre class=\"wp-block-code\"><code>import pyfolio as pf\nfrom pyfolio.utils import extract_rets_pos_txn_from_zipline\n\nreturns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(results)\nbenchmark_rets = results.benchmark_return\n\n# Creating a Full Tear Sheet\npf.create_full_tear_sheet(returns, positions = positions, transactions = transactions,\n                          benchmark_rets = benchmark_rets,\n                          round_trips=False)<\/code><\/pre>\n<figure class=\"wp-block-image size-full caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"rsi moving average\" class=\"wp-image-20400\" height=\"1464\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/E8B387E794A2-2.png\" width=\"2834\"\/><figcaption class=\"wp-element-caption\">Backtest Performance Comparison Chart with the Market<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\">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\u2019s 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\u2019s 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.<\/p>\n<figure class=\"wp-block-image size-full caption-align-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"rsi moving average\" class=\"wp-image-20402\" height=\"710\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/E688AAE59C96-2024-01-18-E4B88BE58D883.35.33.png\" width=\"2062\"\/><figcaption class=\"wp-element-caption\">Monthly Return Rate<\/figcaption><\/figure>\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\">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 <strong><a class=\"ek-link\" href=\"\/en\/databank-solution\/market-data\/\">TEJ Databank<\/a><\/strong>! Utilize high-quality databases to construct trading strategies tailored to your preferences.<\/p>\n<p class=\"wp-block-paragraph\">As a friendly reminder, <strong>this strategy is provided for reference only and does not refer to any product or investment advice.<\/strong><\/p>\n<div aria-hidden=\"true\" class=\"wp-block-spacer\" style=\"height:16px\"><\/div>\n<div class=\"wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button has-custom-width wp-block-button__width-100 has-custom-font-size is-style-fill\" style=\"font-size:20px\"><a class=\"wp-block-button__link has-background wp-element-button\" href=\"\/en\/databank-solution\/market-data\/\" style=\"border-radius:19px;background:linear-gradient(135deg,rgb(240,215,106) 0%,rgb(75,209,200) 50%,rgb(76,132,205) 100%)\"><strong>Learn More about the High-Quality Investment Database by TEJ!<br\/>Construct Trading Strategies With Market Data.<\/strong><\/a><\/div>\n<\/div>\n<div aria-hidden=\"true\" class=\"wp-block-spacer\" style=\"height:16px\"><\/div>\n<h2 class=\"wp-block-heading\">Source Code<\/h2>\n<p class=\"wp-block-paragraph\"><a class=\"ek-link\" href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_Quant\/blob\/782934438f434dde367ffb17fc3ccdbabfbae3b4\/RSI%2B%E5%9D%87%E7%B7%9A%E7%AD%96%E7%95%A5.ipynb\" rel=\"noopener\" target=\"_blank\">Click Here to Github<\/a><\/p>\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-tej-en wp-block-embed-tej-en\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"1u1GjMyPzA\"><a href=\"https:\/\/www.tejwin.com\/en\/insights\/rsi-indicator\/\">RSI Indicator<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; visibility: hidden;\" title=\"\u201cRSI Indicator\u201d \u2014 TEJ\" src=\"https:\/\/www.tejwin.com\/en\/insights\/rsi-indicator\/embed\/#?secret=85PntwAHrj#?secret=1u1GjMyPzA\" data-secret=\"1u1GjMyPzA\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-tej-en wp-block-embed-tej-en\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"9TRW2BGzp8\"><a href=\"https:\/\/www.tejwin.com\/en\/insights\/loss-aversion-strategy\/\">TQuant Lab Loss Aversion Strategy \u2014 Average True Range<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; visibility: hidden;\" title=\"\u201cTQuant Lab Loss Aversion Strategy \u2014 Average True Range\u201d \u2014 TEJ\" src=\"https:\/\/www.tejwin.com\/en\/insights\/loss-aversion-strategy\/embed\/#?secret=z7NER0CRdN#?secret=9TRW2BGzp8\" data-secret=\"9TRW2BGzp8\" width=\"600\" height=\"338\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n<h2 class=\"wp-block-heading\">Extended Reading<\/h2>\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-7387b849 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-vertically-aligned-top is-layout-flow wp-block-column-is-layout-flow\">\n<\/div>\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Creating a convergence strategy with the RSI moving average strategy. The RSI is an oscillating technical indicator representing the comparative strength between buyers and sellers in the market.<\/p>\n","protected":false},"featured_media":1671,"template":"","tags":[52,100],"insight_category":[16],"class_list":["post-1672","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-quantitative-analysis","tag-quantitative-trading","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/1672","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/1671"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=1672"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=1672"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=1672"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}