pandas のローリングウィンドウ関数

Pythonでの時系列データ操作

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

pandas のウィンドウ関数

  • ウィンドウは時系列内のサブ期間を特定する
  • ウィンドウ内のサブ期間で指標を計算する
  • 指標の新しい時系列を作成する
  • ウィンドウの種類は2つ:
    • ローリング: 一定サイズでスライド(本動画)
    • エクスパンディング: それ以前の全値を含む(次の動画)
Pythonでの時系列データ操作

移動平均の計算

data = pd.read_csv('google.csv', parse_dates=['date'], index_col='date')
DatetimeIndex: 1761 entries, 2010-01-04 to 2016-12-30
Data columns (total 1 columns):
price     1761 non-null float64
dtypes: float64(1)

ch3_1_v2 - Rolling Window Functions with Pandas.010.png

Pythonでの時系列データ操作

移動平均の計算

# 整数ベースのウィンドウサイズ
data.rolling(window=30).mean() # 観測数で固定
DatetimeIndex: 1761 entries, 2010-01-04 to 2017-05-24
Data columns (total 1 columns):
price    1732 non-null float64
dtypes: float64(1)
  • window=30: 営業日数
  • min_periods: 30未満を指定すると初期日でも結果取得
Pythonでの時系列データ操作

移動平均の計算

# オフセットベースのウィンドウサイズ
data.rolling(window='30D').mean() # 期間長で固定
DatetimeIndex: 1761 entries, 2010-01-04 to 2017-05-24
Data columns (total 1 columns):
price    1761 non-null float64
dtypes: float64(1)
  • 30D: カレンダー日数
Pythonでの時系列データ操作

90日の移動平均

r90 = data.rolling(window='90D').mean()

google.join(r90.add_suffix('_mean_90')).plot()

ch3_1_v2 - Rolling Window Functions with Pandas.017.png

Pythonでの時系列データ操作

90日・360日の移動平均

data['mean90'] = r90

r360 = data['price'].rolling(window='360D'.mean()
data['mean360'] = r360; data.plot()

ch3_1_v2 - Rolling Window Functions with Pandas.020.png

Pythonでの時系列データ操作

複数のローリング指標 (1)

r = data.price.rolling('90D').agg(['mean', 'std'])

r.plot(subplots = True)

ch3_1_v2 - Rolling Window Functions with Pandas.022.png

Pythonでの時系列データ操作

複数のローリング指標 (2)

rolling = data.google.rolling('360D')

q10 = rolling.quantile(0.1).to_frame('q10')
median = rolling.median().to_frame('median')
q90 = rolling.quantile(0.9).to_frame('q90')
pd.concat([q10, median, q90], axis=1).plot()

ch3_1_v2 - Rolling Window Functions with Pandas.024.png

Pythonでの時系列データ操作

Passons à la pratique !

Pythonでの時系列データ操作

Preparing Video For Download...