Candlestick Charts in Python with mplfinance

Draw candlestick and OHLC charts from a pandas DataFrame with mpf.plot(): volume panel, moving averages, custom colors, signal markers, weekly bars and Matplotlib annotations.

To make a candlestick chart in Python, pass a pandas DataFrame with Open, High, Low, Close and Volume columns and a DatetimeIndex to mpf.plot(df, type="candle") from mplfinance. It is a Matplotlib package built for price charts, so one call gives you candles, a volume panel and moving averages. The Plotly equivalent is covered in Interactive Candlestick Charts in Plotly.

The latest mplfinance is 0.12.10b0 (still tagged beta, released in 2023). It imports six without declaring it as a dependency, so install both with pip install mplfinance six. This post was run with Matplotlib 3.11 and pandas 3.1.

Quick Example

The data here is a simulated stock called ACME (120 trading days, seeded so you get the same chart). The last lines are the part you would keep for real prices.

import numpy as np
import pandas as pd
import mplfinance as mpf

rng = np.random.default_rng(11)
days = pd.bdate_range("2026-01-02", periods=120, name="Date")
close = 82 * np.exp(np.cumsum(rng.normal(0.0006, 0.015, len(days))))
open_ = np.r_[82, close[:-1]] * np.exp(rng.normal(0, 0.004, len(days)))
high = np.maximum(open_, close) * (1 + rng.uniform(0.001, 0.012, len(days)))
low = np.minimum(open_, close) * (1 - rng.uniform(0.001, 0.012, len(days)))
volume = rng.integers(800_000, 2_400_000, len(days)) * (1 + 6 * np.abs(np.log(close / open_)))
df = pd.DataFrame(
    {"Open": open_, "High": high, "Low": low, "Close": close, "Volume": volume.astype(int)},
    index=days,
).round(2)

mpf.plot(df, type="candle", volume=True, mav=(10, 20), style="yahoo",
         title="ACME daily price", figratio=(16, 9), figscale=1.2)

Candlestick chart of a simulated stock with green and red candles, 10 and 20 day moving average lines and a volume panel underneath

Each candle is one trading day. The body runs from the open to the close, and the thin wick runs from the low to the high. With style="yahoo", green means the close was above the open and red means it was below. Over these 120 days, 64 closed above their open. The price fell to a closing low of 76.97 on March 9 and reached a closing high of 96.21 on June 16.

Two things in that call are easy to miss. type defaults to "ohlc" (bars with tick marks), so you have to ask for "candle". And mav=(10, 20) draws a 10-day and a 20-day simple moving average without you computing anything.

What format does mplfinance need?

mpf.plot() accepts a DataFrame with a DatetimeIndex and columns named Open, High, Low, Close and (if you want a volume panel) Volume. Lowercase names (open, high, ...) also work. A DataFrame with any other kind of index raises TypeError: Expect data.index as DatetimeIndex, and a missing column raises a ValueError that names it. Convert the index with parse_dates or pd.to_datetime:

df.to_csv("acme.csv")  # stand-in for your own file
prices = pd.read_csv("acme.csv", index_col="Date", parse_dates=True)
print(prices.index.dtype, list(prices.columns))
datetime64[us] ['Open', 'High', 'Low', 'Close', 'Volume']

If your columns have other names, pass columns=("o", "h", "l", "c", "v") in the order open, high, low, close, volume.

Candle, OHLC, line and hollow candles

type takes "candle", "ohlc", "line", "hollow_and_filled", "renko" and "pnf" (point and figure). To put several in one figure, create the axes yourself and pass each one as ax=:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2, figsize=(10, 6.5))
for ax, kind in zip(axes.flat, ["candle", "ohlc", "line", "hollow_and_filled"]):
    mpf.plot(df.tail(40), type=kind, style="yahoo", ax=ax, axtitle=f'type="{kind}"', ylabel="")
fig.tight_layout()
plt.show()

Four panels showing the last 40 days of the same prices as candles, OHLC bars, a line and hollow and filled candles

"hollow_and_filled" encodes two things. The body is hollow when the close is above the open and filled when it is below, while the outline color shows whether the close is above or below the previous day's close. That is why a hollow candle can still be red.

How do I change the candle colors?

Colors live in a style. Build one with mpf.make_marketcolors() for the candles and mpf.make_mpf_style() for everything around them. edge="inherit" and wick="inherit" make the outline and wick match the candle body:

colors = mpf.make_marketcolors(up="#2a9d8f", down="#e76f51",
                               edge="inherit", wick="inherit", volume="inherit")
style = mpf.make_mpf_style(marketcolors=colors, base_mpf_style="yahoo",
                           gridstyle=":", facecolor="white")

mpf.plot(df, type="candle", volume=True, style=style, title="ACME daily price",
         figratio=(16, 9), figscale=1.2,
         update_width_config=dict(volume_linewidth=0))  # no outline on the volume bars

Candlestick chart with teal up candles and orange-red down candles, a dotted grid and matching volume bars

up and down are the colors for rising and falling candles. Colorblind-safe pairs such as blue and orange work better than red and green if the chart is going into a report. Run mpf.available_styles() to list the built-in styles ("charles", "binance", "nightclouds", "tradingview" and others) before building your own.

How do I add indicators and markers?

mpf.make_addplot() draws any series on the price axis (or a panel of its own, with panel=1). Pass the results to addplot= as a list. Here a 20-day average is drawn as a line and the days when the close crosses above it are marked with triangles:

sma = df["Close"].rolling(20).mean()
cross_up = (df["Close"] > sma) & (df["Close"].shift() <= sma.shift())
markers = (df["Low"] * 0.99).where(cross_up)  # NaN everywhere except the signal days

extra = [
    mpf.make_addplot(sma, color="#264653", width=1.2),
    mpf.make_addplot(markers, type="scatter", marker="^", markersize=70, color="#1d3557"),
]
mpf.plot(df, type="candle", style=style, addplot=extra, figratio=(16, 9), figscale=1.2)

Candlestick chart with a 20 day moving average line and five dark triangles marking the days the close crossed above it

The close crossed above its 20-day average five times: March 2, March 16, May 7, June 2 and June 8. Every addplot series must have the same index as df. Using NaN for the days with no marker is the trick that keeps the lengths equal. The same pattern draws Bollinger bands, RSI or MACD panels.

How do I make weekly or monthly candles?

mplfinance plots whatever rows you give it, so resample first. Each period's open is the first open, the high is the maximum, the low is the minimum, the close is the last close, and volume is summed:

weekly = df.resample("W-FRI").agg(
    {"Open": "first", "High": "max", "Low": "min", "Close": "last", "Volume": "sum"}
)
print(len(df), "daily rows ->", len(weekly), "weekly rows")

mpf.plot(weekly, type="candle", volume=True, style=style, mav=4,
         title="ACME weekly price", figratio=(16, 9), figscale=1.2,
         update_width_config=dict(volume_linewidth=0))
120 daily rows -> 25 weekly rows

Weekly candlestick chart with 25 candles, a 4 week moving average and weekly volume bars

Use "ME" for month-end candles. The mav=4 here means four weeks. The same agg dictionary works on intraday data: resample minute bars to "15min" or "1h".

How do I annotate a candlestick chart?

Pass returnfig=True to get the Matplotlib Figure and the list of axes back instead of showing the chart. From there it is ordinary Matplotlib. One catch: the x-axis is the row number (0, 1, 2, ...) and not the date, because mplfinance skips weekends and holidays. Use df.index.get_loc() to turn a date into an x position:

fig, axes = mpf.plot(df, type="candle", style=style, returnfig=True,
                     figratio=(16, 9), figscale=1.2)
ax = axes[0]  # the price axis

peak_day = df["High"].idxmax()
x, y = df.index.get_loc(peak_day), df["High"].max()
ax.annotate(f"High {y:.2f} on {peak_day:%b %d}", xy=(x, y), xytext=(x - 35, y - 1),
            arrowprops=dict(arrowstyle="->"))
ax.set_ylabel("Price (USD)")
plt.show()

Candlestick chart with an arrow pointing at the highest price, 97.19 on June 16

axes is a list. The price axis is axes[0], and when volume=True the volume axis is axes[2]. Pass show_nontrading=True if you want empty gaps for the missing days instead. The x-axis is then real dates,.

mplfinance vs Plotly vs plain Matplotlib

mplfinance Plotly go.Candlestick Matplotlib by hand
Output Static image Interactive (hover, zoom) Static image
Volume panel, moving averages One argument each Add traces and subplots yourself Draw every part yourself
Skips weekends and holidays Yes, by default Needs rangebreaks Yourself
Best for Reports, notebooks, quick analysis Dashboards and web pages Unusual layouts

For a chart in a PDF or slide, use mplfinance. For something a reader will zoom into on a web page, use Plotly.

Practical Tips

  • Pass type="candle" every time. The default is "ohlc".
  • Candle body color follows the open and close, not the change from yesterday. A gap-up day can still be a red candle.
  • A chart with more than about 250 candles gets hard to read. Resample to weekly bars, or plot df.tail(250).
  • mplfinance does not download data. You need a DataFrame from a CSV, a database or a data vendor. Check the vendor's license before you publish charts built from it.
  • mpf.plot() calls plt.show() unless you pass savefig= or returnfig=True. savefig="chart.png" writes the file directly, and savefig=dict(fname="chart.png", dpi=200) sets the resolution.

Similar Topics