Matplotlib Candlestick Chart
In this demonstration, we will introduce candlestick charts or plots and see how to mplfinance
create an OHLC (Open, High, Low, Close) candlestick chart using the module in Python Matplotlib.
mplfinance
Create candlestick charts
using the Matplotlib library
pandas
The Matplotlib Financial API makes it easy to plot stock prices. It requires the and modules
to be installed on our machine mplfinance
.
mplfinance
The module makes it very easy to do various operations such as OHLC charts, candlestick charts and even point and figure charts, all on one line.
For example, the first thing to do is to get some data. We downloaded Amazon's stock price from 2019 to 2020 from Yahoo Finance.
To download, go to Yahoo Finance, search for Amazon, and go to the Historical Data tab to download. We are using Amazon's stock price, but you can use any stock price data you like.
If the module is not installed on your machine mplfinance
, you must install it.
pip install mplfinance
Import the following required modules.
# %matplotlib inline
import pandas as pd
import mplfinance as mplf
The following line show()
will display our plot or chart inline without using the method, but if we use a different IDLE, for example pycharm
, we don't need to write this line as it will produce an error.
%matplotlib inline
Let's create a file
variable called and give it the name of the CSV file we downloaded. Make sure you are in the correct file path location, otherwise you will have to put the path here and use os
the Python package.
file = "AMZN.csv"
We will then create a data frame and read the CSV file.
data = pd.read_csv(file)
This is called a data frame below. It's 252 rows by 7 columns, and we have these columns here, and you can see that it's automatically indexed.
data
If you write your code into a different IDLE, the above line will not work. You need to print it to see your data.
Sometimes when we download data from yahoo, the names of the columns have spaces in front of them. This can be annoying, so you have to change it.
We will Date
convert the column to datetime
, since the object is a string. We need to use the pandas to_datetime()
method to convert it to datetime
.
We can info()
view Date
a summary of the columns and their data types using the method.
data.Date = pd.to_datetime(data.Date)
data.info()
When we execute it, we will now see that we have a datetime
data type, instead of before we had an object.
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 252 entries, 0 to 251
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 252 non-null datetime64[ns]
1 Open 252 non-null float64
2 High 252 non-null float64
3 Low 252 non-null float64
4 Close 252 non-null float64
5 Adj Close 252 non-null float64
6 Volume 252 non-null int64
dtypes: datetime64[ns](1), float64(5), int64(1)
memory usage: 13.9 KB
If we want to manipulate this data to display our chart, we need to access 日期
the columns since we will be displaying the stock price corresponding to a date. We need to make the index Date
a column of our dataframe and the padding will be added automatically to that index.
data = data.set_index("Date")
data
Date
The column is now our index.
We will be using the Finance API in the following examples. We have our data and types mplf
, which is our mplfinance
reference to the module.
We call the method from this module plot()
.
# %matplotlib inline # remove this line when use do not use jupyter notebook
import pandas as pd
import mplfinance as mplf
file = "AMZN.csv"
data = pd.read_csv(file)
data.Date = pd.to_datetime(data.Date)
data.info()
data = data.set_index("Date")
mplf.plot(data)
# use this when you are not using jupyter notebook
mplf.show()
If we want to show volume, we will make a line graph because it is easier to see on this scale and the volume is True
.
# %matplotlib inline # remove this line when we use jupyter notebook
import pandas as pd
import mplfinance as mplf
file = "AMZN.csv"
data = pd.read_csv(file)
data.Date = pd.to_datetime(data.Date)
data.info()
data = data.set_index("Date")
mplf.plot(data, type="line", volume=True)
# use this when you are not using jupyter notebook
mplf.show()
We have a line graph that is different from the OHLC graph. We also have volume, so we can see that it's doing something for us here.
It has labeled the axes and rotated those labels.
Let's find the months using the time series in pandas. We mav
put the data from May to July into the moving average using the parameter, and then we specify the type as candlestick
a candle named and we will keep the volume.
# %matplotlib inline # remove this line when wuse do not use jupyter notebook
import pandas as pd
import mplfinance as mplf
file = "AMZN.csv"
data = pd.read_csv(file)
data.Date = pd.to_datetime(data.Date)
data.info()
data = data.set_index("Date")
mplf.plot(
data.loc["2020-03":"2020-07"],
figratio=(20, 12),
title="Amazon price 2019 - 2020",
type="candle",
mav=(20),
volume=True,
)
# use this when you are not using jupyter notebook
mplf.show()
If we execute the code, we get a candlestick, an OHLC chart with volumes only for the moving average.
We can style
change the style of the plot's appearance using the parameter, "yahoo"
setting to the value of this method.
# %matplotlib inline # remove this line when wuse do not use jupyter notebook
import pandas as pd
import mplfinance as mplf
file = "AMZN.csv"
data = pd.read_csv(file)
data.Date = pd.to_datetime(data.Date)
data.info()
data = data.set_index("Date")
mplf.plot(
data.loc["2020-03":"2020-07"],
figratio=(20, 12),
title="Amazon price 2019 - 2020",
type="candle",
mav=(20),
volume=True,
style="yahoo",
)
# use this when you are not using jupyter notebook
mplf.show()
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Enumerating a dictionary in Python
Publish Date:2025/05/05 Views:98 Category:Python
-
The function in Python enumerate() returns an object of enumeration type and adds a counter variable to iterate over a list or other type of collection. It makes looping over such objects easier. When we pass an enumeration object to list()
Changing dictionary values in Python
Publish Date:2025/05/05 Views:108 Category:Python
-
This tutorial will discuss various ways to change the value of a particular key in Python dictionary. We can do this by using the following methods. dict.update() method for cycle. Dictionary Unpacking dict.update() How to change dictionary
Finding the maximum value in a Python dictionary
Publish Date:2025/05/05 Views:60 Category:Python
-
This tutorial explains how to get a key with the maximum value in Python. Since the method has changed from the previous Python versions, it also lists some sample codes to clarify the concepts. Use operator.itemgetter() the method to get t
How to read input from stdin in Python
Publish Date:2025/05/05 Views:124 Category:Python
-
This tutorial discussed stdin the methods of reading input from in Python. You can read directly from the console or from a file name specified in the console. In Python, fileinput.input() use stdin fileinput We can use the read module in P
Maximum integer in Python
Publish Date:2025/05/05 Views:55 Category:Python
-
This tutorial will discuss the maximum integer value in different versions of Python and how we can get it. In Python 2, integers and long integers are different data types. The maximum value of an integer is 2 31 -1. If the value exceeds t
Get a list of time zones using Python
Publish Date:2025/05/05 Views:107 Category:Python
-
When developing real-world applications, software developers must ensure that the application can support users from both their own country and other parts of the world. Since most countries have different time zones and many people around
Convert NumPy array to list in Python
Publish Date:2025/05/05 Views:101 Category:Python
-
Lists and arrays are the two most basic and commonly used collection objects in Python. They are both mutable and are used to store a collection of elements under a common name and each element has a specific location that can be used to ac
Appending 2D Arrays in Python
Publish Date:2025/05/05 Views:64 Category:Python
-
In Python, we can have ND arrays. We can use NumPy module to process arrays in Python. This tutorial demonstrated the different methods you can use to append values to a two-dimensional array in Python. Use append() the function to ap
Sliding average of NumPy arrays in Python
Publish Date:2025/05/05 Views:190 Category:Python
-
The sliding average is often used to study time series data by calculating the average of data at a specific time interval. It is used to eliminate some short-term fluctuations and study data trends. When studying stock price trends, the si