関数の作り方
関数に慣れていこう、ということで
ちょうど、ドローダウンを算出したかったので、各時点でのドローダウンを算出する関数を作っていく
ドローダウンについては、ネットの記事見ると指している内容がそれぞれ微妙に異なったりする、、、
今回は、
ドローダウン=各時点における、最大資産からの下落率
最大ドローダウン=上記のドローダウンが最大となった時の値
として進めまーす
やりたいこと
各時点におけるドローダウンを調べる
使ったデータ
pandas.DataFrame
形式の累積リターンのヒストリカルデータ
Return Date 2009-01-22 0.000000 2009-01-23 0.000000 2009-02-02 0.000000 2009-02-03 0.000000 2009-02-04 0.000000 ... ... 2020-03-03 0.085272 2020-03-04 0.087329 2020-03-05 0.086057 2020-03-06 0.090031 2020-03-09 0.113653
コード
def draw_down(actual_return_df : pd.DataFrame) -> 'list[float]': index_0 = actual_return_df.index[0] drawdown_list = [] for idx, row in actual_return_df.iterrows(): calculation_period_df = actual_return_df[index_0: idx] max_in_period = (1.0 + calculation_period_df.max()) return_in_idx = (1.0 + row.values) drawdown = (max_in_period - return_in_idx) / max_in_period * 100 drawdown_list.append(drawdown) return drawdown_list drawdown_list = draw_down(actual_return_df)
結構すぐできた
追記
pandasとfor文はあまり相性が良くないそうなので、numpy配列でもやってみた
def draw_down(cumulative_sum_return : 'np.array') -> 'list[float]': drawdown_list = [] for cnt in range(len(cumulative_sum_return)): calculation_period_array = cumulative_sum_return[ : cnt + 1] max_in_period = (1.0 + np.max(calculation_period_array)) return_at_cnt = (1.0 + cumulative_sum_return[cnt]) drawdown=(max_in_period - return_at_cnt) / max_in_period * 100 drawdown_list.append(drawdown) return drawdown_list