[Python] Drawing Candlestick and volume chart using Matplotlib's bar chart with skip weekend

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    As I was trying to print out a stock candlestick chart using Matplotlib, I noticed they've moved their candlestick_ohlc to another library (mpl_finance) that should be installed and imported separately. As I didn't want to do that, I thought of sharing how to do it with the standard Matplotlib's library as I saw most guides on the internet are rather old and using that separate library. So if you want, you can suggest ways to improve this code too (this code skips weekends too):

    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()

    Continue reading...

Compartilhe esta Página