Pandas ウィンドウ関数(rolling / expanding / ewm)
ウィンドウ関数は時系列データや順序付けられたデータに対してスライディングウィンドウ計算を行うために使用され、金融分析、信号処理などの分野における重要なツールです。
rolling ローリングウィンドウ
基本的な使い方
例
import pandas as pd
import numpy as np
# 時系列データを作成
np.random.seed(42)
dates = pd.date_range("2024-01-01", periods=20, freq="D")
ts = pd.Series(np.random.randint(100, 200, 20), index=dates)
print("元データ(最初の10件):")
print(ts.head(10))
print()
# 7日間のローリング平均
ma7 = ts.rolling(window=7).mean()
print("7日間のローリング平均(最初の10件):")
print(ma7.head(10))
print()
# ローリング合計
rolling_sum = ts.rolling(window=5).sum()
print("5日間のローリング合計:")
print(rolling_sum.head(10))
import numpy as np
# 時系列データを作成
np.random.seed(42)
dates = pd.date_range("2024-01-01", periods=20, freq="D")
ts = pd.Series(np.random.randint(100, 200, 20), index=dates)
print("元データ(最初の10件):")
print(ts.head(10))
print()
# 7日間のローリング平均
ma7 = ts.rolling(window=7).mean()
print("7日間のローリング平均(最初の10件):")
print(ma7.head(10))
print()
# ローリング合計
rolling_sum = ts.rolling(window=5).sum()
print("5日間のローリング合計:")
print(rolling_sum.head(10))
ローリングウィンドウの種類
例
import pandas as pd
import numpy as np
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# 固定ウィンドウサイズ
print("固定ウィンドウ (3):")
print(s.rolling(3).mean())
print()
# 移動ウィンドウ(時間ウィンドウ)
# 1分後のウィンドウ
s2 = pd.Series([1, 2, 3, 4, 5], index=pd.date_range("2024-01-01", periods=5, freq="T"))
print("時間ウィンドウ(1分):")
print(s2.rolling("1min").sum())
import numpy as np
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# 固定ウィンドウサイズ
print("固定ウィンドウ (3):")
print(s.rolling(3).mean())
print()
# 移動ウィンドウ(時間ウィンドウ)
# 1分後のウィンドウ
s2 = pd.Series([1, 2, 3, 4, 5], index=pd.date_range("2024-01-01", periods=5, freq="T"))
print("時間ウィンドウ(1分):")
print(s2.rolling("1min").sum())
expanding 拡張ウィンドウ
拡張ウィンドウは開始位置から現在位置まで累積し、ウィンドウサイズが徐々に大きくなります。
例
import pandas as pd
import numpy as np
s = pd.Series([1, 2, 3, 4, 5])
# 拡張ウィンドウで累積平均を計算
exp_mean = s.expanding().mean()
print("累積平均:")
print(exp_mean)
print()
# 拡張ウィンドウで累積最大値を計算
exp_max = s.expanding().max()
print("累積最大値:")
print(exp_max)
print()
# 拡張ウィンドウで標準偏差を計算
exp_std = s.expanding().std()
print("累積標準偏差:")
print(exp_std)
import numpy as np
s = pd.Series([1, 2, 3, 4, 5])
# 拡張ウィンドウで累積平均を計算
exp_mean = s.expanding().mean()
print("累積平均:")
print(exp_mean)
print()
# 拡張ウィンドウで累積最大値を計算
exp_max = s.expanding().max()
print("累積最大値:")
print(exp_max)
print()
# 拡張ウィンドウで標準偏差を計算
exp_std = s.expanding().std()
print("累積標準偏差:")
print(exp_std)
ewm 指数加重移動
指数加重移動平均(EWMA)は、最近のデータにより大きな重みを与えます。
例
import pandas as pd
import numpy as np
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# alpha が小さいほど、最近のデータの重みが大きくなる
ewm_05 = s.ewm(alpha=0.5).mean()
ewm_2 = s.ewm(alpha=0.2).mean()
print("元データ:")
print(s.values)
print("\nalpha=0.5:")
print(ewm_05.values)
print("\nalpha=0.2:")
print(ewm_2.values)
print()
# span を使用(alpha との関係:alpha = 2/(span+1))
ewm_span = s.ewm(span=5).mean()
print("span=5:")
print(ewm_span.values)
import numpy as np
s = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# alpha が小さいほど、最近のデータの重みが大きくなる
ewm_05 = s.ewm(alpha=0.5).mean()
ewm_2 = s.ewm(alpha=0.2).mean()
print("元データ:")
print(s.values)
print("\nalpha=0.5:")
print(ewm_05.values)
print("\nalpha=0.2:")
print(ewm_2.values)
print()
# span を使用(alpha との関係:alpha = 2/(span+1))
ewm_span = s.ewm(span=5).mean()
print("span=5:")
print(ewm_span.values)
EWM はトレンドの変化に対してより敏感で、迅速な対応が必要なシーンに適しています。
実践:株式テクニカル指標
例
import pandas as pd
import numpy as np
# 株価データをシミュレーション
np.random.seed(42)
dates = pd.date_range("2024-01-01", periods=30, freq="D")
df = pd.DataFrame({
"日付": dates,
"終値": 100 + np.random.randn(30).cumsum()
})
# テクニカル指標を計算
# 5日移動平均線
df["MA5"] = df["終値"].rolling(5).mean()
# 10日移動平均線
df["MA10"] = df["終値"].rolling(10).mean()
# 5日指数加重移動平均線
df["EMA5"] = df["終値"].ewm(span=5).mean()
# ボラティリティ(5日間のローリング標準偏差)
df["Volatility"] = df["終値"].rolling(5).std()
# 累積最高価格
df["Highest"] = df["終値"].expanding().max()
print("株式テクニカル指標:")
print(df.round(2))
import numpy as np
# 株価データをシミュレーション
np.random.seed(42)
dates = pd.date_range("2024-01-01", periods=30, freq="D")
df = pd.DataFrame({
"日付": dates,
"終値": 100 + np.random.randn(30).cumsum()
})
# テクニカル指標を計算
# 5日移動平均線
df["MA5"] = df["終値"].rolling(5).mean()
# 10日移動平均線
df["MA10"] = df["終値"].rolling(10).mean()
# 5日指数加重移動平均線
df["EMA5"] = df["終値"].ewm(span=5).mean()
# ボラティリティ(5日間のローリング標準偏差)
df["Volatility"] = df["終値"].rolling(5).std()
# 累積最高価格
df["Highest"] = df["終値"].expanding().max()
print("株式テクニカル指標:")
print(df.round(2))
ウィンドウ関数の比較
| 種類 | 説明 | 適用シーン |
|---|---|---|
rolling |
固定サイズウィンドウ | 移動平均、ボラティリティ |
expanding |
累積ウィンドウ | 累積統計、損切り/利確 |
ewm |
指数加重 | トレンド追跡、迅速な対応 |