[PYTHON] Generate technical indicators for system trading in Anaconda environment Try to create technical indicators for Bitcoin using TA-LIB

table of contents

  1. Overview
  2. Create a conda environment for system trading
  3. Install TA-LIB
  4. Try using TA-LIB
  5. Summary

1. Overview

I wanted to make my own system trade, [[Wikipedia] Moving Average](https://ja.wikipedia.org/wiki/%E7%A7%BB%E5%8B%95%E5%B9%B3%E5%9D If you wrote% 87) or [Wikipedia] MACD yourself, I knew that there was a package for creating a nice technical index called TA-LIB without having to press it by hand. Describe the introduction method, environment construction method, and execution example

⬇️ You can easily create innumerable indicators with one line like this

Create Bollinger Bands: [[Wikipedia] Bollinger Bands](https://en.wikipedia.org/wiki/%E3%83%86%E3%82%AF%E3%83%8B%E3%82%AB% E3% 83% AB% E6% 8C% 87% E6% A8% 99% E4% B8% 80% E8% A6% A7 #% E3% 83% 9C% E3% 83% AA% E3% 83% B3% E3 % 82% B8% E3% 83% A3% E3% 83% BC% E3% 83% 90% E3% 83% B3% E3% 83% 89)

python


import ta-lib as ta
pperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)

There are a lot of technical indicators. Many things I don't know ...

Screen Shot 2020-02-25 at 22.00.51.png

2. Create a conda environment for system trading

[Qiita] Save / Reconstruct / Duplicate virtual environment using Anaconda The above article was very easy to understand about the virtual environment using conda, so if you are not familiar with it, please go to see it.

Checking the conda environment

Terminal


conda info -e

Execution example: Base only in Default environment Screen Shot 2020-02-25 at 21.36.26.png

Clone conda environment

This time I will clone the Base environment and create a new environment

Terminal


conda create -n <New environment name> --clone <Environment name you want to duplicate>

Execution example Screen Shot 2020-02-25 at 21.41.22.png

Activate the new conda environment

Terminal


conda activate <New environment name>

Execution example Screen Shot 2020-02-25 at 21.43.52.png

3. Install TA-LIB

Search TA-LIB by conda

Terminal


anaconda search -t conda ta-lib

Execution example: This time Platform: linux-64, Builds: py37_0 I wanted an environment, so make a note of the corresponding environment name "quantnet / ta-lib"

Note: For Mac OS and Windows users, please select "Quantopian / ta-lib" Also, since "Quantopian / ta-lib" only supports up to Python 3.6, It cannot be used with the clone of the base environment (Python3.7) by the above procedure. Create a Python 3.6 environment with conda create -n <new environment name> python = 3.6

Screen Shot 2020-02-25 at 21.46.34.png

Search for the installation command of the target Package

Terminal


anaconda show <Target Package name>

Execution example Screen Shot 2020-02-25 at 21.55.31.png

Conda install TA-LIB

Terminal


conda install --channel https://conda.anaconda.org/quantnet ta-lib

Check if TA-LIB is installed

Terminal


conda list | grep ta-lib

Execution example Screen Shot 2020-02-25 at 22.05.50.png

4. Try using TA-LIB

Get daily data of BTC and make it DataFrame

This time, we will get the daily data of Bitcoin in bitFlyer from Cryptwatch. [Cryptowatch] bifFlyer BITCFXJPY daily data

python


import requests
import pandas as pd

#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()

#Take a look at the acquired data
df_btc.head()
Execution example: You should get the following result.
Screen Shot 2020-02-26 at 16.36.51.png

Convert to array for use with TA-LIB

** [Caution] Information such as open and close when creating technical indicators with TA-LIB cannot be processed by DataFrame and must be an array **

python


import numpy as np

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'])

Create various technical indicators using TA-LIB

I wrote only the representative indicators that are often used, but there are really innumerable. Please refer to TA-LIB

python


# TA-Import LIB package
import talib as ta

#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)

#Take a look at the results
df_btc.tail(10)
Execution example: Due to the size of the image, only the results of up to 3 lines are pasted, but the results can be obtained properly up to 10 lines.
Screen Shot 2020-02-26 at 16.46.59.png

5. Summary

So far, it's close to the preparation for automatic trading, so is it so much fun? There may be no one. Next time, I would like to make an article about plotting this result and backtesting for system trading (a test like cross-validating a model by separating train and test data in machine learning).

Recommended Posts

Generate technical indicators for system trading in Anaconda environment Try to create technical indicators for Bitcoin using TA-LIB
I tried using TradeWave (BitCoin system trading in Python)
Command line collection for using virtual environment in Anaconda
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
Introduction to docker Create ubuntu environment in ubuntu
[Cloudian # 10] Try to generate a signed URL for object publishing in Python (boto3)
For beginners to build an Anaconda environment. (Memo)
Try to separate Controllers using Blueprint in Flask
Try to calculate RPN in Python (for beginners)
Try to create an HTTP server using Node.js