概要説明
RDS(MySQL)にアップロードする株式CSVを半分自動化。そのメモです。
アップロード時
モジュールとログイン情報を入力
import csv
import codecs
import mysql.connector
rds = 'xxxxxxxxxxx'
con = mysql.connector.connect(
host=rds,
user="xxxx",
password="xxxxx",
database='xxxx'
)
cursor = con.cursor()
UP用のメソッドを作成
def to_RDS(csvdata):
try:
with codecs.open(csvdata, "r", "Shift-JIS") as f:
reader = csv.reader(f)
header = next(reader) # 会社名情報
next(reader)
cursor.execute(f"DROP TABLE IF EXISTS `stock_table_{header[0]}`")
cursor.execute(f"""CREATE TABLE IF NOT EXISTS `stock_table_{header[0]}`(
date DATETIME PRIMARY KEY ,opening_price FLOAT, high_price FLOAT, low_price FLOAT,
closing_price FLOAT,volume FLOAT,closing_price_adjustment_value FLOAT);""")
sql = f"INSERT INTO `stock_table_{header[0]}` (date, opening_price, high_price, low_price, " \
f"closing_price, volume, closing_price_adjustment_value) VALUES (%s, %s, %s, %s, %s, %s, %s);"
for row in reader:
cursor.execute(sql, (row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
con.commit()
except mysql.connector.Error as e:
print("Error code:", e.errno) # error number
print("SQLSTATE value:", e.sqlstate) # SQLSTATE value
print("Error message:", e.msg) # error message
print("Error:", e) # errno, sqlstate, msg values
s = str(e)
print("Error:", s)
cursor.close()
con.close()
大本のCSVをファイルを見ると会社名情報が(0,0)に入ってますので、取得したheader
をheader[0]}
としてテーブル名に会社情報を入れています。1 "Shift-JIS"
はエンコードです。
ダウンロード時
DOWN用のメソッド
def get_RDS(cname):
sql = f'select * from `stock_table_{cname}`'
cursor.execute(sql)
for row in cursor.fetchall():
print('date', row[0], 'opening_price', row[1],
'high_price', row[2], 'low_price', row[3],
'closing_price', row[4], 'volume', row[5],
'closing_price_adjustment_value', row[6])
get_RDS('6433 東証JQS ヒーハイスト精工(株)(機械)')
cursor.close()
con.close()
'''
結果
date 2018-01-04 00:00:00 opening_price 585.0 high_price 589.0 low_price 569.0 closing_price 580.0 volume 172100.0 closing_price_adjustment_value 580.0
date 2018-01-05 00:00:00 opening_price 586.0 high_price 619.0 low_price 586.0 closing_price 613.0 volume 337200.0 closing_price_adjustment_value 613.0
date 2018-01-09 00:00:00 opening_price 634.0 high_price 649.0 low_price 614.0 closing_price 626.0 volume 215300.0 closing_price_adjustment_value 626.0
...
連続アップできていたようでした。
ちなみにこの株価CSVファイルは下記
株式投資メモ
を使用させていただきました。
データのアップは半自動化できたのでこれをどうやってwebで出力しようか考え中...
-
本当はPythonのフォーマット形式ではなくSQL構文の形式を使って挿入したほうがいいそうです。 ↩