3

My very 1st need is to overlay a curve over a candlestick chart. To draw this candlestick chart, mplfinance appears very nice. Unfortunately, I have found no way to overlay additional curve to the candlestick.

Considering example below, if anyone of you knows how to overlay 'Noise' column over the candlesticks drawn from 'minutely' dataframe, this would be great!

import pandas as pd
import mplfinance as mpf

minutely = pd.DataFrame({'Date':[pd.Timestamp('2021-01-07 00:00:00'),
                                 pd.Timestamp('2021-01-07 00:01:00'),
                                 pd.Timestamp('2021-01-07 00:02:00'),
                                 pd.Timestamp('2021-01-07 00:03:00'),
                                 pd.Timestamp('2021-01-07 00:04:00')],
                          'Open':[36769.36, 36880.00, 36851.42,36922.19,37083.18],
                          'High':[36880.00, 36880.00, 36950.00, 37089.69, 37094.70],
                          'Low': [36760.00,  36817.64, 36810.03, 36922.13, 36565.49],
                          'Close':[36880.00, 36851.97, 36922.14, 37075.80, 36691.3]})

noise = pd.DataFrame({'Date':[pd.Timestamp('2021-01-07 00:00:00'),
                                 pd.Timestamp('2021-01-07 00:01:00'),
                                 pd.Timestamp('2021-01-07 00:02:00'),
                                 pd.Timestamp('2021-01-07 00:03:00'),
                                 pd.Timestamp('2021-01-07 00:04:00')],
                          'Noise':[36779.36, 36870.00, 36881.42,36902.19,37103.18]})

# Draw candlesticks
minutely = minutely.set_index('Date')
noise = noise.set_index('Date')
mpf.plot(minutely, type='candle')

Not stopping here, I had in mind to use the 'old' candlestick_ohlcv function to draw a candlestick graph, then overlay data using native matplotlib capabilities. This gives the code below, but when displaying the candlesticks, the x scale appears meaningless.

I should have only 5 candles, with a x scale going from 2020/01/07 00:00 to 2020/01/07 00:04.

I can see the graph shows a x scale starting from 2020/01/06 16:48 to 2020/01/07 07:12.

I don't understand this and candles are meaningless...

import pandas as pd
import matplotlib.pyplot as plt 
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mpdates 

minutely = pd.DataFrame({'Date':[pd.Timestamp('2021-01-07 00:00:00'),
                                 pd.Timestamp('2021-01-07 00:01:00'),
                                 pd.Timestamp('2021-01-07 00:02:00'),
                                 pd.Timestamp('2021-01-07 00:03:00'),
                                 pd.Timestamp('2021-01-07 00:04:00')],
                          'Open':[36769.36, 36880.00, 36851.42,36922.19,37083.18],
                          'High':[36880.00, 36880.00, 36950.00, 37089.69, 37094.70],
                          'Low': [36760.00,  36817.64, 36810.03, 36922.13, 36565.49],
                          'Close':[36880.00, 36851.97, 36922.14, 37075.80, 36691.3]})

noise = pd.DataFrame({'Date':[pd.Timestamp('2021-01-07 00:00:00'),
                                 pd.Timestamp('2021-01-07 00:01:00'),
                                 pd.Timestamp('2021-01-07 00:02:00'),
                                 pd.Timestamp('2021-01-07 00:03:00'),
                                 pd.Timestamp('2021-01-07 00:04:00')],
                          'Noise':[36779.36, 36870.00, 36881.42,36902.19,37103.18]})

minutely['Date'] = minutely['Date'].map(mpdates.date2num)

plt.style.use('dark_background')
fig, ax = plt.subplots() 
candlestick_ohlc(ax, minutely.values, width = 0.6,  
                 colorup = 'green', colordown = 'red',  
                 alpha = 0.8) 
# Setting labels  
ax.set_xlabel('Date') 
ax.set_ylabel('Price')
# Formatting Date
date_format = mpdates.DateFormatter('%d-%m-%Y %H:%M') 
ax.xaxis.set_major_formatter(date_format) 
fig.autofmt_xdate() 
fig.tight_layout() 
# show the plot 
plt.show()

Please, would someone know of a way to overlay this external data to candlestick data? Thanks in advance for any help, Bests,

4

2 回答 2

3

您可以通过在上面的第一个代码示例中仅添加一行代码来做到这一点:

就在调用之前mpf.plot()添加以下行:

ap = mpf.make_addplot(noise)

然后将调用更改mpf.plot()为包含addplot关键字,因此:

ap = mpf.make_addplot(noise)
mpf.plot(minutely, type='candle', addplot=ap)

在此处输入图像描述

如果需要,还可以修改日期时间格式:

ap = mpf.make_addplot(noise)
mpf.plot(minutely, type='candle', addplot=ap, datetime_format='%b %d, %H:%M')

在此处输入图像描述

我强烈建议您通读这两个教程。它们相对较短,可能只需要 15 到 30 分钟就可以仔细阅读它们:


PS 作为一般规则,我不鼓励访问 mplfinance 的 Figure 和 Axes 对象:因此,您的代码会简单得多。对图形和轴的访问只能用于需要 mplfinance 尚不支持的高级功能的绘图。如果您通读了这些教程,我相信您会发现大多数使用金融图完成的事情都可以简单地完成,而无需直接操纵 Figure 和 Axes

于 2021-01-24T04:04:24.337 回答
2

returnfig=True您可以通过使用参数获取 matplotlib Figure 和 Axes 对象,在烛台图顶部叠加一个绘图。返回两个轴:主要和次要。在以下示例中,基于您提供的样本,噪声线图是使用主轴创建的。

请注意,mpf.plot返回一个数字,其中 x 轴刻度由默认从零开始的整数单位组成(如熊猫条形图)。这是因为绘图功能是为了可视化交易时间的数据而不是连续的日期时间变量而构建的,该变量将包括许多非交易时间的差距。可以通过设置更改此行为show_nontrading=True。在下面的示例中,我为这两种选择提供了一个解决方案,使用 pandas 绘图函数来绘制线条,因为与 matplotlib 相比,它使用起来稍微方便一些:

import pandas as pd                                        # v 1.1.3
import matplotlib.pyplot as plt                            # v 3.3.2
import matplotlib.dates as mpdates
import mplfinance as mpf                                   # v 0.12.7a4
from mplfinance.original_flavor import candlestick_ohlc

# Create sample data
dti = pd.date_range('2021-01-07', periods=5, freq='min')

minutely = pd.DataFrame({'Open':[36769.36, 36880.00, 36851.42,36922.19,37083.18],
                         'High':[36880.00, 36880.00, 36950.00, 37089.69, 37094.70],
                         'Low': [36760.00,  36817.64, 36810.03, 36922.13, 36565.49],
                         'Close':[36880.00, 36851.97, 36922.14, 37075.80, 36691.3]},
                        index=dti)

noise = pd.DataFrame({'Noise':[36779.36, 36870.00, 36881.42,36902.19,37103.18]},
                     index=dti)

# Create candlestick chart overlaid with a pandas line plot
fig, (ax1, ax2) = mpf.plot(minutely, type='candle', returnfig=True, figsize=(6,4))
noise.plot(ax=ax1, use_index=False);

# # Create same figure including non-trading hours, in this case the datetime
# # variable is used for the x-axis scale
# fig, (ax1, ax2) = mpf.plot(minutely, type='candle', show_nontrading=True,
#                            returnfig=True, figsize=(6,4))
# noise.plot(ax=ax1, x_compat=True);

mpf_candlestick


关于您问题的第二部分,旧candlestick_ohlcv函数的文档字符串指出这width是一天的一小部分(对应于 matplotlib 日期单位)。示例数据仅跨越几分钟,但您已设置width=0.6(超过半天),这会产生非常宽的烛台,使绘图无法阅读。设置width=0.0003似乎运作良好。需要调整的另一件事是 x 刻度,因为它们似乎被放置在一些随机的位置。这是使用与上述相同数据的示例:

# Edit minutely dataframe for use with candlestick_ohlc function
minutely['Date'] = mpdates.date2num(minutely.index)
minutely = minutely[['Date', 'Open', 'High', 'Low', 'Close']]

# Create candlestick chart overlaid with a pandas line plot
plt.style.use('dark_background')
fig, ax = plt.subplots(figsize=(6,4))
candlestick_ohlc(ax, minutely.values, width=0.0003,
                 colorup='green', colordown='red', alpha=0.8)
noise.plot(ax=ax, x_compat=True)

# Set labels
ax.set_xlabel('Date')
ax.set_ylabel('Price')

# Create ticks that match the locations of the candlesticks and format labels
ax.set_xticks(minutely['Date'])
date_format = mpdates.DateFormatter('%H:%M\n%d-%m-%Y ') 
ax.xaxis.set_major_formatter(date_format)
fig.autofmt_xdate(rotation=0, ha='center')

mpf_candlestick_old



参考:Daniel Goldfarb(当前的mplfinance 包维护者)的这个答案;pandas 绘图函数,以及x_compat用于将 pandas 绘图日期单位转换为 matplotlib 日期单位的参数

于 2021-01-22T16:57:44.547 回答