RSI 14 Crossover Trading Strategy: Turning $100K into $180K with AAPL

How the RSI 14 Crossover Trading Strategy Achieved 80% Returns on AAPL Stock

Hey there, fellow traders and coders! Today, we’re diving into a popular technical analysis strategy involving the Relative Strength Index (RSI). Specifically, we’ll explore how to leverage the RSI 14 Crossover Trading Strategy for trading decisions. The strategy is simple: buy when the RSI 14 crosses above 30 from below, and sell when it crosses below 70 from above. This approach can help identify potential entry and exit points in the market, aiming to capitalize on momentum shifts. Let’s get started!

Understanding the RSI 14 Crossover Trading Strategy

What is RSI?

The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and change of price movements. The RSI oscillates between 0 and 100 and is typically used to identify overbought or oversold conditions in a market. An RSI value below 30 generally indicates that the market is oversold, while an RSI value above 70 suggests that the market is overbought.

The RSI 14 Crossover Trading Strategy

  1. Buy Signal: When RSI 14 crosses above 30 from below, it signals a potential buying opportunity, indicating that the market is recovering from an oversold condition.
  2. Sell Signal: When RSI 14 crosses below 70 from above, it signals a potential selling opportunity, indicating that the market is pulling back from an overbought condition.

Implementing the RSI 14 Crossover Trading Strategy with Python

To illustrate this strategy, we’ll use Python with the yfinance library to fetch historical stock data and the pandas library to calculate the RSI and implement the trading logic.

Step 1: Fetch Historical Data

First, let’s fetch the historical data for a stock using yfinance:

import yfinance as yf
import pandas as pd

# Define the ticker and the period for the last 10 years
ticker = 'AAPL'
period = '10y'

# Download historical data for the last 10 years
data = yf.download(ticker, period=period)

# Ensure that the index is a datetime index
data.index = pd.to_datetime(data.index)

Step 2: Calculate the RSI 14

Next, we’ll calculate the 14-period RSI:

def calculate_rsi(data, window=14):
    delta = data['Close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

data['RSI'] = calculate_rsi(data)

Step 3: Implement the RSI 14 Crossover Trading Logic

Now, let’s implement the trading logic for the buy and sell signals based on the RSI 14 crossover trading strategy:

 Initialize the buy and sell signals
data['Buy_Signal'] = (data['RSI'] > 30) & (data['RSI'].shift(1) <= 30)
data['Sell_Signal'] = (data['RSI'] < 70) & (data['RSI'].shift(1) >= 70)
Combined graph showing the historical price of AAPL and the RSI 14 values over a 10-year period, with buy and sell signals highlighted.
Combined graph showing the historical price of AAPL and the RSI 14 values over a 10-year period.

Step 4: Backtest the RSI 14 Crossover Trading Strategy

To backtest the strategy, we’ll simulate trading based on the signals. In this example, we start with an initial investment of $100,000. The objective is to determine how much this investment would grow over a period of 10 years using the RSI 14 crossover trading strategy. We’ll track the performance of our portfolio by buying and selling shares of AAPL based on the RSI signals and calculate the portfolio value over time.

Here’s how we do it:

  1. Initial Setup: We begin with $100,000 in cash and no shares. We will buy shares when we receive a buy signal (RSI crossing above 30) and sell them when we receive a sell signal (RSI crossing below 70).
  2. Simulating Trades: For each day in the historical data, we check if a buy or sell signal is generated:
    • Buy Signal: If the RSI crosses above 30 and we have cash available, we buy as many shares as we can with the available cash.
    • Sell Signal: If the RSI crosses below 70 and we hold shares, we sell all the shares at the current price.
  3. Tracking Portfolio Value: We keep track of the portfolio value by adding the value of the shares we hold (if any) to our cash balance. This is done for each trading day over the 10-year period.
  4. Calculating Annual Returns: At the end of each year, we calculate the annual return as the percentage change in the portfolio value compared to the previous year. This helps us understand the performance of the strategy on a yearly basis.
  5. Final Portfolio Value: After simulating the trades over the 10-year period, we calculate the final portfolio value to see how much our initial $100,000 investment has grown.

Here’s the code for this backtesting process:

initial_cash = 100000  # Initial investment
cash = initial_cash
shares = 0
portfolio_value = []

for i, row in data.iterrows():
    if row['Buy_Signal'] and cash > 0:
        shares = cash // row['Close']
        cash -= shares * row['Close']
        print(f"Bought {shares} shares at {row['Close']} on {i}")
    elif row['Sell_Signal'] and shares > 0:
        cash += shares * row['Close']
        shares = 0
        print(f"Sold shares at {row['Close']} on {i}")
    
    portfolio_value.append(cash + shares * row['Close'])

data['Portfolio_Value'] = portfolio_value

# Calculate annual returns as percentage change
data['Year'] = data.index.year
annual_returns = data.groupby('Year')['Portfolio_Value'].last().pct_change().dropna() * 100

# Display the final portfolio value
print(f"Final portfolio value: ${data['Portfolio_Value'].iloc[-1]:.2f}")

Step 5: Plotting the RSI 14 Crossover Trading Results

import matplotlib.pyplot as plt

# Plot the results
plt.figure(figsize=(14, 14))

plt.subplot(4, 1, 1)
plt.plot(data['Close'], label='Close Price')
plt.title('Close Price and RSI')
plt.legend()

plt.subplot(4, 1, 2)
plt.plot(data['RSI'], label='RSI', color='orange')
plt.axhline(70, color='r', linestyle='--')
plt.axhline(30, color='g', linestyle='--')
plt.legend()

plt.subplot(4, 1, 3)
plt.plot(data['Portfolio_Value'], label='Portfolio Value', color='purple')
plt.legend()

# Plot annual returns
plt.subplot(4, 1, 4)
annual_returns.plot(kind='bar')
plt.title('Annual Average Returns from RSI 14 Crossover Trading Strategy')
plt.xlabel('Year')
plt.ylabel('Return (%)')
plt.grid(True)

plt.tight_layout()
plt.show()

# Calculate cumulative returns directly from portfolio value
cumulative_return = (data['Portfolio Value'].iloc[-1] / initial_cash - 1) * 100

# Plot cumulative returns
plt.figure(figsize=(10, 5))
plt.plot(data['Year'].unique(), (data.groupby('Year')['Portfolio Value'].last() / initial_cash - 1) * 100)
plt.title('Cumulative Returns from RSI 14 Crossover Trading Strategy')
plt.xlabel('Year')
plt.ylabel('Cumulative Return (%)')
plt.grid(True)
plt.show()

plt.tight_layout()
plt.show()

The Results

Annual Returns from RSI 14 Crossover Trading Strategy:

Bar chart showing the annual returns from the RSI 14 crossover trading strategy over a 10-year period.
Bar chart showing the annual returns from the RSI 14 crossover trading strategy over a 10-year period.

Cumulative Portfolio Value from RSI 14 Crossover Trading Strategy:

Line graph showing the cumulative returns from the RSI 14 crossover trading strategy, demonstrating the percentage growth of the initial $100,000 investment over a 10-year period.
Line graph showing the cumulative returns from the RSI 14 crossover trading strategy, demonstrating the percentage growth of the initial $100,000 investment over a 10-year period.
Line graph showing the cumulative portfolio value from the RSI 14 crossover trading strategy, demonstrating the growth of an initial $100,000 investment over a 10-year period.
Line graph showing the cumulative portfolio value from the RSI 14 crossover trading strategy, demonstrating the growth of an initial $100,000 investment over a 10-year period.

Close Price and RSI:

These plots illustrate the annual returns and the cumulative portfolio value over time, showing how an initial investment of $100,000 could grow by reinvesting all outputs through the years using the RSI 14 crossover trading strategy.

Analysis and Insights

The RSI 14 crossover trading strategy provides a clear framework for identifying buy and sell signals based on momentum shifts in the market. By backtesting this strategy with Python, we can visualize its performance and make informed decisions.

  1. Annual Returns:
    • The strategy demonstrated positive annual returns in most years, with notable gains in 2016, 2018, and 2023.
    • There were some negative years, such as 2020 and 2022, indicating periods of market volatility or misalignment with the strategy.
  2. Cumulative Returns:
    • The cumulative returns plot shows a steady increase over the years, with significant growth peaking in 2021.
    • Despite the dip in 2022, the strategy rebounded strongly in 2023, demonstrating resilience and potential for long-term gains.
  3. Portfolio Value:
    • The portfolio value plot highlights the strategy’s performance over the entire period, showing growth from the initial investment to over $180,000.
    • The buy and sell signals effectively captured profitable trades, contributing to the overall portfolio growth.

Conclusion

Alright, let’s wrap this up with some cool insights. Based on our backtest, the RSI 14 crossover trading strategy really showed its potential. We saw average annual returns above 5% in six out of nine years, and the overall cumulative return was a whopping 80%! Starting with $100,000, our portfolio grew to around $180,000 over a decade. Pretty neat, right?

Of course, it wasn’t all smooth sailing. We hit some bumps in the road, especially in 2020 and 2022, but the strategy bounced back nicely, showing it’s got some resilience.

So, should you use this strategy? Well, it’s a solid tool for spotting momentum in trending markets. Just remember to mix it up with other strategies and always keep an eye on those transaction costs. This little Python backtest exercise on AAPL stock was a fun way to see how algorithmic trading can work in the real world.

Give it a try, tweak it, and see how it fits with your trading style. Happy trading and coding!

By 8buky

Leave a Reply

Your email address will not be published. Required fields are marked *