什么是自回归滑动平均

1. 首先说一下什么是自回归 (AR, Autoregressive Model)
    自回归模型假设当前值  是过去若干时刻值的线性组合。
    其原理模型利用前 p 个时间点的数据预测当前时间点的数据。    

使用了股票价格数据,展示如何拟合AR模型并进行预测,并生成两个以上的数据分析图形。使用一个股票价格的时间序列数据,首先对数据进行预处理,然后拟合一个自回归模型,最后生成几个图形,包括时间序列图、ACF图、PACF图和预测图。使用 yfinance 库来获取股票价格数据。

代码如下: 

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.ar_model import AutoReg
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 下载数据
ticker = 'AAPL'  # 以苹果公司股票为例
start_date = '2020-01-01'
end_date = '2023-01-01'
data = yf.download(ticker, start=start_date, end=end_date)
close_prices = data['Close']

# 绘制时间序列图
plt.figure(figsize=(14, 7))
plt.plot(close_prices, label='Close Price')
plt.title('Apple Stock Close Prices')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()

# ACF和PACF图
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(14, 10))
plot_acf(close_prices, ax=ax1, lags=50)
plot_pacf(close_prices, ax=ax2, lags=50)
plt.show()

# 拟合自回归模型
lags = 30
model = AutoReg(close_prices, lags=lags)
model_fit = model.fit()

# 模型预测
pred_start = len(close_prices)
pred_end = pred_start + 50
predictions = model_fit.predict(start=pred_start, end=pred_end)

# 绘制预测结果
plt.figure(figsize=(14, 7))
plt.plot(close_prices, label='Observed')
plt.plot(predictions, label='Forecast', linestyle='--')
plt.title('Apple Stock Close Price Forecast')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()

2.在说一下什么是移动平均 (MA, Moving Average Model)

   移动平均模型假设当前值  是过去若干时刻误差的线性组合。

   其原理模型利用前 q 个时间点的误差预测当前时间点的数据。

假设我们有一个月度的销售数据,该数据包含一些季节性和随机波动。我们将使用移动平均模型来平滑数据,并比较平滑后的数据与原始数据。此外,我们还将计算并绘制残差。软代码如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 生成模拟的时间序列数据
np.random.seed(42)
n_periods = 120
date_range = pd.date_range(start='2010-01', periods=n_periods, freq='M')
seasonal_pattern = np.sin(2 * np.pi * date_range.month / 12)
random_noise = np.random.normal(scale=0.5, size=n_periods)
sales = 10 + seasonal_pattern + random_noise

# 创建数据框
data = pd.DataFrame({'Date': date_range, 'Sales': sales})
data.set_index('Date', inplace=True)

# 绘制原始数据
plt.figure(figsize=(14, 6))
plt.plot(data.index, data['Sales'], label='Original Sales Data')
plt.title('Monthly Sales Data')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.show()

# 使用移动平均模型进行平滑
window_size = 12
data['Sales_MA'] = data['Sales'].rolling(window=window_size).mean()

# 绘制平滑后的数据
plt.figure(figsize=(14, 6))
plt.plot(data.index, data['Sales'], label='Original Sales Data')
plt.plot(data.index, data['Sales_MA'], label=f'{window_size}-month Moving Average', color='red')
plt.title('Monthly Sales Data with Moving Average')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.show()

# 计算残差
data['Residual'] = data['Sales'] - data['Sales_MA']

# 绘制残差
plt.figure(figsize=(14, 6))
plt.plot(data.index, data['Residual'], label='Residuals', color='green')
plt.title('Residuals from Moving Average Model')
plt.xlabel('Date')
plt.ylabel('Residual')
plt.legend()
plt.show()

# 绘制自相关图和偏自相关图
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
plot_acf(data['Residual'].dropna(), ax=axes[0], lags=40)
plot_pacf(data['Residual'].dropna(), ax=axes[1], lags=40)
axes[0].set_title('ACF of Residuals')
axes[1].set_title('PACF of Residuals')
plt.show()

3.最后说一下:自回归滑动平均 (ARMA, Autoregressive Moving Average Model)

      ARMA模型结合了自回归和移动平均模型。其原理模型利用前 p 个时间点的数据和前 q 个时间点的误差预测当前时间点的数据。

我们使用Python中的 statsmodels 库来进行ARMA建模和分析,并使用 matplotlib 来绘制图形。代码如下:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

# 生成示例时间序列数据
np.random.seed(42)
n = 200
ar_params = np.array([0.75, -0.25])
ma_params = np.array([0.65, 0.35])
ar = np.r_[1, -ar_params]  # add zero-lag and negate
ma = np.r_[1, ma_params]   # add zero-lag
y = np.random.normal(size=n)
x = np.convolve(y, ma)[:n] + np.random.normal(size=n)
time_series = pd.Series(x)

# 绘制原始时间序列数据
plt.figure(figsize=(12, 6))
plt.plot(time_series, label='Original Time Series')
plt.title('Original Time Series')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.show()

# 绘制自相关图 (ACF) 和偏自相关图 (PACF)
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
plot_acf(time_series, ax=axes[0], title='Autocorrelation Function (ACF)')
plot_pacf(time_series, ax=axes[1], title='Partial Autocorrelation Function (PACF)')
plt.show()

# 建立并拟合ARMA模型
model = ARIMA(time_series, order=(2, 0, 2))
arma_result = model.fit()

# 打印模型摘要
print(arma_result.summary())

# 绘制拟合后的时间序列和残差图
plt.figure(figsize=(12, 6))
plt.plot(time_series, label='Original Time Series')
plt.plot(arma_result.fittedvalues, color='red', label='Fitted Values')
plt.title('Original and Fitted Time Series')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.show()

# 绘制残差图
residuals = arma_result.resid
plt.figure(figsize=(12, 6))
plt.plot(residuals, label='Residuals')
plt.title('Residuals of ARMA Model')
plt.xlabel('Time')
plt.ylabel('Residual')
plt.legend()
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值