Appendix O — Candlestick Charts with plotly

In financial applications, we may have access to OHLC data (containing the open, high, low, and closing prices on each day).

With OHLC data, we can use a candlestick chart to display the price movements within each day.

To implement a candlestick chart, we can use the Candlestick class from plotly’s Graph Objects sub-library.

We start with some OHLC data:

ohlc_data = [
    {
        "date": "2030-03-16",
        "open": 237.8000,
        "high": 239.2000,
        "low": 237.0000,
        "close": 238.6500,
        "volume": 26800000
    },
    {
        "date": "2030-03-15",
        "open": 235.2500,
        "high": 238.9000,
        "low": 235.0000,
        "close": 237.8000,
        "volume": 27400000
    },
    {
        "date": "2030-03-12",
        "open": 236.5000,
        "high": 237.7500,
        "low": 234.8000,
        "close": 235.2500,
        "volume": 24800000
    },
    {
        "date": "2030-03-11",
        "open": 234.1000,
        "high": 238.0000,
        "low": 233.0000,
        "close": 236.5000,
        "volume": 31200000
    },
    {
        "date": "2030-03-10",
        "open": 232.0000,
        "high": 235.5000,
        "low": 230.2500,
        "close": 234.1000,
        "volume": 29500000
    }
]

Mapping the data to get into a format the chart likes (separate lists):

dates = []
opens = []
highs = []
lows = []
closes = []

for item in ohlc_data:
    dates.append(item["date"])
    opens.append(item["open"])
    highs.append(item["high"])
    lows.append(item["low"])
    closes.append(item["close"])

Finally, creating and displaying the chart:

from plotly.graph_objects import Figure, Candlestick

stick = Candlestick(x=dates, open=opens, high=highs, low=lows, close=closes)

fig = Figure(data=[stick])
fig.update_layout(title="Example Candlestick Chart")
fig.show()