FAQ · Getting systematic research right

How do I backtest an RSI mean reversion strategy in Python?

Compute RSI with Wilder's smoothing from closed bars, buy when it falls below an oversold level, usually only while price is above a long moving average, and sell when RSI recovers. Use the same smoothing your charting tool uses, fill at the next bar, and include costs, because mean reversion trades are short and their average gain is small.

Compute RSI with Wilder's smoothing from closed bars, buy when it falls below an oversold level, usually only while price is above a long moving average, and sell when RSI recovers. Use the same smoothing your charting tool uses, fill at the next bar, and include costs, because mean reversion trades are short and their average gain is small.

The indicator

The Relative Strength Index, introduced by J. Welles Wilder in 1978, compares recent gains with recent losses on a scale of 0 to 100:

  1. Split each bar-to-bar change into a gain (or 0) and a loss (or 0).
  2. Average each over n bars. Wilder's method starts with a simple mean and then smooths: avg = (avg × (n − 1) + new) / n.
  3. RSI = 100 − 100 / (1 + avg_gain / avg_loss).

Because of the smoothing, RSI depends on more history than its n bars. Computing it over a short window gives a different value from a chart that has years of history behind it. Give the calculation several times n bars so the values settle.

The rule

The classic levels are 30 (oversold) and 70 (overbought) with n = 14. A widely used short-term version, popularised by Larry Connors, uses RSI(2): buy when it drops below 10 while price is above its 200-bar average, and sell when it rises back above a level such as 70, or when price closes above a short average. The trend filter keeps the strategy buying dips in uptrends rather than catching falling markets.

What to check in the backtest

  • Win rate and payoff together. Mean reversion often wins most trades with small gains and takes occasional large losses. A high win rate alone says little; read it with the profit factor and the largest loss, as in reading a backtest report.
  • Costs per trade. With an average gain of a fraction of a percent, spread and commission can be most of it.
  • No stop by default. Many RSI rules exit only on recovery. Test a time stop or a price stop and see what it does to the worst trade.

How Reamer Research handles it

In Reamer Research this is a configured object: the levels are constructor arguments, so a sweep is a loop over objects.

import numpy as np
import reamer_research as rr

def rsi(close, n):
    diff = np.diff(close)
    gain, loss = np.clip(diff, 0, None), np.clip(-diff, 0, None)
    avg_gain, avg_loss = gain[:n].mean(), loss[:n].mean()
    for g, l in zip(gain[n:], loss[n:]):            # Wilder's smoothing
        avg_gain = (avg_gain * (n - 1) + g) / n
        avg_loss = (avg_loss * (n - 1) + l) / n
    return 100.0 if avg_loss == 0 else 100 - 100 / (1 + avg_gain / avg_loss)

class RsiReversion:
    def __init__(self, period=2, entry=10, exit=70, trend=200, qty=10):
        self.period, self.entry, self.exit, self.trend, self.qty = period, entry, exit, trend, qty
        self.lookback = trend + 1
    def on_bar(self, d):
        c = d.close
        if c[0] == 0:
            return None
        r = rsi(c, self.period)
        if d.position() == 0 and r < self.entry and c[-1] > c[-self.trend:].mean():
            return rr.buy_market(self.qty)
        if d.position() > 0 and r > self.exit:
            return rr.close_position()

result = rr.backtest(RsiReversion(period=2, entry=10), 'data/SPY.bin',
                     spread=0.01, commission_per_unit=0.005)
print(result.win_rate, result.profit_factor, result.net_ev_per_trade)

The engine reads lookback from the object, so the window always holds enough bars for the trend filter, and RSI is computed over all of them. The same rule runs as a function on_bar(data) or a class as well. net_ev_per_trade gives the average result per trade after costs, which is the number mean reversion lives or dies on.

Limits to know

  • The indicator is yours. The engine supplies the bars; RSI is the dozen lines above, or a library such as TA-Lib.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to check the code; a test over years of history needs a licence.

A $20 month includes the full kit, so you can test your own RSI levels on your own data and cancel if it does not fit.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.