matplotlib.finance.candlestick_ohlc plot intraday 1min bar data with time breaks and proper xticklabels at every hour

后端 未结 1 487
臣服心动
臣服心动 2020-12-06 14:46

The problem is:

I want to plot the intraday 1 minute OHLC bars of one stock. The daily trading hour is composed of several segments of trading periods. Which is lis

相关标签:
1条回答
  • 2020-12-06 15:19

    Currently you are plotting the data against its index. However, if you want to use matplotlib.dates locators and formatters you would need to plot dates on the axes. This is not possible using candlestick2_ohlc. Instead you would need to use candlestick_ohlc function. Actually this is also said in this answer to the question you link to. Using actual dates however, does not allow to merge the sements, other than possibly plotting in different subplots, see ☼broken axes example.

    So a solution here might be to stay with plotting the index and setting the ticks to the locations that correspond the desired tick labels.

    xdate = bar_df.index
    def mydate(x, pos):
        try:
            return xdate[int(x)]
        except IndexError:
            return ''
    # create date ranges of possible dates to show as major and minor ticklabels
    major_dr = pd.date_range('2017-09-13 21:00:00','2017-09-14 15:00:00', freq='60min')
    minor_dr = pd.date_range('2017-09-13 21:00:00','2017-09-14 15:00:00', freq='15min')
    # calculate positions of the above dates inside the dataframe index
    major_ticks = np.isin(xdate, major_dr).nonzero()[0] 
    minor_ticks = np.isin(xdate, minor_dr).nonzero()[0]
    # use those positions to put ticks at
    ax.xaxis.set_major_locator(ticker.FixedLocator(major_ticks))
    ax.xaxis.set_minor_locator(ticker.FixedLocator(minor_ticks))
    ax.minorticks_on()
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
    fig.autofmt_xdate()
    

    The result would look like

    This is reading very confusingly, but to the best of my understanding this is what the question asks for.

    0 讨论(0)
提交回复
热议问题