如何在mplfinance.plot()或任何类似的库中添加字符串注释到每个蜡烛图上方?

4

我想要的图片

我希望使用mplfinance包在每个蜡烛图上方添加一个字符串注释。

是否有一种方法可以使用mplfinance或其他包来实现呢?

以下是我使用的代码:

import pandas as pd
import mplfinance as mpf
import matplotlib.animation as animation
from mplfinance import *
import datetime
from datetime import date, datetime

fig = mpf.figure(style="charles",figsize=(7,8))
ax1 = fig.add_subplot(1,1,1 , title='ETH')

def animate(ival):
    idf = pd.read_csv("test1.csv", index_col=0)
    idf['minute'] = pd.to_datetime(idf['minute'], format="%m/%d/%Y %H:%M")

    idf.set_index('minute', inplace=True)

    ax1.clear()
    mpf.plot(idf, ax=ax1, type='candle',  ylabel='Price US$')

ani = animation.FuncAnimation(fig, animate, interval=250)

mpf.show()
1个回答

3
你应该能够使用 Axes.text() 来完成这个任务。
在调用 mpf.plot() 之后,再调用。
ax1.text()

对于您想要的每个文本(在您的情况下,对于每个蜡烛),都有一个重要的警告与传递给ax1.text()x轴值相关:

  • 如果您没有指定show_nontrading=True,则默认为False,在这种情况下,您传递给ax1.text()x轴值用于文本位置的必须是相应蜡烛所在行的行号,从DataFrame中的第一行开始计数,编号从0开始。
  • 另一方面,如果您设置了show_nontrading=True,则传递给ax1.text()的x轴值将需要是matplotlib datetime。您可以将DataFrame DatetimeIndex中的pandas datetimes转换为matplotlib datetimes,方法如下:
import matplotlib.dates as mdates
my_mpldates = mdates.date2num(idf.index.to_pydatetime())

我建议使用第一种选项(DataFrame行号),因为它更简单。我目前正在开发一个mplfinance增强功能,它将允许您将x轴值输入为任何类型的日期时间对象(这是更直观的方法),但可能需要一个月或两个月才能完成该增强功能,因为它并不是微不足道的。
使用mplfinance存储库示例数据文件夹中的数据,以下是代码示例:
import pandas as pd
import mplfinance as mpf

infile = 'data/yahoofinance-SPY-20200901-20210113.csv'

# take rows [18:28] to keep the demo small:
df = pd.read_csv(infile, index_col=0, parse_dates=True).iloc[18:25]

fig, axlist = mpf.plot(df,type='candle',volume=True,
                       ylim=(330,345),returnfig=True)

x = 1
y = df.loc[df.index[x],'High']+1
axlist[0].text(x,y,'Custom\nText\nHere')

x = 3
y = df.loc[df.index[x],'High']+1
axlist[0].text(x,y,'High here\n= '+str(y-1),fontstyle='italic')

x = 5
y = df.loc[df.index[x],'High']+1
axlist[0].text(x-0.2,y,'More\nCustom\nText\nHere',fontweight='bold')

mpf.show()

上述代码示例的评论:

  • I am setting the ylim=(330,345) in order to provide a little extra room above the candles for the text. In practice you might choose the high dynamically as perhaps high_ylim = 1.03*max(df['High'].values).

  • Notice that the for first two candles with text, the text begins at the center of the candle. The 3rd text call uses x-0.2 to position the text more over the center of the candle.

  • For this example, the y location of the candle is determined by taking the high of that candle and adding 1. (y = df.loc[df.index[x],'High']+1) Of course adding 1 is arbitrary, and in practice, depending on the maginitude of your prices, adding 1 may be too little or too much. Rather you may want to add a small percentage, for example 0.2 percent:

    y = df.loc[df.index[x],'High']
    y = y * 1.002
    
  • Here is the plot the above code generates:

enter image description here


1
听起来很酷,你能提供代码示例吗?我发现做起来有些困难,谢谢。 - Mr Dream

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接