Candlestick charts are often used to show the trend of stock prices. A single candlestick can indicate four prices, which are the highest price, the opening price, the closing price, and the lowest price. This article will introduce how to use Python’s mplfinance and Plotly packages to draw candlestick charts.
The complete code can be found in .
Table of Contents
Sample Dataset
This article will use TSMC’s (2330) February 2021 stock price as an example. The meaning of each field is as follows:
- Date: date
- Volume: Volume
- Open: Opening price
- High: Highest price
- Low: Lowest price
- Close: Closing price
We will use the following code to load the stock price.
import pandas as pd df = pd.DataFrame([ ['2021-02-01',70161939,595.00,612.00,587.00,611.00], ['2021-02-02',80724207,629.00,638.00,622.00,632.00], ['2021-02-03',59763227,638.00,642.00,630.00,630.00], ['2021-02-04',47547873,626.00,632.00,620.00,627.00], ['2021-02-05',57350831,638.00,641.00,631.00,632.00], ['2021-02-17',115578402,663.00,668.00,660.00,663.00], ['2021-02-18',54520341,664.00,665.00,656.00,660.00], ['2021-02-19',51651844,656.00,657.00,647.00,652.00], ['2021-02-22',39512078,660.00,662.00,650.00,650.00], ['2021-02-23',52868029,641.00,643.00,633.00,641.00], ['2021-02-24',80010637,627.00,636.00,625.00,625.00], ['2021-02-25',45279276,636.00,636.00,628.00,635.00], ['2021-02-26',137933162,611.00,618.00,606.00,606.00], ], columns=['Date', 'Volume', 'Open', 'High', 'Low', 'Close']
mplfinance
mplfinance is a utility of Matplotlib for visualizing financial data. It is easy to a candlestick chart by using the plot() of mplfinance. Let us first look at the declaration of plot(). For other parameters, please refer to the official website.
mplfinance.plot(data, type, style, volume, mav, title, ylabel, ylabel_lower, columns)
- data: Data. The type is DataFrame.
- type: The category of the chart. The value can be candle, candlestick, ohlc, ohlc_bars, line, renko, pnf.
- style: The style of the chart.
- volume: Whether to display the trading volume.
- mav: Moving average line.
- title: The title of the chart.
- ylabel: The title of the y-axis.
- ylabel_lower: The y-axis title of the volume.
- columns: Specifying different column names.
Basic Usage
Generally speaking, a candlestick chart has the following basic elements: date, opening price, closing price, highest price, lowest price, trading volume, and stock price. Because these elements are necessary, plot() predefines the column names of these data. These pre-defined column names are the same as the names used in our sample data set.
- Volume: Volume
- Opening price: Open
- Highest price: High
- Lowest price: Low
- Closing price: Close
In addition, it will use index as the date, and its type must be Date
. So let’s adjust the data with the following code first.
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') df.set_index('Date', inplace=True)
After the data is ready, we can call plot() to draw a candlestick chart!
import mplfinance as mpf mpf.plot(df, type='candle', title='2330')
If you want to display the volume, set the parameter volume to True.
import mplfinance as mpf mpf.plot(df, type='candle', title='2330', volume=True, ylabel_lower='Shares')
Setting Styles and Colors
Although we have just drawn a candlestick chart easily. But the black and white candlestick chart is really not so good-looking. Let us beautify our candlestick chart.
We can quickly beautify a candlestick chart by setting the style parameter of plot(). Many styles are built in mplfinance. We can execute the code below to list the built-in styles.mpf.
mpf.available_styles()
['binance', 'blueskies', 'brasil', 'charles', 'checkers', 'classic', 'default', 'mike', 'nightclouds', 'sas', 'starsandstripes', 'yahoo']
I believe many people have used Yahoo to watch stocks, so let’s apply Yahoo’s style.
mpf.plot(df, type='candlestick', style='yahoo', ylabel='$', title='2330')
Is the style of Yahoo much better? However, in Taiwan, we are still used to using red to for raising and green for falling. It’s just the opposite of the picture above. mplfinance allows us to make some adjustments to a certain style.
The make_marketcolors() of mplfinance allows us to set the color of a single candlestick. In the code below, we set it to be red when it is rising and green when it is falling. inherit
means to inherit the settings of the style.
mc = mpf.make_marketcolors(up='r', down='g', edge='', wick='inherit', volume='inherit') s = mpf.make_mpf_style(base_mpf_style='yahoo', marketcolors=mc) mpf.plot(df, type='candle', style=s, volume=True)
In addition to allowing us to use the built-in styles of mplfinance, it also allows us to use the built-in styles of Matplotlib. We can use the following code to list the built-in styles of Matplotlib.
import matplotlib as mpl mpl.style.available
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
If you want to use the style of Matplotlib, the method is the same as that of using mplfinance, which is called mplfinance.make_mpf_style()
. However, use parameters instead base_mpl_style
.
s = mpf.make_mpf_style(base_mpl_style='seaborn-whitegrid', marketcolors=mc) mpf.plot(df, type='candle', style=s, volume=True)
Moving Average (MA)
When looking at stock price trends, we not only use candlestick charts, but also use moving averages (MA). mplfinance.plot() can also plot moving average lines. We can set the number of days of the moving average in the parameter mav. In the example below, we have set two moving averages, one is a 2-day moving average, and the other is a 3-day moving average. Since the amount of data is not large, we set the number of days short.
mpf.plot(df, type='candle', style='yahoo', mav=(2, 3), title='2330', volume=True, ylabel_lower='Shares')
Change the default field name
Although mplfinance presets the name of the columns, it also allows us to specify a different name. We only need to pass the specified column name array into the parameter columns. Among them, the order of names in the array is Open, High, Low, Close, and Volume. The usage example is as follows.
df_c = pd.DataFrame([ ['2021-02-01',70161939,595.00,612.00,587.00,611.00], ['2021-02-02',80724207,629.00,638.00,622.00,632.00], ['2021-02-03',59763227,638.00,642.00,630.00,630.00], ['2021-02-04',47547873,626.00,632.00,620.00,627.00], ['2021-02-05',57350831,638.00,641.00,631.00,632.00], ['2021-02-17',115578402,663.00,668.00,660.00,663.00], ['2021-02-18',54520341,664.00,665.00,656.00,660.00], ['2021-02-19',51651844,656.00,657.00,647.00,652.00], ['2021-02-22',39512078,660.00,662.00,650.00,650.00], ['2021-02-23',52868029,641.00,643.00,633.00,641.00], ['2021-02-24',80010637,627.00,636.00,625.00,625.00], ['2021-02-25',45279276,636.00,636.00,628.00,635.00], ['2021-02-26',137933162,611.00,618.00,606.00,606.00], ], columns=['日期', '成交股數', '開盤價', '最高價', '最低價', '收盤價']) df_c['日期'] = pd.to_datetime(df_c['日期'], format='%Y-%m-%d') df_c.set_index('日期', inplace=True) mpf.plot(df_c, type='candle', title='2330', columns=['開盤價', '最高價', '最低價', '收盤價', '成交股數'])
Plotly
Plotly is also a commonly used data visualization package. It also provides a method of drawing candlestick charts. Let us first look at the declaration of Candlestick. For its parameters, please refer to the official website.
Candlestick(close=None, high=None, low=None, open=None, x=None)
- x: Date.
- open: Opening price.
- high: The highest price.
- low: The lowest price.
- close: Closing price.
Basic Usage
Candlestick is a Plotly Trace, not a Plotly Figure. Therefore, we must put a candlestick Trace into a figure, and then draw it out.
import plotly.graph_objects as go candlestick = go.Candlestick(x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close']) fig = go.Figure(data=[candlestick]) fig.show()
If you do not like the bottom of the Slider, you can call using update_layout()
to hide it. In addition, update_layout() can also set the title of the chart and the title of the y-axis.
fig.update_layout(xaxis_rangeslider_visible=False) fig.update_layout(title="2330", yaxis_title='Price') fig.show()
Setting Colors
Like the Yahoo style of mplfinance, it is preset the rise to green and the fall to red. Let’s set the rise to red and the fall to green.
candlestick = go.Candlestick(x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'], increasing_line_color='red', decreasing_line_color='green') fig = go.Figure(data=[candlestick]) fig.show()
Moving Average (MA)
Plotly’s Candlestick cannot draw a moving average. However, we can use Plotly’s Scatter to draw moving averages. If you are not familiar with Plotly’s Scatter, you can read the following article first.
First of all, we can use the rolling() of the DataFrame to easily calculate the data required for the moving average.
df['MA5'] = df['Close'].rolling(5).mean() df['MA10'] = df['Close'].rolling(10).mean()
Then, we generate a candlestick trace, and then generate two moving average traces. Finally, put these traces into a figure, and draw the figure.
candlestick = go.Candlestick(x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['Close'], increasing_line_color='red', decreasing_line_color='green') ma5_scatter = go.Scatter(x=df['Date'], y=df['MA5'], line=dict(color='orange', width=1), mode='lines') ma10_scatter = go.Scatter(x=df['Date'], y=df['MA10'], line=dict(color='green', width=1), mode='lines') fig = go.Figure(data=[candlestick, ma5_scatter, ma10_scatter]) fig.show()
Conclusion
We introduced two packages for drawing candlestick charts. Whether it is mplfinance or Plotly, they all allow us to easily draw candlestick charts. Moreover, they can draw pretty beautiful charts. However, Plotly additionally provides interactive toolbars. Decide which package to use according to your needs and preferences!