Time-Series, Sequential and Forecasting AlgorithmsIntroduction and contextA time series is a sequence of observations indexed by time: sales recorded daily, electricity demand measured every 15 minutes, or machine vibration sampled every second. Unlike ordinary independent observations, temporal data may exhibit dependence: the value at time t can be related to earlier values, recent shocks, calendar effects and changing variance. Sequential prediction extends this idea to ordered data in which the objective may be forecasting, classification, anomaly detection or decision-making. Forecasting is therefore not simply a regression problem with a date column. It requires preservation of temporal order, explicit treatment of information availability, appropriate handling of non-stationarity, and evaluation against realistic operational baselines. This chapter examines classical statistical models, state-space methods, recurrent neural networks and attention-based architectures. Learning objectivesBy the end of this chapter, learners should be able to: - Explain trend, seasonality, cycles, stationarity, autocorrelation and temporal dependence.
- Build and interpret naïve, moving-average, exponential-smoothing, ARIMA and state-space forecasts.
- Distinguish recursive, direct and multi-output forecasting strategies.
- Apply recurrent and attention-based models to sequential prediction.
- Design leakage-resistant validation and select suitable forecasting metrics.
- Evaluate forecasting systems in operational, ethical and governance contexts.
1. Structure of temporal dataLet yt denote an observation at time t. A useful conceptual decomposition is: yt = Tt + St + Rt Here Tt is the trend, St is a systematic seasonal component, and Rt is the remainder or irregular component. This additive form is appropriate when seasonal fluctuations have roughly constant absolute size. A multiplicative decomposition is often more suitable when seasonal variation grows with the level: yt = Tt × St × Rt The components are not always uniquely identifiable. A long-term cycle may be confused with trend, and a changing seasonal pattern may violate the assumption of fixed seasonality. Important properties include: - Trend: persistent long-term movement.
- Seasonality: a repeated pattern with a known period, such as 7 days or 12 months.
- Cycle: recurrent movement without a fixed or known period.
- Noise: unpredictable variation.
- Lag: the interval between observations being compared.
- Autocorrelation: correlation between a series and its lagged values.
- Stationarity: broadly, statistical behaviour that does not change over time. Weak stationarity requires constant mean and variance and autocovariance depending only on lag, not calendar time.
For a stationary series, autocovariance at lag k is: γk = Cov(yt, yt-k) and autocorrelation is: ρk = γk ÷ γ0 where γ0 is the variance. These quantities are meaningful when the relevant moments are stable and the observations are measured at consistent intervals. A series may be transformed to improve stationarity. First differences are: ∆yt = yt − yt−1 Seasonal differences with period m are: ∆m yt = yt − yt−m Differencing removes persistent level movement but can also remove useful signal and amplify noise. It should be justified diagnostically rather than applied automatically. 2. Forecasting workflowA professional workflow begins with the decision and forecast horizon. Predicting tomorrow’s demand for staffing is different from predicting annual capacity. The horizon determines the information available, the acceptable error and the useful model complexity. A sound process is: - Define the target, time granularity, horizon and decision cost.
- Audit timestamps, missing intervals, duplicates, outliers and revisions.
- Establish naïve and seasonal-naïve baselines.
- Explore plots, rolling statistics and autocorrelation.
- Create time-ordered training, validation and test periods.
- Fit transformations and features using training data only.
- Compare candidate models using rolling-origin evaluation.
- Produce prediction intervals where decisions require uncertainty.
- Monitor errors, drift and data quality after deployment.
Random shuffling is generally invalid for forecasting because it allows future information to influence the past. A rolling-origin design repeatedly trains on an earlier interval and tests on a later interval. 3. Baselines and classical forecastingNaïve and seasonal-naïve forecastsThe naïve forecast uses the most recent observation: ŷt+h|t = yt for horizon h. A seasonal-naïve forecast uses the observation from the corresponding previous season: ŷt+h|t = yt+h−m where m is the seasonal period. These baselines are difficult to outperform in highly persistent or strongly seasonal series and are essential for judging whether machine learning adds value. Moving averagesA trailing moving average of window w is: MAt = (1 ÷ w) ∑i=0w−1 yt−i It smooths noise but lags behind rapid changes. It is useful for descriptive smoothing and simple level estimation, but it is not automatically an optimal forecast. Exponential smoothingSimple exponential smoothing updates an estimated level: ℓt = αyt + (1−α)ℓt−1 where 0 < α ≤ 1. A one-step forecast is ŷt+1|t = ℓt. Larger α responds more rapidly to new observations; smaller values produce smoother estimates. Initialisation must be specified, for example by setting the initial level to the first observation or estimating it from the data. Holt’s method adds a trend. One common additive form is: ℓt = αyt + (1−α)(ℓt−1+bt−1) bt = β(ℓt−ℓt−1) + (1−β)bt−1 ŷt+h|t = ℓt + hbt where 0 < β ≤ 1 and h is the forecast horizon. Damped-trend variants reduce unrealistic long-range extrapolation. Holt–Winters methods additionally estimate seasonality and may use additive or multiplicative seasonal terms. AR, MA and ARIMA modelsAn autoregressive model of order p, AR(p), predicts from its own lags: yt = c + φ1yt−1 + … + φpyt−p + εt where c is an intercept, φi are coefficients, and εt is an error with mean approximately zero. Stationarity imposes restrictions on the autoregressive coefficients; arbitrary coefficients should not be assumed valid. A moving-average model of order q, MA(q), models current values through past shocks: yt = μ + εt + θ1εt−1 + … + θqεt−q ARMA(p,q) combines both. ARIMA(p,d,q) applies d differences before fitting an ARMA model. Seasonal ARIMA, written SARIMA, adds seasonal autoregressive, differencing and moving-average terms. Model identification commonly uses domain knowledge, autocorrelation and partial autocorrelation, but final selection should use time-aware validation rather than visual rules alone. A small worked exampleSuppose daily demand for the last three days is 100, 110 and 105 units. A three-day moving-average forecast is: MAt = (100 + 110 + 105) ÷ 3 = 105 units If the previous week’s corresponding demand was 112 units, the seasonal-naïve forecast is 112 units. Neither method is universally superior: the moving average dampens recent variation, whereas the seasonal-naïve method preserves weekly seasonality. Historical rolling-origin errors should determine the choice. 4. State-space models and uncertaintyState-space modelling separates an unobserved state from the measurement process. A general linear Gaussian form is: xt = Ft xt−1 + Btut + wt yt = Htxt + vt Here xt is the latent state, ut an optional known input, Ft the state-transition matrix, Ht the observation matrix, and wt, vt process and observation errors. In the classical model, these errors are commonly assumed zero-mean Gaussian, mutually independent, and with specified covariance matrices. The Kalman filter recursively performs prediction and updating. It first predicts the next state from the previous estimate, then corrects that prediction using the new observation. It is computationally efficient and naturally produces uncertainty estimates. Exponential smoothing models can also be expressed in state-space form, making likelihood-based estimation and prediction intervals possible. State-space methods are valuable when data contain missing observations, changing latent levels, noisy sensors or time-varying components. Nonlinear or non-Gaussian systems may require extended, unscented or particle filters, each introducing additional approximations and computational cost. 5. Sequential machine learningA supervised learning representation converts a series into input-output windows. With look-back length L, an input may be: Xt = [yt−L+1, …, yt] and the target may be yt+1 or a vector of future values. Exogenous variables—weather, promotions, prices or calendar indicators—may be included only when their future availability is known or separately forecast. A model can forecast one step recursively, forecast every horizon directly, or produce all horizons jointly. | Strategy | Strength | Main risk |
|---|
| Recursive | One model; simple deployment | Errors accumulate across horizons | | Direct | Horizon-specific behaviour | Many models and inconsistent forecasts | | Multi-output | Joint horizon prediction | More complex training and calibration |
Tree ensembles and gradient boosting often perform strongly when lag, rolling, calendar and external features are engineered carefully. They do not inherently understand order; the designer must encode temporal structure and prevent leakage in rolling features. 6. Recurrent neural networksAn RNN maintains a hidden state summarising previous inputs: ht = tanh(Wxxt + Whht−1 + bh) ŷt = g(Wyht + by) where xt is the input, ht the hidden state, Wx, Wh and Wy are learned parameters, and g is an output function appropriate to the task. Training uses backpropagation through time. Long sequences can cause vanishing or exploding gradients. LSTM networks address this using gates. A simplified LSTM has input, forget and output gates: it = σ(Wi[xt,ht−1] + bi) ft = σ(Wf[xt,ht−1] + bf) ot = σ(Wo[xt,ht−1] + bo) ct = ft⊙ct−1 + it⊙tanh(Wc[xt,ht−1] + bc) ht = ot⊙tanh(ct) Here σ is the sigmoid function, ⊙ denotes elementwise multiplication, and ct is the cell state. GRUs use fewer gates and can be faster, sometimes with comparable performance. Neural sequence models require scaling, adequate data, regularisation, careful window construction and a validation scheme reflecting deployment. Greater capacity does not guarantee better forecasts, particularly for short, noisy or structurally changing series. 7. Attention and transformer-based forecastingAttention allows a model to weight relevant positions in a sequence rather than compressing all history into one recurrent state. Given query matrix Q, key matrix K and value matrix V, scaled dot-product attention is: Attention(Q,K,V) = softmax(QKᵀ ÷ √dk)V where dk is the key dimension. The scaling reduces excessively large dot products. Multi-head attention computes several attention transformations and combines them, enabling different relationships across lags or variables. Transformers require positional information because attention alone is not inherently ordered. Forecasting architectures may use causal masks so that a prediction cannot attend to future targets. Encoder-only models, encoder–decoder models and specialised temporal transformers differ in how they represent history, known future covariates and forecast horizons. Attention can capture long-range relationships and parallelise training more effectively than recurrence, but it may be data-hungry and computationally expensive. An attention map should not automatically be interpreted as a causal explanation; high attention weight is not proof that a variable caused an outcome. 8. Evaluation, uncertainty and monitoringLet actual values be yi, forecasts ŷi, and let n be the number of evaluated cases. Mean absolute error is: MAE = (1 ÷ n)∑|yi−ŷi| It has the same units as the target. Root mean squared error is: RMSE = √((1 ÷ n)∑(yi−ŷi)2) RMSE penalises large errors more strongly. Mean absolute percentage error is: MAPE = (100 ÷ n)∑| (yi−ŷi) ÷ yi | MAPE is unsuitable when actual values are zero or near zero. Weighted or symmetric alternatives may be preferable. Metrics should reflect business loss: a missed safety threshold may be more serious than an overprediction of equal size. Point forecasts are incomplete when decisions depend on risk. Prediction intervals should be evaluated for coverage and sharpness. A nominal 90% interval should contain the future observation approximately 90% of the time under stable conditions, although finite samples and drift can reduce coverage. Quantile forecasting estimates conditional quantiles using pinball loss. For quantile level τ: L_τ(y,q) = (τ−I(y<q))(y−q) where I is an indicator and q is the predicted quantile. After deployment, monitor data distributions, missingness, residual patterns, forecast bias, interval coverage and performance by subgroup or operating regime. Retraining should be triggered by evidence, not merely by calendar habit. 9. Illustrative case: forecasting hospital emergency demandBackground. A regional hospital must forecast emergency arrivals by hour for the next 24 hours to plan clinicians and beds. Historical data contain hourly arrivals, day-of-week, holidays, weather and public-event indicators. Problem. Demand is strongly intraday and weekly seasonal, occasionally affected by extreme weather, and contains missing sensor records. Underprediction creates safety and staffing risks; moderate overprediction is less costly. Analysis. The team first verifies time zones and reconstructs missing intervals without fabricating target values. A seasonal-naïve baseline uses arrivals from the same hour one week earlier. Exploratory analysis reveals changing variance and holiday effects. Weather forecasts, rather than future observed weather, are used as covariates because deployment cannot access the future observations. Approach. The team compares seasonal naïve, Holt–Winters, dynamic regression with ARIMA errors, gradient boosting using lagged and calendar features, and an LSTM. Rolling-origin validation uses several historical evaluation windows. Models are scored with MAE and a weighted loss that penalises underprediction more heavily. A calibrated prediction interval is supplied to the staffing system. The selected model is not the most complex model; it is the model with the best stable validation performance and acceptable latency. Outcome. In this illustrative scenario, the model is deployed with a dashboard showing forecasts, intervals, missing-data warnings and recent errors. Clinicians retain decision authority. Forecasts are reviewed during unusual events, and performance is monitored separately for ordinary days, holidays and severe weather. Learning points. Baselines expose whether complexity adds value; covariate availability is a deployment constraint; asymmetric costs affect evaluation; and human oversight is essential when forecasts influence healthcare capacity. 10. Limitations, governance and best practiceForecasts cannot remove irreducible uncertainty. Structural breaks, pandemics, policy changes and sensor failures can invalidate historical relationships. Correlation in historical sequences does not establish causation. Models may also encode inequities if data quality or service access differs across populations. Governance should address data minimisation, access control, audit logs, retention, reproducibility and documented model ownership. In high-impact settings, users need understandable uncertainty communication and escalation procedures. Personal or sensitive temporal data require lawful processing, appropriate security and careful consideration of re-identification risks. Best practice includes: - begin with a strong naïve baseline;
- preserve temporal order in preprocessing and validation;
- document forecast horizon, information cut-off and missing-data treatment;
- use only deployable future covariates;
- compare accuracy, calibration, latency and maintenance cost;
- inspect residuals and performance across regimes;
- version data, code, features and model parameters;
- monitor drift and define retraining and rollback criteria;
- communicate intervals and limitations to decision-makers.
Contemporary developmentsCurrent forecasting systems increasingly combine probabilistic prediction, foundation models, global models trained across many related series, graph-based representations of spatial networks and hybrid statistical–neural methods. These approaches can transfer information across products, locations or sensors, but transfer may fail when domains differ. Efficient attention, patch-based representations and retrieval of similar historical episodes are active areas of research. Their adoption should be justified by measurable improvement, robust evaluation and governance readiness rather than novelty alone. Chapter SummaryTemporal forecasting differs from ordinary prediction because order, information availability and dependence matter. Decomposition clarifies trend and seasonality, while differencing and autocorrelation support diagnostic analysis. Naïve methods provide essential baselines; moving averages and exponential smoothing offer transparent level, trend and seasonal models. ARIMA models represent dependence through lagged values and shocks, while state-space models represent latent states and provide recursive uncertainty estimates. Supervised windowing enables tree-based and neural models, but feature construction must prevent leakage. RNNs, LSTMs and GRUs model sequential state; attention and transformers provide flexible long-range interaction, subject to positional, computational and data requirements. Evaluation should use time-aware validation, decision-relevant metrics and calibrated uncertainty. Successful deployment combines technical accuracy with monitoring, governance, human oversight and explicit recognition of structural change. Key TermsTime series: Ordered observations indexed by time. Temporal dependence: Relationship between observations at different times. Trend: Persistent long-term movement in a series. Seasonality: Repeating pattern with a known period. Stationarity: Stability of relevant statistical properties over time. Autocorrelation: Correlation between a series and a lagged version of itself. Lag: Time interval separating observations. Differencing: Subtracting earlier observations to reduce non-stationarity. Naïve forecast: Forecast based on the latest observation. Exponential smoothing: Weighted updating method giving greater or lesser emphasis to recent data. ARIMA: Autoregressive integrated moving-average model. State-space model: Model separating latent state dynamics from observations. Kalman filter: Recursive estimator for linear Gaussian state-space systems. Autoregressive model: Model using previous values of the series as predictors. Recursive forecasting: Predicting multiple steps by feeding forecasts back as inputs. RNN: Neural network that maintains a hidden state across sequence positions. LSTM: Gated recurrent network designed to retain information over long sequences. Attention: Mechanism that weights relationships among sequence positions. Prediction interval: Range intended to contain a future observation with stated probability. Data leakage: Use of information unavailable at prediction time. Review QuestionsShort Answer Questions- What distinguishes seasonality from a general cycle?
- Why is a seasonal-naïve forecast an important baseline?
- State one limitation of MAPE.
- What problem do LSTM gates address?
- Why must future covariates be available at deployment time?
Long Answer Questions- Explain the decomposition of a time series and discuss when additive and multiplicative forms are appropriate.
- Compare exponential smoothing, ARIMA and state-space methods in terms of assumptions, interpretability and uncertainty.
- Explain how rolling-origin validation prevents misleading evaluation.
- Describe the design of an LSTM forecasting system, including windowing, scaling and multi-step prediction.
- Compare recurrent networks with attention-based architectures for long sequential data.
Analytical / Application Questions- A retailer has hourly demand with strong daily and weekly patterns. Design a baseline, validation scheme and metric set for a 24-hour forecast, justifying each decision.
- A model has lower RMSE but systematically underpredicts peak hospital demand. How should model selection and governance respond?
- A deployed forecast suddenly fails after a new regulation changes customer behaviour. Diagnose the likely causes and propose a monitoring, retraining and fallback plan.
Multiple Choice Questions with AnswersQuestion 1Which forecast is defined by ŷt+h|t=yt? A. Naïve forecast B. Seasonal-naïve forecast C. Moving-average forecast D. Direct multi-output forecast Correct Answer: A. Naïve forecast Question 2What is the main purpose of differencing a non-stationary series? A. To increase the number of observations B. To reduce persistent level movement C. To guarantee normally distributed errors D. To remove all random noise Correct Answer: B. To reduce persistent level movement Question 3For a three-period moving average of 8, 10 and 12, what is the forecast? A. 9 B. 10 C. 11 D. 30 Correct Answer: B. 10 Question 4Which metric has the same units as the target variable? A. MAPE B. MAE C. A percentage error only D. A correlation coefficient Correct Answer: B. MAE Question 5What is a principal advantage of a state-space model? A. It never requires assumptions B. It can represent latent states and recursive uncertainty C. It eliminates structural breaks D. It always outperforms neural networks Correct Answer: B. It can represent latent states and recursive uncertainty Question 6Why is random shuffling usually inappropriate for time-series validation? A. It reduces the sample size B. It can allow future information to influence training C. It prevents calculation of MAE D. It forces seasonal differencing Correct Answer: B. It can allow future information to influence training Question 7Which mechanism helps an LSTM retain information over longer sequences? A. Seasonal decomposition only B. Gated cell-state updates C. Random shuffling D. MAPE optimisation Correct Answer: B. Gated cell-state updates Question 8In scaled dot-product attention, why is QKᵀ divided by √dk? A. To remove all positional information B. To control the scale of dot products C. To convert forecasts into percentages D. To guarantee causal interpretation Correct Answer: B. To control the scale of dot products Question 9Which situation makes MAPE especially problematic? A. All actual values are large and positive B. The forecast horizon is one step C. Actual values are zero or near zero D. The series has weekly seasonality Correct Answer: C. Actual values are zero or near zero Question 10A recursive multi-step forecast primarily faces which risk? A. It cannot use historical observations B. Errors can accumulate across forecast steps C. It always requires a transformer D. It cannot produce a one-step forecast Correct Answer: B. Errors can accumulate across forecast steps
|