生データの変換
前の章では、移動平均を計算しました。この演習では、直近のデータポイントが、直前のデータポイント群の平均に対してどれだけ変化したか(パーセント変化)を計算する関数を定義します。この関数を使うと、移動ウィンドウに対するパーセント変化を計算できます。
これは、Machine Learning で役立つことが多い、より安定した種類の時系列表現です。
この演習はコースの一部です
Pythonで学ぶMachine Learningによる時系列データ解析
演習の手順
- 入力の時系列を受け取り、次を行う
percent_change関数を定義してください。- 入力系列の最後の値以外すべて(
previous_valuesに代入)と、時系列の最後の値のみ(last_valueに代入)を取り出します。 - 最後の値とそれ以前の値の平均とのパーセント差を計算します。
- 入力系列の最後の値以外すべて(
- ウィンドウ幅20のローリングでこの関数を
pricesに適用し、与えられたコードで可視化してください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Your custom function
def percent_change(series):
# Collect all *but* the last value of this window, then the final value
previous_values = series[:____]
last_value = series[-1]
# Calculate the % difference between the last value and the mean of earlier values
percent_change = (____ - np.mean(previous_values)) / np.mean(previous_values)
return percent_change
# Apply your custom function and plot
prices_perc = prices.rolling(20).____
prices_perc.loc["2014":"2015"].plot()
plt.show()