In this post, we discuss a straightforward trading strategy based on the Relative Strength Index (RSI) and demonstrate how to implement it using the QuantConnect platform. We also share insights about the strategy's performance, including a detailed analysis of key metrics.

The Strategy

The strategy is based on two simple rules:

1. **Entry:** If the RSI(2) of SPY falls below 15, it signals an oversold market condition. The strategy takes this as a buying opportunity and enters a long position at the close of the day.
2. **Exit:** The strategy closes the position if today's closing price is higher than yesterday's high.

This approach uses the RSI, a popular momentum oscillator, to identify potential buy opportunities in oversold market conditions. The RSI is calculated based on recent price changes, and an RSI period of 2 makes it very sensitive to the latest movements. The RSI lower threshold is set aggressively at 15 (compared to the commonly used level of 30), allowing the strategy to react to more extreme oversold conditions.

Implementation on QuantConnect

QuantConnect provides a robust platform for backtesting and live trading of such strategies. For our strategy, we particularly utilize the QuantConnect's `RollingWindow` and `TradeBar` features.

`RollingWindow` is used to store the trailing data, keeping the strategy's memory footprint low and providing efficient access to historical data points. It is used in this strategy to maintain the high prices of the last two days.

`TradeBar` is a data type in QuantConnect that represents a period in a financial security's trading session. In this strategy, we use daily `TradeBar` data of SPY for calculating the RSI and determining entry and exit points.

Performance Analysis

The backtest results of the strategy from 2010 to 2022 show promising returns with a net profit of 158.251% and a compounding annual return of 7.568%. The strategy executed a total of 852 trades during this period, with a win rate of 62%.

81860_1690075039.jpgSimple RSI Equity Curve

However, the strategy experienced a significant drawdown of 23.5%. In particular, the years between 2018 and 2021 saw a downturn in the portfolio value. This could be due to a combination of factors, including adverse market conditions during that period (including the COVID-19 market crash), limitations in the strategy's model, high transaction costs, or the strategy being overfitted to past market conditions.

import numpy as np
from QuantConnect.Algorithm import QCAlgorithm
from QuantConnect.Indicators import *
from QuantConnect import Resolution
from QuantConnect.Data.Market import TradeBar

class RsiCloseAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2010, 1, 1) # Set the start date for backtesting
        self.SetEndDate(2023, 1, 1) # Set the end date for backtesting
        self.SetCash(100000) # Set the initial cash balance for backtesting

        # Define the symbol we want to trade
        self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol

        # RSI parameters
        self.rsi_period = 2
        self.rsi_lower = 15

        # Set up the RSI indicator
        self.rsi = self.RSI(self.symbol, self.rsi_period, MovingAverageType.Simple, Resolution.Daily)

        # Initialize a RollingWindow to keep track of past TradeBars
        self.barWindow = RollingWindow[TradeBar](2)

    def OnData(self, data):
        # Add the current TradeBar to the RollingWindow
        self.barWindow.Add(data[self.symbol])

        # Skip if the RollingWindow is not ready
        if not self.barWindow.IsReady:
            return

        # Get the past high price from the RollingWindow
        pastHigh = self.barWindow[1].High

        # Check if RSI is lower than the defined threshold
        if self.rsi.Current.Value < self.rsi_lower:
            self.SetHoldings(self.symbol, 1.0)

        # Check if today's close is higher than yesterday's high
        if self.Portfolio[self.symbol].Invested and self.Securities[self.symbol].Close > pastHigh:
            self.Liquidate(self.symbol)

        # Plot RSI on chart
        self.Plot("Indicators", "RSI", self.rsi.Current.Value)
        self.Plot("Indicators", "Oversold Level", self.rsi_lower)

 

Conclusion

This simple RSI-based trading strategy shows potential for profitable trades, but like all strategies, it has periods of drawdowns and may not perform well in all market conditions. Regular performance monitoring, tweaking the parameters, and considering other factors such as transaction costs and market impact can help improve the strategy's performance.

QuantConnect provides a powerful and flexible platform for developing, backtesting, and deploying algorithmic trading strategies. With features like `RollingWindow` for efficient data handling and `TradeBar` for capturing market data, QuantConnect makes it easier to implement and test a wide range of trading strategies.