Share @ LinkedIn Facebook  candlestick, mplfinance, plotly, bokeh
Candlestick Chart in Python (mplfinance, plotly, bokeh)

Candlestick Chart in Python (mplfinance, plotly, bokeh)

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

This ends our small tutorial on candlestick graphs using mplfiance, plotly, and bokeh. Please feel free to let us know your views in the comments section.

References


Sunny Solanki  Sunny Solanki