Time Series Analysis and Forecasting Tutorial
Learn Time Series Analysis and Forecasting step by step: 40 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is a Time Series? Learn what a time series is, how it differs from ordinary tabular data, the main goals of time series analysis, and how to build and plot your first series with pandas.
- The Datetime Index in pandas Master the pandas DatetimeIndex for time series: parse dates, build date ranges, slice by date strings, extract calendar parts, shift, diff and compute rolling statistics.
- Missing Data and Resampling Fix gaps and irregular timestamps in time series: find missing dates, fill with ffill, interpolation or seasonal values, and resample to coarser or finer frequencies.
- The Forecasting Workflow and Baselines Learn the time series forecasting workflow, split data by time, and build naive, seasonal naive, mean and drift baselines that every fancy model must beat.
- Moving Averages and Rolling Windows Smooth noisy series with simple, centered and weighted moving averages, and compute rolling statistics, expanding windows and exponentially weighted means with pandas.
Components and Decomposition
- Trend, Seasonality and Noise Understand the components of a time series: trend, seasonality, cycles and noise. Learn additive versus multiplicative structure and build one by simulation to see how they combine.
- Classical Decomposition Split a series into trend, seasonal and remainder parts with classical additive and multiplicative decomposition: the moving-average algorithm by hand and with statsmodels.
- STL Decomposition Use STL (Seasonal-Trend decomposition using Loess) in statsmodels: evolving seasonal patterns, robust fitting against outliers, tuning smoothness, and multiplicative series via logs.
- Trend and Seasonality by Regression Model trend and seasonality with ordinary regression: linear and polynomial trends, seasonal dummy variables, Fourier terms, and how to extrapolate them for forecasts.
- Calendar Effects and Cycles Handle working-day, holiday, leap-year and moving-holiday effects in time series, plus multiple seasonalities, cycles and how to tell a cycle from a season using the periodogram.
Stationarity and Transformations
- Stationarity and Random Walks Learn what stationarity means, why models need it, and how white noise, random walks with drift, trends and changing variance differ, with simulations you can run.
- Differencing and Detrending Make a series stationary with first and seasonal differencing, learn when to difference or detrend, avoid over-differencing, and invert differences to return forecasts to the original scale.
- Transformations: Log and Box-Cox Stabilize growing variance with log, square-root and Box-Cox transformations, pick lambda, back-transform forecasts correctly, and know when a transformation hurts.
- Autocorrelation: ACF and PACF Understand autocorrelation, the ACF and the PACF: compute them by hand and with statsmodels, read confidence bands, recognise AR, MA, trend and seasonal patterns, and test with Ljung-Box.
- Unit Root Tests: ADF and KPSS Test stationarity formally with the Augmented Dickey-Fuller and KPSS tests in statsmodels: hypotheses, p-values, the four-way decision table, regression options and common pitfalls.
Smoothing and Exponential Methods
- Simple Exponential Smoothing Forecast level-only series with simple exponential smoothing: the recursion by hand, the smoothing parameter alpha, optimising it with statsmodels, and when SES fails.
- Holt's Linear Trend Method Extend exponential smoothing to trending data with Holt's method: level and slope equations, the beta parameter, damped trends that stop runaway forecasts, and statsmodels examples.
- The Holt-Winters Seasonal Method Forecast seasonal data with Holt-Winters: additive and multiplicative seasonality, the gamma parameter, damped trend, statsmodels ExponentialSmoothing and choosing between variants.
- ETS State-Space Models Understand the ETS (Error, Trend, Seasonal) taxonomy of exponential smoothing, fit ETSModel in statsmodels, select models with AIC, and get proper prediction intervals.
ARIMA and SARIMA
- Autoregressive (AR) Models Learn how an autoregressive model predicts a series from its own past, when it is stationary, how the ACF and PACF reveal its order, and how to fit and forecast in Python.
- Moving Average (MA) Models Understand the MA(q) model as a weighted sum of past shocks, how it differs from a smoothing average, how to read its ACF cutoff, invertibility, and how to fit one in Python.
- ARIMA Model Fitting and Forecasting Combine AR, differencing and MA into ARIMA(p, d, q): fit a model with statsmodels, read its summary, check the residuals, and produce forecasts with confidence intervals.
- Choosing ARIMA Orders: Box-Jenkins and AIC Pick p, d and q with the Box-Jenkins method: unit-root tests for d, ACF and PACF patterns for p and q, a grid search by AIC, and the parsimony rules that avoid overfitting.
- SARIMA: Seasonal ARIMA Add seasonality to ARIMA with SARIMA(p,d,q)(P,D,Q)s: understand seasonal differencing, fit SARIMAX in statsmodels, compare candidates by AIC, and forecast monthly data.
- ARIMAX and Exogenous Regressors Add outside drivers such as price, weather or holidays to an ARIMA model with SARIMAX: dummy variables, lagged effects, the future-values requirement and how to read coefficients.
- ARIMA Residual Diagnostics Check whether an ARIMA model is adequate: residual ACF, the Ljung-Box test, normality checks, heteroskedasticity and what to change when the residuals still contain structure.
- Multivariate Series: VAR and Granger Causality Model several related time series together with a VAR in statsmodels: lag selection, forecasting, impulse responses and the Granger causality test, with the warnings that come with it.
Machine Learning Forecasting
- Lag Features and Supervised Framing Turn a time series into a table that scikit-learn can learn from: lag columns, rolling statistics, calendar features, and a leakage-safe chronological train/test split.
- Tree Models for Forecasting Forecast with random forests and histogram gradient boosting in scikit-learn: nonlinear lag features, the extrapolation limit of trees, detrending, feature importance and tuning.
- Multi-step Forecasting Strategies Forecast many steps ahead with machine learning models: the recursive strategy, the direct strategy, multi-output models, error accumulation and how to choose between them.
- Regularized Linear Models for Forecasting Forecast with Ridge, Lasso and Elastic Net on lag, calendar and Fourier features: scaling inside a pipeline, time-ordered tuning, sparse lag selection and why linear models extrapolate.
- Neural Networks for Forecasting Forecast with neural networks: windowing a series, a scikit-learn MLP on scaled windows, how LSTM and other deep models fit in, and honest guidance on when deep learning beats simpler models.
Evaluation and Cross-validation
- Forecast Accuracy Metrics Measure forecast errors correctly: MAE, RMSE, MAPE, sMAPE, MASE and bias, when each one misleads, why MASE compares fairly across series, and how to report errors by horizon.
- Time Series Cross-validation Evaluate forecasting models honestly: why random k-fold leaks the future, TimeSeriesSplit, expanding and rolling windows, gaps, a backtest loop for any model and how to compare models fairly.
- Prediction Intervals and Uncertainty Report forecast uncertainty: ARIMA and ETS intervals, empirical residual intervals, quantile regression with gradient boosting, coverage checks and the pinball loss.
Anomalies and Applications
- Anomaly Detection in Time Series Find outliers and unusual behaviour in time series: global and rolling z-scores, robust MAD scores, residual-based detection after removing trend and seasonality, Isolation Forest and alert design.
- Change Point Detection Detect structural breaks where a series changes level, trend or variance: CUSUM, a from-scratch binary segmentation with a penalty, rolling comparisons and what to do with the breaks.
Projects and Practice
- Project: Retail Demand Forecast A complete forecasting project: build a realistic daily sales series, set baselines, engineer calendar and lag features, train a boosted model, backtest it against baselines and add prediction intervals.
- Project: Sensor Monitoring with Anomaly Alerts Build a monitoring pipeline for hourly sensor data: remove the daily cycle, flag spikes with a robust score, catch a stuck sensor and a level shift, and score the alerts against known incidents.
- Time Series Practice Set Eight worked practice problems for time series analysis: resampling, stationarity, decomposition, forecasting baselines, ARIMA choice, leakage-free features, backtesting and interval coverage.