Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 31 ยท Projects

Project: Stock Price Candlestick Chart

Build a candlestick chart from OHLC data: compute moving averages in Python, add a volume subplot, and zoom with a range slider in an SVG stand-in.

A candlestick chart is the standard picture of a price that moves over time. Each candle packs four numbers into one mark: where the price opened, how high and how low it went, and where it closed. Add two moving averages and a volume panel underneath and you have the layout that trading apps, crypto sites and finance dashboards all use.

In this project you build that chart in two halves. A Python program creates the data and computes the indicators, the way you would with pandas. A JavaScript stand-in draws the candles, the averages, the volume bars and a range slider as SVG. Plotly has a ready-made go.Candlestick trace and Bokeh and Altair can draw the same thing from lower-level marks; their code appears in read-only blocks.

All prices on this page are synthetic, produced by a seeded random walk. Nothing here is real market data, and nothing is financial advice. The goal is to learn how the chart is built.

Anatomy of a candle

One row of OHLC data has four prices for a period (a day, an hour): open, high, low, close. The candle has two parts:

  • The body is a rectangle between the open and the close. If the close is above the open, the price rose (conventionally green or hollow). If it is below, the price fell (red or filled).
  • The wicks (or shadows) are thin lines from the body up to the high and down to the low.
flowchart TB
    H["High: top of the upper wick"] --- B["Body: from open to close<br/>up day if close is above open"]
    B --- L["Low: bottom of the lower wick"]

A candle is a vertical range (low to high) with a thick part (open to close) in the middle.

The red and green convention is not universal and is a poor choice for people with red-green color blindness. Use a second cue: filled versus hollow bodies, or a blue and orange pair. The color and accessibility lesson explains why.

Step 1: generate OHLC data and compute indicators

Real code would load a CSV with pandas.read_csv. Here a tiny seeded random generator (a linear congruential generator) produces 30 days. Each day opens at the previous close, which is typical for continuous markets, and the high and low extend beyond the body by a random amount.

Then we compute two simple moving averages (SMA) of the close: a fast one over 5 days and a slow one over 10. An SMA is the same rolling mean you met in the trend explorer project. Where the fast line crosses the slow one, traders talk about a "crossover"; we detect those and count up days and down days.

Python OHLC data, moving averages and crossovers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the results. The first candle opens at exactly 100.0 and closes at 101.05, so day 1 is an up day with a body 1.05 tall. The fast average crosses above the slow one on day 15 and back below on day 26; those are the two moments a crossover strategy would react. The split is 15 up days and 15 down days, so this walk drifts sideways, and the volume peak (4,951 on day 4) happens to fall on a down day. The last line is the data as compact arrays [open, high, low, close, volume], ready to paste into a page.

Two details are worth noticing. First, the first size - 1 averages are None, not zero. Second, a moving average is a lagging indicator: it is built only from the past, so it reacts after the price has already turned.

Step 2: the same chart in real libraries

Plotly has the chart built in. With a pandas DataFrame df that has date, open, high, low, close and volume columns, a candlestick with a volume subplot looks like this (read-only):

Python
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
                    row_heights=[0.75, 0.25], vertical_spacing=0.03)

fig.add_trace(go.Candlestick(x=df["date"], open=df["open"], high=df["high"],
                             low=df["low"], close=df["close"], name="Price"),
              row=1, col=1)
fig.add_trace(go.Scatter(x=df["date"], y=df["sma5"], name="SMA 5"), row=1, col=1)
fig.add_trace(go.Scatter(x=df["date"], y=df["sma10"], name="SMA 10"), row=1, col=1)
fig.add_trace(go.Bar(x=df["date"], y=df["volume"], name="Volume"), row=2, col=1)

fig.update_layout(xaxis_rangeslider_visible=True)

shared_xaxes=True ties the zoom of both panels together, row_heights gives the price panel three times the space of the volume panel, and xaxis_rangeslider_visible adds the small overview strip with draggable handles under the chart. The special charts lesson shows the candlestick trace on its own.

In Altair a candle is two layered marks that share an x position: a mark_rule for the wick from low to high, and a mark_bar for the body from open to close, colored by a calculated "up or down" field:

Python
import altair as alt

base = alt.Chart(df).encode(x="date:T")
wick = base.mark_rule().encode(y="low:Q", y2="high:Q")
body = base.mark_bar().encode(
    y="open:Q", y2="close:Q",
    color=alt.condition("datum.close >= datum.open",
                        alt.value("#2563eb"), alt.value("#ea580c")),
)
candles = wick + body

The + operator layers charts, as explained in the composition lesson. Bokeh draws the same with a segment glyph for the wicks and a vbar for the bodies.

Step 3: draw it yourself

The page below renders the data from Step 1 with no library. It does what the libraries do:

  • A linear y scale for prices fitted to the visible candles, so zooming in also zooms the vertical axis.
  • A second, smaller panel for volume with its own y scale, sharing the x positions.
  • A range slider (two sliders for the first and last visible day) that acts as the zoom control.
  • Candles with filled bodies for down days and light bodies for up days, plus two SMA lines computed in the browser.
Candlesticks, moving averages, volume and a range slider

Drag the first-day slider to 12 and the y axis rescales to the visible prices, so the candles grow. That is what the range slider in Plotly does too. Hover a candle in your browser to see its four prices in the tooltip; hover the volume bar for the volume. Down days are drawn with a dark body and a dark volume bar, so the meaning does not rely on red and green alone.

Step 4: checks before you publish

  • Order and gaps. Candles must be sorted by time. Weekends and holidays have no data; Plotly draws a gap unless you tell it to skip those dates (rangebreaks), while the stand-in here simply uses equal slots.
  • Sanity-check each row. low <= min(open, close) and high >= max(open, close) must hold. A short assertion on the data catches bad feeds early; the testing lesson shows how.
  • Zoomed y axis is fine here. A price chart is not a bar chart, so the axis need not start at zero, but label it clearly.
  • Performance. Thousands of candles are fine in SVG; hundreds of thousands need WebGL or aggregation to weekly candles, as in the large datasets lesson.
  • Honest labelling. Say that averages are simple moving averages and over how many periods.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do the wicks of a candle represent?

    The body spans open to close. The thin wicks extend to the period's high and low.
  2. 2. Why are the first four values of a 5-day simple moving average empty?

    A 5-day average needs five values. Earlier points are None (or NaN) and should be drawn as gaps.
  3. 3. Why does the stand-in use dark bodies for down days and white bodies for up days instead of red and green only?

    Color-blind readers may not tell red and green apart. A fill difference is a redundant encoding.
  4. 4. In Altair, how is a candle built?

    Altair has no candle mark. Layering a wick rule and a body bar, sharing the same x encoding, gives the same picture.
  5. 5. What does shared_xaxes=True do in make_subplots?

    With a shared x axis, zooming the price panel also zooms the volume panel, so both always show the same days.

Summary

  • A candle encodes open, high, low and close: a body between open and close and wicks to the high and low.
  • Simple moving averages are rolling means of the close; they lag and have empty values at the start.
  • A volume subplot shares the x axis with the price panel; a range slider zooms both.
  • Plotly has go.Candlestick; Altair layers a rule and a bar; Bokeh combines segment and vbar.
  • Do not rely on red and green alone; validate the OHLC rows; label what the averages are.

Next: Project: Survey Results Report