LoginSignup
7

More than 5 years have passed since last update.

numpy+matplotlib+仮想通貨api | 第3回pythonリモート社内勉強会

Last updated at Posted at 2018-01-21

「python社内勉強会&ハッカソン」の公開ログになります。
今回から徐々に実践的なものを題材に進めていきたいと思います。
「数学関数、Numpy」、「グラフ表示」について、そして年末に少し調べた「仮想通貨API」について共有します。
※プログラミング作法的な話は勉強会の流れ的に、面白くなくなってきたので各自座学していきましょう。

この勉強会について

各回30〜60分程度。ダラダラとはやらずpythonのwhy、whatを共有していく時間になります。
基本的なプログラミングなどの実装は会内はやらず、実行デモ程度を予定しています。宿題も特にありませんので各自勉強したことを再学習していってください。

前半(基礎編)

これまでの勉強会の過去ログはこちら。
第1回 : https://qiita.com/classfox/items/edba3e8971aaa067b88b
第2回 : https://qiita.com/classfox/items/095c4f4b8aa9247a4392
第3回 : https://qiita.com/classfox/items/825116980ac7ca255a13
第4回 : https://qiita.com/classfox/items/9a4b8a513fd5b642534d

数学関数、Numpy

http://www.numpy.org/
https://qiita.com/search?q=numpy

NumPy は Pythonプログラミング言語の拡張モジュールであり、大規模な多次元配列や行列のサポート、これらを操作するための大規模な高水準の数学関数ライブラリを提供。(via Wikipedia)
mathライブラリもpythonは標準で搭載しているが、numpyを用いて処理していくことがもはや一般的な印象。
SciPyという、科学向けのライブラリも存在する(これはまた次回少しピックアップ予定)。

実行中、このような問題にぶちあたった。。。

Traceback (most recent call last):
  File "/Users/teamcodor/anaconda3/envs/study/numpy.py", line 3, in <module>
    import numpy as np
AttributeError: module 'numpy' has no attribute 'xxx'

解決策:https://qiita.com/tonosamart/items/df5155bb79694fa64206

numpytest.py

#coding: UTF-8

import numpy as np

# sin([0, 1])
res = np.sin([0, 1])
print(res)

# cos([0, 1])
res = np.cos([0, 1])
print(res)

# tan([0, 1])
res = np.tan([0, 1])
print(res)

# 度からラジアンへ (np.deg2rad)
res = np.deg2rad([np.rad2deg(1), 0, 90])
print(res)

# ラジアンから度へ
res = np.rad2deg([np.deg2rad(180), 1, 0.5])
print(res)

# 行列をまとめて計算
res = np.array([i for i in range(12)])
res = res.reshape(3,2,2) # 2次元3x2行列に整形
print(res)

グラフ表示(matplotlib)

https://pythondatascience.plavox.info/matplotlib
http://bicycle1885.hatenablog.com/entry/2014/02/14/023734

matploglib.py

#coding: UTF-8
import numpy as np
import matplotlib.pyplot as plt

# 乱数を生成
x = np.random.rand(100)
y = np.random.rand(100)

# 散布図を描画
plt.scatter(x, y)
plt.show()

plt.scatter(x, y, s=600, c="pink", alpha=0.5, linewidths="2",
            edgecolors="red")
plt.show()

plt.scatter(x, y, s=600, c="yellow", marker="*", alpha=0.5,
            linewidths="2", edgecolors="orange")
plt.show()

# 乱数を 100 件生成
value = np.random.rand(100)

# 散布図を表示
plt.scatter(x, y, s=100, c=value, cmap='Blues')

# カラーバーを表示
plt.colorbar()
plt.show()

# 棒グラフ
left = np.array([1, 2, 3, 4, 5])
height = np.array([110, 250, 180, 350, 460])
plt.bar(left, height)
plt.show()

# 積み上げ棒グラフ
left = np.array([1, 2, 3, 4, 5])
height1 = np.array([110, 250, 180, 350, 460])
height2 = np.array([1200, 850, 500, 450, 240])
p1 = plt.bar(left, height1, color="green")
p2 = plt.bar(left, height2, bottom=height1, color="orange")
plt.legend((p1[0], p2[0]), ("Class 1", "Class 2"))
plt.show()

# 折れ線グラフを出力
left = np.array([1, 2, 3, 4, 5])
height = np.array([110, 250, 180, 350, 460])
p1 = plt.plot(left, height, linewidth=2)
p2 = plt.plot(left, height/2, linewidth=2, linestyle="dashed")
plt.legend((p1[0], p2[0]), ("Class 1", "Class 2"), loc=2)
plt.show()

# 棒グラフと折れ線グラフを混在して出力
bar_height = np.array([110, 250, 180, 350, 460])
line_height = np.array([120, 200, 150, 400, 280])

# 棒グラフを出力
fig, ax1 = plt.subplots()
ax1.bar(left, bar_height, align="center", color="royalblue", linewidth=0)
ax1.set_ylabel('Axis for bar')

# 折れ線グラフを出力
ax2 = ax1.twinx()
ax2.plot(left, line_height, linewidth=4, color="crimson")
ax2.set_ylabel('Axis for line')
plt.show()

# 平均 50, 標準偏差 10 の正規乱数を1,000件生成
x = np.random.normal(50, 10, 1000)

# ヒストグラムを出力
plt.hist(x, bins=16)
plt.show()

# 平均 20, 標準偏差 10 の正規乱数を1,000件生成
labels = ['V1', 'V2']
y = np.random.normal(10, 10, 1000)
plt.hist([x, y], label=labels, histtype="barstacked")
plt.legend()
plt.show()

仮想通貨API

各仮想通貨取引所が、それぞれのAPIを提供している。
取引履歴や、実際の売買などが可能。
※国内取引所のAPIはまだBTCのみしか対応していないAPIが比較的多い印象。

coincheck : https://coincheck.com/ja/documents/exchange/api
Binance : https://www.binance.com/restapipub.html
※Binanceのほうは会員登録が必要。
bitFlyer : https://lightning.bitflyer.jp/docs?lang=ja&_ga=2.204426192.1502021313.1516445923-295197369.1516445923
Zaif : https://corp.zaif.jp/api-docs/

coincheck.py

from coincheckjp.coincheck import CoinCheck
import logging
import json

# CoinCheck.DEBUG = True
# CoinCheck.DEBUG_LEVEL = logging.DEBUG
access_key = 'YOUR_ACCESS_KEY'
secret_access_key = 'YOUR_SECRET_ACCESS_KEY'
coinCheck = CoinCheck(access_key, secret_access_key)

#Public API
res = coinCheck.ticker.all()
dec = json.loads(res)
#print(dec)
for key, item in dec.items():
    print("%-9s : %-10.9s " % (key, item))
print(" ")

res = coinCheck.trade.all()
dec = json.loads(res)
#print(dec)
for key, item in dec.items():
    print("%s : %s " % (key, item))
print(" ")

res = coinCheck.order_book.all()
dec = json.loads(res)
#print(dec)
for key in dec.keys():
    print(key, ":")
    for value in dec[key]:
        print(value)
    print()
print(" ")

params = {}
#res = coinCheck.order.opens(params)
#print(res)
# 未決済の注文を取得

# 取引履歴
res = coinCheck.order.transactions(params)
dec = json.loads(res)
#print(dec)
for key, item in dec.items():
    print("%s : %s " % (key, item))
print(" ")

# 残高
res = coinCheck.account.balance(params)
#print(res)
dec = json.loads(res)
#print(dec)
for key, item in dec.items():
    print("%s : %s " % (key, item))
print(" ")

# アカウント情報
res = coinCheck.account.info(params)
dec = json.loads(res)
#print(dec)
for key, item in dec.items():
    print("%s : %s " % (key, item))
print(" ")
binance.py

from binance.client import Client

api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET_KEY'
client = Client(api_key, api_secret)

# get market depth
depth = client.get_order_book(symbol='TRXBTC')
print(depth)
# dec = json.loads(depth)
#print(dec)
for key, value in depth.items():
    print(key, ":", value)
print(" ")

# place market buy order
'''
order = client.create_order(
    symbol='TRXBTC',
    side=Client.SIDE_BUY,
    type=Client.ORDER_TYPE_MARKET,
    quantity=100)
'''

# get all symbol prices
prices = client.get_all_tickers()
#print(prices)
#dec = json.loads(prices)
print(" symbol :  price")
for value in prices:
    print(value['symbol'], ' : ', value['price'])
print(" ")

# withdraw 100 ETH
# check docs for assumptions around withdrawals
from binance.exceptions import BinanceAPIException, BinanceWithdrawException
'''
try:
    result = client.withdraw(
        asset='ETH',
        address='<eth_address>',
        amount=100)
except BinanceAPIException as e:
    print(e)
except BinanceWithdrawException as e:
    print(e)
else:
    print("Success")
'''

# fetch list of withdrawals
withdraws = client.get_withdraw_history()
#print(withdraws)
#dec = json.loads(withdraws)
#print(dec)
for key, item in withdraws.items():
    print("%s : %s " % (key, item))
print(" ")

次回の予定

第3回はここまで。次回以降のラインナップは以下を参照ください。
※内容が大幅に変更となる場合もあります。

これまでの勉強会の過去ログはこちら。
第1回 : https://qiita.com/classfox/items/edba3e8971aaa067b88b
第2回 : https://qiita.com/classfox/items/095c4f4b8aa9247a4392
第3回 : https://qiita.com/classfox/items/825116980ac7ca255a13
第4回 : https://qiita.com/classfox/items/9a4b8a513fd5b642534d

SciPy

https://www.scipy.org/
https://qiita.com/search?q=scipy

ファイル・ディレクトリ制御

https://docs.python.jp/3/library/filesys.html
https://qiita.com/zaburo/items/0ba12417dfb39fcb1555
https://qiita.com/supersaiakujin/items/12451cd2b8315fe7d054

関数型プログラミング

https://qiita.com/Tocyuki/items/25092d0d589ab52e83e4
https://docs.python.jp/3/library/functional.html

並列実行

https://docs.python.jp/3/library/concurrency.html
https://qiita.com/yukiB/items/203a6248c2d466b80d38

デバッグ・プロファイラ

https://docs.python.jp/3/library/debug.html
https://docs.python.jp/3/library/pdb.html

メール・JSON・API

https://docs.python.jp/3/library/netdata.html
https://www.craneto.co.jp/archives/1331/

後半(応用編)の予定

  1. おすすめライブラリ( https://qiita.com/haminiku/items/5187713bba6cb30532bf
  2. DBを用いたクエリビルダ
  3. WEBアプリケーション
  4. API実装
  5. csvファイル制御
  6. tensorflow
  7. レコメンドエンジンの実装(スコアリング)
  8. 自然言語処理プログラムの実装(※mecab等も活用?)
  9. 画像処理エンジンの実装(※deep learningを実装?)
  10. 回帰分析などの統計プログラムの実装
  11. その他アルゴリズムの構築、ハッカソン形式

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
7