0
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.

超初心者がHistdata.comから取得したローソク足データをMySQLに保存してみた

Last updated at Posted at 2021-08-03

毎回CSVから読み込むよりデータベースから読み込んだほうが早そうだったのでMySQLに保存してみました。

参考

Histdata.comからのデータ取得は以下でやってます。

PythonとMySQLの連携は以下あたりを参考

Code

テーブルを作成する

データベースはあらかじめ作成しておく。

create database fx;

通貨ペアごとのテーブルにする。今回はUSDJPY、GBPJPY、AUDJPY、EURJPYの4つを選択。テーブルのインデックスはidにしておくことにした。

create_histdata_table.py
import mysql.connector as mydb

try:
    conn = mydb.connect(
        host='hostname',
        port='3306',
        user='user',
        password='pass',
        database='fx'
    )

    conn.ping(reconnect=True)
    print(conn.is_connected())

    cursor = conn.cursor()
    for pair in ['usdjpy', 'gbpjpy', 'audjpy', 'eurjpy']:
        sql = '''
            CREATE TABLE IF NOT EXISTS '''+pair+''' (
            id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
            date DATETIME,
            open FLOAT,
            close FLOAT,
            high FLOAT,
            low FLOAT
        ) DEFAULT CHARSET=utf8mb4'''
        cursor.execute(sql)
        cursor.execute("SHOW TABLES")
        print(cursor.fetchall())

    cursor.close()

except Exception as e:
    print(f"Error Occurred: {e}")

finally:
    if conn is not None and conn.is_connected():
        conn.close()

作成したテーブルにデータを挿入する

insert_histdata_to_table.py
import mysql.connector as mydb
import pandas as pd

try:
    conn = mydb.connect(
        host='hostname',
        port='3306',
        user='user',
        password='pass',
        database='fx'
    )

    conn.ping(reconnect=True)
    print(conn.is_connected())
    cursor = conn.cursor()

    for pair in ['usdjpy', 'gbpjpy', 'audjpy', 'eurjpy']:
        path = './temp_historical_data/' + pair.upper() + '.csv'
        df = pd.read_csv(path)
        df.columns = ["Date", "Open", "High", "Low", "Close", "Volume"]
        df["Date"] = pd.to_datetime(df["Date"])
        df["Date"] = df["Date"].dt.strftime('%Y-%m-%d %H:%i:%s')
        
        print(path)
        cursor.execute('truncate '+ pair)
        for index, row in df.iterrows():
            sql = '''
                INSERT INTO '''+pair+'''
                (date, open, close, high, low)
                values
                (%s, %s, %s, %s, %s)
                '''
            cursor.execute(sql, [row.Date, row.Open, row.Close, row.High, row.Low])
    cursor.close()

except Exception as e:
    print(f"Error Occurred: {e}")
    
finally:
    if conn is not None and conn.is_connected():
        conn.close()

完走した感想(激寒ギャグ)

pd.to_datetimeで作ったTimestampデータはMySQLにそのまま挿入できなかった。恥ずかしがり屋で控えめなMySQLにあわせて文字列に変換してあげるとスルスルと挿入っていった。欲しがってたんだな(馬鹿)

0
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
0
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?