mplfinance plot doesn't show time values correctly

829 Views Asked by At

My first question on Stackoverflow. Hope the format satisfies Stackoverflow's requirement.

I'm learning Python and using "mplfinance" to plot 5-minute stock price, but the time on the x-axes is not right. My test code is as below. The time axes of the plot is "18:05, 18:30, 18:55, 19:20, 19:45, 20:10, 20:35" which don't show in the data file at all. I extracted 3 days data up to Dec 4 (or Dec 5), 2020 from Yahoo and plotted the last 35 points after some simple processing. (if you run the program at a different day, the time axis will be different)

Thank you for any help and enlightenment!

import pandas as pd
import yfinance as yf
import mplfinance as mpf

def plot_5min_chart():
        # 5-minute data
        mdata = yf.download('DDD', period='3d', interval='5m')
        mdata = pd.DataFrame(mdata)
        mdata['10ma'] = mdata['Close'].rolling(window=10, min_periods=0).mean()
        mdata['20ma'] = mdata['Close'].rolling(window=20, min_periods=0).mean()
        mdata['50ma'] = mdata['Close'].rolling(window=50, min_periods=0).mean()
        mdata.dropna(inplace=True)
        mdata.to_csv('test_5minute.csv')

        # plot 5-minute chart
        mpf.figure()
        ntl2 = 35
        kwargs = dict(type='candle', volume=True, figratio=(8,5),
                      figscale=0.85, num_panels=3, panel_ratios=(6,2,2))
        ap2 = [
            mpf.make_addplot(mdata['10ma'].tail(ntl2), width=2, linestyle='-', color='lime', panel=0),
            mpf.make_addplot(mdata['20ma'].tail(ntl2), width=2, linestyle='--', color='c', panel=0),
            mpf.make_addplot(mdata['50ma'].tail(ntl2), width=2, linestyle='-', color='orange', panel=0),
        ]
        titlem = '5-minute chart'
        mpf.plot(mdata.tail(ntl2),**kwargs, addplot=ap2, style='charles', title=titlem,
                 savefig=dict(fname='5minutechart.png', dpi=800, pad_inches=8)
                 )

plot_5min_chart()

test 5-minute chart

1

There are 1 best solutions below

1
On

I think this is the same as a known-bug in mplfinance, reported here: https://github.com/matplotlib/mplfinance/issues/236

The fix for this is released now. To get the newest code: pip install --upgrade mplfinance

If anyone was depending on the old behavior (that used time zone info, when present, in the datetime index, to convert to UTC) they can access that old behavior by setting kwarg tz_localize=False when calling mpf.plot().

The new behavior is to ignore tzinfo in the datetime index and always plot according to the local time in the datetime index.