Updated On : Jul-23,2022 Time Investment : ~20 mins

Candlestick Charts in Python (mplfinance, plotly, bokeh, bqplot, and cufflinks)

Candlestick chart is the most commonly used chart type in financial markets to display the movement of security price for a particular time period. It is almost like a bar chart but helps us capture details of all 4 price details (open, high, low, and closing prices of security) in one bar instead of just one like traditional bar charts. A Candlestick chart can be used to show the movement of price for data captured at different time intervals (hourly, daily, monthly, minutely, etc).

Below we have included two simple images (taken from Wikipedia) explaining how candlestick charts are created based on OHLC (Open, High, Low, and Close Prices) data of security. As we can see (according to chart 1) the thick bar (also referred to as real body) in the chart is created based on open and close prices. It shows us the variance in price for the specified period (hour, minute, day, etc). Then, we have lines extending above and below that bar that shows how high and the low price went during trading for that time interval.

The second chart shows us how green and red bars are created. If open price is below close price then green bar is created highlighting that the security price increased (bullish) for that period else red bar is created highlighting a decrease (bearish) (Please take a look how open and close price location changes based on bar color). The lines extending help us see how much price fluctuated (price change range) during the time interval. It can go well above opening price and can end below it or above it. During this fluctuation, the price can go below close price and cover little from there as well. In case, bars are created as black and white then white bars will be for bullish and black bars will be for bearish.

Chart 1:

Candlestick Charts in Python

Chart 2:

Candlestick Charts in Python

As a part of this tutorial, we have explained how to create candlestick charts in python using data visualization libraries mplfinance, plotly, bokeh, bqplot and cufflinks. The charts created using mplfinance are static whereas charts created using other libraries are interactive. Apart from creating basic candlestick charts from the dataset, we have also explained things like styling charts, layout management, adding moving average lines, adding sliders to select range, displaying volume bars, adding Bollinger bands, and saving figures, etc. The dataset used for creating charts is Apple stock price data for one month available from Yahoo finance. The dataset is loaded as pandas dataframe and all charts are created from it.

Below, we have listed important sections of the Tutorial to give an overview of the material covered.

Important Sections Of Tutorial

  1. mplfinance (Built on top of Matplotlib)
    • 1.1 Simple Candlestick Charts
    • 1.2 CandleStick Charts with Volume Bars
    • 1.3 CandleStick Layout, Styling, and Moving Average Lines
    • 1.4 Save Figure
  2. Plotly
    • 2.1 CandleStick Charts with Slider to Analyze Range
    • 2.2 CandleStick Charts without Slider
    • 2.3 CandleStick Charts Layout & Styling
  3. Bokeh
    • 3.1 Simple Candlestick Charts
  4. Bqplot
    • 4.1 CandleStick Charts using bqplot matplotlib-like API
    • 4.2 CandleStick Charts using bqplot Internal Object Model API
  5. Cufflinks
    • 5.1 Simple Candlestick Charts
    • 5.2 Quant Figure

Below, we have imported the necessary Python libraries that we have used in our tutorial and printed the version as well.

Install Python Libraries

  • pip install --upgrade mplfinance plotly bokeh cufflinks bqplot
import mplfinance as fplt

print("MPLFinance Version : {}".format(fplt.__version__))
MPLFinance Version : 0.12.3a3
import plotly

print("Plotly Version : {}".format(plotly.__version__))
Plotly Version : 4.5.2
import bokeh

print("Bokeh Version : {}".format(bokeh.__version__))
Bokeh Version : 2.0.2
import bqplot

print("Bqplot Version : {}".format(bqplot.__version__))
Bqplot Version : 0.12.14
import cufflinks as cf

print("Cufflinks Version : {}".format(cf.__version__))
Cufflinks Version : 0.17.3

0. Load Dataset

We'll be using apple stock price data downloaded from yahoo finance. We'll be loading it using the pandas library as a dataframe.

We'll be filtering data to keep only March-2020 data into dataframe which we'll utilize for plotting.

import pandas as pd
apple_df = pd.read_csv('~/datasets/AAPL.csv', index_col=0, parse_dates=True)
dt_range = pd.date_range(start="2020-03-01", end="2020-03-31")
apple_df = apple_df[apple_df.index.isin(dt_range)]
apple_df.head()
Open High Low Close Adj Close Volume
Date
2020-03-02 282.279999 301.440002 277.720001 298.809998 298.809998 85349300
2020-03-03 303.670013 304.000000 285.799988 289.320007 289.320007 79868900
2020-03-04 296.440002 303.399994 293.130005 302.739990 302.739990 54794600
2020-03-05 295.519989 299.549988 291.410004 292.920013 292.920013 46893200
2020-03-06 282.000000 290.820007 281.230011 289.029999 289.029999 56544200

1. mplfinance (Built on top of Matplotlib)

The first library which we'll explore for plotting candlestick charts in Python is mplfinance. It used to be available as a matplotlib module earlier but now it has moved out and has become an independent library. We can generate static candlestick charts using it.

1.1 Simple CandleStick

We'll start by generating a simple candlestick chart. First, we'll import mplfinance as fplt and then call the plot method of it passing apple dataframe along with type of the chart as candle. We can also provide title and ylabel.

import mplfinance as fplt
fplt.plot(
            apple_df,
            type='candle',
            title='Apple, March - 2020',
            ylabel='Price ($)'
        )

Apple March-2020 CandleStick Mplfinance

We can try various plotting styles by setting a style attribute to various values. Below we are printing list of styles available with mplfinance.

fplt.available_styles()
['blueskies',
 'brasil',
 'charles',
 'checkers',
 'classic',
 'default',
 'mike',
 'nightclouds',
 'sas',
 'starsandstripes',
 'yahoo']
fplt.plot(
            apple_df,
            type='candle',
            style="classic",
            title='Apple, March - 2020',
            ylabel='Price ($)'
        )

Apple March-2020 CandleStick Mplfinance

fplt.plot(
            apple_df,
            type='candle',
            style='charles',
            title='Apple, March - 2020',
            ylabel='Price ($)',
            )

Apple March-2020 CandleStick Mplfinance

fplt.plot(
            apple_df,
            type='candle',
            style='mike',
            title='Apple, March - 2020',
            ylabel='Price ($)',
        )

Apple March-2020 CandleStick Mplfinance

1.2 CandleStick with Volume

The mplfinance also provides us with functionality to plot the volume of stocks traded during that day. We can simply pass volume=True to plot() method to see the volume plot below the candlestick chart. We need volume information present in the dataframe for it to work. We can also pass ylabel_lower to change label of the y-axis of the volume plot.

fplt.plot(
            apple_df,
            type='candle',
            style='charles',
            title='Apple, March - 2020',
            ylabel='Price ($)',
            volume=True,
            ylabel_lower='Shares\nTraded',
            )

Apple March-2020 CandleStick Mplfinance

Below we are again plotting the same candlestick as above one but with gaps showing for non-trading days as well. We need to pass show_nontrading=True to be able to show gaps for non-trading days.

fplt.plot(
            apple_df,
            type='candle',
            style='charles',
            title='Apple, March - 2020',
            ylabel='Price ($)',
            volume=True,
            ylabel_lower='Shares\nTraded',
            show_nontrading=True
            )

Apple March-2020 CandleStick Mplfinance

1.3 CandleStick Layout, Styling and Moving Average Lines

We can try various styling functionalities available with mplfinance. We can pass the color of up, down and volume bar charts as well as the color of edges using the make_marketcolors() method. We need to pass colors binding created with make_marketcolors() to make_mpf_style() method and output of make_mpf_style() to style attribute plot() method. The below examples demonstrate our first styling. We can even pass the figure size using figratio attribute.

mc = fplt.make_marketcolors(
                            up='tab:blue',down='tab:red',
                            edge='lime',
                            wick={'up':'blue','down':'red'},
                            volume='tab:green',
                           )

s  = fplt.make_mpf_style(marketcolors=mc)

fplt.plot(
        apple_df,
        type="candle",
        title='Apple, March - 2020',
        ylabel='Price ($)',
        figratio=(12,8),
        volume=True,
        ylabel_lower='Shares\nTraded',
        show_nontrading=True,
        style=s
    )

Apple March-2020 CandleStick Mplfinance

We can also change styling of whole plot by setting value of base_mpl_style parameter of make_mpf_style() method. We can try values like ggplot, seaborn, etc.

mc = fplt.make_marketcolors(
                            up='tab:blue',down='tab:red',
                            edge='lime',
                            wick={'up':'blue','down':'red'},
                            volume='lawngreen',
                           )

s  = fplt.make_mpf_style(base_mpl_style="ggplot", marketcolors=mc)

fplt.plot(
        apple_df,
        type="candle",
        title='Apple, March - 2020',
        ylabel='Price ($)',
        figratio=(12,8),
        volume=True,
        ylabel_lower='Shares\nTraded',
        show_nontrading=True,
        style=s
    )

Apple March-2020 CandleStick Mplfinance

We can also add moving averages of price by passing value to mav parameter of plot() method. We can either pass scaler value for single moving average or tuple/list of integers for multiple moving averages. We'll explain it's usage with below few examples.

mc = fplt.make_marketcolors(
                            up='tab:blue',down='tab:red',
                            edge='lime',
                            wick={'up':'blue','down':'red'},
                            volume='lawngreen',
                           )

s  = fplt.make_mpf_style(base_mpl_style="seaborn", marketcolors=mc, mavcolors=["yellow"])

fplt.plot(
        apple_df,
        type="candle",
        title='Apple, March - 2020',
        ylabel='Price ($)',
        mav=2,
        figscale=1.5,
        style=s
    )

Apple March-2020 CandleStick Mplfinance

mc = fplt.make_marketcolors(
                            up='tab:blue',down='tab:red',
                            edge='lime',
                            wick={'up':'blue','down':'red'},
                            volume='lawngreen',
                           )

s  = fplt.make_mpf_style(base_mpl_style="seaborn", marketcolors=mc, mavcolors=["yellow","orange","skyblue"])

fplt.plot(
        apple_df,
        type="candle",
        title='Apple, March - 2020',
        ylabel='Price ($)',
        mav=(2,4,6),
        figratio=(12,6),
        style=s
    )

Apple March-2020 CandleStick Mplfinance

1.4 Save Figure

We can also save figure passing name of a file to savefig attribute.

mc = fplt.make_marketcolors(
                            up='tab:blue',down='tab:red',
                            edge='lime',
                            wick={'up':'blue','down':'red'},
                            volume='lawngreen',
                           )

s  = fplt.make_mpf_style(base_mpl_style="seaborn", marketcolors=mc)

fplt.plot(
        apple_df,
        type="candle",
        title='Apple, March - 2020',
        ylabel='Price ($)',
        figratio=(12,6),
        style=s,
        savefig='apple_march_2020.png'
    )

Apple March-2020 CandleStick Mplfinance

We can further pass information about the size and quality of an image to be saved as well to savefig parameter.

mc = fplt.make_marketcolors(
                            up='tab:blue',down='tab:red',
                            edge='lime',
                            wick={'up':'blue','down':'red'},
                            volume='lawngreen',
                           )

s  = fplt.make_mpf_style(base_mpl_style="seaborn", marketcolors=mc)

fplt.plot(
        apple_df,
        type="candle",
        title='Apple, March - 2020',
        ylabel='Price ($)',
        mav=(2,4,6),
        figratio=(12,6),
        style=s,
        savefig=dict(fname='apple_march_2020.png',dpi=100,pad_inches=0.25)
    )

Apple March-2020 CandleStick Mplfinance

2. Plotly

Plotly is another Python library that provides functionality to create candlestick charts. It allows us to create interactive candlestick charts.

2.1 CandleStick with Slider to Analyze Range

We can create a candlestick chart by calling Candlestick() method of plotly.graph_objects module. We need to pass it a value of x as date as well as open, low, high and close values.

Plotly provides another small summary chart with sliders to let us highlight and view a particular period of a candlestick.

import plotly.graph_objects as go

candlestick = go.Candlestick(
                            x=apple_df.index,
                            open=apple_df['Open'],
                            high=apple_df['High'],
                            low=apple_df['Low'],
                            close=apple_df['Close']
                            )

fig = go.Figure(data=[candlestick])

fig.show()

Apple March-2020 CandleStick Plotly

2.2 CandleStick without Slider

We can only create a candlestick chart without a range slider as well by setting the value of parameter xaxis_rangeslider_visible as False.

candlestick = go.Candlestick(
                            x=apple_df.index,
                            open=apple_df['Open'],
                            high=apple_df['High'],
                            low=apple_df['Low'],
                            close=apple_df['Close']
                            )

fig = go.Figure(data=[candlestick])

fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()

Apple March-2020 CandleStick Plotly

2.3 CandleStick Layout & Styling

We can change the styling of Plotly graph by setting its width, height, title as well as colors of up and down bars.

candlestick = go.Candlestick(
                            x=apple_df.index,
                            open=apple_df['Open'],
                            high=apple_df['High'],
                            low=apple_df['Low'],
                            close=apple_df['Close']
                            )

fig = go.Figure(data=[candlestick])

fig.update_layout(
    width=800, height=600,
    title="Apple, March - 2020",
    yaxis_title='AAPL Stock'
)

fig.show()

Apple March-2020 CandleStick Plotly

candlestick = go.Candlestick(
                                x=apple_df.index,
                                open=apple_df['Open'],
                                high=apple_df['High'],
                                low=apple_df['Low'],
                                close=apple_df['Close'],
                                increasing_line_color= 'blue', decreasing_line_color= 'orange',

                            )

fig = go.Figure(data=[candlestick])

fig.update_layout(
    title="Apple, March - 2020",
    yaxis_title='AAPL Stock',
)

fig.show()

Apple March-2020 CandleStick Plotly

3. Bokeh

Bokeh is another Python library that can be used to create interactive candlestick charts. We'll be using vbar() and segment() methods of bokeh to create bars and lines to eventually create a candlestick chart. We'll need to do simple calculations to create a candlestick with bokeh.

3.1 Simple CandleStick Charts

from math import pi
from bokeh.plotting import figure
from bokeh.io import output_notebook,show
from bokeh.resources import INLINE

output_notebook(resources=INLINE)

inc = apple_df.Close > apple_df.Open
dec = apple_df.Open > apple_df.Close

w = 12*60*60*1000

p = figure(x_axis_type="datetime", plot_width=800, plot_height=500, title = "Apple, March - 2020")

p.segment(apple_df.index, apple_df.High, apple_df.index, apple_df.Low, color="black")

p.vbar(apple_df.index[inc], w, apple_df.Open[inc], apple_df.Close[inc], fill_color="lawngreen", line_color="red")

p.vbar(apple_df.index[dec], w, apple_df.Open[dec], apple_df.Close[dec], fill_color="tomato", line_color="lime")

show(p)

Apple March-2020 CandleStick Bokeh

If you are looking for a guide to style, annotate and change the theme/layout of the candlestick chart then we would recommend you to visit the below links. It'll help you with that.

4. Bqplot

Bqplot is a python library to create interactive visualizations developed by the Bloomberg developers. It also provides us with two different ways to create candlestick charts.

4.1 bqplot matplotlib-like API

This API is almost the same as that of the matplotlib.pyplot API. It can be very easy for a person with a background in matplotlib to switch to bqplot using this API. We can create a candlestick chart in bqplot by calling the ohlc() method. We need to pass date data for X-axis and OHLC data for creating candles. We have explained below how we can create a candlestick chart using bqplot's pyplot API.

If you are interested in learning about bqplot's this API then please feel free to check our tutorial on the same which can help you to grasp API fast.

from bqplot import pyplot as plt
fig = plt.figure(title="Apple Mar-2020 CandleStick Chart")

fig.layout.width="800px"


ohlc = plt.ohlc(x=apple_df.index, y=apple_df[["Open","High","Low","Close"]],
                marker="candle", stroke="blue")

ohlc.colors=["lime", "tomato"]
plt.xlabel("Date")

plt.show()

Apple March-2020 CandleStick Mplfinance

Below we have created the same chart as the above one but with the marker parameter set as bar instead of candle. This chart is also sometimes referred to as the OHLC chart.

fig = plt.figure(title="Apple Mar-2020 CandleStick Chart")

fig.layout.width="800px"

ohlc = plt.ohlc(x=apple_df.index, y=apple_df[["Open","High","Low","Close"]],
                marker="bar", stroke="blue")

ohlc.colors=["lime", "tomato"]
plt.xlabel("Date")

plt.show()

Apple March-2020 CandleStick Mplfinance

4.2 bqplot - Internal Object Model API

Bqplot also provides their internal object model API to create charts which are very flexible and provide us with lots of options to tweak the look of charts. In order to create a chart using this API, we'll need to create scales, axis, chart, and combine them all into one figure to create a chart.

If you are interested in learning about this API of bqplot in-depth then please feel free to check our tutorial on the same.

from bqplot import OHLC, DateScale, LinearScale, Axis, Figure

x_date = DateScale()
y_linear = LinearScale()

ohlc = OHLC(x=apple_df.index, y=apple_df[["Open","High","Low","Close"]],
            scales={'x':x_date, 'y':y_linear},
            marker="candle",
            stroke="dodgerblue", stroke_width=1.0,
            colors=["lime", "tomato"],
            )

ax_x = Axis(scale=x_date, label="Date",
            label_offset="35px", grid_color="gray",
            )
ax_y = Axis(scale=y_linear, label="Price",
            orientation="vertical", label_offset="35px",
            grid_color="gray",
            tick_format="0.1f")

fig = Figure(marks=[ohlc],
             axes=[ax_x, ax_y],
             title="Apple Mar-2020 CandleStick Chart",
             fig_margin= dict(top=60, bottom=40, left=50, right=20),
             background_style = {"fill":"black"}
      )

fig.layout.height="550px"


fig

Apple March-2020 CandleStick Mplfinance

Below we have created an OHLC chart using bqplot's internal object model API. The code is the same as the previous chart with only a difference in the value of the marker parameter which is changed from candle to bar.

x_date = DateScale()
y_linear = LinearScale()

ohlc = OHLC(x=apple_df.index, y=apple_df[["Open","High","Low","Close"]],
            scales={'x':x_date, 'y':y_linear},
            marker="bar",
            stroke="dodgerblue", stroke_width=2.0,
            )

ax_x = Axis(scale=x_date, label="Date",
            label_offset="35px", grid_color="gray",
            )
ax_y = Axis(scale=y_linear, label="Price",
            orientation="vertical", label_offset="35px",
            grid_color="gray",
            tick_format="0.1f")

fig = Figure(marks=[ohlc],
             axes=[ax_x, ax_y],
             title="Apple Mar-2020 CandleStick Chart",
             fig_margin= dict(top=60, bottom=40, left=50, right=20),
      )

fig.layout.height="600px"


fig

Apple March-2020 CandleStick Mplfinance

The fifth library that we'll use to explain how we can create a candlestick chart using Python is cufflinks. Cufflinks is a wrapper library around plotly & pandas and let us create plotly charts directly from the pandas dataframe with just one line of code. As cufflinks is based on plotly, all charts are interactive.

5.1 Simple CandleStick Charts

Below we have explained how we can create a candlestick chart using plotly with just one line of code. We first need to import plotly and set the configuration to get started as explained below. We can call the iplot() method on the dataframe with OHLC data passing kind parameter value as candle to create a candlestick chart using cufflinks. We have even added a range selector to the figure. Please feel free to visit this link to add different types of range selectors to the figure.

If you are interested in learning about cufflinks then please feel free to check our tutorial which can help you to learn many different chart types.

import cufflinks as cf

cf.set_config_file(theme='pearl',sharing='public',offline=True)
apple_df.iplot(kind="candle",
                          keys=["Open", "High", "Low", "Close"],
                          rangeslider=True
                          )

Apple March-2020 CandleStick Mplfinance

The cufflinks also provide us with an OHLC chart by setting the kind parameter of the iplot() method to ohlc as explained below.

apple_df.iplot(kind="ohlc",
                          keys=["Open", "High", "Low", "Close"])

Apple March-2020 CandleStick Mplfinance

5.2 Quant Figure

Cufflinks also let us add volume, Bollinger bands, exponential moving average, relative strength indicator, moving average convergence divergence, average directional index, commodity channel indicator, directional movement index, parabolic SAR, resistance line, and trend line functionalities to our chart. We first need to create a figure object by calling the QuantFig() method of cufflinks passing it pandas dataframe with OHLC data. We can then call the list of below methods on QuantFig instance to add functionalities one by one to the figure before calling iplot() to finally display the figure.

  • add_bollinger_bands() - It adds Bollinger Bands (BOLL) study to the figure.
  • add_volume() - It adds volume bar charts to the figure.
  • add_sma() - It adds Simple Moving Average (SMA) study to the figure.
  • add_rsi() - It adds Relative Strength Indicator (RSI) study to the figure.
  • add_adx() - It adds Average Directional Index (ADX) study to the figure.
  • add_cci() - It adds Commodity Channel Indicator study to the figure.
  • add_dmi() - It adds Directional Movement Index (DMI) study to the figure.
  • add_ema() - It adds Exponential Moving Average (EMA) to the figure.
  • add_atr() - It adds Average True Range (ATR) study to the figure.
  • add_macd() - It adds Moving Average Convergence Divergence (MACD) to the figure.
  • add_ptps() - It adds Parabolic SAR (PTPS) study to the figure.
  • add_resistance() - It adds resistance line to the figure.
  • add_trendline() - It adds trend line to the figure.
  • add_support() - It adds support line to the figure.

Please make a note that we have explained below mostly usage of the above methods with default parameters. If you are interested in tweaking the parameters of these methods then please feel free to check the signature of these methods by pressing Shift + Tab in the Jupyter notebook.

Below we have again loaded our apple OHLC dataset. We have then added Bollinger bands and volume to our figure.

apple_df = pd.read_csv('/datasets/AAPL.csv', index_col=0, parse_dates=True)

qf=cf.QuantFig(apple_df,title='Apple Quant Figure',legend='top',name='GS')
qf.add_bollinger_bands()
qf.add_volume()

qf.iplot()

Apple March-2020 CandleStick Mplfinance

Below we have explained another example of creating a candlestick chart using cufflinks. We have added Bollinger bands, simple moving average, and relative strength index studies to the chart as well this time.

qf=cf.QuantFig(apple_df,title='Apple Quant Figure',legend='top',name='GS')

qf.add_bollinger_bands(periods=20,boll_std=2,colors=['magenta','grey'],fill=True)
qf.add_sma([10,20],width=2,color=['green','lightgreen'],legendgroup=True)
qf.add_rsi(periods=20,color='java')

qf.iplot()

Apple March-2020 CandleStick Mplfinance

The last candlestick chart that we have created using cufflinks adds average directional index, commodity channel indicator, directional movement index, and exponential moving average studies to the chart.

qf=cf.QuantFig(apple_df,title='Apple Quant Figure',legend='top',name='GS')

qf.add_adx()
qf.add_cci()
qf.add_dmi()
qf.add_ema()

qf.iplot()

Apple March-2020 CandleStick Mplfinance

This ends our small tutorial on candlestick graphs using mplfinance, plotly, bokeh, bqplot, and cufflinks. Apart from these libraries, there is another interactive library named Altair which also provides interactive candlestick charts (see References for the link to it). Please feel free to let us know your views in the comments section.

References

Sunny Solanki  Sunny Solanki

Share Views Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.