我正在使用 mplfinance 库创建绘图,以绘制带有技术指标的财务图表。但我需要隐藏周末或假期带来的间隙。当尝试使用参数
show_nontrading=False
隐藏它们时,图表会超出比例并且 x 轴会中断。这是我的代码:
def plot_mplfinance(self, path):
from matplotlib.ticker import MaxNLocator
from matplotlib.dates import MonthLocator, DateFormatter
from matplotlib.ticker import FixedLocator
from matplotlib.gridspec import GridSpec
import os
import warnings
warnings.filterwarnings("ignore")
try:
cmf= self.CMF().dropna()
sma_cmf= self.sma_aux(20, cmf).SMA
sma_cmf= sma_cmf.iloc[19:]
fallacmf=False
except: #Esto ocurrirá cuando Eikon no traiga datos de volumen
fallacmf=True
macd = self.MACD(12,26,9)
rsi = self.RSI(14)
rsi=rsi.iloc[13:]
macd= macd[['MACD','Signal','Histogram']]
sma_df= self.SMA(20)
sma_df= sma_df.iloc[19:]
psar_df= self.PSAR()
psarbull= psar_df["PSAR_BULL"]
psarbear= psar_df["PSAR_BEAR"]
os.chdir(path)
prices= self.prices[['Open','High','Low','Adj Close','Volume']]
prices.columns= ['Open','High','Low','Close','Volume']
last_price = prices['Close'].iloc[-1]
fig = plt.figure(figsize=(11.692913385826772, 8)) # Ajusta el tamaño según tus necesidades
if fallacmf==False:
gs = GridSpec(5, 1, height_ratios=[3, 1, 1, 1, 1])
# Subplot superior para el gráfico de precios con PSAR y SMA
ax1 = plt.subplot(gs[0])
ax0 = plt.subplot(gs[1], sharex=ax1)
mpf.plot(prices, type='candle', style='yahoo', figscale=1.5, volume=ax0, show_nontrading=True, tight_layout=False, returnfig=True, ax=ax1)
ax1.set_title(f'{self.ticker} - Último precio ${last_price:.2f}', fontsize=15, loc='center')
ax1.plot(psarbull.index, psarbull, 'o', markersize=1, color="blue", label='Up Trend')
ax1.plot(psarbear.index, psarbear, 'o', markersize=1, color="red", label='Down Trend')
ax1.plot(sma_df.index, sma_df.SMA, color="green", label='SMA 20', linewidth=1.0)
ax1.axhline(y=last_price, color='gray', linestyle='--', linewidth=1.0, label='Último precio')
ax2 = plt.subplot(gs[2], sharex=ax1) # Compartir el mismo eje X con el subplot superior
ax2.plot(macd.index, macd['MACD'], color="green", label="MACD (12,26)")
ax2.plot(macd.index, macd['Signal'], color="lightgreen", label="Signal Line (9)")
ax2.fill_between(macd.index, macd['Histogram'], color='g', alpha=0.5, label="Histogram")
ax3 = plt.subplot(gs[3], sharex=ax1) # Compartir el mismo eje X con el subplot superior
ax3.plot(rsi.index, rsi['RSI'], color="purple", label="RSI (14)")
ax3.set_ylim(0, 100)
ax3.axhline(y=30, color='gray', linestyle='--', linewidth=1.0)
ax3.axhline(y=70, color='gray', linestyle='--', linewidth=1.0)
ax4 = plt.subplot(gs[4], sharex=ax1) # Compartir el mismo eje X con el subplot superior
ax4.plot(cmf.index, cmf, color="orange", label="CMF")
ax4.plot(sma_cmf.index, sma_cmf, color="brown", label='SMA 20')
# Configurar etiquetas, leyendas, etc. para ambos subplots según tus necesidades
# Remove x-axis from ax1
ax1.get_xaxis().set_visible(False) # Eliminar la etiqueta del eje X del subplot superior
ax0.get_xaxis().set_visible(False)
ax2.get_xaxis().set_visible(False)
ax3.get_xaxis().set_visible(False)
ax1.tick_params(axis='y', labelleft=True, labelright=False)
ax1.yaxis.set_ticks_position('left')
ax1.yaxis.set_label_position("left")
ax1.set_ylabel('Precios')
ax2.set_ylabel('MACD')
ax3.set_ylabel('RSI')
ax4.set_ylabel('CMF')
ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
ax4.grid(axis='y')
for ax in [ax1, ax0, ax2, ax3, ax4]:
for spine in ax.spines.values():
spine.set_visible(False)
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
lines3, labels3 = ax3.get_legend_handles_labels()
lines4, labels4 = ax4.get_legend_handles_labels()
ax1.legend(lines1, labels1, loc='upper left', fontsize=8)
ax2.legend(lines2, labels2, loc='upper left', fontsize=8)
ax3.legend(lines3, labels3, loc='upper left', fontsize=8)
ax4.legend(lines4, labels4, loc='upper left', fontsize=8)
将参数更改为
show_nontrading=False
时,图像完全损坏,我不知道如何修复它,以便我可以隐藏非交易日......有人知道吗?当我将非交易日设置为 False 时,会发生以下情况:
更新:现在我更改了一些代码,更改了我的绘图方式:
prices= self.prices[['Open','High','Low','Adj Close','Volume']]
prices.columns= ['Open','High','Low','Close','Volume']
last_price = prices['Close'].iloc[-1]
try:
cmf= self.CMF().dropna()
sma_cmf= self.sma_aux(20, cmf).SMA
sma_cmf= sma_cmf.iloc[19:]
prices['CMF']= cmf
prices['SMA_CMF']= sma_cmf
fallacmf=False
except: #Esto ocurrirá cuando Eikon no traiga datos de volumen
fallacmf=True
macd = self.MACD(12,26,9)
rsi = self.RSI(14)
rsi=rsi.iloc[13:]
prices['RSI']= rsi["RSI"]
macd= macd[['MACD','Signal','Histogram']]
prices= pd.merge(prices, macd, left_index=False, right_index=False, on='Date',how='left')
sma_df= self.SMA(20)
sma_df= sma_df.iloc[19:]
prices= pd.merge(prices, sma_df, left_index=False, right_index=False, on='Date',how='left')
psar_df= self.PSAR()
psarbull= psar_df["PSAR_BULL"]
psarbear= psar_df["PSAR_BEAR"]
prices['PSAR_BULL']= psarbull
prices['PSAR_BEAR']= psarbear
# Agregar elementos adicionales a los subgráficos
ap = [
mpf.make_addplot(prices['PSAR_BULL'], type='scatter', panel=0, markersize=0.5, color='blue',label='PSAR Bull'),
mpf.make_addplot(prices['PSAR_BEAR'], type='scatter', panel=0, markersize=0.5, color='red',label='PSAR Bear'),
mpf.make_addplot(prices['SMA'],panel=0,color='green', label='SMA (20)'),
mpf.make_addplot(prices['MACD'],panel=2,color='green', label='MACD (12,26)',secondary_y=False,ylabel='MACD'),
mpf.make_addplot(prices['Signal'],panel=2,color='lightgreen', label='Signal Line (9)',secondary_y=False),
mpf.make_addplot(prices['Histogram'],type='bar',width=0.7,panel=2, color='g',alpha=1,secondary_y=False),
mpf.make_addplot(prices['RSI'], panel=3, color='violet', label='RSI (14)', ylabel='RSI'),
mpf.make_addplot(prices['CMF'],panel=4,color='orange', label='CMF (21)',secondary_y=False,ylabel='CMF'),
mpf.make_addplot(prices['SMA_CMF'],panel=4,color='brown', label='SMA (20)',secondary_y=False)
]
save = dict(fname='ypf.png', dpi=300, pad_inches=0.25)
# Graficar los precios con los elementos adicionales
mpf.plot(prices, volume=True, addplot=ap, xrotation=0, type='candle',style='yahoo',ylabel_lower='Shares\nTraded', figratio=(12,8),
figscale=1.2, tight_layout=True, show_nontrading=False, panel_ratios=(4,2,2,2,2), savefig=save) #title=f'{self.ticker} - Último precio ${last_price:.2f}'
我现在唯一的问题是如何更改子图中的 y 轴,如何更改 RSI y 轴的大小(例如从 0 到 100),以及如何在 30 和 70 级别添加水平线等。另外我在 MACD 图中看到图例位于右侧,有什么方法可以指定图例位置吗?
我现在唯一的问题是如何更改子图中的 y 轴,如何更改 RSI y 轴的大小(例如从 0 到 100),以及如何在 30 和 70 级别添加水平线等。另外我在 MACD 图中看到图例位于右侧,有什么方法可以指定图例位置吗?
请参阅 mplfinance 绘图自定义,了解各种简单的绘图自定义。可能不存在,但您可能还需要 kwarg
ylim=
,您可能需要 RSI(例如,设置 ylim=(0,100)
)。
另请参阅使用线条,了解有关在绘图上放置水平线和垂直线的信息。
您是说
loc='upper left'
不适用于 MACD 子图吗?