【Python3】bitbank.cc APIより取得したビットコインのチャートデータをPostgreSQLに保存する②
前回データを整形するところまで終わったので、今度は
テーブルの作成をする。
PostgreSQLのセットアップは終わっているものとする。
float型のデータはdouble precision、
datetime.datetime型のデータはtimestamp without time zoneを指定した。
$ psql mydb ←データベースにmydbを指定してpsqlを起動 --テーブルを作成-- mydb=> CREATE TABLE bitbank mydb-> (high double precision , mydb(> sell double precision , mydb(> buy double precision , mydb(> last double precision , mydb(> timestamp timestamp without time zone , mydb(> low double precision , mydb(> vol double precision , mydb(> PRIMARY KEY (timestamp)); NOTICE: CREATE TABLE / PRIMARY KEYはテーブル"bitbank"に暗黙的なインデックス"bitbank_pkey"を作成します CREATE TABLE
--テーブルの項目を確認-- mydb=> \d bitbank テーブル "public.bitbank" 列 | 型 | 修飾語 -----------+-----------------------------+---------- high | double precision | sell | double precision | buy | double precision | last | double precision | timestamp | timestamp without time zone | not null low | double precision | vol | double precision | インデックス: "bitbank_pkey" PRIMARY KEY, btree ("timestamp")
ここまでの一連の流れ(前回記事①含め)を.pyファイルにまとめたもの。
冗長ですが許してね。
#bitbank.cc APIからデータを取得 import requests import simplejson as json from datetime import datetime base_url = "https://public.bitbank.cc" api_urls = {'ticker':'/btc_jpy/ticker'} class Public(object): def __init__(self): pass def public_api(self,url): ''' template function of public api''' try : url in api_urls return json.loads(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e) def getticker(self): '''Ticker を取得''' return self.public_api('ticker') P=Public() a=P.getticker() #dictに必要な部分のデータを保存 dict = a['data'] timestamp = str(dict['timestamp']) a = timestamp[:10] b = timestamp[10:] c = "." dict['timestamp'] = a + c + b dict['timestamp']= float(dict['timestamp']) dict['timestamp'] = datetime.utcfromtimestamp(dict['timestamp']) dict['high'] = float(dict['high']) dict['sell'] = float(dict['sell']) dict['buy'] = float(dict['buy']) dict['last'] = float(dict['last']) dict['low'] = float(dict['low']) dict['vol'] = float(dict['vol']) #PostgreSQLに接続 import psycopg2 connection = psycopg2.connect("host=localhost port=5432 dbname=mydb user=yoshiaki password=69SK6X0O") #conneection.cursor()をcurに代入 #cursorオブジェクトをconnection.cursor()で取得する。 cur = connection.cursor() #APIより取得したデータをデータベースに保存(PostgresSQL) cur.execute( "INSERT INTO bitbank (high, sell, buy, last, timestamp, low, vol) VALUES (%s, %s, %s, %s, %s, %s, %s);" ,(dict['high'], dict['sell'], dict['buy'], dict['last'], dict['timestamp'], dict['low'], dict['vol']) ) #トランザクションをコミットする connection.commit() #クローズする cur.close()
ターミナルで実行(ファイル名:APIデータ(bitbank)→PostgreSQL.py)
$python3 APIデータ(bitbank)→PostgreSQL.py
.pyファイル実行ごとにデータが追加されることを確認
mydb=> SELECT * FROM bitbank; high | sell | buy | last | timestamp | low | vol --------+--------+--------+--------+-------------------------+--------+--------- 450001 | 438350 | 434200 | 436275 | 2017-09-20 09:03:22.862 | 423943 | 17.5622 450001 | 438348 | 434200 | 436274 | 2017-09-20 09:14:16.193 | 423943 | 17.5666 446386 | 435609 | 433000 | 435609 | 2017-09-20 11:43:08.626 | 423943 | 16.0655 446386 | 435609 | 431364 | 433486 | 2017-09-20 11:48:47.766 | 423943 | 16.0669 (4 行)
あとは実際にデータを使いながら、適宜調整していく予定。
定期的に実行する場合は、
に少しまとめました。
終わり。