Plot Bitcoin candle charts and technical indicators in Python

table of contents

  1. Overview
  2. Install mpl-finance
  3. Try plotting with mpl-finance
  4. Summary

1. Overview

[Qiita] Creating technical indicators for Bitcoin using TA-LIB to generate technical indicators for system trading in Anaconda environment continued is. Now that we have obtained the technical indicators for Bitcoin, we would like to plot the candle chart and the created indicators together.

Bitcoin chart information is described on the assumption that it has been acquired, so if you have not done so, please refer to the above Qiita article and create it.

Goal: Create a graph like this
Screen Shot 2020-03-03 at 18.22.09.png

2. Install mpl-finance

Activate the conda environment where you want to install mpl-finance

Terminal


conda activate <Target CONDA environment name>
Execution example: is "trading"
Screen Shot 2020-03-03 at 17.36.52.png

Install mpl-finance with pip

I really wanted to do conda install, but I didn't have the conda package for the target environment, so I will install it with pip.

Terminal


pip install mpl-finance
Execution example
Screen Shot 2020-03-03 at 17.40.07.png

Start jupyter lab. People in Local environment run jupyter lab with no options

Terminal


jupyter lab --ip=0.0.0.0 --no-browser
Execution example
Screen Shot 2020-03-03 at 17.44.53.png

Access jupyter lab with a browser. People in the Local environment will automatically start jupyter lab with a browser.

Make a note of the external IP surrounded by the red frame Screen Shot 2020-03-03 at 17.47.02.png

Access ": 8888" with a browser Screen Shot 2020-03-03 at 17.50.19.png

Screen Shot 2020-03-03 at 17.52.06.png

3. Try plotting with mpl-finance

Get Bitcoin OHLC data

OHLC stands for Open (open price), High (high price), Low (low price), Close (close price) Since the content is the same as the previous article, those who have already done it can skip it.

import requests
import pandas as pd
import numpy as np
import talib as ta

#1 day of BTC OHLC from Cryptowatch(14400 minutes)Create a function that gets and returns in a DataFrame
def get_btc_ohlc(period=14400):

    #Request to Cryptowatch
    response_data = requests.get("https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc",params = { "periods" : period , "after" : 1})
    response_data = response_data.json()

    #Transformed into a DataFrame
    df_tmp = pd.DataFrame(pd.DataFrame(response_data)[:1]['result'][0],
                        columns=['date', 'open', 'high', 'low', 'close', 'tmp1', 'tmp2']).drop(columns=['tmp1', 'tmp2'])

    #Since date is int, convert to datetime
    df_tmp['date'] = pd.to_datetime(df_tmp['date'].astype(int), unit='s')
    return df_tmp

#Actually get BTC OHLC information
df_btc = get_btc_ohlc()

# TA-Converted to array type so that it can be processed by LIB
btc_open = np.array(df_btc['open'])
btc_close = np.array(df_btc['close'])
btc_high = np.array(df_btc['high'])
btc_low = np.array(df_btc['low'])

#Calculate Bollinger Bands
upperband, middleband, lowerband = ta.BBANDS(btc_close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)

#Calculate momentum
momentum=ta.MOM(btc_close,timeperiod=10)

#Calculate RSI
rsi = ta.RSI(btc_close, timeperiod=14)

# MACD
macd, macdsignal, macdhist = ta.MACD(btc_close, fastperiod=12, slowperiod=26, signalperiod=9)

# Stochastic
slowk, slowd = ta.STOCH(btc_high, btc_low, btc_close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)

# ATR
real = ta.ATR(btc_high, btc_low, btc_close, timeperiod=14)

# EMA
ema25 = ta.EMA(btc_close, timeperiod=25)
ema75 = ta.EMA(btc_close, timeperiod=75)


#In order to combine with the original DataFrame, the array of created technical indicators is put together into a DataFrame.
array_tmp = np.c_[upperband, middleband, lowerband, momentum, rsi, macd, macdsignal, macdhist, slowk, slowd, real, ema25, ema75]
df_tmp = pd.DataFrame(data=array_tmp, columns=['upperband', 'middleband', 'lowerband', 'momentum', 'rsi', 'macd', 'macdsignal', 'macdhist', 'slowk', 'slowd', 'real', 'ema25', 'ema75'])


#Join by Dataframe,Index-based guy
df_btc = df_btc.merge(df_tmp, left_index=True, right_index=True)

Preprocessing for Plot: Timed & Arrayed

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import mpl_finance

#Specify the period to display.If you want to see all, "df_btc.copy()Is OK
df_w = df_btc.query('"2020-02-01" <= date <= "2020-02-29"').copy()

#Sort in chronological order
df_w.sort_values(by='date', ascending=True, inplace=True)

#Index time
df_w.set_index('date', inplace=True)

#In matplotlib, the time is not processed unless it is set to unix time, so convert from datatime to unix time
df_w.index = mdates.date2num(df_w.index)

# mpl_Plot using finance.Just pass an array of OHLC and it will write a candle chart
data_w = df_w[['open', 'high', 'low', 'close']].copy().reset_index().values

Plot: Candle Chart, Bollinger Bands, EMA, RSI, MACD

#Display graph in 3 rows and 1 column. sharex=True x-axis sharing. gridspec_Adjust the ratio of each graph with kw
fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(20, 10), sharex=True, gridspec_kw={'height_ratios': [3, 1, 1]})

# mpl_finance.candlestick_In ohlc, pass the OHLC data of array and display the candle graph
mpl_finance.candlestick_ohlc(axes[0], data_w, width=0.1, alpha=0.8, colorup='limegreen', colordown='red')

#Bollinger band overlaid on candle graph
axes[0].plot(df_w.index, df_w['upperband'], color='green', alpha=0.9)
axes[0].plot(df_w.index, df_w['lowerband'], color='green', alpha=0.9)

#Overlay EMA on candle graph
axes[0].plot(df_w.index, df_w['ema25'], color='red', alpha=0.8)
axes[0].plot(df_w.index, df_w['ema75'], color='orange', alpha=0.8)

#Show RSI graph
axes[1].plot(df_w.index, df_w['rsi'], color='deepskyblue')

#Show MACD graph
axes[2].bar(df_w.index, df_w['macdhist'], color='skyblue')

#Add grid to the graph
axes[0].grid()
axes[1].grid()
axes[2].grid()

#Add legend
axes[0].legend(['upperband', 'lowerband', 'ema25', 'ema75'])
axes[1].legend(['RSI'])
axes[2].legend(['MACD'])

locator = mdates.AutoDateLocator()
axes[0].xaxis.set_major_locator(locator)
axes[0].xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))

#Since the x-axis notation is covered, rotate 70 °
plt.xticks(rotation=70)

#plot
plt.show()
Execution example
Screen Shot 2020-03-03 at 18.22.09.png

4. Summary

It can be displayed nicely like this, but if you just want to see the chart, it is more convenient to use Tradingview lol

Screen Shot 2020-03-03 at 18.27.58.png

However, if Tradingview is a Free plan, you can only use up to 3 technical indicators, so please refer to this article and plot various indicators for free.

When I tried to display Bollinger Bands, EMA25, EMA75, RSI, I was told to make a paid plan ..
Screen Shot 2020-03-03 at 18.29.05.png

Recommended Posts

Plot Bitcoin candle charts and technical indicators in Python
Drawing candle charts in python
How to plot autocorrelation and partial autocorrelation in python
Plot and understand the multivariate normal distribution in Python
Get stock prices and create candlestick charts in Python
Stack and Queue in Python
Unittest and CI in Python
Plot geographic information in Python
Poisson distribution and Poisson cumulative distribution plot via sqlite in Python and Java
MIDI packages in Python midi and pretty_midi
Difference between list () and [] in Python
Difference between == and is in python
View photos in Python and html
Sorting algorithm and implementation in Python
Manipulate files and folders in Python
About dtypes in Python and Cython
Assignments and changes in Python objects
Check and move directories in Python
Ciphertext in Python: IND-CCA2 and RSA-OAEP
Hashing data in R and Python
Function synthesis and application in Python
Export and output files in Python
Reverse Hiragana and Katakana in Python2.7
Reading and writing text in Python
[GUI in Python] PyQt5-Menu and Toolbar-
Create and read messagepacks in Python
Overlapping regular expressions in Python and Java
Differences in authenticity between Python and JavaScript
Notes using cChardet and python3-chardet in Python 3.3.1.
Modules and packages in Python are "namespaces"
Avoid nested loops in PHP and Python
Displaying candlestick charts in Python (matplotlib edition)
Differences between Ruby and Python in scope
difference between statements (statements) and expressions (expressions) in Python
Eigenvalues and eigenvectors: Linear algebra in Python <7>
Implementation module "deque" in queue and Python
Line graphs and scale lines in python
Differences in syntax between Python and Java
Check and receive Serial port in Python (Port check)
Search and play YouTube videos in Python
Difference between @classmethod and @staticmethod in Python
Write O_SYNC file in C and Python
Dealing with "years and months" in Python
Private methods and fields in python [encryption]
Find and check inverse matrix in Python
Linear Independence and Basis: Linear Algebra in Python <6>
Call sudo in Python and autofill password
Differences in multithreading between Python and Jython
Displaying candlestick charts in Python (Plotly edition)
Module import and exception handling in python
How to use is and == in Python
Project Euler # 1 "Multiples of 3 and 5" in Python
plot the coordinates of the processing (python) list and specify the number of times in draw ()
Technical events and study sessions held in Nagoya
Organize python modules and packages in a mess
What is "functional programming" and "object-oriented" in Python?
File DL, byte value and delete in Python3
Python variables and data types learned in chemoinformatics
Receive and display HTML form data in Python
[python] Difference between variables and self. Variables in class
Implemented memoization recursion and exploration in Python and Go