The dataframe df has a datetime index ranging from 2019-12-02 to 2020-01-30 and I can plot it fine using mplfinance's plot function:
But as soon as I set the tick locators, the tick values get messed up and the years only show "1970."
I read this, this, and this but still can't figure it out because I'm actually using matplotlib's pyplot to make the plot (instead of pandas), my dates are actually DateTimeIndex, and I already added Year as a separate x-axis.
Goal: The format of the second plot above is exactly what I want but the days, months, and years are obviously incorrect. What am I doing wrong? Here's a reproducible code:
import yfinance as yf
import mplfinance as mpf
from datetime import datetime
import matplotlib.pylab as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
# downloading some sample stock price data from Yahoo Finance
start_date = datetime(2019, 12, 1)
end_date = datetime(2020, 1, 31)
df = yf.download('AAPL', start=start_date, end=end_date)
# using the mplfinance library to make a candle chart out of the data
fig, ax = plt.subplots(figsize = (20, 10))
mpf.plot(df, ax = ax, type='candle', style = 'charles')
# plotting months as major ticks
months = mdates.MonthLocator()
months_fmt = mdates.DateFormatter('%b')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
# plotting days as minor ticks
days = mdates.DayLocator(interval=1)
days_fmt = mdates.DateFormatter('%d')
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_minor_formatter(days_fmt)
plt.tick_params(pad=10)
# create a second x-axis beneath the first x-axis to show the year in YYYY format
years = mdates.YearLocator()
years_fmt = mdates.DateFormatter('%Y')
sec_xaxis = ax.secondary_xaxis(-0.08)
sec_xaxis.xaxis.set_major_locator(years)
sec_xaxis.xaxis.set_major_formatter(years_fmt)
# Hide the second x-axis spines and ticks
sec_xaxis.spines['bottom'].set_visible(False)
sec_xaxis.tick_params(length=0, pad=10, labelsize=15)

