“Buying low, selling high” is surprisingly difficult in real life. History tells us that rising companies often keep going up, making it hard to know when to take profits off the table.

It’s why an entire industry of technical analysis exists. Strategies like the Relative Strength Index (RSI)** **attempt to use historical price data to predict future movements. But does it work?

## What Is the Relative Strength Index (RSI)?

The Relative Strength Index (RSI) is a contrarian technical analysis indicator that uses price movements to find “overbought” and “oversold” assets. The system was introduced by J. Welles Wilder Jr. in 1978 and has remained popular among swing traders since.

The RSI uses a straightforward formula to create an indicator that ranges from zero to 100.

Stocks and other assets are bought whenever the indicator drops below “30” and sold above “70.” The lower the RSI indicator, the more bullish investors should become.

The system works… Or at least it seems to. Here’s the same graph for **Coca-Cola** (NYSE:** KO**) with its share prices expanded. You’ll notice that buys happen in local troughs and sales happen at peaks. It’s the classic “buy low, sell high” way of making money.

There are also different versions of the RSI. The standard index is calculated over a 14-day period, which is referred to as “RSI-14” or “RSI (14D)”. Longer ranges, such as 20 days and 50 days, can also be used. They’re notated as RSI-20 and RSI-50, respectively.

Few fundamental-driven investors, however, take the RSI seriously. Studies have shown that the indicator fails to perform in trending markets, which is the equivalent of saying, “I’m right all the time… Unless when I’m wrong.” Technical analysis also gets a relatively poor name for its lack of intellectual rigor. Why, for instance, should RSI indicators be calibrated on a 14-day cycle instead of a 13-day one? And as I’ve repeatedly noted, how many billionaires got rich from drawing lines across stock charts?

That said, my work in quantitative and machine-learning trading has made me more open to technical analysis. Results from my quantitative stock-picking system ** MarketMasterAI** show that past price movements

*can*predict future prices, as long as they’re paired with other indicators. This is especially true with assets driven by human emotions, such as meme stocks, illiquid companies and penny stocks.

## How to Calculate the Relative Strength Index

To calculate the Relative Strength Index, let’s assume we’re using a 14-day average. Calculating the first RSI-14 figure involves:

**Gains.**Take the average value of the past 14 days of gains. Losses are ignored.**Losses.**Take the average loss from the past 14 days. Gains are ignored.**Find RS.**Divide the two numbers to get the Relative Strength (RS) figure. Higher numbers indicate greater strength since gains outweigh losses.**Calculate RSI.**Plug the RS value into the formula 100 / (1+RS) to output your RSI value.

Subsequent RS figures are calculated by:

**Gains.**[(Previous Average Gain) x 13 + Current Gain] / 14.**Losses.**[(Previous Average Loss) x 13 + Current Loss] / 14.

## Using Python to Calculate the Relative Strength Index

To test the performance of the Relative Strength Index, it’s possible to code the strategy by hand. Here, let’s assume we have a Python dictionary of stock prices — in this case, the values of **Omnicell **(NASDAQ:**OMCL**) between 2017 and 2023.

We’ll then calculate the daily percentage price change by creating a new column called “prev_day_price” and comparing it to present-day prices to get a “pct_change” column. Gains and losses are tallied with a lambda function. (Note that we fill the “gains” column with zeros on negative days and the “losses” column with zeros on positive days.)

Our next step is to calculate RSI values over time. Here, we’ll use a for-loop since next-day RSI values depend on previous-day figures. Finding RS and RSI values then uses straightforward formulas.

Once we have our RSI for Omnicell, we can put it into a Matplotlib chart. Here’s what it looks like, with the RSI indicator creating plenty of buy/sell signals over time.

As for the performance, here’s what would have happened if we bought whenever shares of Omnicell hit “30” and sold at “70.” (Notice that we’re shifting to logarithmic returns because it’s more accurate than algebraic returns. We’re also using next-day returns to make our performance more realistic.)

The results look decent. $10,000 invested in Omnicell would have turned into $12,560 over five years, compared to $8,214 with a buy-and-hold strategy. Had we achieved the close price of each day rather than a “T+1” price, our return would have been even higher at $27,233.

Things look even better if shorting is allowed. To find this, we change one line of code to permit negative positions and rerun.

~~df.loc[(df['RSI'] > 70) & (df['prev_RSI'] <= 70), "position"] = 0~~
**df.loc[(df['RSI'] > 70) & (df['prev_RSI'] <= 70), "position"] = -1**

Our return increases to $17,537 if we allow shorting and use T+1 trading prices…

…And jumps to $87,704 if we manage to get day-of pricing. That’s roughly 10 times better than a buy-and-hold strategy! (These inter-day figures also show the importance of day trading when buying on 14-day momentum.)

## Does the RSI Index Work on Stocks?

Of course, Omnicell’s outperformance could be a fluke. One positive finding doesn’t mean RSI works every time, and even Omnicell saw several years of underperformance before breaking out in 2022.

To test this, we can run the RSI-14 indicator on *every*** Russell 3000** stock since 2018 and average the results. (The index includes the 3000 largest U.S.-listed firms, which covers around 98% of total market value.) Here, I use a large dataset collected from Refinitiv, a Thomson Reuters service that covers current and defunct companies. Including bankrupt and merged firms reduces survivorship bias and gives us a better idea of how a strategy would have performed without knowing which companies would survive and which would fold.

To streamline our code, I’ll use TA Python, a pre-made package, to calculate RSI values. I’ll also convert our strategy into a reusable function called “add_rsi_strategy” and add a data aggregation function called “get_overall_perf” to average returns across all 3000 members of the Russell 3000. This allows us to reuse the same code to test multiple strategies.

### The Results

The returns *are *positive across the Russell 3000. $10,000 invested in the broad-based index rebalanced daily would have grown to $11,055, compared to $7,400 in a buy-and-hold strategy. This assumes we bought any stock when it crossed above the “30” mark and shorted them at the “70” level.

Even without allowing short positions, our return beats the index by a healthy 36%.

We can also perform a t-test on these results to make sure this wasn’t all luck. Below, I select an end date of “1516” (i.e., Oct 12, 2023) and compare whether the cumulative returns are positively different. The output from the statistical package SciPy shows they are significant at the 99% confidence level (i.e., we can be 99% sure our outperformance was genuine).

## Turning the Relative Strength Indicator Into a Profit Spinner

Until now, we’ve used the RSI indicator without considering company fundamentals. The result is that we’re scrounging for returns. Turning $10,000 into $12,560 over five years isn’t exactly the most compelling strategy.

*So, how can we do better?*

Regular readers will know that adding fundamental data to technical analysis can go a long way, especially if you understand the nature of your system. It’s the equivalent of using the right tool for the job.

In the case of RSI, we know the strategy is a “mean-reversion” type, where stocks are bought at bottom-of-cycle moments and sold at the top. Mathematically, stocks only reach the “oversold” signal of 30 when losses significantly outweigh gains. That means RSI will outperform when stocks wobble around a central value and underperform when they break out of that range.

So, let’s try re-running the RSI strategy on mean-reverting stocks — in this case, consumer non-cyclicals and utilities. These are firms like **Procter and Gamble **(NYSE:**PG**) and **American Water Works **(NYSE:**AWK**), where earnings tend to gravitate around a central value.

Now, we start getting some interesting performance:

Here, we see the RSI trading strategy outperforming by an *enormous*** **margin! An investor following the strategy would have been net-positive in every period starting in 2018 and turned $10,000 into $14,000 (using our conservative T+1 pricing method). It’s a stunning result for a risk-reduction strategy.

The RSI-14 strategy is also valuable in helping us avoid high-risk companies. That’s because the most volatile firms will often rise quickly (triggering the “overbought” signal) and then slowly deflate as speculators realize their mistake. Meme stocks like **GameStop **(NYSE:**GME**) and **AMC Entertainment **(NYSE:**AMC**) fall into this category.

One measure of this type of risk is the Altman Z-score, a financial metric that combines working capital, retained earnings, operating performance and sales into a single figure. Any number under 1.81 is considered in the “distress zone.” Let’s take companies in extreme distress that score under 1.20.

Here, we see the RSI indicator excelling at helping us avoid significant underperformance. Our outcome is a stunning 71.7% return over five years, or roughly 11.4% annualized.

The effect is even more apparent among biotech firms, whose shares often see enormous price spikes during early successes, which causes the RSI indicator to trigger a short position. Shares then sink as the harsh realities of late-stage clinical trials kick in, rewarding investors with consistent returns. Only about 10% of biotech drugs submitted to the U.S. Food and Drug Administration (FDA) ever make it to approval.

## Reverse-RSI Strategies

On the other hand, “breakout” stocks need the opposite strategy, where high prices are rewarded and low prices are penalized. Put another way: We need to modify our RSI strategy when we face situations where winners keep going up.

The most straightforward modification is to run our RSI strategy in reverse. We buy whenever the indicator tells us to sell and sell when it tells us to buy. (Anyone with a 2-year-old will know the game of *opposite day*.) We can do this by reversing the “1” and “-1” position sizes in our trading algorithm.

` df.loc[(df['RSI'] < 30) & (df['prev_RSI'] >= 30), "position"] = `**-1**
df.loc[(df['RSI'] > 70) & (df['prev_RSI'] <= 70), "position"] = **1**

The strategy works surprisingly well. Here’s a graph of the “reverse-RSI” strategy on companies that paid no dividends in 2017. I selected this group knowing that zero-dividend stocks tend to either be 1) startups with no cashflow to distribute or 2) dying companies that can’t afford payouts.

Here, $10,000 grows to $10,688 rather than shrinking to $6,564.

We can tune things to be even better. Here is the same group of zero-dividend stocks with two additional criteria to screen for “breakout” potential:

**Stock Issuance.**The company raised money from public markets in 2017.**Growth.**Analysts expected the firm to increase sales by 20% or more the following year.

The performance is excellent, as we would expect. $10,000 invested using the “reverse-RSI” strategy on breakout stocks would have risen 50.2% to $15,020 over five years, compared to a 47.1% decline if we had used a buy-and-hold strategy. The figures are even better if we update the fundamental data over time. (Our initial tests only used information from the end of 2017.)

Consider Grubhub, a high-growth company that lands on our 2018 list of “breakout” stocks. In its short history as a public company, the meal delivery firm would reward momentum-seeking investors by hitting the overbought RSI level of 70 *and then keep going up*. Then, when prices started to deflate, the opposite would happen. The company would eventually lose 80% of its peak value and get bought out by rival **Just Eat Takeaway.com** (OTCMKTS:** JTKWY**). It’s why we must be so careful to apply the right RSI strategy to the right stocks.

## What’s Next?

Hopefully, this exercise illustrates how quantitative strategies *can* help you beat the market. By taking a technical strategy and applying it to the right assets, investors can gain an edge over fundamental-only buyers.

Finding the right assets can be a challenge. Some firms can switch between momentum-seeking and mean-reverting. A large-cap healthcare firm like **Eli Lilly **(NYSE:**LLY**), for instance, might be a mean-reverting firm for decades until they discover a blockbuster drug. Shares have risen more than 600% since the obesity-combating drug tirzepatide was identified in 2016.

Markets can also change priorities. Prices of struggling moonshots outperformed higher-quality peers during the 2021 “everything rally.” Many questionable cryptocurrencies and non-fungible tokens (NFTs) would see their market capitalizations join the billion-dollar club, only to come crashing back down once the tide receded. It’s why some technical strategies, like Bollinger Bands, outperform during certain markets and underperform in others.

That’s why you need to read about ** MarketMasterAI**, a machine-learning algorithm that combines years of fundamental and technical analysis data into a single stock recommendation system. It’s a neural network that adapts to current market conditions and can quickly tell if a company is beginning to struggle or surge.

Together, it has created a trading system that works in both good times and bad. During the summer rally of 2023, the system recommended riskier bets, then quickly switched to blue-chip picks two months later once markets started wobbling.

Today, it has a new set of recommendations. Keep following me here at *InvestorPlace* to stay up-to-date.

*On the date of publication, Tom Yeung did not hold (either directly or indirectly) any positions in the securities mentioned in this article. The opinions expressed in this article are those of the writer, subject to the InvestorPlace.com Publishing Guidelines.*

*Tom Yeung is a market analyst and portfolio manager of the Omnia Portfolio, the highest-tier subscription at InvestorPlace. He is the former editor of Tom Yeung’s Profit & Protection, a free e-letter about investing to profit in good times and protecting gains during the bad.*