1
---
2
name: Time Series Analysis
3
description: Analyze temporal data patterns including trends, seasonality, autocorrelation, and forecasting for time series decomposition, trend analysis, and forecasting models
4
---
5
6
# Time Series Analysis
7
8
## Overview
9
10
Time series analysis examines data points collected over time to identify patterns, trends, and seasonality for forecasting and understanding temporal dynamics.
11
12
## When to Use
13
14
- Forecasting future values based on historical trends
15
- Detecting seasonality and cyclical patterns in data
16
- Analyzing trends over time in sales, stock prices, or website traffic
17
- Understanding autocorrelation and temporal dependencies
18
- Making time-based predictions with confidence intervals
19
- Decomposing data into trend, seasonal, and residual components
20
21
## Core Components
22
23
- **Trend**: Long-term directional movement
24
- **Seasonality**: Repeating patterns at fixed intervals
25
- **Cyclicity**: Long-term oscillations (non-fixed periods)
26
- **Stationarity**: Constant mean, variance over time
27
- **Autocorrelation**: Correlation with past values
28
29
## Key Techniques
30
31
- **Decomposition**: Separating trend, seasonal, residual components
32
- **Differencing**: Making data stationary
33
- **ARIMA**: AutoRegressive Integrated Moving Average models
34
- **Exponential Smoothing**: Weighted average of past values
35
- **SARIMA**: Seasonal ARIMA models
36
37
## Implementation with Python
38
39
```python
40
import pandas as pd
41
import numpy as np
42
import matplotlib.pyplot as plt
43
from statsmodels.tsa.seasonal import seasonal_decompose
44
from statsmodels.tsa.stattools import adfuller, acf, pacf
45
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
46
from statsmodels.tsa.arima.model import ARIMA
47
from statsmodels.tsa.holtwinters import ExponentialSmoothing
48
49
# Create sample time series data
50
dates = pd.date_range('2020-01-01', periods=365, freq='D')
51
values = 100 + np.sin(np.arange(365) * 2*np.pi / 365) * 20 + np.random.normal(0, 5, 365)
52
ts = pd.Series(values, index=dates)
53
54
# Visualize time series
55
fig, axes = plt.subplots(2, 2, figsize=(14, 8))
56
57
axes[0, 0].plot(ts)
58
axes[0, 0].set_title('Original Time Series')
59
axes[0, 0].set_ylabel('Value')
60
61
# Decomposition
62
decomposition = seasonal_decompose(ts, model='additive', period=30)
63
axes[0, 1].plot(decomposition.trend)
64
axes[0, 1].set_title('Trend Component')
65
66
axes[1, 0].plot(decomposition.seasonal)
67
axes[1, 0].set_title('Seasonal Component')
68
69
axes[1, 1].plot(decomposition.resid)
70
axes[1, 1].set_title('Residual Component')
71
72
plt.tight_layout()
73
plt.show()
74
75
# Test for stationarity (Augmented Dickey-Fuller)
76
result = adfuller(ts)
77
print(f"ADF Test Statistic: {result[0]:.6f}")
78
print(f"P-value: {result[1]:.6f}")
79
print(f"Critical Values: {result[4]}")
80
81
if result[1] <= 0.05:
82
print("Time series is stationary")
83
else:
84
print("Time series is non-stationary - differencing needed")
85
86
# First differencing for stationarity
87
ts_diff = ts.diff().dropna()
88
result_diff = adfuller(ts_diff)
89
print(f"\nAfter differencing - ADF p-value: {result_diff[1]:.6f}")
90
91
# Autocorrelation and Partial Autocorrelation
92
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
93
94
plot_acf(ts_diff, lags=40, ax=axes[0])
95
axes[0].set_title('ACF')
96
97
plot_pacf(ts_diff, lags=40, ax=axes[1])
98
axes[1].set_title('PACF')
99
100
plt.tight_layout()
101
plt.show()
102
103
# ARIMA Model
104
arima_model = ARIMA(ts, order=(1, 1, 1))
105
arima_result = arima_model.fit()
106
print(arima_result.summary())
107
108
# Forecast
109
forecast_steps = 30
110
forecast = arima_result.get_forecast(steps=forecast_steps)
111
forecast_df = forecast.conf_int()
112
forecast_mean = forecast.predicted_mean
113
114
# Plot forecast
115
fig, ax = plt.subplots(figsize=(12, 5))
116
ax.plot(ts.index[-90:], ts[-90:], label='Historical')
117
ax.plot(forecast_df.index, forecast_mean, label='Forecast', color='red')
118
ax.fill_between(
119
forecast_df.index,
120
forecast_df.iloc[:, 0],
121
forecast_df.iloc[:, 1],
122
color='red', alpha=0.2
123
)
124
ax.set_title('ARIMA Forecast with Confidence Interval')
125
ax.legend()
126
ax.grid(True, alpha=0.3)
127
plt.show()
128
129
# Exponential Smoothing
130
exp_smooth = ExponentialSmoothing(
131
ts, seasonal_periods=30, trend='add', seasonal='add', initialization_method='estimated'
132
)
133
exp_result = exp_smooth.fit()
134
135
# Model diagnostics
136
fig = exp_result.plot_diagnostics(figsize=(12, 8))
137
plt.tight_layout()
138
plt.show()
139
140
# Custom moving average analysis
141
window_sizes = [7, 30, 90]
142
fig, ax = plt.subplots(figsize=(12, 5))
143
144
ax.plot(ts.index, ts.values, label='Original', alpha=0.7)
145
146
for window in window_sizes:
147
ma = ts.rolling(window=window).mean()
148
ax.plot(ma.index, ma.values, label=f'MA({window})')
149
150
ax.set_title('Moving Averages')
151
ax.legend()
152
ax.grid(True, alpha=0.3)
153
plt.show()
154
155
# Seasonal subseries plot
156
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
157
for i, month in enumerate(range(1, 5)):
158
month_data = ts[ts.index.month == month]
159
axes[i // 2, i % 2].plot(month_data.values)
160
axes[i // 2, i % 2].set_title(f'Month {month} Pattern')
161
162
plt.tight_layout()
163
plt.show()
164
165
# Forecast accuracy metrics
166
def calculate_forecast_metrics(actual, predicted):
167
mae = np.mean(np.abs(actual - predicted))
168
rmse = np.sqrt(np.mean((actual - predicted) ** 2))
169
mape = np.mean(np.abs((actual - predicted) / actual)) * 100
170
return {'MAE': mae, 'RMSE': rmse, 'MAPE': mape}
171
172
metrics = calculate_forecast_metrics(ts[-30:], forecast_mean[:30])
173
print(f"\nForecast Metrics:\n{metrics}")
174
175
# Additional analysis techniques
176
177
# Step 10: Seasonal subseries plots
178
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
179
for i, season in enumerate([1, 2, 3, 4]):
180
seasonal_ts = ts[ts.index.month % 4 == season % 4]
181
axes[i // 2, i % 2].plot(seasonal_ts.values)
182
axes[i // 2, i % 2].set_title(f'Season {season}')
183
plt.tight_layout()
184
plt.show()
185
186
# Step 11: Granger causality (for multiple series)
187
from statsmodels.tsa.stattools import grangercausalitytests
188
189
# Create another series for testing
190
ts2 = ts.shift(1).fillna(method='bfill')
191
192
try:
193
print("\nGranger Causality Test:")
194
print(f"Test whether ts2 Granger-causes ts:")
195
gc_result = grangercausalitytests(np.column_stack([ts.values, ts2.values]), maxlag=3)
196
except Exception as e:
197
print(f"Granger causality not performed: {str(e)[:50]}")
198
199
# Step 12: Autocorrelation and partial autocorrelation analysis
200
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
201
202
acf_values = acf(ts.dropna(), nlags=20)
203
pacf_values = pacf(ts.dropna(), nlags=20)
204
205
# Step 13: Seasonal strength
206
def seasonal_strength(series, seasonal_period=30):
207
seasonal = seasonal_decompose(series, model='additive', period=seasonal_period)
208
var_residual = np.var(seasonal.resid.dropna())
209
var_seasonal = np.var(seasonal.seasonal)
210
return 1 - (var_residual / (var_residual + var_seasonal)) if (var_residual + var_seasonal) > 0 else 0
211
212
ss = seasonal_strength(ts)
213
print(f"\nSeasonal Strength: {ss:.3f}")
214
215
# Step 14: Forecasting with uncertainty
216
fig, ax = plt.subplots(figsize=(12, 5))
217
ax.plot(ts.index[-60:], ts.values[-60:], label='Historical', linewidth=2)
218
219
# Multiple horizon forecasts
220
for steps_ahead in [10, 20, 30]:
221
try:
222
fc = arima_result.get_forecast(steps=steps_ahead)
223
fc_mean = fc.predicted_mean
224
ax.plot(pd.date_range(ts.index[-1], periods=steps_ahead+1)[1:],
225
fc_mean.values, marker='o', label=f'Forecast (+{steps_ahead})')
226
except:
227
pass
228
229
ax.set_title('Multi-step Ahead Forecasts')
230
ax.set_xlabel('Date')
231
ax.set_ylabel('Value')
232
ax.legend()
233
ax.grid(True, alpha=0.3)
234
plt.tight_layout()
235
plt.show()
236
237
# Step 15: Model comparison summary
238
print("\nTime Series Analysis Complete!")
239
print(f"Original series length: {len(ts)}")
240
print(f"Trend strength: {1 - np.var(decomposition.resid.dropna()) / np.var((ts - ts.mean()).dropna()):.3f}")
241
print(f"Seasonal strength: {ss:.3f}")
242
```
243
244
## Stationarity
245
246
- **Stationary**: Mean, variance, autocorrelation constant over time
247
- **Non-stationary**: Trend or seasonal patterns present
248
- **Solution**: Differencing, log transformation, or detrending
249
250
## Model Selection
251
252
- **ARIMA**: Good for univariate forecasting
253
- **SARIMA**: Includes seasonal components
254
- **Exponential Smoothing**: Simpler, good for trends
255
- **Prophet**: Handles holidays and changepoints
256
257
## Evaluation Metrics
258
259
- **MAE**: Mean Absolute Error
260
- **RMSE**: Root Mean Squared Error
261
- **MAPE**: Mean Absolute Percentage Error
262
263
## Deliverables
264
265
- Decomposition analysis charts
266
- Stationarity test results
267
- ACF/PACF plots
268
- Fitted models with diagnostics
269
- Forecast with confidence intervals
270
- Accuracy metrics comparison
271