PythonForFinance Chapter5

PythonForFinanceの5章を読んだのでメモ。基本的にはmatplotlibの使い方を紹介している。

まずは基本的なグラフの作成。乱数のCumSumをプロットする。

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

#One dimensional data set
np.random.seed(1000)
y=np.random.standard_normal(20)
plt.plot(y.cumsum())

すると結果はこんな感じ。

これでは何についてのグラフなのかわからないので、軸の名前やタイトルなどをつける。

#customising the style
plt.plot(y.cumsum(), 'r') #can choose the color: b=blue, r=red etc
plt.grid(True) #grid subline is added (dot line)
plt.xlim(-1,20)
plt.ylim(np.min(y.cumsum())-1, np.max(y.cumsum())+1)

#title of graph, axes
plt.xlabel('Index')
plt.ylabel('value')
plt.title('A simple plot')


次はデータセットが2つの場合。

#Generating the data
np.random.seed(2000)
y=np.random.standard_normal((20,2)).cumsum(axis=0)

#two data sets, with different expressions
plt.figure(figsize=(7,4))
plt.plot(y[:,0],lw=1.5,label='1st')
plt.plot(y[:,1],lw=1.5,label='2nd')
plt.plot(y,'ro')
plt.grid(True)
plt.legend(loc=0) #LEGEND=凡例
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value')
plt.title('A Simple Plot')


データが2種類だと同じ軸を使うことが不適切な場合があるが、その解決策として筆者は2つ上げている。

1. 第2軸を使う
2. グラフを分ける

個人的にはグラフを分けるという選択肢はあまり用いない気がするのだが…とりあえず2つ載せておく。

第2軸を使う場合。

fig, ax1=plt.subplots()
plt.plot(y[:,0],'b',lw=1.5,label='1st')
plt.plot(y[:,0],'ro')
plt.grid(True)
plt.legend(loc=6) #loc=XXXは、凡例の位置の調整
plt.axis('tight')
plt.xlabel('index')
plt.ylabel('value 1st')
plt.title('A Simple Plot')
ax2=ax1.twinx() #Use the right axis for second data sets
plt.plot(y[:,1],'g',lw=1.5,label='2nd')
plt.plot(y[:,1],'ro')
plt.legend(loc=0)
plt.ylabel('value 2nd')

右側に軸が現われている。

で、最後に2の分けて表示の場合。

#Two different data, two separate graphs
plt.figure(figsize=(7,5))
plt.subplot(211)
plt.plot(y[:,0],lw=1.5,label='1st')
plt.plot(y[:,0],'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.ylabel('value')
plt.title('A Simple plot')
plt.subplot(212)
plt.plot(y[:,1],'g',lw=1.5,label='2nd') #lw is width of the line
plt.plot(y[:,1],'ro')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.ylabel('value')

こんな感じ。

あと他には散布図とかヒストグラムとかもできますよという話が載っている。