第一章 时间序列基础
1.1 什么是时间序列
时间序列是按时间顺序排列的数据点序列,通常用于分析随时间变化的数据。
- 时序数据特征:趋势、季节性、周期性、噪声
- 时间戳:DatetimeIndex
- 频率:秒、分、时、日、周、月、年
- 平稳性:统计特性不随时间变化
💡 时间序列分析广泛应用于销售预测、股票分析、天气预报等领域。
1.2 Pandas时间序列处理
import pandas as pd
# 创建时间序列数据
dates = pd.date_range(start='2023-01-01', periods=365, freq='D')
data = {'sales': [100 + i * 0.5 + (i % 7) * 10 for i in range(365)]}
df = pd.DataFrame(data, index=dates)
print(df.head())
print(f"\n数据类型: {type(df.index)}")
print(f"时间范围: {df.index.min()} 到 {df.index.max()}")
第二章 趋势和季节性分析
2.1 移动平均
移动平均用于平滑数据,揭示潜在趋势。
# 计算移动平均
df['MA7'] = df['sales'].rolling(window=7).mean()
df['MA30'] = df['sales'].rolling(window=30).mean()
print("移动平均结果:")
print(df[['sales', 'MA7', 'MA30']].head(10))
2.2 季节性分解
将时间序列分解为趋势、季节性和残差分量。
from statsmodels.tsa.seasonal import seasonal_decompose
# 季节性分解
result = seasonal_decompose(df['sales'], model='additive', period=7)
print("分解结果:")
print("趋势分量:", result.trend.dropna().head())
print("季节分量:", result.seasonal.head())
print("残差:", result.resid.dropna().head())
第三章 ARIMA模型
3.1 ARIMA简介
ARIMA(自回归综合移动平均模型)是常用的时间序列预测方法:
- AR(p):自回归项
- I(d):差分阶数
- MA(q):移动平均项
3.2 ACF和PACF分析
自相关函数(ACF)和偏自相关函数(PACF)用于确定ARIMA参数。
第四章 时间序列预测实战
4.1 完整预测示例
💻 在线代码编辑器
练习题(共5题)
练习 1:创建时间序列
创建一个简单的时间序列数据集。
练习 2:移动平均计算
计算时间序列的移动平均值。
练习 3:时间序列切片
对时间序列进行切片操作。
练习 4:增长率计算
计算时间序列的增长率。
练习 5:时间序列重采样
对时间序列进行重采样操作。
测试题(共 5 题,满分 100 分)
1. 时间序列数据的特点是什么?
2. Pandas中创建时间索引的函数是?
3. 移动平均的主要作用是什么?
4. ARIMA模型中的I代表什么?
5. 重采样操作resample('M')表示什么频率?
作业提交
📝 时间序列分析作业
请完成以下任务:
- 创建一个包含趋势和季节性的时间序列
- 计算移动平均值
- 计算增长率
- 进行重采样分析
💻 作业代码提交