问题是:
我想绘制一只股票的日内1分钟OHLC柱。 每日交易时间由几个交易周期组成。其中列出如下:
交易日期: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。
如您所见,如果我直接使用org.springframework.jdbc.BadSqlGrammarException: CallableStatementCallback;badSQLgrammar [{call find_spot()}]; nestedexception is org.postgresql.util.PSQLException: ERROR: functionfind_spot()
,则会有间隙。
现在,如果我将1分钟的数据作为数据帧。我如何绘制烛台图,任何栏之间没有间隙(例如,在10:15和10:30之间没有间隙),并且xticklabels只显示每小时的主要刻度,如22:00,23: 00,10:00,每15分钟一次,如21:15,21:30,21:45等。
您可以在此处生成一些类似形式的伪数据:
candlestick_ohlc
我在matplotlib.finance模块中看到,有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
和candlestic2_ohlc
。
我的第一个试验是使用candlestick_ohlc
,因为它不需要数字candlestick2_ohlc
参数,这会使条纹陷入困境。
我没有任何差距,但我不能将xticklabels作为我想要的,因为我不知道如何将datetimeIndex信息传递给xticklabels。
以下是我首先尝试的内容: 基本上从这篇文章中了解到: how to plot ohlc candlestick with datetime in matplotlib?
datetime
请帮忙。
答案 0 :(得分:2)
目前,您正在根据索引绘制数据。
但是,如果要使用matplotlib.dates
定位器和格式化程序,则需要在轴上绘制日期。
使用candlestick2_ohlc
无法做到这一点。相反,您需要使用candlestick_ohlc
函数。实际上,在this answer中也会对您链接的问题进行说明。
但是,使用实际日期不允许合并分页,除了可能在不同的子图中绘图之外,请参阅☼broken axes example。
因此,这里的解决方案可能是保留绘制索引并将刻度设置为与所需刻度标签对应的位置。
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()
结果看起来像
阅读非常令人困惑,但据我所知,这就是问题所在。