Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Introduction

Créer un graphique en chandelier (candlestick chart) en Python est simple grâce à des bibliothèques comme Plotly, Matplotlib, ou mplfinance (spécialement conçue pour la visualisation de données financières).

Un graphique en chandelier est un type de visualisation financière utilisé pour représenter les variations de prix d’un actif — tel qu’une action, une cryptomonnaie ou une matière première — sur une période donnée.
Chaque chandelier représente un intervalle de temps (par exemple une journée ou une heure) et affiche quatre valeurs clés :

  • Open (Ouverture) – le prix au début de l’intervalle
  • High (Haut) – le prix le plus élevé atteint
  • Low (Bas) – le prix le plus bas atteint
  • Close (Fermeture) – le prix à la fin de l’intervalle

Ces valeurs sont représentées sous forme de « bougie » :

  • Le corps (rectangle) montre la différence entre les prix d’ouverture et de fermeture.
  • Les mèches (traits fins) indiquent les prix maximum et minimum.
  • Une bougie verte (ou blanche) signifie généralement une hausse (close > open), tandis qu’une bougie rouge (ou noire) indique une baisse (close < open).

Les graphiques en chandelier sont largement utilisés en analyse financière et en trading, car ils permettent de visualiser facilement le sentiment du marché, les tendances et la volatilité.
Ils aident les analystes à identifier des motifs tels que les retournements haussiers ou baissiers, les changements de momentum ou les niveaux de support et de résistance.

En Python, plusieurs bibliothèques — comme Matplotlib, Plotly et mplfinance — permettent de créer et de personnaliser facilement des graphiques en chandelier, que ce soit pour la recherche ou la présentation.

Option 1 : Utiliser Plotly (Interactif et Moderne)

 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

# Exemple de jeu de données
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)

# Création du graphique en chandelier
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='Exemple de graphique en chandelier',
    xaxis_title='Date',
    yaxis_title='Prix',
    xaxis_rangeslider_visible=False  # Masquer la barre de défilement
)

fig.show()

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Idéal pour : tableaux de bord interactifs, info-bulles, zoom et navigation
Bibliothèque requise : plotly (pip install plotly)

Option 2 : Utiliser mplfinance (basé sur Matplotlib)

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

# Exemple de données
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')

# Tracé avec mplfinance
mpf.plot(df, type='candle', style='charles', title='Graphique en chandelier', ylabel='Prix')

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Idéal pour : graphiques statiques de qualité publication
Bibliothèque requise : mplfinance (pip install mplfinance)

Option 3 : Utiliser Matplotlib (version manuelle, éducative)

Si vous ne souhaitez pas utiliser de dépendances supplémentaires, vous pouvez créer le graphique à la main avec Matplotlib :

 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

# Exemple de données
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')
    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('Graphique en chandelier manuel')
ax.set_ylabel('Prix')
plt.tight_layout()
plt.show()

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Idéal pour : comprendre le fonctionnement interne des chandeliers
Aucune bibliothèque externe requise

Amélioration du graphique en chandelier

Génération de données boursières simulées

 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
import numpy as np
import pandas as pd

np.random.seed(42)
n_days = 60
dates = pd.date_range(start="2025-01-01", periods=n_days, freq="D")

price = np.cumsum(np.random.normal(0, 1, n_days)) + 100
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")

df["MA5"] = df["Close"].rolling(5).mean()
df["MA10"] = df["Close"].rolling(10).mean()

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Version Matplotlib

 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
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)):
    ax.plot([i, i], [l, h], color='black', linewidth=1)
    ax.add_patch(plt.Rectangle((i - width / 2, min(o, c)),
                               width, abs(o - c),
                               color=color, alpha=0.8, linewidth=0.5))

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)
tick_labels = df.index.strftime('%b %d').iloc[tick_positions]
ax.set_xticks(tick_positions)
ax.set_xticklabels(tick_labels, rotation=45, ha='right')

ax.set_title("Graphique en chandelier simulé", fontsize=16, fontweight='bold', pad=15)
ax.set_ylabel("Prix ($)")
ax.legend()
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Version Plotly (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
import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Candlestick(
    x=df.index,
    open=df["Open"],
    high=df["High"],
    low=df["Low"],
    close=df["Close"],
    name="Prix"
))
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)
))
fig.update_layout(
    title="📈 Simulation de prix d’action (Plotly)",
    yaxis_title="Prix ($)",
    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()

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Caractéristiques :

  • Zoom et survol interactifs
  • Moyennes mobiles superposées
  • Style moderne et épuré

Version mplfinance

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

mpf.plot(
    df,
    type='candle',
    mav=(5, 10),
    volume=True,
    title="📊 Simulation de prix d’action (mplfinance)",
    ylabel="Prix ($)",
    ylabel_lower="Volume",
    style='yahoo',
    figratio=(14, 8),
    figscale=1.2
)

Comment Créer un Graphique en Chandelier (Candlestick) en Python ?
Comment Créer un Graphique en Chandelier (Candlestick) en Python ?

Caractéristiques :

  • Calcule automatiquement les moyennes mobiles
  • Sous-graphe du volume intégré
  • Styles financiers intégrés (charles, yahoo, nightclouds, etc.)

Tableau comparatif

Bibliothèque Points forts Interactivité Volume Style personnalisé
Plotly Moderne, interactif, web Manuel Élevé
mplfinance Spécialisée pour la finance, simple à utiliser Intégré Moyen
Matplotlib Flexible et éducative Manuel Très élevé

Références

Liens Site
https://matplotlib.org/stable/gallery/lines_bars_and_markers/candlestick_chart.html Galerie officielle Matplotlib – Exemple de graphique en chandelier
https://plotly.com/python/candlestick-charts/ Documentation officielle Plotly – Graphiques en chandelier en Python
https://github.com/matplotlib/mplfinance Dépôt GitHub officiel mplfinance – Documentation et code source
Image

of