3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

超初心者がPythonでHistData.comから為替レートの1分足チャートを通貨ペア毎に取得してみた

Last updated at Posted at 2021-07-18

タイトル通りだが、取得先はHistData.comで、histdataというライブラリを使用している。histdataはpipでインストールできます。

参考

コード

download_histdata.py
import glob
import os
import pandas as pd
import zipfile

from datetime import datetime
from histdata import download_hist_data as dl

# FXデータをダウンロードして1つに結合する関数
def download_forex_data(symbol, start_year, folder):

    # 去年以前のデータをDL(ファイルは年ごと)して解凍
    for year in range(start_year, datetime.now().year, 1):
        filename1 = (folder + '/DAT_ASCII_' + symbol + '_M1_' + str(year) +
                     '.zip')
        #print("[01]" + filename1)
        if os.path.exists(filename1)==False:
            dl(year=str(year), pair=str.lower(symbol), output_directory=folder)
            zip_f = zipfile.ZipFile(filename1)
            zip_f.extractall(folder)
            zip_f.close()
    
    # 今年のデータをDL(ファイルは月ごと)して解凍
    for month in range(1, datetime.now().month, 1):
        if month < 10:
            filename1 = (folder + '/DAT_ASCII_' + symbol + '_M1_' + str(datetime.now().year) + '0' + str(month) + '.zip')
        else:
            filename1 = (folder + '/DAT_ASCII_' + symbol + '_M1_' + str(datetime.now().year) + str(month) + '.zip')
        #print("[02]" + filename1)

        if os.path.exists(filename1)==False:
                dl(year=str(datetime.now().year), month=str(month), pair=str.lower(symbol), output_directory=folder)
                zip_f = zipfile.ZipFile(filename1)
                zip_f.extractall(folder)
                zip_f.close()
    
    # 上で解凍したCSVを通貨ペアごとに結合
    filenames = sorted(glob.glob(folder + '/DAT_ASCII_' + symbol + '*.csv'))
    df = pd.DataFrame()
    for filename in filenames:    
        #print("[03]" + filename1)

        temp = pd.read_csv(filename, sep=';', header=None, index_col=0)
        df = df.append(temp)
    df.to_csv(os.path.expanduser(folder + '/' + symbol + '.csv'))



start_year = 2018
folder = './temp_historical_data'
# for symbol in ['AUDUSD', 'EURUSD', 'GBPUSD', 'NZDUSD', 'USDCAD', 'USDCHF', 'USDJPY']:
for symbol in ['USDJPY', 'GBPJPY', 'AUDJPY']:
    download_forex_data(symbol, start_year, folder)

ちょっと説明

  1. 年間のデータをzipでダウンロードしてみて、あったら解凍し、csvにしておく
  2. 年間データがなければ月毎データをzipでダウンロードして解凍し、csvにしておく
  3. 通貨ペアごとにcsvを結合

という流れ。ダウンロード先、解凍先はtemp_historical_dataディレクトリなので実行前に作成しておく。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?