Updated On : Dec-05,2020 Tags candlestick, mplfinance, plotly, bokeh, bqplot, cufflinks
Candlestick Chart in Python (mplfinance, plotly, bokeh, bqplot & cufflinks)

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

Table of Contents

Introduction

Candlestick charts are commonly used in financial markets to display the movement of security throughout the time period. It's based on open, high, low and closing prices of a security. Each candlestick typically shows the movement of price for one day though candlesticks can be drawn for one day period as well. We'll be explaining how to draw candlestick charts in python using plotting libraries mplfinance, plotly, bokeh, bqplot and cufflinks. We'll be using Apple stock price data downloaded from yahoo finance.

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.

In [1]:
import pandas as pd
In [2]:
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()
Out[2]:
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

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

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.

In [1]:
import mplfinance as fplt
In [ ]:
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.

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

Apple March-2020 CandleStick Mplfinance

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

Apple March-2020 CandleStick Mplfinance

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

Apple March-2020 CandleStick Mplfinance

1.2 CandleStick with Volume

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.

In [ ]:
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.

In [ ]:
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.

In [ ]:
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.

In [ ]:
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.

In [ ]:
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

In [ ]:
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.

In [ ]:
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.

In [ ]:
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 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.

In [ ]:
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.

In [ ]:
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.

In [ ]:
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

In [ ]:
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 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 a simple calculations to create candlestick with bokeh.

In [ ]:
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

4. Bqplot

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

  • bqplot - Matplotlib's Pyplot-like API
  • bqplot - Internal Object Model API

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.

In [3]:
from bqplot import pyplot as plt
In [ ]:
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.

In [ ]:
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

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, charts, 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.

In [ ]:
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.

In [ ]:
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 candlestick chart using Python is cufflinks. Cufflinks is a wrapper library around plotly & pandas and let us create plotly charts directly from pandas dataframe with just one line of code. As cufflinks is based on plotly, all charts are interactive.

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 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.

In [ ]:
import cufflinks as cf

cf.set_config_file(theme='pearl',sharing='public',offline=True)
In [ ]:
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.

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

Apple March-2020 CandleStick Mplfinance

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.

In [ ]:
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.

In [ ]:
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.

In [ ]:
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 mplfiance, 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