matplotlib.finance.candlestick_ohlc以小时为单位绘制盘中的1分钟柱形数据,其中包含时间间隔和每小时适当的xticklabels [英] matplotlib.finance.candlestick_ohlc plot intraday 1min bar data with time breaks and proper xticklabels at every hour

查看:138
本文介绍了matplotlib.finance.candlestick_ohlc以小时为单位绘制盘中的1分钟柱形数据,其中包含时间间隔和每小时适当的xticklabels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是:

我想绘制一只股票的盘中1分钟OHLC线. 每日交易时间由交易时段的几个部分组成.列出如下:

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 listed below:

交易日期:2017/09/14

Trade date: 2017/09/14

包括的交易时间: 2017/09/13 21:00-23:00, 2017/09/14 9:00-10:15,10:30-11:30,13:30-15:00.

Included trading hour: 2017/09/13 21:00 - 23:00, 2017/09/14 9:00 - 10:15, 10:30 - 11:30, 13:30 - 15:00.

如您所见,如果我直接使用candlestick_ohlc,则会出现空白.

As you can see, if I just use candlestick_ohlc directly, there will be gaps.

现在,如果我获得1分钟数据作为数据帧.如何绘制烛台图,在任何柱线之间都没有间隙(例如,在10:15和10:30柱线之间没有间隙),并且xticklabel仅每小时显示主要刻度线,例如22:00、23: 00、10:00,以及每15分钟的小滴答声,例如21:15、21:30、21:45,等等.

Now if I get 1minute data as a dataframe. How can I plot a candlestick graph, with no gaps between any bars(e.g, no gap between 10:15 and 10:30 bar), and have the xticklabels only displaying the major ticks at every hour, like 22:00, 23:00, 10:00, and minor ticks at every 15 minutes, like 21:15, 21:30, 21:45, etc.

以下是我的数据框在1个交易日内的样子:

Here is a picture of what my dataframe looks like for 1 trading day:

您可以在此处生成一些具有类似形式的伪数据:

You can generate some pseudo data with similar form here:

def generate_pseudo_data():
    # datetime index data
    idx = pd.date_range('2017-09-13 21:01:00',
                        '2017-09-13 23:00:00', freq='1min')
    idx = idx.append(pd.date_range('2017-09-14 09:01:00',
                                   '2017-09-14 10:15:00', freq='1min'))
    idx = idx.append(pd.date_range('2017-09-14 10:31:00',
                                   '2017-09-14 11:30:00', freq='1min'))
    idx = idx.append(pd.date_range('2017-09-14 13:31:00',
                                   '2017-09-14 15:00:00', freq='1min'))

    # OHLC
    inc = np.random.randint(-2, 3, size=idx.shape).cumsum()
    opens = 3500 + inc
    closes = opens + np.random.randint(-3, 3, idx.shape)
    range_max = np.max(np.concatenate([opens.reshape(-1, 1),
                                       closes.reshape(-1, 1)], axis=1), axis=1)
    highs = range_max + np.random.randint(0, 5, size=idx.shape)
    range_min = np.min(np.concatenate([opens.reshape(-1, 1),
                                       closes.reshape(-1, 1)], axis=1), axis=1)
    lows = range_min - np.random.randint(0, 5, size=idx.shape)
    bar_df = pd.DataFrame({'open': opens, 'high': highs, 'low': lows,
                           'close': closes}, index=idx)
    return bar_df

我在matplotlib.finance模块中看到,有candlestic2_ohlccandlestick_ohlc. 我的第一个尝试是使用candlestick2_ohlc,因为它不需要数字datetime参数,该参数会弄乱很多缝隙. 我没有任何差距,但是我无法按自己的意愿制作xticklabels,因为我现在不知道如何将datetimeIndex信息传递给xticklabels.

I saw in matplotlib.finance module, there is candlestic2_ohlc, and candlestick_ohlc. My first trial was to use candlestick2_ohlc since it doesn't require a numerical datetime argument which would mess up the bars with many gaps. I don't get any gaps, but I can't make the xticklabels as what I want because I don't know how to pass the datetimeIndex information to the xticklabels now.

这是我首先尝试的方法: 基本上从这篇文章中学到: 如何在matplotlib中用日期时间绘制ohlc烛台?

Here is what I have tried first: Basically learnt from this post: how to plot ohlc candlestick with datetime in matplotlib?

from datetime import datetime, time

import pandas as pd
import numpy as np

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc, candlestick_ohlc
import matplotlib.dates as mdates
from matplotlib import ticker

bar_df = generate_pseudo_data()
fig, ax = plt.subplots()
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()

candlestick2_ohlc(ax, bar_df.open, bar_df.high, bar_df.low, bar_df.close,
                  width=0.6, colorup='r', colordown='c', alpha=1)
xdate = bar_df.index
def mydate(x, pos):
    try:
        return xdate[int(x)]
    except IndexError:
        return ''

ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
# Everything works fine up to now.
# However the xticklabels are not exactly at 22:00, 23:00, etc.
# And no minor tick labels set up at 21:15, 21:30, 21:45, etc.

# I tried either one of the command below, but both failed with no xticklabels
# showed up.

ax.xaxis.set_major_locator(mdates.HourLocator())
ax.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 15, 30, 45],
                                                interval=1))

# This one works because it only tells xticklabels to have at most
# 8 tick labels, but no info about where the xticklabels should be.
ax.xaxis.set_major_locator(ticker.MaxNLocator(8))

请帮助.

推荐答案

当前,您正在根据其索引绘制数据. 但是,如果要使用matplotlib.dates定位器和格式化程序,则需要在轴上绘制日期. 使用candlestick2_ohlc无法做到这一点.相反,您将需要使用candlestick_ohlc函数.实际上,在您链接到的问题的此答案中也说了这一点. 但是,使用实际日期不允许合并这些结点,除了可能在不同的子图中作图外,请参见 axes断轴示例.

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()

结果看起来像

这读起来很混乱,但是据我所知,这就是问题的根源.

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

这篇关于matplotlib.finance.candlestick_ohlc以小时为单位绘制盘中的1分钟柱形数据,其中包含时间间隔和每小时适当的xticklabels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆