【Pythonメモ】片対数グラフ
やりたいこと
片対数グラフを作りたい
参考サイト
[Pythonによる科学・技術計算] 対数グラフ,可視化,matplotlib - Qiita
コード
import numpy as np import matplotlib.pyplot as plt import pandas as pd from dateutil.relativedelta import relativedelta def get_asset_return(file_path : 'str') -> pd.DataFrame: df_price = pd.read_csv(file_path, header=0) df_price['date'] = pd.to_datetime(df_price['date'], format='%Y-%m-%d') df_price['date'] = df_price['date'].dt.date df_price = df_price.set_index('date') eight_asset = ['TP1', 'ES1', 'CF1', 'JB1', 'TY1', 'RX1', 'GC1', 'CL1'] df_price = df_price[eight_asset] df_return = df_price.pct_change().dropna() return df_return def getSFE(tested_cov : np.array, actual_cov : np.array) -> 'scalar': tested_cov_tril = np.tril(tested_cov) actual_cov_tril = np.tril(actual_cov) diff = actual_cov_tril - tested_cov_tril SFE = np.sum(np.square(diff)) return SFE # メイン処理 if __name__ == '__main__': # パラメータ等設定 file_path = 'input/mktdata.csv' renew_freq = 1 # 最適比率更新頻度 calc_period = 36 # bootstrap抽出元データ期間 # 収益率データ作成 df_return = get_asset_return(file_path) first_index = df_return.index[0] last_index = df_return.index[-1] target_index = first_index + relativedelta(months=60) # 適宜修正 SFE_Series = pd.Series() while target_index <= last_index: # データフレーム作成 pre_data_frame = df_return[target_index - relativedelta(months=calc_period): target_index] data_frame = df_return[target_index: target_index + relativedelta(months=renew_freq) - relativedelta(days=1)] # 分散共分散行列作成 tested_cov = pre_data_frame.cov().values actual_cov = data_frame.cov().values # SFE取得 SFE = getSFE(tested_cov, actual_cov) SFE_Series[target_index] = SFE # target_index更新 target_index += relativedelta(months=renew_freq) # グラフ作成 fig = plt.figure(figsize = (12, 8)) ax = fig.add_subplot(1, 1, 1) ax.plot(SFE_Series) ax.set_yscale('log') ax.grid(which = 'both', color = 'black', lw = 0.2) fig.savefig('output/SFE' + str(calc_period) + '.png')
ちなみに
最初は片対数にするつもりなんてなかったけど、せずにつくったらしたみたいなわけわからんグラフになっちゃったのがはじまり