import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
# Define the ticker symbol and the start and end dates
ticker = "AAPL"
start_date = "2022-01-01"
end_date = "2022-03-01"
# Download the data from Yahoo Finance
data = yf.download(ticker, start=start_date, end=end_date)
# Define the 20-day simple moving average
data['SMA20'] = data['Close'].rolling(window=20).mean()
# Define the high and low of the flag pattern
flag_high = data['High'].rolling(window=5).max()
flag_low = data['Low'].rolling(window=5).min()
# Check if the current candlestick is a flag pattern
data['Flag'] = ((data['High'] >= flag_high.shift(1)) & (data['Low'] <;= flag_low.shift(1)))
# Plot the data and the flag pattern
fig, ax = plt.subplots(figsize=(12,6))
ax.plot(data['Close'], label='Price')
ax.plot(data['SMA20'], label='SMA20')
ax.fill_between(data.index, flag_low, flag_high, alpha=0.2, color='gray')
ax.scatter(data[data['Flag']].index, data[data['Flag']]['Low'], marker='s', color='green', label='Flag pattern')
ax.legend()
plt.show()