DS Concepts DS Languages

Candlestick charts in Python: FA14

Candlestick charts in Python

Hi All!

In this tutorial, we will be learning how to create candlestick charts in Python along with volume bars and moving average lines.

  • The library we will be using to create these charts in this tutorial is mplfinance.
  • We will be fetching stock data using yfinance library.
  • The stock we will be plotting on is MSFT (Microsoft Corporation).

This is the part 14 of the Financial Analytics series taught by us. Here’s the link to part 13. If you’re new to this series, please go to part 1 here to get good grasp on the core concepts of financial analytics.

Candlestick charts in Python – Theory

Before proceeding to code, let’s first understand what, why, how and when of candlestick charts.

  • The origin of candlestick charts dates back to over 100 years.
  • It was discovered by Homma, a Japanese man that trading is not only linked to prices, supply and demand chains, it was also linked to emotions and sentiments of the traders.
  • Candle stick charts help in identifying the emotions of traders based on past patters.
  • A trading day usually consists of 4 price components – Open (O), High (H), Low (L) and Close (C) – (OHLC). All these 4 components can be shown by a candlestick chart.
  • A single candlestick in a candlestick chart typically correspond to one trading day, though this time-period can be reduced or made higher depending upon requirements.
  • If, in a trading day, the Close price of a stock is higher than the Open price, that stock is said to be bullish for that day.
  • If, in a trading day, the Close price of a stock is less than the Open price, that stock is said to be bearish for that day.
Here’s an image which shows how bullish and breaish candlesticks look like.
Candlestick chart

Candlestick charts in Python – Code

Let’s start by importing and loading the libraries. We will be importing 4 libraries:

  • Pandas for dataframe manipulation
  • yfinance for downloading finance data
  • mplfinance for plotting of candlestick charts – mplfinance is matplotlib utilities for visualization and visual analysis of financial data
In [1]:
import pandas as pd
import yfinance as yf
import mplfinance as mf

The next step is to download the financial data-set from yahoo finance using download function of yfinance library.

  • The date range we are selecting varies from 1st May 2020 till today.
  • For that, let’s fetch today’s date using pandas first and store it in a variable.
  • Then we will pass this to the end parameter of download function.
In [2]:
today = pd.Timestamp('today')
today
Out[2]:
Timestamp('2020-05-17 19:27:16.948274')
In [3]:
StockData = yf.download( 'MSFT',
                        start = '2020-05-01',
                        end = today,
                        progress = False)

Let’s now see what’s there in the data-set using head function.

In [4]:
StockData.head()
Out[4]:
Open High Low Close Adj Close Volume
Date
2020-04-30 180.000000 180.399994 176.229996 179.210007 179.210007 53875900
2020-05-01 175.800003 178.639999 174.009995 174.570007 174.570007 39370500
2020-05-04 174.490005 179.000000 173.800003 178.839996 178.839996 30372900
2020-05-05 180.619995 183.649994 179.899994 180.759995 180.759995 36839200
2020-05-06 182.080002 184.199997 181.630005 182.539993 182.539993 32139300

Let’s now check the variable statistics using the describe function.

In [5]:
StockData.describe()
Out[5]:
Open High Low Close Adj Close Volume
count 12.000000 12.000000 12.000000 12.000000 12.000000 1.200000e+01
mean 180.936666 183.482498 178.823332 181.407500 181.407500 3.732838e+07
std 3.741320 3.116302 3.637908 3.185623 3.185623 8.013742e+06
min 174.490005 178.639999 173.800003 174.570007 174.570007 2.831600e+07
25% 178.679996 180.617500 176.092495 179.615002 179.615002 3.090762e+07
50% 181.349998 184.125000 178.449997 181.634995 181.634995 3.448925e+07
75% 183.404995 185.509998 182.370003 183.270004 183.270004 4.258330e+07
max 186.800003 187.509995 183.360001 186.740005 186.740005 5.387590e+07

Let’s also see if the data contains any missing values (which is not there, but still checking!).

In [6]:
StockData.isnull().any()
Out[6]:
Open         False
High         False
Low          False
Close        False
Adj Close    False
Volume       False
dtype: bool

No missing values (as expected)! Let’s now start plotting the candlestick chart. We will use plot function of mplfinance to achieve that. In the type parameter, we will pass candle to acheive this.

Creating candlestick chart

In [7]:
mf.plot(StockData, 
        type = 'candle',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
1

Here, we can see that the bearish candlesticks are represented using black color and bullish ones are in white color.

Exploring styles of candlestick plots

Now, let’s see what are the available styles for mplfinance based plots by applying available_styles() function on mf alias.

In [8]:
mf.available_styles()
Out[8]:
['binance',
 'blueskies',
 'brasil',
 'charles',
 'checkers',
 'classic',
 'default',
 'mike',
 'nightclouds',
 'sas',
 'starsandstripes',
 'yahoo']

Let’s apply all these styles and choose the best style for our plot.

In [9]:
# Applying binance style
mf.plot(StockData, 
        type = 'candle',
        style =  'binance',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
2

Here, in binance style, we can see that the bearish candlesticks are represented using pink color and bullish ones are in green color.

In [10]:
# Applying blueskies style
mf.plot(StockData, 
        type = 'candle',
        style =  'blueskies',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
3

Here, in blueskies style, we can see that the bearish candlesticks are represented using blue color and bullish ones are in white color.

In [11]:
# Applying brasil style
mf.plot(StockData, 
        type = 'candle',
        style =  'brasil',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
4

Here, in brasil style, we can see that the bearish candlesticks are represented using blue color and bullish ones are in yellow color.

In [12]:
# Applying charles style
mf.plot(StockData, 
        type = 'candle',
        style =  'charles',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
5

Here, in charles style, we can see that the bearish candlesticks are represented using maroon color and bullish ones are in green color.

In [13]:
# Applying checkers style
mf.plot(StockData, 
        type = 'candle',
        style =  'checkers',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
6

Here, in checkers style, we can see that the bearish candlesticks are represented using red color and bullish ones are in black color.

In [14]:
# Applying classic style
mf.plot(StockData, 
        type = 'candle',
        style =  'classic',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
7

Classic style looks somewhat like default except that default has light blue background while classic has white background. Here, in checkers style, we can see that the bearish candlesticks are represented using black color and bullish ones are in white color.

In [15]:
# Applying mike style
mf.plot(StockData, 
        type = 'candle',
        style =  'mike',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
8

Here, in mike style, we can see that the bearish candlesticks are represented using blue color and bullish ones are in black color.

In [16]:
# Applying nightclouds style
mf.plot(StockData, 
        type = 'candle',
        style =  'nightclouds',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
9

Here, in nightclouds style, we can see that the bearish candlesticks are represented using blue color and bullish ones are in white color.

In [17]:
# Applying sas style
mf.plot(StockData, 
        type = 'candle',
        style =  'sas',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
10

Here, in sas style, we can see that the bearish candlesticks are represented using maroon color and bullish ones are in dark blue color.

In [18]:
# Applying starsandstripes style
mf.plot(StockData, 
        type = 'candle',
        style =  'starsandstripes',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
11

So, sas and starsandstripes are producing the same result. They’re the same styles with different style names.

In [19]:
# Applying yahoo style
mf.plot(StockData, 
        type = 'candle',
        style =  'yahoo',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8))
12

In yahoo style, we can see that the bearish candlesticks are represented using orange color and bullish ones are in green color.

So, which style did you like the most? I loved the charles one. So, I will be using the same in this tutorial.

Adding volume to candlestick chart

In order to add volume variable and candlesticks in one chart, we will have to set the volume parameter of the plot function to True.

In [20]:
mf.plot(StockData, 
        type = 'candle',
        style =  'charles',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
       figratio=(12,8),
       volume = True )
13

As you can see, the volume stats have now been added. But this graph is not showing the non-trading days currently. The chart is showing trading days only. Let’s add them in the chart using show_nontrading = True.

In [21]:
mf.plot(StockData, 
        type = 'candle',
        style =  'charles',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
        figratio=(12,8),
       volume = True,
       show_nontrading = True)
14

We can also name the ylabel of volumes subchart by setting ylabel_lower to anything we want the label to be.

In [22]:
mf.plot(StockData, 
        type = 'candle',
        style =  'charles',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
        figratio=(12,8),
       volume = True,
       show_nontrading = True,
       ylabel_lower='Volume of \n traded shares')
15

Adding moving averages to candlestick chart

Let’s now add moving average lines to this plot. This can be achieved by setting mav parameter to a number. This number defines the window of the moving average. Since, I have daily trading data, setting mav = 2 will set the window to two days.

In [23]:
mf.plot(StockData, 
        type = 'candle',
        style =  'charles',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
        figratio=(12,8),
       volume = True,
       show_nontrading = True,
       ylabel_lower='Volume of \n traded shares',
       mav = 2)
16

I can set multiple windows for these moving averages and add multiple lines corresponding to these windows in my plot by passing tuple of these window numbers to mav.

In [24]:
mf.plot(StockData, 
        type = 'candle',
        style =  'charles',
        title = 'MSFT May 2020 walkthorugh',
        ylabel = 'MSFT Prices',
        figratio=(12,8),
       volume = True,
       show_nontrading = True,
       ylabel_lower='Volume of \n traded shares',
       mav = (2, 3, 4))
17

So guys, in this tutorial, we learnt how to make candlestick charts using mplfinance library of Python. We also learnt how to add volume stats and moving average lines in candlestick charts and to get a holistic view of what all is happening in a stock lifetime for the timeline we’ve defined.

Don’t forget to subscribe to our channel, ML for Analytics, where we teach all this by means of videos. Stay tuned!

 

 

3 thoughts on “Candlestick charts in Python: FA14

  1. I just wanna thank you for the content! I will explore in detail thanks for sharing!

Leave a Reply

Back To Top
%d bloggers like this: