Рисование подсвечника и графика объема с использованием гистограммы Matplotlib с пропуском выходных - PullRequest
0 голосов
/ 27 апреля 2020

Когда я пытался распечатать биржевую свечную диаграмму с помощью Matplotlib, я заметил, что они переместили свои подсвечник_ohl c в другую библиотеку (mpl_finance), которую следует установить и импортировать отдельно. Поскольку я не хотел этого делать, я думал о том, как поделиться этим со стандартной библиотекой Matplotlib, так как я увидел, что большинство руководств по inte rnet довольно старые и используют эту отдельную библиотеку. Поэтому, если вы хотите, вы также можете предложить способы улучшить этот код (этот код пропускает и выходные):

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

fig, ax = plt.subplots()
df = df.sort_values(by=['trade_date'], ascending=True)
N = len(dsh_sorted['trade_date']) 
ind = np.arange(N)
# A function to remove weekends 
def format_date(x, pos=None): # x counts for all ticks, pos counts for the visible ticks.
    thisind = np.clip(int(x), 0, N-1)
    if x<0 or x>(N-1): #There are one more x on each side of data range to have spaces from the chart edge
        date_string=""
    else:
        date_string = df.iloc[thisind , df.columns.get_loc('trade_date')].strftime('%Y-%m-%d')
    return date_string
df['candle_height'] = df["close"]-df["open"]
candle_chart = ax.bar(x=ind, height = df.candle_height.abs(), bottom = df[["open", "close"]].min(axis=1),
                       yerr=[df[["open", "close"]].max(axis=1)-df["min"],df["max"]-df[["open", "close"]].max(axis=1)], 
                       color = ['green' if i>=0 else 'red' for i in df['candle_height']],
                       ecolor= ['green' if i>=0 else 'red' for i in df['candle_height']], 
                       width=0.25, label=[], alpha=1, error_kw={'alpha':0.8})
#Now to put the volume chart bellow the candlestick chart
ax_vol=ax.twinx()
vol_chart = ax_vol.bar(ind, df['volume'], width=0.25, color=('blue'), label=[])
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=1.0))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
#Although candlestick chart is obvious and might not need a legend, I put this here as help on how to add a combined legend to a matplotlib's plot manually.
ax_legend = plt.legend(handles=[candle_chart, vol_chart], labels=['Prices', 'Volumes'], loc='best', framealpha=0.6)
plt.gca().add_artist(ax_legend)
ax_vol.set_ylim(0,3*df['volume'].max())    #it kinda squishes down the volume scale
ax_vol.grid(False)    #if you don't do this, the y grids of both charts will be mixed in a not pretty way
fig.autofmt_xdate()
plt.show()
...