Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Mean Reversion Trading Strategy with Python Code

Mean Reversion Trading Strategy with Python Code

Mean reversion is a popular trading strategy that involves identifying assets that are currently overbought or oversold and betting on their price to return to their mean or average level. This strategy is based on the assumption that prices of assets will eventually revert to their long-term historical average, which makes it popular among short-term traders and hedge funds.

The mean reversion strategy involves identifying the deviation of the current price of an asset from its mean or average level. This deviation is measured using various technical indicators such as the Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), and Bollinger Bands. These indicators help traders identify assets that are currently overbought or oversold and are likely to experience a reversal in their price trend.

To implement the mean reversion trading strategy in Python, you will need to import the necessary libraries such as pandas, numpy, and matplotlib. You will also need to have access to a dataset of historical prices of the asset you want to trade. In this example, we will use the historical price data of Apple Inc (AAPL) obtained from Yahoo Finance.

Here is the Python code example:

import pandas as pd
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt

# Load historical price data for a stock
stock = 'AAPL' # Change this to the ticker symbol of the stock you want to trade
data = yf.download(stock, start='2020-01-01', end='2022-03-29')

# Define the mean reversion trading strategy
def mean_reversion_strategy(data, ma_period, rsi_period, rsi_oversold, rsi_overbought):
    # Calculate the moving average and RSI
    data['MA'] = data['Adj Close'].rolling(window=ma_period).mean()
    delta = data['Adj Close'].diff()
    gain = delta.where(delta > 0, 0)
    loss = -delta.where(delta < 0, 0)
    avg_gain = gain.rolling(window=rsi_period).mean()
    avg_loss = loss.rolling(window=rsi_period).mean()
    rs = avg_gain / avg_loss
    data['RSI'] = 100 - (100 / (1 + rs))

    # Generate trading signals based on the strategy
    data['Signal'] = np.where((data['Adj Close'] < data['MA']) & (data['RSI'] < rsi_oversold), 'Buy', '')
    data['Signal'] = np.where((data['Adj Close'] > data['MA']) & (data['RSI'] > rsi_overbought), 'Sell', data['Signal'])

    # Return the trading signals
    return data['Signal']

# Generate trading signals using the mean reversion strategy
signals = mean_reversion_strategy(data, ma_period=20, rsi_period=14, rsi_oversold=30, rsi_overbought=70)

# Plot the historical prices and trading signals
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(data.index, data['Adj Close'], label='Close')
ax.plot(data.index, data['MA'], label='MA')
ax.fill_between(data.index, data['RSI'], 30, where=(data['RSI'] <= 30), facecolor='red', alpha=0.5)
ax.fill_between(data.index, data['RSI'], 70, where=(data['RSI'] >= 70), facecolor='green', alpha=0.5)
ax.plot(data[data['Signal'] == 'Buy'].index, data['Adj Close'][data['Signal'] == 'Buy'], '^', markersize=10, color='g')
ax.plot(data[data['Signal'] == 'Sell'].index, data['Adj Close'][data['Signal'] == 'Sell'], 'v', markersize=10, color='r')
ax.set_title('AAPL Mean Reversion Trading Signals')
ax.legend(['Close', 'MA', 'Oversold', 'Overbought', 'Buy', 'Sell'])
plt.show()

This code is similar to the previous example but also includes code to plot the historical prices, moving average, RSI, and trading signals generated by the mean reversion strategy.

After generating the trading signals using the mean_reversion_strategy function, the code creates a new figure and axis using the plt.subplots() function, and plots the historical prices, moving average, RSI, and trading signals on the axis using various plotting functions.

The resulting plot shows the historical prices, moving average, and RSI on the same chart, with shaded regions indicating

The code then plots the historical price data, the moving averages, and the RSI to visualize the trends and identify potential buying and selling opportunities. It also plots the signals generated by the mean reversion strategy, which are indicated by green upward-pointing triangles for buying and red downward-pointing triangles for selling.

The mean reversion strategy can be a useful tool for short-term traders and hedge funds looking to take advantage of short-term price movements in assets. However, it is important to note that this strategy is not foolproof and can result in losses if the market does not behave as expected. It is therefore important to use risk management strategies such as stop-loss orders and position sizing to mitigate potential losses.

Lastly, the mean reversion trading strategy is a popular approach that involves identifying assets that are currently overbought or oversold and betting on their price to return to their mean or average level. Python provides a powerful and flexible platform for implementing this strategy using various technical indicators and libraries. By combining technical analysis with risk management strategies, traders can potentially profit from short-term price movements in the market.