我对 plotly 和 finplot 不是很熟悉,但是(完全披露)我是 mplfinance 的维护者。mplfinance 中特定蜡烛的着色尚不支持,但我们已对此提出要求并计划在未来支持它。
与此同时,这可以通过一些额外的工作使用 mplfinance 来完成。基本思想是这样的:
- 将您的数据框一分为二,以获得您想要的两种不同颜色,每个数据框仅包括您想要的颜色的蜡烛,以及所有其他蜡烛的 NaN 值。
- 创建两个自定义“mplfinance 样式”,每个蜡烛只有一种颜色,但每种样式的颜色不同。
- 在相同的轴上绘制两个数据框,每个轴都有其指定的颜色样式。
这是一些示例代码。此示例的数据可在此处找到。
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()
上述代码的结果:
顺便说一句,由于您提到了垂直线vlines
,因此使用 mplfinance 的(垂直线)kwarg用垂直线突出显示特定蜡烛很简单:
## 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)
结果: