我对 plotly 和 finplot 不是很熟悉,但是(完全披露)我是 mplfinance 的维护者。目前尚不支持在 mplfinance 中为特定蜡烛着色,但我们已对此提出要求并计划在未来支持它。
与此同时,这可以使用 mplfinance 完成一些额外的工作。基本思路是这样的:
- 将您的数据框分成两部分,以获得您想要的两种不同颜色,每个数据框仅包含您想要的颜色的蜡烛,以及所有其他蜡烛的 NaN 值。
- 创建两个自定义“mplfinance 样式”,每个样式的蜡烛只有一种颜色,但每种样式的颜色不同。
- 在相同的轴上绘制两个数据框,每个轴都有其指定的颜色样式。
这是一些示例代码。这个例子的数据可以在here找到。
import pandas as pd
import mplfinance as mpf
# Read in S&P500 November 2019 OHLCV:
df1 = pd.read_csv('data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True)
df1.drop('Volume',axis=1,inplace=True) # Drop Volume (not needed for this demo)
# Create a DataFrame with the same shape, but all NaN values:
nc = [float('nan')]*len(df1) # nc = Nan Column
df2 = pd.DataFrame(dict(Open=nc,High=nc,Low=nc,Close=nc))
df2.index = df1.index
# Copy specific values from one DataFrame to the Other
df2.loc['11/8/2019'] = df1.loc['11/8/2019'].copy()
df2.loc['11/15/2019'] = df1.loc['11/15/2019'].copy()
df2.loc['11/21/2019'] = df1.loc['11/21/2019'].copy()
df2.loc['11/27/2019'] = df1.loc['11/27/2019'].copy()
# Set the same values to NaN back in the original DataFrame:
df1.loc[ '11/8/2019'] = [float('nan')]*4
df1.loc['11/15/2019'] = [float('nan')]*4
df1.loc['11/21/2019'] = [float('nan')]*4
df1.loc['11/27/2019'] = [float('nan')]*4
# Now make 2 custom styles where the candles are all the same color
# (But a different color for each style)
# style1 has all candles 'blue'
m = mpf.make_marketcolors(base_mpf_style='default',up='b',down='b')
style1 = mpf.make_mpf_style(base_mpf_style='default',marketcolors=m)
# style2 has all candles 'lime'
m = mpf.make_marketcolors(base_mpf_style='default',up='lime',down='lime')
style2 = mpf.make_mpf_style(base_mpf_style='default',marketcolors=m)
# Now plot each DataFrame on the same Axes but with different styles:
# Use returnfig=True to get the Axes and pass to the next call:
fig, ax = mpf.plot(df1,type='candle',style=style1,returnfig=True)
mpf.plot(df2,type='candle',style=style2,ax=ax[0])
mpf.show()
以上代码的结果:
顺便说一下,既然您提到了垂直线,使用 mplfinance 的 vlines(垂直线)用垂直线突出显示特定蜡烛很简单) 夸格:
## Easier just to add vertical lines:
# Read in S&P500 November 2019 OHLCV:
df1 = pd.read_csv('data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True)
v = dict(vlines=['11/7/2019','11/15/2019','11/21/2019','11/27/2019'],
alpha=0.3,colors=['lime'],linewidths=[7])
mpf.plot(df1,type='candle',vlines=v)
结果: