You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于滑动窗口与多项式回归的股票收盘价预测实现求助

滑动窗口结合多项式回归预测股票收盘价实现方案

核心思路修正

你的方向是对的,但rolling().apply()的用法需要调整——rolling传入的是窗口内的整行数据,不能直接拆分X和y,得在自定义函数里处理窗口内的特征和标签。另外要明确:窗口大小W对应的是用前W周的数据,预测第W+1周的收盘价,预测时需用第W+1周的Open作为输入特征。

完整实现代码

1. 数据准备

import pandas as pd
import numpy as np

# 构造样本数据
data = {
    'Week_Number': [0,1,2,3,4],
    'Year': [2020]*5,
    'Open': [46.270000, 46.748001, 50.888000, 52.724999, 49.892001],
    'Close': [46.045000, 47.506000, 51.382000, 52.530000, 49.424001]
}
df_20 = pd.DataFrame(data)

2. 自定义回归预测函数

该函数接收窗口内的切片数据,完成模型拟合与预测:

def window_regression(window_data, degree=1):
    # 将窗口数据转为DataFrame方便处理
    window_df = pd.DataFrame(window_data, columns=['Week_Number', 'Year', 'Open', 'Close'])
    X = window_df['Open'].values
    y = window_df['Close'].values
    
    # 拟合多项式回归模型,捕获拟合失败的异常
    try:
        model_coeffs = np.polyfit(X, y, degree)
        model = np.poly1d(model_coeffs)
    except np.linalg.LinAlgError:
        return np.nan
    
    # 获取下一周的Open值作为预测输入
    next_week_idx = window_df.index[-1] + 1
    if next_week_idx >= len(df_20):
        return np.nan
    next_week_open = df_20.loc[next_week_idx, 'Open']
    
    # 返回预测的收盘价
    return model(next_week_open)

3. 滑动窗口应用

设置raw=False确保传入函数的是窗口内的DataFrame对象:

# 测试窗口大小W=3,线性回归(阶数1)
df_20['Predicted_Close'] = df_20.rolling(window=3, raw=False).apply(window_regression, args=(1,))

4. 最优参数搜索

通过**均方误差(MSE)**评估不同参数组合的效果,筛选最优方案:

def evaluate_params(window_size, degree):
    # 生成预测值
    pred = df_20.rolling(window=window_size, raw=False).apply(window_regression, args=(degree,))
    # 筛选有真实值的有效预测结果
    valid_mask = ~pred.isna() & ~df_20['Close'].isna()
    mse = np.mean((df_20.loc[valid_mask, 'Close'] - pred[valid_mask])**2)
    return mse

# 遍历参数组合(示例:窗口2-3,阶数1-2)
param_grid = [(w, d) for w in range(2,4) for d in range(1,3)]
results = []
for w, d in param_grid:
    mse = evaluate_params(w, d)
    results.append({'window_size':w, 'degree':d, 'mse':mse})

# 按MSE排序,最小的即为最优参数
results_df = pd.DataFrame(results).sort_values('mse')
print(results_df)

关键注意事项

  • 数据对齐:预测值对应下一周的收盘价,需确保索引计算正确,避免越界。
  • 异常处理:窗口内数据线性相关时np.polyfit会报错,需捕获异常返回NaN。
  • 参数范围:窗口大小建议不超过数据量的1/3,多项式阶数过高易过拟合,优先尝试1-3阶。

内容的提问来源于stack exchange,提问作者Jean-Paul Azzopardi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:56:04