σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademySkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
Skills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
Python skill›Module 2 · NumPy & pandas for market data›Topic 2.19·~40 minIntermediate

Candlestick charts

Skill positionModule 2 of 11 · Topic 19 of 20
2.19 Candlestick charts
—Lab score— / 100Total XP—Streak—

Four prices in one picture

A line chart of closing prices throws away most of a day. A candlestick keeps four prices at once: the open, the high, the low and the close. The thick body runs from the open to the close and is coloured by direction (green when the close is at or above the open, red otherwise). The thin wick runs from the low to the high. At a glance you see where the day went, how far it ranged and whether buyers or sellers won.

import numpy as np
import pandas as pd

df = pd.DataFrame(
    {
        "open":  [100.0, 103.0, 102.0, 104.0],
        "high":  [104.0, 105.0, 106.0, 104.5],
        "low":   [ 99.0, 101.0, 101.5, 101.0],
        "close": [103.0, 102.0, 105.5, 104.0],
    },
    index=pd.bdate_range("2026-03-02", periods=4),
)

# Green when the day closed at or above its open, red otherwise: one np.where on whole columns
colors = np.where(df["close"] >= df["open"], "green", "red")
print(colors.tolist())   # ['green', 'red', 'green', 'green']

Computing the body

A body is a rectangle. It starts at the lower of the open and the close (df[["open", "close"]].min(axis=1) takes the row-wise minimum) and its height is the absolute difference abs(close - open). A day that opens and closes at the same price has a body of height 0: a doji, a candle of indecision. Comparing the body with the whole range high - low tells you how decisive the day was, and doing it on whole columns finds every doji of a year in one line.

body = pd.DataFrame({
    "bottom": df[["open", "close"]].min(axis=1),    # the lower of open and close, row by row
    "height": (df["close"] - df["open"]).abs(),
})
print(body)
#             bottom  height
# 2026-03-02   100.0     3.0
# 2026-03-03   102.0     1.0
# 2026-03-04   102.0     3.5
# 2026-03-05   104.0     0.0

# Body as a share of the day's range: the last day is a doji
share = body["height"] / (df["high"] - df["low"])
print(share.round(2).tolist())          # [0.6, 0.25, 0.78, 0.0]
print((share <= 0.1).tolist())          # [False, False, False, True]

Drawing: wicks and bars

matplotlib has no candlestick call, but two plain ones are enough. ax.vlines(x, ymin, ymax) draws a vertical line for each x in one go: that is the wicks, from low to high. ax.bar(x, height, bottom=..., width=0.6, color=...) draws one bar for each x starting at bottom: that is the bodies, and color accepts a list with one colour per bar. Put the candles at the positions 0, 1, 2, ... (np.arange(len(df))) rather than at dates, so weekends leave no gaps. Passing whole columns avoids any loop over days.

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
x = np.arange(len(df))
ax.vlines(x, df["low"], df["high"], color="black", linewidth=1)                       # the wicks
ax.bar(x, body["height"], bottom=body["bottom"], width=0.6, color=colors)               # the bodies

print(len(ax.collections), len(ax.patches))            # 1 4   one set of wicks, four bodies
print([p.get_y() for p in ax.patches])                  # [100.0, 102.0, 102.0, 104.0]   body bottoms
print(ax.collections[0].get_segments()[0].tolist())     # [[0.0, 99.0], [0.0, 104.0]]    the first wick, low to high
# Candles whose body is at most 10% of the day's range are dojis
doji = share <= 0.1
print(df.index[doji].strftime("%d %b").tolist())   # ['05 Mar']
Pictures can be read backA chart is data too: ax.patches holds the bars and ax.collections the wicks, each with positions, sizes and colours you can check. Testing the Axes, not the pixels, is how a plotting function is verified automatically, and it is also how you debug a chart that looks wrong.
  • A candle shows open, high, low and close: a body from open to close, a wick from low to high.
  • The body bottom is min(open, close) row by row (min(axis=1)), its height abs(close - open); a body of 0 is a doji.
  • Draw all wicks with one ax.vlines call and all bodies with one ax.bar call (list of colours); no loop over days.

Next up: histograms and distributions, counting how often returns fall in each range.

Lab · what's graded

  • Colour each candle by its direction with candle_colors25 pts
  • Measure the body of each candle with candle_body25 pts
  • Find the indecisive days with doji_days25 pts
  • Draw the candles on an Axes with draw_candles25 pts
Explorer · lab-52-1
▾ lab-52-1
…
bash · in-browser
learner@quantcraft:~/lab-52-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-52-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes

Log in to run your code.

Every lecture is free to read. Create an account or log in to run code, run tests and submit this lab.

  • In-browser IDE with a bash terminal — nothing to install
  • Instant grading, XP and your place on the skill
Create an accountLog in
OR
Continue with GitHub