Using the Bollinger Bands Breakout Strategy for Entries and Exits
Step 1
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
Step 2
symbol = 'AAPL'
start_date = '2022-01-01'
end_date = '2022-12-31'
data = yf.download(symbol, start=start_date, end=end_date)
Step 3
window = 20 # 20-days SMA
multiplier = 2 # usually 2 standard deviations are considered
# Calculate the moving average (middle band)
data['Middle_Band'] = data['Close'].rolling(window=window).mean()
# Calculate the upper and lower bands
data['Upper_Band'] = data['Middle_Band'] + (data['Close'].rolling(window=window).std() * multiplier)
data['Lower_Band'] = data['Middle_Band'] - (data['Close'].rolling(window=window).std() * multiplier)
Step 4
data['Long_Entry'] = data.Close > data.Upper_Band
data['Long_Exit'] = data.Close < data.Middle_Band
data['Short_Entry'] = data.Close < data.Lower_Band
data['Short_Exit'] = data.Close > data.Middle_Band
Step 5
plt.figure(figsize=(12,6))
plt.plot(data.index, data['Close'], label='Price', alpha=0.5)
plt.plot(data.index, data['Upper_Band'], label='Upper Band', linestyle='--')
plt.plot(data.index, data['Middle_Band'], label='Middle Band', linestyle='--')
plt.plot(data.index, data['Lower_Band'], label='Lower Band', linestyle='--')
plt.title('Bollinger Bands Breakout Strategy')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(loc='best')
plt.show()
Step 6
position = 0 # 1 for long, -1 for short, 0 for no position
for i in range(window, len(data)):
if position == 0:
if data['Long_Entry'][i]:
position = 1
entry_price = data['Close'][i]
elif data['Short_Entry'][i]:
position = -1
entry_price = data['Close'][i]
elif position == 1:
if data['Long_Exit'][i]:
position = 0
profit = data['Close'][i] - entry_price
elif position == -1:
if data['Short_Exit'][i]:
position = 0
profit = entry_price - data['Close'][i]