如何用Pandas计算最近5期的滚动Slope与滚动R-squared值?
Pandas实现滚动5期Slope与R-squared值(匹配Excel SLOPE/RSQ函数)
问题背景
需要在Pandas中实现与Excel SLOPE、RSQ函数一致的滚动5期计算,用户提供的数据集如下,原有代码结果与Excel不符,需修正:
import pandas as pd import numpy as np from scipy.stats import linregress data = { "SL no": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "Close": [46.20, 49.90, 51.85, 54.00, 57.70, 56.60, 52.95, 55.35, 57.20, 58.05, 56.65], "Ln": [3.83, 3.91, 3.95, 3.99, 4.06, 4.04, 3.97, 4.01, 4.05, 4.06, 4.04] } df = pd.DataFrame(data)
原有代码错误点
- 列名大小写不匹配:数据列名为
Close、SL no,但代码中误用close、sno,导致取数错误。 - 索引取值逻辑错误:在
lambda中使用df['sno'].iloc[x.index],x.index是原DataFrame的索引标签,iloc是按位置取值,应改用loc按索引标签匹配窗口内的SL no值。
正确实现代码
1. 滚动Slope计算(匹配Excel SLOPE函数)
def rolling_slope(y_series): # 获取当前窗口对应的SL no值 x_vals = df.loc[y_series.index, "SL no"].values # 用scipy的linregress计算斜率,与Excel SLOPE逻辑一致 slope, _, _, _, _ = linregress(x_vals, y_series.values) return slope # 滚动窗口设为5,min_periods=5确保不足5期时返回NaN df['rolling_slope'] = df['Close'].rolling(window=5, min_periods=5).apply(rolling_slope, raw=False)
2. 滚动R-squared计算(匹配Excel RSQ函数)
def rolling_rsq(y_series): x_vals = df.loc[y_series.index, "SL no"].values _, _, r_value, _, _ = linregress(x_vals, y_series.values) # R平方为相关系数的平方 return r_value ** 2 df['rolling_rsq'] = df['Close'].rolling(window=5, min_periods=5).apply(rolling_rsq, raw=False)
3. 针对Ln列的计算
若需对Ln列计算滚动值,只需将上述代码中的df['Close']替换为df['Ln']即可。
结果验证
以第5行(SL no=5)为例,窗口包含SL no 1-5的Close值,计算得到的slope为2.71,与Excel中=SLOPE(B2:B6,A2:A6)的结果完全一致;R-squared值为0.992,匹配Excel=RSQ(B2:B6,A2:A6)的计算结果。
内容的提问来源于stack exchange,提问作者aditya
相关产品推荐
相关产品推荐

