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.
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()
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.
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 ($)'
)
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()
fplt.plot(
apple_df,
type='candle',
style="classic",
title='Apple, March - 2020',
ylabel='Price ($)'
)
fplt.plot(
apple_df,
type='candle',
style='charles',
title='Apple, March - 2020',
ylabel='Price ($)',
)
fplt.plot(
apple_df,
type='candle',
style='mike',
title='Apple, March - 2020',
ylabel='Price ($)',
)
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',
)
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
)
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
)
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
)
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
)
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
)
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'
)
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)
)
Plotly
is another library that provides functionality to create candlestick charts. It allows us to create interactive candlestick charts.
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()
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()
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()
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()
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.
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)
Bqplot is a python library developed by the Bloomberg developers team. It also provides us with two different ways to create candlestick charts.
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()
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()
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.
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
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
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.
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
)
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"])
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.
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()
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()
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()
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.
If you want to