先日、pythonでbitcoinの平均相場を取得するという記事をアップしましたが、今回はその取得した値をグラフとして表示してみます。
使うライブラリはpythonのグラフ描画で有名なmatplotlibです。
では早速コードです。
import matplotlib.pyplot as plt import MySQLdb import numpy as np connection = MySQLdb.connect(host='hogehoge.hoge', user='hoge', passwd='hogegegege', db='hoge_db', charset='utf8') cursor = connection.cursor() try: str_sql = (" SELECT") str_sql += (" log_date") str_sql += (" ,bitcoin_kind") str_sql += (" ,bitcoin_price") str_sql += (" FROM") str_sql += (" hoge_db.tbl_bitcoin_price_hogehoge") str_sql += (" WHERE") str_sql += (" bitcoin_kind = %s") str_sql += (" ORDER BY") str_sql += (" log_date;") cursor.execute(str_sql,("FX_BTC_JPY",)) s = [] x = [] y1 = [] for row in cursor: s.append(row) for i in range(len(s)): x.append(s[i][0]) y1.append(s[i][2]) x = np.array(x) y1 = np.array(y1) plt.plot(x, y1) plt.show() except MySQLdb.Error as e: print('MySQLdb.Error: ', e) # 接続を閉じる connection.close()
データ取得用のSQL書いて、データをnumpy配列として格納して、matplotlibにplotして表示という流れですね。
これを実行すると↓のようにグラフが返ってきます。