[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.
Terminal
conda activate <Target CONDA environment name>
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
jupyter lab
with no optionsTerminal
jupyter lab --ip=0.0.0.0 --no-browser
Make a note of the external IP surrounded by the red frame
Access "
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)
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
#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()
It can be displayed nicely like this, but if you just want to see the chart, it is more convenient to use Tradingview lol
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.
Recommended Posts