import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
# Function to identify support and resistance levels
def identify_levels(data, window=14):
data['High_Rolling'] = data['High'].rolling(window=window).max()
data['Low_Rolling'] = data['Low'].rolling(window=window).min()
return data
# Function to identify breakouts
def identify_breakouts(data):
data['Breakout_High'] = np.where(data['High'] > data['High_Rolling'].shift(1), 1, 0)
data['Breakout_Low'] = np.where(data['Low'] < data['Low_Rolling'].shift(1), 1, 0)
return data
# Function to identify false breakouts
def identify_false_breakouts(data, reversal_period=3):
data['False_Breakout_High'] = np.where(
(data['Breakout_High'] == 1) &
(data['Close'] < data['High_Rolling'].shift(1)) &
(data['Close'] > data['Close'].shift(1).rolling(window=reversal_period).min()),
1, 0
)
data['False_Breakout_Low'] = np.where(
(data['Breakout_Low'] == 1) &
(data['Close'] > data['Low_Rolling'].shift(1)) &
(data['Close'] < data['Close'].shift(1).rolling(window=reversal_period).max()),
1, 0
)
return data
# Function to backtest the false breakout strategy
def backtest_strategy(data):
initial_capital = 10000
position = 0
capital = initial_capital
for i in range(len(data)):
if data['False_Breakout_High'].iloc[i] == 1:
position = capital / data['Close'].iloc[i]
capital = 0
elif data['False_Breakout_Low'].iloc[i] == 1 and position > 0:
capital = position * data['Close'].iloc[i]
position = 0
final_capital = capital + (position * data['Close'].iloc[-1] if position > 0 else 0)
return final_capital
# Load historical data
stock_data = yf.download('AAPL', start='2020-01-01', end='2023-01-01')
stock_data = identify_levels(stock_data)
stock_data = identify_breakouts(stock_data)
stock_data = identify_false_breakouts(stock_data)
# Backtest the strategy
final_capital = backtest_strategy(stock_data)
print(f"Final capital after backtesting: ${final_capital:.2f}")
# Plot the results
plt.figure(figsize=(14, 7))
plt.plot(stock_data['Close'], label='Close Price')
plt.scatter(stock_data.loc[stock_data['False_Breakout_High'] == 1].index,
stock_data.loc[stock_data['False_Breakout_High'] == 1].Close, color='red',
label='False Breakout High', marker='^', alpha=1)
plt.scatter(stock_data.loc[stock_data['False_Breakout_Low'] == 1].index,
stock_data.loc[stock_data['False_Breakout_Low'] == 1].Close, color='blue',
label='False Breakout Low', marker='v', alpha=1)
plt.title('False Breakout Strategy')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()