テクニカル指標の作成

ProbSpace公開ノートブック

米国株式市場 将来株価予測

外部ライブラリ Ta-Libを用いてテクニカル指標を作成
# Mount Google colab
from google.colab import drive
drive.mount('/content/drive')
!wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz
!tar -xzvf ta-lib-0.4.0-src.tar.gz
!cd ta-lib && ./configure --prefix=/usr && make && make install
!pip install Ta-Lib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import talib
# 訓練データのファイルパス
path = "***"
# 訓練データの読み込み
df = pd.read_csv(f"{path}/data/train_data.csv")
# indexを"Date"列へ変更
df["Date"] = pd.to_datetime(df["Date"], format="%Y/%m/%d")
df.set_index(keys="Date", inplace=True)

print(f"df.shape: {df.shape}")
df.head(2)
df.shape: (420, 3278)
VGSH JEF IVZ KTCC FBZ PLOW JBK IAC IVR VSH VCV OKE ROK FTAG BRKR GSK JPS SRPT VMI IMKTA BDR JAKK MVC AMSF APTO CNX XOMA LBY BIOL PAAS KOF LAC EML IVC TILE IEF CSV QADA TBNK HOG ... KRO MORN BHV MMU SGRP PBA GF OSPN J AMKR CPHI TRT OPRX DXYN GFED FRAF HWCC WYND CHMG EVC NNA IOR ATLC STWD TTM NOC EQS MKC MXL NEV ASFI JTA MNR TFSL GTN TYG VIRC BIS WOOD MASI
Date
2011-11-13 55.942184 17.649006 13.770864 4.77 13.818835 10.198389 12.440549 38.484608 4.836254 8.575465 7.877108 23.100210 59.334507 84.253273 11.731660 28.273636 4.168243 4.86 75.028809 12.110400 1.13 18.456266 7.713052 15.194721 2.88 29.963728 30.400000 10.973586 14.384466 20.405405 73.412354 1.75 16.415005 19.071070 10.358725 88.829475 5.339281 10.804994 15.03547 29.228592 ... 12.701912 53.690952 13.001904 8.411827 1.22 16.457903 6.239215 8.04 39.470684 4.63 0.88 2.40 3.06 2.93 4.992733 10.988591 9.748321 10.293147 17.453051 1.078169 33.496590 1.92 3.16 6.810544 15.831424 47.542465 2.21 40.948685 4.96 8.450615 3.721562 4.747546 5.567790 7.262252 1.80 20.079035 1.504111 826.767029 30.918266 18.430309
2011-11-20 55.978844 16.270664 12.719761 4.94 12.744166 10.035272 12.065370 36.252533 4.658076 7.657301 7.939425 22.540537 55.720310 78.528595 11.262002 27.104542 4.072667 4.08 69.938858 11.282884 1.14 17.461733 6.991731 14.490328 2.52 27.630514 30.799999 10.061356 12.466537 20.022963 68.245247 1.65 16.306412 18.346851 8.876307 89.084717 5.274280 9.564995 14.27878 27.989960 ... 11.972300 52.916691 12.470938 8.487832 1.22 16.131611 5.840057 7.13 37.356007 4.15 0.82 2.48 3.09 2.88 5.225369 11.137086 8.741022 10.082382 17.491066 0.787348 30.493443 1.67 3.59 6.498439 15.531258 45.167881 2.13 40.328121 4.75 8.548306 3.590744 4.549112 5.473421 7.125532 1.56 19.711763 1.474619 769.836304 29.410889 17.534525

2 rows × 3278 columns

Create technical indicators by Ta-Lib
class TechnicalIndicators():
    """
    Create technical indicators by Ta-Lib,
    the open-source library(https://mrjbq7.github.io/ta-lib/index.html).

    Returns:
        dict_df(dict): dictionary of dataframe of each ticker
            key: ticker name
            value: dataset as DataFrame
    
    Indicator:
        MACD
        RSI
    """
    def __init__(self, df, ticker):
        """
        Args:
            df(DataFrame): Dataset of stock prices for each stock
            ticker(list): Ticker, e.g. MSFT, FB..
        """
        self.df = df
        self.ticker = ticker

        # for return
        self.dict_df = {}
    
    def __call__(self):
        """
        Create each indicator
        """
        for ticker in self.ticker:
            # Stock price of the ticker
            price = self.df[ticker]
            # Data of one of the tickers
            self.df_each = pd.DataFrame()
            self.df_each['price'] = price

            # Create indicators
            self.macd(price, fastperiod=12, slowperiod=26, signalperiod=9)
            self.rsi(price, timeperiod=14)

            # Add the created DataFrame to the dictionary
            self.dict_df[ticker] = self.df_each
        
        return self.dict_df
    
    """
    Momentum-indicator Part
    """
    def macd(self, price, fastperiod=12, slowperiod=26, signalperiod=9):
        """
        MACD - Moving Average Convergence/Divergence
            Ref. http://www.tadoc.org/indicator/MACD.htm
        Args:
            price: price of close values
            fastperiod: 
            slowperiod: 
            signalperiod: 
        """
        macd, macdsignal, macdhist = talib.MACD(price, fastperiod=12, slowperiod=26, signalperiod=9)
        self.df_each['macd'] = macd
        self.df_each['macdsignal'] = macdsignal
        self.df_each['macdhist'] = macdhist
    
    def rsi(self, price, timeperiod=14):
        """
        RSI - Relative Strength Index
            Ref. http://www.tadoc.org/indicator/RSI.htm
        Args:
            price: price of close values
        """
        rsi = talib.RSI(price, timeperiod=14)
        self.df_each['rsi'] = rsi
    
    """
    Plot
    """
    def plot_indicator(self, ticker, indicator):
        plt.plot(self.dict_df[ticker][indicator], label=indicator)
        plt.xlabel('date')
        plt.ylabel('indicator value')
        plt.legend()
        plt.show()

    def plot_macd(self, macd, macdsignal, macdhist):
        plt.plot(macd, label='macd')
        plt.plot(macdsignal, label='macdsignal')
        plt.bar(macdhist.index,macdhist, label='macdhist')
        plt.xlabel('date')
        plt.ylabel('indicator value')
        plt.legend()
        plt.show()
# ti: technical
ticker = ['VGSH', 'JEF']
ti = TechnicalIndicators(df, ticker)
df_dict = ti()

# print(df_dict)
# MACD
ticker, indicator = 'JEF', 'macd'
ti.plot_macd(df_dict[ticker]['macd'], df_dict[ticker]['macdsignal'], df_dict[ticker]['macdhist'])
# RSI
ticker, indicator = 'JEF', 'rsi'
ti.plot_indicator(ticker, indicator)

添付データ

  • technical_indicator_public2probspace.ipynb?X-Amz-Expires=10800&X-Amz-Date=20241221T123353Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIP7GCBGMWPMZ42PQ
  • Icon21
    Sho

    各銘柄の株価からテクニカル指標を作成するコードを作成しました。 TA-Libという外部ライブラリを用いると簡単に作成することができます。 今回は代表的な指標であるMACDとRSIを実装してみました。

    間違いの指摘など、色々ご意見頂けますと嬉しいです。 また、コンペではありますが、自作指標の提案など議論の活発化の手助けなれば幸いです。

    Favicon
    new user
    コメントするには 新規登録 もしくは ログイン が必要です。