この記事は matplotlib に基づき、過去 60 日間の上証 300ETF とナスダック ETF の動向を動的に復盤しました。動的復盤の制作を通じて、matplotlib でよく使われる関数をまとめて整理しました。実際、動的復盤は目的ではなく、その業務的意義もあまり大きくありません。これに基づく matplotlib のノート整理がこの記事の最大の目的です。
1. 関連ライブラリのインポート#
# 必要なライブラリをインポート
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
matplotlib のバージョンを確認(筆者が使用しているのは 3.0.2)#
print(mpl.__version__)
2. グローバルパラメータの初期化#
matplotlib は主に plt.rc、plt.rcParams を通じてグローバルパラメータの設定を行います。以下の 2 つの設定方法は等価です。
plt.rc('axes', axisbelow=True)
plt.rcParams['axes.axisbelow'] = True
この他にも、plt.rcParams.update () を使用して実現することもでき、この方法はより便利です。
# グローバルパラメータの設定
#font.sans-serif:中文ラベルを正常に表示するため
#animation.embed_limit:動的図が大きすぎると、デフォルトのバイトを超えやすく、
#設定しないと表示される図が不完全になります。
#保険のために比較的大きな数(例えば 2^64)を設定できます。
params = {'axes.axisbelow': True,
'font.sans-serif': 'SimHei',
'figure.figsize': (16, 8),
'animation.embed_limit':2**64}
plt.rcParams.update(params)
表示スタイルの設定#
plt.style.use('ggplot')
使用中に、パラメータを随時調整して個別にカスタマイズすることもできます。この場合、初期値に戻すだけで済みます。
plt.rcParams.update(mpl.rcParamsDefault)
3. データのインポート —JoinQuant に基づく#
security_list=['510300.XSHG','513100.XSHG']
上証 300ETF#
stock = '510300.XSHG'
ナスダック ETF#
stock2 = '513100.XSHG'
df = history(count=60, unit='1d', field='close', security_list=security_list, df=True, skip_paused=False, fq='pre')
4. 静的価格図#
最初に plt.xxx () で描画コードを実行すると、システムは figure オブジェクトがすでに存在するかどうかを判断します。
存在しない場合、システムは自動的に figure オブジェクトを作成し、その figure の上に自動的に axes 座標系を作成します(注意:デフォルトでは figure オブジェクトと axes 座標系が 1 つ作成されます)。つまり、figure オブジェクトを設定しなければ、1 つの figure オブジェクトには 1 つの axes 座標系しか存在できず、1 つのグラフしか描画できません。Figure、Axes および Axis の関係は図 1 を参照してください。
図 1 Figure、Axes および Axis の関係
plt.plot (x,y,format) の例を挙げると、plt.plot () はデフォルトで折れ線グラフを描画し、パラメータ format は {color}{marker}{linestyle} の 3 つの要素から構成されます(この 3 つの要素は個別に指定することもできます)。例えば、
- ‘go-’:緑色の点と実線
- 'r*--' : 赤い星と破線
- 'bD-.' : 青いダイヤモンドと点線
plt.text と plt.annotate は、テキストや注釈を追加するために使用できます。
plt.plot(df.index,df[stock],'r*--')
Arrow Props と bbox を使用して注釈#
注釈を付ける点の位置を設定#
x_annotate = df[stock].idxmax(axis=1)
y_annotate = max(df[stock])
xy: 注釈を付ける点の位置#
xytext:注釈テキストの位置#
arrowprops: xy→xytext の矢印#
bbox:注釈テキストの表示形状#
plt.annotate(y_annotate,
xy=(x_annotate, y_annotate), xytext=(x_annotate, y_annotate*1.02),
bbox=dict(boxstyle='square', fc='red', linewidth=0.2),
arrowprops=dict(facecolor='red', shrink=0.01, width=0.1),
fontsize=12, color='white', horizontalalignment='center')
テキスト注釈#
テキスト注釈の位置を設定#
x_text = df[stock].idxmin(axis=1)
y_text = min(df[stock])
テキスト注釈#
plt.text (df.index [-1], df [stock][-1],s="上証 300 ETF", color='red', size=12, ha='center', va='top')
図 2 静的価格図
1 つの Figure 上に 1 つの Axes を配置することができ、主に plt.subplot の方法で実現します。より複雑なサブプロットレイアウトを実現するには、plt.subplot2grid や plt.GridSpec 関数を使用できます。ここでは詳細には説明しません。
# 各位置の axes オブジェクトを取得
subplot (x,y,n) は、axes サブプロットの配置を x 行 * y 列とし、n は第 n のサブプロットを示します#
axes1 = plt.subplot(211)
axes1.plot(df.index,df[stock])
axes2 = plt.subplot(212)
axes2.plot(df.index, df[stock2])
5. 動的価格の再現#
(1)静的描画関数の構築#
animate (frame) を構築します。ここで frame は df の変化するインデックスと見なすことができます。異なる frame では df.iloc [,:] をスライスします。
#animate (frame) を構築します。ここで frame は df の変化するインデックスと見なすことができます。
#異なる frame では df.iloc [,:] をスライスします
def animate(frame):
axes1.clear()
axes2.clear()
# 異なる frame では df.iloc [,:] をスライスします
df_temp = df.iloc[0,:]
# 折れ線グラフ
axes1.plot(df_temp.index,df_temp[stock],color='blue')
axes2.plot(df_temp.index,df_temp[stock2],'r*--')
#
axes1.set_xlabel (' 日付 ')
axes1.set_ylabel (' 上証 300 ETF', color='blue')
axes1.tick_params(axis='y', rotation=0, labelcolor='blue' )
axes2.set\_ylabel("ナスダックETF", color='red')
axes2.tick\_params(axis='y', labelcolor='red')
axes2.set\_title("上証300ETF & ナスダックETF 過去3ヶ月のパフォーマンス", fontsize=18)
# テキストラベル
axes1.text(df\_temp.index\[-1\], df\_temp\[stock\]\[-1\],s='上証300 ETF', color='blue', size=7, ha='center', va='top')
axes2.text(df\_temp.index\[-1\], df\_temp\[stock2\]\[-1\],s='ナスダックETF', color='red', size=7, ha='center', va='top')
# Arrow Propsとbboxを使用した注釈
x\_annotate\_min = df\_temp\[stock\].idxmin(axis=1)
y\_annotate\_min = min(df\_temp\[stock\])
# xy:注釈を付ける点の位置
# xytext:注釈の位置
# arrowprops: xy→xytextの矢印
axes1.annotate(y\_annotate\_min,
xy=(x\_annotate\_min, y\_annotate\_min),
xytext=(x\_annotate\_min, y\_annotate\_min\*0.98),
bbox=dict(boxstyle='square', fc='blue', linewidth=0.1),
arrowprops=dict(facecolor='blue', shrink=0.01, width=0.1),
fontsize=12, color='white', horizontalalignment='center')
x\_annotate\_max = df\_temp\[stock\].idxmax(axis=1)
y\_annotate\_max = max(df\_temp\[stock\])
axes1.annotate(y\_annotate\_max,
xy=(x\_annotate\_max, y\_annotate\_max),
xytext=(x\_annotate\_max, y\_annotate\_max\*1.01),
bbox=dict(boxstyle='square', fc='blue', linewidth=0.1),
arrowprops=dict(facecolor='blue', shrink=0.01, width=0.1),
fontsize=12, color='white', horizontalalignment='center')
x\_annotate2\_min = df\_temp\[stock2\].idxmin(axis=1)
y\_annotate2\_min = min(df\_temp\[stock2\])
# xy:注釈を付ける点の位置
# xytext:注釈の位置
# arrowprops: xy→xytextの矢印
axes2.annotate(y\_annotate2\_min,
xy=(x\_annotate2\_min, y\_annotate2\_min),
xytext=(x\_annotate2\_min, y\_annotate2\_min\*0.98),
bbox=dict(boxstyle='square', fc='red', linewidth=0.1),
arrowprops=dict(facecolor='red', shrink=0.01, width=0.1),
fontsize=12, color='white', horizontalalignment='center')
# Arrow Propsとbboxを使用した注釈
x\_annotate2\_max = df\_temp\[stock2\].idxmax(axis=1)
y\_annotate2\_max = max(df\_temp\[stock2\])
# xy:注釈を付ける点の位置
# xytext:注釈の位置
# arrowprops: xy→xytextの矢印
axes2.annotate(y\_annotate2\_max,
xy=(x\_annotate2\_max, y\_annotate2\_max),
xytext=(x\_annotate2\_max, y\_annotate2\_max\*1.01),
bbox=dict(boxstyle='square', fc='red', linewidth=0.1),
arrowprops=dict(facecolor='red', shrink=0.01, width=0.1),
fontsize=12, color='black', horizontalalignment='center')
(2)figure、axes1、axes2 の生成#
静的価格図の生成とは異なり、ここでは figure 関数を明示的に呼び出します。axes.twinx を使用して右側の y 軸を実現できます。
fig, axes1 = plt.subplots(1, 1, dpi=80)
右側の y 軸を生成#
axes2 = axes1.twinx()
(3)FuncAnimation () 関数の呼び出し#
#パラメータ設定
#fig:Figure オブジェクト
#animate:以前に定義した静的描画関数
#frames:アニメーションのフレーム数。このフレーム数で animate の頻度を設定します。
#interval:各フレームの時間間隔
ani = FuncAnimation(fig,
animate,
frames=np.arange(1,df.shape[0],1),
interval=300)
ani.save("movie.mp4")
参考文献と推奨読書:
- 王聖元,《盤一盤 Python 系列特別篇 - Matplotlib Animation》
- MechinelearningPlus,《Matplotlib Tutorial – A Complete Guide to Python Plot w/ Examples》
- MechinelearningPlus,《Top 50 matplotlib Visualizations – The Master Plots》