LoginSignup
3
3

More than 3 years have passed since last update.

GMOコインの過去取引データを1分足OHLCに集計する

Last updated at Posted at 2021-05-17

はじめに

目的

前回は、GMOコインから過去の取引データを取得しました。
今回は、ミリ秒のデータを1分足のOHLCデータ (open, high, low, close) に集計したいと思います。

前提

前回のコードにて、ダウンロードしたCSVを集計対象とします。

集計コード

実行すると、1分足で集計されたOHLCデータがone_min.csvが出力されます。

from logging import getLogger,INFO,StreamHandler,FileHandler
import datetime
import traceback
import pandas as pd
import numpy as np

logger = getLogger(__name__)
logger.setLevel(INFO)
fh = FileHandler('one_min.csv')
logger.addHandler(fh)

if __name__ == '__main__':
    try:
        # ダウンロードしたCSVファイルの開始日 - 終了日を指定
        start_datetime = datetime.datetime.strptime("2021-04-01 00:00:00", "%Y-%m-%d %H:%M:%S")
        end_datetime = datetime.datetime.strptime("2021-05-01 00:00:00", "%Y-%m-%d %H:%M:%S")

        while start_datetime != end_datetime:
            print("converting :", start_datetime)
            year = str(start_datetime.year)
            month = str(start_datetime.strftime('%m'))
            day = str(start_datetime.strftime('%d'))
            filename = year + month + day + '_BTC_JPY.csv'

            # 元データ読み込み
            df = pd.read_csv(filename, names=('symbol', 'side', 'volume', 'price', 'timestamp'), skiprows=1)
            volume_values = df.volume.values
            price_values = df.price.values
            timestamp_values = df.timestamp.values

            ohlc = { 'open': '', 'high': '', 'low': '', 'close': '', 'volume': '' }
            current_min = -1
            for i in range(0, len(df)):
                price = float(price_values[i])
                volume = float(volume_values[i])
                trade_datetime = datetime.datetime.strptime(timestamp_values[i], "%Y-%m-%d %H:%M:%S.%f")

                if trade_datetime.minute == current_min:
                    ohlc['high'] = max(ohlc['high'], price)
                    ohlc['low'] = min(ohlc['low'], price)
                    ohlc['close'] = price
                    ohlc['volume'] += volume
                else:
                    # CSV 出力
                    if current_min != -1:
                        logger.info("{},{},{},{},{},{}".format(trade_datetime.strftime('%Y-%m-%d %H:%M:00'), ohlc['open'], ohlc['high'], ohlc['low'], ohlc['close'], ohlc['volume']))

                    current_min = trade_datetime.minute
                    ohlc['open'] = price # 始値
                    ohlc['high'] = price # 高値
                    ohlc['low'] = price # 安値
                    ohlc['close'] = price # 終値
                    ohlc['volume'] = volume # 取引量

            # 1日加算
            start_datetime = start_datetime + datetime.timedelta(days=1)
    except KeyboardInterrupt:
        print("Stop with Keyboard Interrupt.")
    except Exception as e:
        print(traceback.format_exc())
    finally:
        print("All stopped.")
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3