Python数据分析-时间序列预测法

本文介绍了三种基本的时间序列预测方法:朴素法(预测下一天价格等于前一天),简单平均法(预测值等于历史平均值),以及移动平均法(使用滑动窗口计算平均值)。通过实例展示了如何在Python中实现这些预测,并展示了预测结果图表。
摘要由CSDN通过智能技术生成

        print('a.朴素法')
        #如果数据集在一段时间内都很稳定,我们想预测第二天的价格,可以取前面一天的价格,预测第二天的值。
        # 这种假设第一个预测点和上一个观察点相等的预测方法就叫朴素法。即 ^yt+1=yt
        dd = np.asarray(train['value'])
        y_hat = test.copy()
        y_hat['naive'] = dd[len(dd) - 1]
        plt.figure(figsize=(12, 8))
        plt.plot(train.index, train['value'], label='Train')
        plt.plot(test.index, test['value'], label='Test')
        plt.plot(y_hat.index, y_hat['naive'], label='Naive Forecast')
        plt.legend(loc='best')
        plt.title("Naive Forecast")
        plt.show()

        print('b.简单平均法')
        #我们经常会遇到一些数据集,虽然在一定时期内出现小幅变动,但每个时间段的平均值确实保持不变。
        # 这种情况下,我们可以预测出第二天的价格大致和过去天数的价格平均值一致。
        # 这种将预期值等同于之前所有观测点的平均值的预测方法就叫简单平均法。
        y_hat_avg = test.copy()
        y_hat_avg['avg_forecast'] = train['value'].mean()
        plt.figure(figsize=(12, 8))
        plt.plot(train['value'], label='Train')
        plt.plot(test['value'], label='Test')
        plt.plot(y_hat_avg['avg_forecast'], label='Average Forecast')
        plt.legend(loc='best')
        plt.title("Avg Forecast")
        plt.show()
        

        print('c.移动平均')
        # rol_mean = df.rolling(3).mean()
        # df.plot(color='blue', label='Original')
        # rol_mean.plot(color='red', label='Rolling Mean')
        # plt.show()

        y_hat_avg = test.copy()
        y_hat_avg['moving_avg_forecast'] = train['value'].rolling(6).mean().iloc[-1]
        plt.figure(figsize=(16, 8))
        plt.plot(train['value'], label='Train')
        plt.plot(test['value'], label='Test')
        plt.plot(y_hat_avg['moving_avg_forecast'], label='Moving Average Forecast')
        plt.legend(loc='best')
        plt.show()
 

        print('d.指数平滑法')
        from statsmodels.tsa.api import SimpleExpSmoothing

        y_hat_avg = test.copy()
        fit = SimpleExpSmoothing(np.asarray(train['value'])).fit(smoothing_level=0.6, optimized=False)
        y_hat_avg['SES'] = fit.forecast(len(test))
        plt.figure(figsize=(16, 8))
        plt.plot(train['value'], label='Train')
        plt.plot(test['value'], label='Test')
        plt.plot(y_hat_avg['SES'], label='SES')
        plt.legend(loc='best')
        plt.show()
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值