如何使用rolling计算滚动窗口统计量?
进阶统计学
答题要点
import pandas as pd
import numpy as np
# 简单移动平均(SMA)
df['ma7'] = df['price'].rolling(window=7).mean() # 7日移动平均
# 滚动统计
df['std7'] = df['price'].rolling(7).std() # 7日标准差
df['max7'] = df['price'].rolling(7).max() # 7日最大值
df['min7'] = df['price'].rolling(7).min() # 7日最小值
df['sum7'] = df['price'].rolling(7).sum() # 7日总和
# min_periods:最少需要的观测数
df['ma7'] = df['price'].rolling(7, min_periods=1).mean()
# 前6个值也会计算(用1-6个值计算)
# center:居中窗口
df['ma7_center'] = df['price'].rolling(7, center=True).mean()
# 窗口居中在当前值(前3个+当前+后3个)
# 自定义函数
def range_func(x):
return x.max() - x.min()
df['range7'] = df['price'].rolling(7).apply(range_func)
# expanding:累计窗口(从头到当前)
df['cumsum'] = df['sales'].expanding().sum() # 累计和
df['cummean'] = df['price'].expanding().mean() # 累计均值
# ewm:指数加权移动平均
df['ewma'] = df['price'].ewm(span=7).mean() # span=7相当于7日EMA
df['ewma_alpha'] = df['price'].ewm(alpha=0.2).mean() # 直接指定平滑系数
# 时间窗口
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')
df['ma_30d'] = df['price'].rolling('30D').mean() # 30天移动平均(日历天)
# 分组rolling
df['ma7_by_product'] = df.groupby('product')['sales'].rolling(7).mean().reset_index(level=0, drop=True)
# 多列rolling
rolling_stats = df[['price', 'volume']].rolling(7).mean()
# 滚动相关系数
df['corr'] = df['price'].rolling(30).corr(df['volume'])
# 滚动回归
from scipy import stats
def rolling_slope(y):
x = np.arange(len(y))
slope, _, _, _, _ = stats.linregress(x, y)
return slope
df['trend'] = df['price'].rolling(30).apply(rolling_slope, raw=True)
# 布林带(Bollinger Bands)
df['ma20'] = df['close'].rolling(20).mean()
df['std20'] = df['close'].rolling(20).std()
df['upper_band'] = df['ma20'] + 2 * df['std20']
df['lower_band'] = df['ma20'] - 2 * df['std20']
# 去除边界效应
df['ma7'] = df['price'].rolling(7, min_periods=7).mean() # 前6行为NaN
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题