时间序列分析资源专题¶
Time Series Analysis Resources
📚 核心理论¶
经典教材¶
| 书名 | 作者 | 难度 | 特点 |
|---|---|---|---|
| 《时间序列分析》 | Hamilton | ⭐⭐⭐⭐⭐ | 经典权威,理论深入 |
| 《Time Series Analysis and Its Applications》 | Shumway & Stoffer | ⭐⭐⭐⭐ | R 语言实现,应用导向 |
| 《Forecasting: Principles and Practice》 | Hyndman & Athanasopoulos | ⭐⭐⭐ | 免费在线书,实用性强 |
| 《Introductory Time Series with R》 | Cowpertwait & Metcalfe | ⭐⭐ | 入门友好 |
在线阅读: - 《Forecasting: Principles and Practice》: 链接 - 《Time Series Analysis and Its Applications》: 链接
🎓 在线课程¶
系统性课程¶
| 课程名称 | 平台 | 讲师 | 链接 |
|---|---|---|---|
| Practical Time Series Forecasting | Coursera | Indian School of Business | 链接 |
| Time Series Analysis | Coursera | University of Colorado | 链接 |
| 时间序列分析 | 学堂在线 | 清华大学 | 链接 |
🛠️ 工具库¶
Python 库¶
传统统计方法¶
| 库名 | 用途 | 文档链接 |
|---|---|---|
| Statsmodels | ARIMA, SARIMA, VAR 等 | 链接 |
| Prophet | Facebook 时间序列预测 | 链接 |
| pmdarima | 自动 ARIMA 参数选择 | 链接 |
深度学习方法¶
| 库名 | 用途 | 文档链接 |
|---|---|---|
| Darts | 统一的时间序列预测库 | 链接 |
| GluonTS | AWS 概率时间序列库 | 链接 |
| Keras-Timeseries | Keras 时间序列 | 链接 |
| PyTorch Forecasting | PyTorch 预测库 | 链接 |
R 包¶
| 包名 | 用途 | CRAN 链接 |
|---|---|---|
| forecast | 预测模型 | 链接 |
| tsibble | 时间序列数据框 | 链接 |
| fable | 预测建模框架 | 链接 |
📊 实战案例¶
销售预测¶
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from prophet import Prophet
import matplotlib.pyplot as plt
# 加载销售数据
df = pd.read_csv('sales_data.csv', parse_dates=['date'])
df.set_index('date', inplace=True)
# 方法 1: ARIMA 模型
model_arima = ARIMA(df['sales'], order=(1,1,1))
results_arima = model_arima.fit()
forecast_arima = results_arima.forecast(steps=30)
# 方法 2: Prophet 模型
df_prophet = df.reset_index().rename(columns={'date': 'ds', 'sales': 'y'})
model_prophet = Prophet()
model_prophet.fit(df_prophet)
future = model_prophet.make_future_dataframe(periods=30)
forecast_prophet = model_prophet.predict(future)
# 可视化对比
plt.figure(figsize=(14, 6))
plt.plot(df.index, df['sales'], label='历史数据')
plt.plot(forecast_arima.index, forecast_arima, label='ARIMA 预测', alpha=0.7)
plt.plot(forecast_prophet['ds'], forecast_prophet['yhat'], label='Prophet 预测', alpha=0.7)
plt.legend()
plt.title('销售预测对比')
plt.show()
股票价格预测¶
import yfinance as yf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
# 下载股票数据
data = yf.download('AAPL', start='2020-01-01')
prices = data['Close'].values.reshape(-1, 1)
# 数据预处理
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
prices_scaled = scaler.fit_transform(prices)
# 创建 LSTM 输入序列
def create_sequences(data, seq_length):
sequences = []
labels = []
for i in range(len(data) - seq_length):
sequences.append(data[i:i+seq_length])
labels.append(data[i+seq_length])
return np.array(sequences), np.array(labels)
seq_length = 60
X, y = create_sequences(prices_scaled, seq_length)
# 构建 LSTM 模型
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(seq_length, 1)),
LSTM(50),
Dense(1)
])
model.compile(optimizer='adam', loss='mse')
model.fit(X, y, epochs=20, batch_size=32)
# 预测
last_sequence = prices_scaled[-seq_length:]
prediction = model.predict(last_sequence.reshape(1, seq_length, 1))
predicted_price = scaler.inverse_transform(prediction)
print(f"预测明日股价:${predicted_price[0][0]:.2f}")
📖 方法论¶
ARIMA 建模流程¶
graph LR
A[数据可视化] --> B[平稳性检验]
B --> C[差分处理]
C --> D[识别 p,q 参数]
D --> E[模型拟合]
E --> F[残差诊断]
F --> G[模型优化]
G --> H[预测]
模型选择指南¶
| 数据特征 | 推荐模型 | 理由 |
|---|---|---|
| 趋势 + 季节 | SARIMA, Prophet | 可处理季节性 |
| 非线性关系 | LSTM, GRU | 神经网络拟合能力强 |
| 多变量预测 | VAR, Prophet | 支持协变量 |
| 长序列依赖 | Transformer, LSTM | 捕捉长期依赖 |
| 概率预测 | DeepAR, Prophet | 提供置信区间 |
🔍 常见问题¶
Q1: 如何判断时间序列是否平稳?¶
A: 使用 ADF 检验(Augmented Dickey-Fuller Test)
from statsmodels.tsa.stattools import adfuller
result = adfuller(series)
print(f'ADF Statistic: {result[0]:.4f}')
print(f'p-value: {result[1]:.4f}')
if result[1] <= 0.05:
print("序列平稳")
else:
print("序列不平稳,需要差分")
Q2: 如何选择 ARIMA 参数?¶
A: 使用 ACF 和 PACF 图
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
plot_acf(series, ax=ax1, lags=40)
plot_pacf(series, ax=ax2, lags=40)
plt.show()
# 或使用自动选择
from pmdarima import auto_arima
model = auto_arima(series, seasonal=True,
start_p=0, max_p=5,
start_q=0, max_q=5,
trace=True)
print(model.order)
Q3: LSTM 适合什么样的时间序列?¶
A: LSTM 适合以下场景: - 长期依赖关系 - 非线性模式 - 大量历史数据 - 多变量输入
不适合: - 数据量小(<1000 个观测) - 强季节性(用 SARIMA 更好) - 需要可解释性
📈 评估指标¶
from sklearn.metrics import mean_absolute_error, mean_squared_error
import numpy as np
def evaluate_forecast(actual, predicted):
"""评估预测效果"""
mae = mean_absolute_error(actual, predicted)
rmse = np.sqrt(mean_squared_error(actual, predicted))
mape = np.mean(np.abs((actual - predicted) / actual)) * 100
print(f"MAE: {mae:.2f}")
print(f"RMSE: {rmse:.2f}")
print(f"MAPE: {mape:.2f}%")
return {'MAE': mae, 'RMSE': rmse, 'MAPE': mape}
指标说明¶
| 指标 | 公式 | 特点 |
|---|---|---|
| MAE | 平均绝对误差 | 鲁棒性好 |
| RMSE | 均方根误差 | 惩罚大误差 |
| MAPE | 平均绝对百分比误差 | 相对误差,易解读 |
| ACF | 自相关函数 | 残差诊断 |
🔗 更多资源¶
数据集¶
博客与教程¶
最后更新: 2026-06-01