I'm trying to plot simple stock data using yfinance and mplfinance, however I keep running into issues with datetimes (I believe). This is what I have so far.
Here is a portion of the dataframe that I'm using.
Date Open High Low Close Adj Close Volume
2020-01-02 17.6299991607666 17.700000762939453 16.329999923706055 16.39999961853 16.39999961853 3668700
2020-01-03 16.350000381469727 16.729999542236328 15.8100004196167 16.01000022888 16.01000022888 2280600
2020-01-06 16.170000076293945 16.190000534057617 15.260000228881836 15.5 15.5 3035700
2020-01-07 15.619999885559082 15.670000076293945 15.199999809265137 15.32999992375 15.3299999 2038700
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mplfinance as mpf
import talib
import yfinance as yf
stock = yf.download('MSFT', '2020-1-1','2020-07-07')
stock.index = pd.to_datetime(stock.index)
stock = stock[['Open', 'High', 'Low', 'Close', 'Volume']]
inputs = {
'open': stock['Open'],
'high': stock['High'],
'low': stock['Low'],
'close': stock['Close'],
'volume': stock['Volume']
}
close = talib.SMA(stock['Close'])
from talib import MA_Type
upper, middle, lower = talib.BBANDS(close, matype=MA_Type.T3)
output = talib.MOM(close, timeperiod=5)
mpf.plot(stock)
plt.plot(upper)
plt.plot(middle)
plt.plot(lower)
plt.show()
I keep getting this error when plotting it however. I don't know where the "-36881.641" is coming from
ValueError: view limit minimum -36881.641796875 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
First of all, you should not be mixing mpf.plot()
and plt.plot()
. They are not necessarily compatible in the way they handle data; and if you do mix them, the results are undefined.
You should instead be using mpf.make_addplot()
to add your Bollinger Band data to the plot. See this notebook tutorial for examples.
The problem you are seeing is likely related to the fact that mplfinance manipulates the date axis to use an integer index under the hood in order to avoid displaying non-trading days. Setting show_nontrading=True
may fix your problem, but maybe not. However certainly using mpf.make_addplot()
as described above (I expect) will fix your problem. Let me know.