时间序列分析的python代码
由于时间序列分析的方法和应用场景非常广泛,因此涉及的Python代码也非常多,下面是一个简单的时间序列分析的Python代码示例:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_csv('data.csv', index_col='date', parse_dates=True)
# 查看数据
print(data.head())
# 数据预处理
data = data.fillna(method='ffill') # 用前一天的数据填充缺失值
# 绘制时间序列图
plt.plot(data)
plt.title('Time Series')
plt.xlabel('Year')
plt.ylabel('Value')
plt.show()
# 计算移动平均值
rolling_mean = data.rolling(window=12).mean()
# 绘制移动平均值图
plt.plot(data)
plt.plot(rolling_mean, color='red')
plt.title('Moving Average')
plt.xlabel('Year')
plt.ylabel('Value')
plt.show()
# 计算差分序列
diff = data.diff(periods=1)
# 绘制差分序列图
plt.plot(diff)
plt.title('Difference Series')
plt.xlabel('Year')
plt.ylabel('Value')
plt.show()
# 计算自相关系数和偏自相关系数
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
plot_acf(data)
plt.title('Autocorrelation')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.show()
plot_pacf(data)
plt.title('Partial Autocorrelation')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.show()
# 拟合ARIMA模型
from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(data, order=(1, 1, 1))
result = model.fit(disp=-1)
# 绘制拟合值和原始值对比图
plt.plot(data)
plt.plot(result.fittedvalues, color='red')
plt.title('ARIMA Model')
plt.xlabel('Year')
plt.ylabel('Value')
plt.show()
# 预测未来值
forecast = result.forecast(steps=12)
# 绘制未来值预测图
plt.plot(data)
plt.plot(forecast[0], color='red')
plt.title('Future Values')
plt.xlabel('Year')
plt.ylabel('Value')
plt.show()
以上代码中,我们首先读取了一个时间序列数据,然后对数据进行了简单的处理和可视化。接着,我们计算了移动平均值和差分序列,并绘制了相应的图表。接下来,我们使用自相关系数和偏自相关系数分析了时间序列的相关性,并拟合了ARIMA模型。最后,我们使用拟合好的ARIMA模型预测了未来值,并绘制了相应的图表。
原文地址: https://www.cveoy.top/t/topic/g3r 著作权归作者所有。请勿转载和采集!