There are situations where more raw values per time point are needed to understand a trend for prediction. The candlestick plot is a commonly used visualization in technical analysis in finance to show a price trend, most often seen in the stock market. To draw a candlestick plot, we can use the candlestick_ohlc API in the mpl_finance package.
mpl_finance can be downloaded from GitHub. After cloning the repository in the Python site-packages directory, call python3 setup.py install in the terminal to install it.
candlestick_ohlc() takes the input of a Pandas DataFrame with five columns: date in floating-point numbers, open, high, low, and close.
In our tutorial, we use the cryptocurrency market values as an example. Let's again look at the data table we obtained:
import pandas as pd
# downloaded from kaggle "Cryptocurrency Market Data" dataset curated by user jvent
# Source URL: https://www.kaggle.com/jessevent/all-crypto-currencies
crypt = pd.read_csv('crypto-markets.csv')
print(crypt.shape)
crypt.head()
Here is the how the table looks:
Let's select the first cryptocurrency, Bitcoin, as our example. The following code selects the OHLC values in the month of December 2017 and sets the index as date in the datetime format:
from matplotlib.dates import date2num
btc = crypt[crypt['symbol']=='BTC'][['date','open','high','low','close']].set_index('date',drop=False)
btc['date'] = pd.to_datetime(btc['date'], format='%Y-%m-%d').apply(date2num)
btc.index = pd.to_datetime(btc.index, format='%Y-%m-%d')
btc = btc['2017-12-01':'2017-12-31']
btc = btc[['date','open','high','low','close']]
Next, we will draw the candlestick plot. Recall the techniques to set axis ticks to fine-tune time markers:
import matplotlib.pyplot as plt
from matplotlib.dates import WeekdayLocator, DayLocator, DateFormatter, MONDAY
from mpl_finance import candlestick_ohlc
# from matplotlib.finance import candlestick_ohlc deprecated in 2.0 and removed in 2.2
fig, ax = plt.subplots()
candlestick_ohlc(ax,btc.values,width=0.8)
ax.xaxis_date() # treat the x data as dates
ax.xaxis.set_major_locator(WeekdayLocator(MONDAY)) # major ticks on the Mondays
ax.xaxis.set_minor_locator(DayLocator()) # minor ticks on the days
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
# Align the xtick labels
plt.setp(ax.get_xticklabels(), horizontalalignment='right')
# Set x-axis label
ax.set_xlabel('Date',fontsize=16)
# Set y-axis label
ax.set_ylabel('Price (US $)',fontsize=16)
plt.show()
mpl_finance can be installed by running the following command:
pip3 install --user https://github.com/matplotlib/mpl_finance/archive/master.zip
We can observe that the rapid rise of Bitcoin values in early December turns its direction in mid-December 2017: