How to Create a Candlestick Chart in Python ?

Introduction

Creating a candlestick chart in Python is straightforward using libraries like Plotly, Matplotlib, or mplfinance (which is built specifically for financial data visualization).

A candlestick chart is a type of financial visualization used to show the price movement of an asset—such as a stock, cryptocurrency, or commodity—over a specific period of time.
Each candlestick represents one time interval (for example, one day or one hour) and displays four key values:

  • Open – the price at the beginning of the interval
  • High – the highest price reached
  • Low – the lowest price reached
  • Close – the price at the end of the interval

These values are drawn as a “candle”:

  • The body (a rectangle) shows the range between the open and close prices.
  • The wicks (thin lines) show the high and low prices.
  • A green (or white) candle usually indicates the price increased (close > open), while a red (or black) candle indicates a decrease (close < open).

Candlestick charts are widely used in financial analysis and trading because they provide an intuitive way to see market sentiment, trends, and volatility. They help traders identify patterns such as bullish or bearish reversals, momentum shifts, and support/resistance levels.

In Python, several libraries—like Matplotlib, Plotly, and mplfinance—allow you to easily create and customize candlestick charts for both research and presentation purposes.

Option 1: Using Plotly (Interactive & Modern)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import plotly.graph_objects as go
import pandas as pd

# Example dataset
data = {
    'Date': pd.date_range(start='2024-01-01', periods=10, freq='D'),
    'Open': [100, 102, 101, 105, 107, 108, 110, 112, 111, 113],
    'High': [103, 104, 106, 108, 109, 111, 113, 114, 115, 116],
    'Low': [99, 100, 100, 102, 105, 106, 107, 109, 110, 111],
    'Close': [102, 101, 105, 107, 108, 110, 112, 111, 113, 115],
}
df = pd.DataFrame(data)

# Create the candlestick chart
fig = go.Figure(data=[go.Candlestick(
    x=df['Date'],
    open=df['Open'],
    high=df['High'],
    low=df['Low'],
    close=df['Close']
)])

fig.update_layout(
    title='Candlestick Chart Example',
    xaxis_title='Date',
    yaxis_title='Price',
    xaxis_rangeslider_visible=False  # Hide the range slider
)

fig.show()

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Best for: interactive dashboards, hover tooltips, zooming
Libraries needed: plotly (pip install plotly)

Option 2: Using mplfinance (Matplotlib-based for financial data)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import pandas as pd
import mplfinance as mpf

# Example dataset
data = {
    'Date': pd.date_range(start='2024-01-01', periods=10, freq='D'),
    'Open': [100, 102, 101, 105, 107, 108, 110, 112, 111, 113],
    'High': [103, 104, 106, 108, 109, 111, 113, 114, 115, 116],
    'Low': [99, 100, 100, 102, 105, 106, 107, 109, 110, 111],
    'Close': [102, 101, 105, 107, 108, 110, 112, 111, 113, 115],
}
df = pd.DataFrame(data).set_index('Date')

# Plot using mplfinance
mpf.plot(df, type='candle', style='charles', title='Candlestick Chart', ylabel='Price')

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Best for: static publication-quality plots
Libraries needed: mplfinance (pip install mplfinance)

Option 3: Using Matplotlib (manual version, educational)

If you don’t want extra dependencies, you can build it yourself using Matplotlib rectangles:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import matplotlib.pyplot as plt
import pandas as pd

# Example dataset
df = pd.DataFrame({
    'Date': pd.date_range(start='2024-01-01', periods=10),
    'Open': [100, 102, 101, 105, 107, 108, 110, 112, 111, 113],
    'High': [103, 104, 106, 108, 109, 111, 113, 114, 115, 116],
    'Low': [99, 100, 100, 102, 105, 106, 107, 109, 110, 111],
    'Close': [102, 101, 105, 107, 108, 110, 112, 111, 113, 115],
})

fig, ax = plt.subplots(figsize=(10, 5))
width = 0.6

for i, row in df.iterrows():
    color = 'green' if row['Close'] >= row['Open'] else 'red'
    ax.plot([i, i], [row['Low'], row['High']], color='black')  # wick
    ax.add_patch(plt.Rectangle(
        (i - width/2, min(row['Open'], row['Close'])),
        width,
        abs(row['Close'] - row['Open']),
        color=color
    ))

ax.set_xticks(range(len(df)))
ax.set_xticklabels(df['Date'].dt.strftime('%Y-%m-%d'), rotation=45)
ax.set_title('Manual Candlestick Chart')
ax.set_ylabel('Price')
plt.tight_layout()
plt.show()

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Best for: learning how candlesticks work under the hood
No external libraries needed

Improved Candlestick Chart

Generate Fake Stock Data

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import numpy as np
import pandas as pd

# Generate reproducible fake stock data
np.random.seed(42)
n_days = 60
dates = pd.date_range(start="2025-01-01", periods=n_days, freq="D")

# Simulate prices with random walk
price = np.cumsum(np.random.normal(0, 1, n_days)) + 100

# Create OHLC data
open_ = price + np.random.normal(0, 0.5, n_days)
close = open_ + np.random.normal(0, 1, n_days)
high = np.maximum(open_, close) + np.random.uniform(0.5, 1.5, n_days)
low = np.minimum(open_, close) - np.random.uniform(0.5, 1.5, n_days)
volume = np.random.randint(1000, 5000, n_days)

df = pd.DataFrame({
    "Date": dates,
    "Open": open_,
    "High": high,
    "Low": low,
    "Close": close,
    "Volume": volume
}).set_index("Date")

# Add moving averages
df["MA5"] = df["Close"].rolling(5).mean()
df["MA10"] = df["Close"].rolling(10).mean()

df.head()

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Matplotlib Version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
fig, ax = plt.subplots(figsize=(12, 6))

width = 0.6
colors = ['green' if c >= o else 'red' for c, o in zip(df['Close'], df['Open'])]

for i, (o, h, l, c, color) in enumerate(zip(df['Open'], df['High'], df['Low'], df['Close'], colors)):
    # Draw wick
    ax.plot([i, i], [l, h], color='black', linewidth=1)
    # Draw candle body
    ax.add_patch(plt.Rectangle((i - width / 2, min(o, c)),
                               width,
                               abs(o - c),
                               color=color, alpha=0.8, linewidth=0.5))

# Plot moving averages
ax.plot(df.index, df["MA5"], label="MA5", linewidth=1.5, color="blue")
ax.plot(df.index, df["MA10"], label="MA10", linewidth=1.5, color="orange")


tick_positions = np.arange(0, len(df), 5)  # every 5th day
tick_labels = df['Date'].dt.strftime('%b %d').iloc[tick_positions]

ax.set_xticks(tick_positions)
ax.set_xticklabels(tick_labels, rotation=45, ha='right')

ax.set_title("Simulated Stock Price Candlestick Chart", fontsize=16, fontweight='bold', pad=15)
ax.set_ylabel("Price ($)")
ax.legend()
ax.grid(alpha=0.3)

plt.tight_layout()
plt.show()

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Plotly Version (Interactive)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import plotly.graph_objects as go

fig = go.Figure()

# Candlestick trace
fig.add_trace(go.Candlestick(
    x=df.index,
    open=df["Open"],
    high=df["High"],
    low=df["Low"],
    close=df["Close"],
    name="Price"
))

# Moving averages
fig.add_trace(go.Scatter(
    x=df.index, y=df["MA5"], mode='lines', name='MA5', line=dict(color='blue', width=1.5)
))
fig.add_trace(go.Scatter(
    x=df.index, y=df["MA10"], mode='lines', name='MA10', line=dict(color='orange', width=1.5)
))

# Layout customization
fig.update_layout(
    title="📈 Simulated Stock Price (Plotly Candlestick)",
    yaxis_title="Price ($)",
    xaxis_title="Date",
    xaxis_rangeslider_visible=False,
    template="plotly_white",
    legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)

fig.show()

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Features:

  • Interactive zoom, pan, and hover
  • Moving averages overlaid
  • Clean background and modern style

mplfinance Version

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import mplfinance as mpf

# Define moving averages to display
mav = (5, 10)

# Plot with custom style
mpf.plot(
    df,
    type='candle',
    mav=mav,
    volume=True,
    title="📊 Simulated Stock Price (mplfinance)",
    ylabel="Price ($)",
    ylabel_lower="Volume",
    style='yahoo',
    figratio=(14, 8),
    figscale=1.2
)

How to Create a Candlestick Chart in Python ?
How to Create a Candlestick Chart in Python ?

Features:

  • Auto-calculates moving averages
  • Volume subplot included
  • Clean, finance-friendly layout
  • Several built-in styles available (charles, yahoo, nightclouds, default, etc.)

Summary Comparison

Library Strengths Interactivity Volume Support Custom Styling
Plotly Interactive, modern web charts Manual High
mplfinance Tailored for finance charts, easy to use Built-in Medium
Matplotlib Full control, educational Manual Very High

References

Links Site
https://matplotlib.org/stable/gallery/lines_bars_and_markers/candlestick_chart.html Matplotlib Official Gallery – Candlestick chart example
https://plotly.com/python/candlestick-charts/ Plotly Official Documentation – Candlestick charts in Python
https://github.com/matplotlib/mplfinance mplfinance GitHub Repository – Official source and documentation for financial plotting
Image

of