Code
import yfinance as yf
import matplotlib.pyplot as plt
import mplfinance as mpf
# Define the ticker symbol for Apple
ticker_symbol = "AAPL"
# Define the date range (10 years)
start_date_1 = "2013-09-24"
end_date_1 = "2023-09-24"
# Define the date range (5 years)
start_date_2 = "2017-09-24"
end_date_2 = "2023-09-24"
# Define the date range (1 years)
start_date_3 = "2022-09-24"
end_date_3 = "2023-09-24"
# Define the date range (6 month)
start_date_4 = "2023-03-24"
end_date_4 = "2023-09-24"
# Fetch the historical data from Yahoo Finance
apple_ohlc_1 = yf.download(ticker_symbol, start=start_date_1, end=end_date_1, interval="1mo")
apple_ohlc_1["8-Month SMA"] = apple_ohlc_1["Close"].rolling(8).mean()
apple_ohlc_2 = yf.download(ticker_symbol, start=start_date_2, end=end_date_2, interval="1wk")
apple_ohlc_2["40-Week SMA"] = apple_ohlc_2["Close"].rolling(40).mean()
apple_ohlc_3 = yf.download(ticker_symbol, start=start_date_3, end=end_date_3, interval="1d")
apple_ohlc_3["50-Day SMA"] = apple_ohlc_3["Close"].rolling(50).mean()
apple_ohlc_3["200-Day SMA"] = apple_ohlc_3["Close"].rolling(200).mean()
apple_ohlc_4 = yf.download(ticker_symbol, start=start_date_4, end=end_date_4, interval="1d")
apple_ohlc_4["50-Day SMA"] = apple_ohlc_4["Close"].rolling(50).mean()
apple_ohlc_4["200-Day SMA"] = apple_ohlc_4["Close"].rolling(200).mean()
# Create the plot
fig, ax = plt.subplots(2,2,figsize=(30,22))
# Plot the candlestick chart for the first security on the first axis object
ap = mpf.make_addplot(apple_ohlc_1["8-Month SMA"], color="b", label="8-Month SMA")
mpf.plot(apple_ohlc_2, type='candle', ax=ax[0,0], style='yahoo', xrotation=0, addplot=ap)
ax[0,0].set_title("Apple 10-Year Monthly Chart")
ax[0,0].set_xlabel("Date")
ax[0,0].set_ylabel("Price")
ax[0,0].legend()
ax[0,0].grid()
# Plot the candlestick chart for the second security on the second axis object
mpf.plot(apple_ohlc_2, type='candle', ax=ax[0,1], style='yahoo', xrotation=0)
ax[0,1].set_title("Apple 5-Year Weekly Chart")
ax[0,1].set_xlabel("Date")
ax[0,1].set_ylabel("Price")
ax[0,1].legend()
ax[0,1].grid()
# Plot the candlestick chart for the third security on the third axis object
mpf.plot(apple_ohlc_3, type='candle', ax=ax[1,0], style='yahoo', xrotation=0)
ax[1,0].set_title("Apple 1-Year Daily Chart")
ax[1,0].set_xlabel("Date")
ax[1,0].set_ylabel("Price")
ax[1,0].legend()
ax[1,0].grid()
# Plot the candlestick chart for the fourth security on the fourth axis object
mpf.plot(apple_ohlc_4, type='candle', ax=ax[1,1], style='yahoo', xrotation=0)
ax[1,1].set_title("Apple 6-Month Daily Chart")
ax[1,1].set_xlabel("Date")
ax[1,1].set_ylabel("Price")
ax[1,1].legend()
ax[1,1].grid()
Sample Data
Date Open High Low Close Adj Close Volume 8-Month SMA
2013-10-01 17.087499618530273 19.258928298950195 17.08142852783203 18.667856216430664 16.29238510131836 7837732000
2013-11-01 18.71500015258789 19.940357208251953 18.299285888671875 19.859643936157227 17.332521438598633 5225155600
2013-12-01 19.928571701049805 20.540714263916016 19.242856979370117 20.036428451538086 17.588905334472656 7057397200
2014-01-01 19.845714569091797 20.007143020629883 17.626785278320312 17.878570556640625 15.694639205932617 8765954400
2014-02-01 17.95035743713379 19.68535614013672 17.832143783569336 18.794286727905273 16.49850082397461 5880366800
2014-03-01 18.693571090698242 19.60714340209961 18.671785354614258 19.169286727905273 16.928415298461914 5001698800
2014-04-01 19.205713272094727 21.408214569091797 18.26178550720215 21.074642181396484 18.61104393005371 6435060800
2014-05-01 21.14285659790039 23.006071090698242 20.726070404052734 22.60714340209961 19.964397430419922 5735668400 19.760982275009155
2014-06-01 22.641429901123047 23.762500762939453 22.23214340209961 23.232500076293945 20.631237030029297 4827739200 20.331562757492065
2014-07-01 23.3799991607666 24.860000610351562 23.142499923706055 23.899999618530273 21.224002838134766 4140344000 20.836607217788696
2014-08-01 23.725000381469727 25.725000381469727 23.31999969482422 25.625 22.755857467651367 3748308000 21.535178661346436
Error
Traceback (most recent call last):
File E:\Praveen\Python\lib\site-packages\spyder_kernels\py3compat.py:356 in compat_exec
exec(code, globals, locals)
File e:\praveen\technical team\four panel chart\candlestick_fpc.py:46
mpf.plot(apple_ohlc_2, type='candle', ax=ax[0,0], style='yahoo', xrotation=0, addplot=ap)
File E:\Praveen\Python\lib\site-packages\mplfinance\plotting.py:429 in plot
external_axes_mode = _check_for_external_axes(config)
File E:\Praveen\Python\lib\site-packages\mplfinance\_arg_validators.py:446 in _check_for_external_axes
raise ValueError('make_addplot() `ax` kwargs must all be of type `matplotlib.axis.Axes`')
ValueError: make_addplot() `ax` kwargs must all be of type `matplotlib.axis.Axes`
I'm encountering challenges when trying to plot a Simple Moving Average (SMA) line on top of a Candlestick chart using mplfinance in Python. Although I initially attempted to use the 'mav' argument, I couldn't find a straightforward way to add a legend for the SMA line. As an alternative approach, I've calculated the SMA data using the close price and aim to incorporate it while plotting.
import yfinance as yf
import matplotlib.pyplot as plt
import mplfinance as mpf
ticker_symbol = "AAPL"
start_date_1 = "2013-09-24"
end_date_1 = "2023-09-24"
start_date_2 = "2017-09-24"
end_date_2 = "2023-09-24"
start_date_3 = "2022-09-24"
end_date_3 = "2023-09-24"
start_date_4 = "2023-03-24"
end_date_4 = "2023-09-24"
apple_ohlc_1 = yf.download(ticker_symbol, start=start_date_1, end=end_date_1, interval="1mo")
apple_ohlc_1["8-Month SMA"] = apple_ohlc_1["Close"].rolling(8).mean()
apple_ohlc_2 = yf.download(ticker_symbol, start=start_date_2, end=end_date_2, interval="1wk")
apple_ohlc_2["40-Week SMA"] = apple_ohlc_2["Close"].rolling(40).mean()
apple_ohlc_3 = yf.download(ticker_symbol, start=start_date_3, end=end_date_3, interval="1d")
apple_ohlc_3["50-Day SMA"] = apple_ohlc_3["Close"].rolling(50).mean()
apple_ohlc_3["200-Day SMA"] = apple_ohlc_3["Close"].rolling(200).mean()
apple_ohlc_4 = yf.download(ticker_symbol, start=start_date_4, end=end_date_4, interval="1d")
apple_ohlc_4["50-Day SMA"] = apple_ohlc_4["Close"].rolling(50).mean()
apple_ohlc_4["200-Day SMA"] = apple_ohlc_4["Close"].rolling(200).mean()
fig = mpf.figure(figsize=(30,22), dpi=300)
ax1 = fig.add_subplot(2,2,1,style='yahoo')
ax2 = fig.add_subplot(2,2,2,style='yahoo')
ax3 = fig.add_subplot(2,2,3,style='yahoo')
ax4 = fig.add_subplot(2,2,4,style='yahoo')
ap_c18msma = mpf.make_addplot(apple_ohlc_1["8-Month SMA"], color="blue", label="8-Month SMA", ax=ax1)
mpf.plot(apple_ohlc_1, type='candle', ax=ax1, xlabel = "Date", ylabel = "Price($)", axtitle='Apple 10-Year Monthly Chart', xrotation=0, addplot=ap_c18msma, datetime_format='%m/%d/%Y')
ap_c240wsma = mpf.make_addplot(apple_ohlc_2["40-Week SMA"], color="yellow", label="40-Week SMA", ax=ax2)
mpf.plot(apple_ohlc_2, type='candle', ax=ax2, xlabel = "Date", ylabel = "Price($)", axtitle='Apple 5-Year Weekly Chart', xrotation=0, addplot=ap_c240wsma, datetime_format='%m/%d/%Y')
ap_c350200dsma = [mpf.make_addplot(apple_ohlc_3["50-Day SMA"], color="black", label="50-Day SMA", ax=ax3),
mpf.make_addplot(apple_ohlc_3["200-Day SMA"], color="pink", label="200-Day SMA", ax=ax3)]
mpf.plot(apple_ohlc_3, type='candle', ax=ax3, xlabel = "Date", ylabel = "Price($)", axtitle='Apple 1-Year Daily Chart', xrotation=0, addplot=ap_c350200dsma, datetime_format='%m/%d/%Y')
ap_c450200dsma = [mpf.make_addplot(apple_ohlc_4["50-Day SMA"], color="black", label="50-Day SMA", ax=ax4),
mpf.make_addplot(apple_ohlc_4["200-Day SMA"], color="pink", label="200-Day SMA", ax=ax4)]
mpf.plot(apple_ohlc_4, type='candle', ax=ax4, xlabel = "Date", ylabel = "Price($)", axtitle='Apple 6-Month Daily Chart', xrotation=0, addplot=ap_c450200dsma, datetime_format='%m/%d/%Y')
plt.tight_layout(pad=10.0, h_pad=2.5, w_pad=2.5, rect=(0.1, 0.1, 0.9, 0.9))
image_path = "Your Location"
plt.savefig(image_path, bbox_inches='tight', pad_inches=0.1)
plt.close()
Thanks to the guidance of @DanielGoldfarb and my research, I've successfully added multiple SMA lines to enhance my candlestick charts.