Time Series and Forecasting¶
Predicting where an asset price or volatility regime might travel next requires transforming wandering, non-stationary trajectories into stable statistical signals without throwing away their memory. This file walks from classical ARIMA, GARCH, and Kalman state-space models to modern neural forecasters like PatchTST, Temporal Fusion Transformers, and N-BEATS trained with probabilistic quantile loss.
Log Returns, Stationarity, and Fractional Differentiation¶
-
Imagine trying to teach a machine learning model to predict tomorrow's temperature on a spaceship steadily flying closer to the Sun. Every month the average reading climbs higher than anything seen during training, so a model trained on last year's values keeps getting blindsided by brand-new ranges. Raw financial prices behave exactly like that drifting thermometer. They are non-stationary random walks whose mean and variance wander endlessly over time.
-
A time series \(\{x_t\}\) is (weakly) stationary when its mean \(\mathbb{E}[x_t]\), its variance \(\text{Var}(x_t)\), and the covariance \(\text{Cov}(x_t, x_{t-k})\) depend only on the lag \(k\) rather than on the calendar date \(t\). Almost every classical statistical estimator and neural normaliser assumes your inputs sit close to stationarity.
-
The standard first remedy in finance is switching from raw prices \(P_t\) to log returns.
-
Log returns bring three mathematical gifts compared with simple percentage returns \((P_t - P_{t-1})/P_{t-1}\).
- Time additivity lets a multi-day return over \(T\) days equal the plain sum of single-day log returns, \(\sum_{t=1}^T r_t = \ln(P_T / P_0)\), instead of a messy product.
- Symmetry ensures a \(+10\%\) log move followed by a \(-10\%\) log move returns you cleanly to the starting price, whereas simple returns lose money on an equal up-then-down cycle.
- Approximate stationarity strips out the drifting price level so returns fluctuate around a narrow mean near zero.
-
Yet taking a full first difference (\(d = 1\), which turns \(\ln P_t\) into \(r_t\)) hides a painful catch known as the stationarity-memory trade-off. Think of differentiating a smooth hiking trail elevation map into step-by-step slopes. You stabilise the numbers around zero, yet you erase nearly all memory of whether you are standing in a valley or near a snow-capped summit! Long-term valuation levels, multi-month support zones, and slow economic cycles vanish when you take a full integer difference.
-
Fractional differentiation (popularised for financial ML by Marcos López de Prado) threads the needle by applying a fractional power \(0 < d < 1\) of the backshift operator \(B\) (where \(B P_t = P_{t-1}\)).
-
When \(d = 0\), you keep the raw non-stationary price (\(100\%\) memory). When \(d = 1\), only \(w_0 = 1\) and \(w_1 = -1\) survive, erasing all memory past yesterday. Choosing the smallest fractional order (often \(d \approx 0.3\) to \(0.5\)) that passes the Augmented Dickey-Fuller (ADF) test yields a series that is statistically stationary while preserving strong correlation with the underlying price level.
-
Intuitively, the ADF test checks whether a series has a unit root (drifting aimlessly like a drunken sailor) or pulls back toward a stable anchor (like a dog on an elastic leash). It regresses the change \(\Delta y_t\) on its own lagged level \(\gamma y_{t-1}\) plus lagged changes. If \(\gamma\) is significantly negative, high values tend to fall back and low values tend to rise, rejecting the unit root and confirming stationarity.
Classical Time-Series and Volatility Models¶
- Before reaching for million-parameter neural networks, quantitative researchers rely on interpretable linear and volatility baselines that remain remarkably hard to beat on noisy daily data.
AR, MA, ARIMA, and Exponential Smoothing¶
- Picture a ringing bell struck occasionally by random gusts of wind. Its sound right now blends echoes of its own recent vibrations with fresh wind shocks. Classical Box-Jenkins models formalise that exact picture.
- An Autoregressive model \(\text{AR}(p)\) predicts today's value from its own last \(p\) readings plus fresh white noise \(\epsilon_t\), written \(y_t = c + \sum_{i=1}^p \phi_i y_{t-i} + \epsilon_t\).
- A Moving Average model \(\text{MA}(q)\) models today's value as a weighted blend of the last \(q\) unpredictable surprise shocks, written \(y_t = \mu + \epsilon_t + \sum_{j=1}^q \theta_j \epsilon_{t-j}\).
- \(\text{ARIMA}(p, d, q)\) simply differences the raw series \(d\) times to achieve stationarity and then fits a combined \(\text{AR}(p)\) and \(\text{MA}(q)\) model to the differenced series.
- Exponential smoothing (simple smoothing, Holt's linear trend, and Holt-Winters seasonal smoothing) tracks level and trend with exponentially decaying weights, \(\hat{y}_{t+1} = \alpha y_t + (1 - \alpha)\hat{y}_t\). Recent data speaks loudly while ancient history fades smoothly away.
GARCH(1,1) and Volatility Clustering¶
-
Predicting the direction of tomorrow's stock return is notoriously close to flipping a fair coin. Predicting its volatility (how wildly tomorrow's return will swing) is vastly more predictable, because turbulence clusters tightly in time.
-
In 1986, Tim Bollerslev introduced GARCH (Generalised Autoregressive Conditional Heteroscedasticity), building on Robert Engle's Nobel-winning ARCH work. Imagine predicting tomorrow's sea wave height. You combine a calm ocean baseline, the size of today's sudden storm shock, and yesterday's already-elevated swell. The workhorse \(\text{GARCH}(1,1)\) updates conditional variance \(\sigma_t^2\) step by step.
- Every parameter carries crisp economic intuition.
- \(\omega > 0\) pulls variance gently back toward a long-run baseline level.
- \(\alpha \ge 0\) governs shock reactivity (typically \(0.05\) to \(0.15\) on daily equities), spiking \(\sigma_t^2\) immediately after a surprise crash or rally \(r_{t-1}^2\).
- \(\beta \ge 0\) governs volatility persistence (typically \(0.80\) to \(0.93\)), ensuring yesterday's storm takes days or weeks to calm down.
- Stability requires \(\alpha + \beta < 1\), which implies a finite long-run unconditional variance \(\bar{\sigma}^2 = \frac{\omega}{1 - \alpha - \beta}\). Fitting \((\omega, \alpha, \beta)\) simply maximises the Gaussian (or Student-\(t\)) log-likelihood of observed returns \(r_t \sim \mathcal{N}(0, \sigma_t^2)\).
State-Space Models and Kalman Filtering¶
-
Suppose you are navigating a boat through dense fog with a jittery GPS receiver. You know roughly how fast the boat drifts from one second to the next (your motion model), and each second the GPS flashes a noisy position reading (your observation). Neither source is perfect on its own, yet blending them optimally lets you track the ship's true hidden trajectory far more accurately than trusting either alone.
-
Financial markets pose the exact same state-space problem. The observable market price \(y_t\) is polluted by bid-ask bounce and impatient order noise, whereas the hidden latent state \(x_t\) might represent true fair value, an evolving trend slope, or a time-varying hedge ratio between two correlated stocks (pairs trading).
- The Kalman filter (first introduced for Apollo spacecraft navigation and deeply linked to Bayesian inference in chapter 05) solves this linear Gaussian system online in a two-step heartbeat at every tick.
- Predict the next state estimate \(\hat{x}_{t|t-1} = F \hat{x}_{t-1|t-1}\) and grow its uncertainty \(P_{t|t-1} = F P_{t-1|t-1} F^T + Q\) because time elapsed without fresh evidence.
- Update the belief when tick \(y_t\) arrives by measuring the surprise (innovation) \(e_t = y_t - H \hat{x}_{t|t-1}\) and nudging the state using the Kalman gain \(K_t = P_{t|t-1} H^T (H P_{t|t-1} H^T + R)^{-1}\).
- Notice the elegance of \(K_t\). When measurement noise \(R\) is huge compared to process drift \(Q\), \(K_t\) stays small so the filter ignores frantic market jitter. When the true regime moves swiftly (large \(Q\)) and ticks are clean (small \(R\)), \(K_t\) approaches \(1\) so the filter snaps rapidly onto the new trend.
Modern Neural Forecasters¶
-
When Transformers conquered natural language (chapter 07), researchers naturally fed raw time-series steps into vanilla self-attention. Early results were surprisingly humbling, with simple linear models often beating massive Transformers! The reason was intuitive. A single word like "bankruptcy" carries rich meaning on its own, whereas a single scalar price tick like
101.42means almost nothing without its local slope and context. Three modern neural architectures fixed this mismatch. -
PatchTST (Nie et al., 2023) borrowed the Vision Transformer trick from chapter 08. Instead of feeding individual time steps as tokens, it slices a lookback window of length \(L\) into short contiguous patches (say, 16 consecutive steps per patch), projects each patch into a token vector, and runs self-attention across patches. Patching simultaneously shrinks quadratic attention cost dramatically and gives every token rich local shape information (rising wedge, volatility spike, reversal). Crucially, PatchTST processes each asset or feature channel-independently with shared weights, slashing overfitting on noisy multivariate finance datasets.
-
Temporal Fusion Transformer (TFT) (Lim et al., 2021) tackles messy real-world forecasting where not all inputs belong to the same category. Think of forecasting retail sales or quarterly energy demand. You have past observed series (historical prices and volumes), known future covariates (tomorrow's day of the week, scheduled central bank meetings, earnings release dates), and static metadata (industry sector, exchange, asset class). TFT routes each input through learned Variable Selection Networks (gating out irrelevant noisy features automatically), uses an LSTM encoder-decoder for sharp local patterns, applies interpretable multi-head attention over long-range regimes, and outputs calibrated multi-horizon quantiles.
-
N-BEATS (Oreshkin et al., 2020) proves you do not even need recurrence or attention to build a top-tier deep forecaster. Picture peeling an onion layer by layer. Each residual block in N-BEATS takes the input window, projects it onto basis functions (such as low-degree trend polynomials and Fourier sine/cosine waves for seasonality), and outputs two signals. Its backcast subtracts the pattern it just explained from the input, passing only the unexplained residual to the next block, while all blocks sum their forecasts together into the final prediction.
Probabilistic Forecasting and Pinball Loss¶
-
Imagine a risk officer asking your forecasting model how much a portfolio could lose next week. If you trained your network with standard Mean Squared Error (MSE), it hands back a single number (the conditional mean), say \(+0.2\%\). That single point estimate is nearly useless for managing risk. Does \(+0.2\%\) sit inside a tranquil band from \(-0.3\%\) to \(+0.7\%\), or inside a terrifying hurricane ranging from \(-12\%\) to \(+12.4\%\)?
-
Modern financial forecasting therefore predicts the entire conditional distribution via multiple quantiles \(\tau \in (0, 1)\) (for instance, the 10th, 50th, and 90th percentiles) using pinball loss (also called quantile loss).
-
Picture packing water for a desert hike. Carrying one extra litre (over-estimating) is a mild annoyance, whereas running dry mid-trail (under-estimating) is catastrophic. Pinball loss captures that exact asymmetry mathematically.
- When \(\tau = 0.90\), under-predicting (\(y > \hat{y}\)) incurs slope \(0.90\), while over-predicting (\(y < \hat{y}\)) incurs slope only \(0.10\). Under-predicting hurts nine times more, forcing the optimal prediction \(\hat{y}\) upward until \(90\%\) of outcomes fall below it!
- When \(\tau = 0.10\), over-predicting hurts nine times more, pulling \(\hat{y}\) down to the 10th-percentile crash tail (directly estimating Value at Risk).
- When \(\tau = 0.50\), both slopes equal \(0.5\), reducing pinball loss to half the Mean Absolute Error and recovering the conditional median, which is vastly more robust to fat-tailed financial outliers than MSE.
-
Summing pinball loss across several quantiles simultaneously lets a neural network draw a calibrated probabilistic fan chart whose uncertainty cone widens naturally during volatile regimes and tightens during calm markets.
Take-Home¶
- Raw prices drift non-stationarily, so financial pipelines transform prices into log returns for time-additivity and stationarity, or apply fractional differentiation (\(0 < d < 1\)) to pass the ADF test while retaining long-term price memory.
- Volatility is far more predictable than return direction, and \(\text{GARCH}(1,1)\) captures volatility clustering cleanly via \(\sigma_t^2 = \omega + \alpha r_{t-1}^2 + \beta \sigma_{t-1}^2\).
- Kalman filters separate hidden signal from tick noise through a recursive predict-and-update cycle where the Kalman gain balances model trust against incoming measurement noise.
- Modern neural forecasters match time-series structure by patching steps into local tokens (PatchTST), gating mixed static and known-future covariates (TFT), or decomposing residuals onto trend and seasonal bases (N-BEATS).
- Pinball loss replaces brittle point forecasts with asymmetric quantile bands that quantify tail risk directly for position sizing and risk management.
Coding Tasks (use CoLab or notebook)¶
-
Implement fractional differentiation \((1-B)^d P_t\) on a simulated drifting price path to observe the stationarity-versus-memory trade-off across \(d \in \{0.0, 0.35, 0.7, 1.0\}\), then fit a \(\text{GARCH}(1,1)\) model to simulated clustered returns by minimising negative log-likelihood with
jax.grad.import jax import jax.numpy as jnp import matplotlib.pyplot as plt # Part A: Fractional Differentiation on a drifting log-price series key = jax.random.PRNGKey(11) k1, k2 = jax.random.split(key) T = 400 log_price = jnp.cumsum(0.001 + 0.015 * jax.random.normal(k1, (T,))) def frac_diff(series, d, thresh=1e-3): """Apply fixed-window fractional differentiation (1 - B)^d.""" weights = [1.0] for k in range(1, len(series)): w_k = -weights[-1] * (d - k + 1.0) / k if abs(w_k) < thresh: break weights.append(w_k) w = jnp.array(weights) width = len(w) out = [jnp.dot(w, series[t - width + 1 : t + 1][::-1]) for t in range(width - 1, len(series))] return jnp.array(out), width for d in [0.0, 0.35, 0.7, 1.0]: fd, w_len = frac_diff(log_price, d) corr = float(jnp.corrcoef(log_price[w_len - 1:], fd)[0, 1]) print(f"d={d:.2f} | window={w_len:3d} | std={float(jnp.std(fd)):.4f} | corr with raw price={corr:+.3f}") # Part B: Simulate GARCH(1,1) returns and fit parameters with jax.grad true_w, true_a, true_b = 0.000015, 0.11, 0.85 z = jax.random.normal(k2, (T,)) rets, sig2_true = [], [] s2 = true_w / (1.0 - true_a - true_b) for t in range(T): r_t = float(jnp.sqrt(s2) * z[t]) rets.append(r_t) sig2_true.append(s2) s2 = true_w + true_a * (r_t ** 2) + true_b * s2 rets = jnp.array(rets) sig2_true = jnp.array(sig2_true) def garch_nll(params, r): omega = jnp.logaddexp(0.0, params[0]) * 1e-4 alpha = jax.nn.sigmoid(params[1]) * 0.45 beta = jax.nn.sigmoid(params[2]) * 0.95 # Enforce alpha + beta < 0.99 smoothly scale = jnp.minimum(1.0, 0.985 / (alpha + beta + 1e-8)) alpha, beta = alpha * scale, beta * scale s2_cur = jnp.var(r) nll = 0.0 for t in range(len(r)): nll = nll + 0.5 * (jnp.log(s2_cur + 1e-9) + (r[t] ** 2) / (s2_cur + 1e-9)) s2_cur = omega + alpha * (r[t] ** 2) + beta * s2_cur return nll / len(r) params = jnp.array([-1.0, -1.0, 1.0]) grad_fn = jax.grad(garch_nll) for step in range(90): params = params - 0.15 * grad_fn(params, rets) est_w = float(jnp.logaddexp(0.0, params[0]) * 1e-4) est_a = float(jax.nn.sigmoid(params[1]) * 0.45) est_b = float(jax.nn.sigmoid(params[2]) * 0.95) sc = min(1.0, 0.985 / (est_a + est_b + 1e-8)) est_a, est_b = est_a * sc, est_b * sc print(f"True GARCH(1,1) w={true_w:.6f}, a={true_a:.3f}, b={true_b:.3f}") print(f"Fitted GARCH(1,1) w={est_w:.6f}, a={est_a:.3f}, b={est_b:.3f}") # Reconstruct estimated volatility path est_sig, s2_cur = [], float(jnp.var(rets)) for t in range(T): est_sig.append(s2_cur ** 0.5) s2_cur = est_w + est_a * (float(rets[t]) ** 2) + est_b * s2_cur fig, axes = plt.subplots(1, 2, figsize=(12, 4)) fd_035, w_035 = frac_diff(log_price, 0.35) axes[0].plot(log_price[w_035 - 1:], color="#e74c3c", lw=1.6, label="Raw log-price (d=0)") axes[0].plot(fd_035 * 3.0, color="#27ae60", lw=1.4, label="Frac-diff d=0.35 (scaled)") axes[0].set_title("Fractional Differentiation Keeps Memory") axes[0].set_xlabel("Day") axes[0].legend() axes[1].plot(jnp.abs(rets) * 100, color="#3498db", alpha=0.35, lw=1.0, label="|Return| (%)") axes[1].plot(jnp.sqrt(sig2_true) * 100, color="#333333", lw=1.6, ls="--", label="True sigma (%)") axes[1].plot(jnp.array(est_sig) * 100, color="#9b59b6", lw=1.8, label="Fitted GARCH sigma (%)") axes[1].set_title("GARCH(1,1) Tracking Volatility Clusters") axes[1].set_xlabel("Day") axes[1].legend() plt.tight_layout() plt.show() -
Build a 1D local-level Kalman filter from scratch to recover a smooth hidden fair-value trajectory buried inside noisy market ticks, and compare how low versus high process-to-measurement noise ratio (\(Q/R\)) changes filter responsiveness and steady-state Kalman gain.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(7) k1, k2 = jax.random.split(key) T = 180 true_Q, true_R = 0.08, 1.4 # Hidden fair value with regime drift + random walk shocks step_drift = jnp.where(jnp.arange(T) < 90, 0.06, -0.05) x_true = 100.0 + jnp.cumsum(step_drift + jnp.sqrt(true_Q) * jax.random.normal(k1, (T,))) y_obs = x_true + jnp.sqrt(true_R) * jax.random.normal(k2, (T,)) def run_kalman_1d(obs, Q, R): """1D random-walk state-space Kalman filter (F=1, H=1).""" x_hat = float(obs[0]) P = 5.0 xs, gains = [], [] for y_t in obs: # Predict x_pred = x_hat P_pred = P + Q # Update K = P_pred / (P_pred + R) x_hat = x_pred + K * (float(y_t) - x_pred) P = (1.0 - K) * P_pred xs.append(x_hat) gains.append(K) return jnp.array(xs), jnp.array(gains) x_smooth, K_smooth = run_kalman_1d(y_obs, Q=0.08, R=1.4) x_fast, K_fast = run_kalman_1d(y_obs, Q=1.2, R=1.4) rmse_raw = float(jnp.sqrt(jnp.mean((y_obs - x_true) ** 2))) rmse_opt = float(jnp.sqrt(jnp.mean((x_smooth - x_true) ** 2))) rmse_fast = float(jnp.sqrt(jnp.mean((x_fast - x_true) ** 2))) print(f"RMSE vs True Value | Raw ticks={rmse_raw:.3f} | Tuned Kalman={rmse_opt:.3f} | Over-reactive Kalman={rmse_fast:.3f}") print(f"Steady-state Kalman Gain | Tuned={float(K_smooth[-1]):.3f} | Over-reactive={float(K_fast[-1]):.3f}") fig, axes = plt.subplots(1, 2, figsize=(12, 4)) axes[0].scatter(jnp.arange(T), y_obs, s=10, alpha=0.4, color="#666666", label="Noisy Market Ticks") axes[0].plot(x_true, color="#333333", lw=2.0, ls="--", label="Hidden True Value") axes[0].plot(x_smooth, color="#f39c12", lw=2.2, label="Tuned Kalman Filter") axes[0].plot(x_fast, color="#e74c3c", lw=1.2, alpha=0.75, label="High-Q (Noisy) Filter") axes[0].set_xlabel("Time Step") axes[0].set_ylabel("Price") axes[0].set_title("Kalman Filter Separating Latent Value from Noise") axes[0].legend() axes[1].plot(K_smooth, color="#f39c12", lw=2.0, label="Tuned K_t (Q=0.08, R=1.4)") axes[1].plot(K_fast, color="#e74c3c", lw=2.0, label="Reactive K_t (Q=1.2, R=1.4)") axes[1].set_xlabel("Time Step") axes[1].set_ylabel("Kalman Gain K_t") axes[1].set_title("Kalman Gain Converges Quickly to Optimal Blend") axes[1].legend() plt.tight_layout() plt.show() -
Train a small multi-quantile neural forecaster in JAX with asymmetric Pinball Loss for \(\tau \in \{0.10, 0.50, 0.90\}\) on a synthetic time series whose volatility expands with time, then plot the predicted probabilistic uncertainty band and verify empirical quantile coverage.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(2026) k1, k2, k3 = jax.random.split(key, 3) # Synthetic heteroscedastic data: wider swings as feature x (volatility proxy) grows N = 300 x = jnp.linspace(0.0, 1.0, N)[:, None] true_mean = jnp.sin(2.0 * jnp.pi * x[:, 0]) * 0.45 true_sigma = 0.08 + 0.42 * (x[:, 0] ** 1.4) y = true_mean + true_sigma * jax.random.normal(k1, (N,)) taus = jnp.array([0.10, 0.50, 0.90]) ka, kb = jax.random.split(k2) W1 = jax.random.normal(ka, (1, 10)) * 0.8 b1 = jnp.zeros((10,)) W2 = jax.random.normal(kb, (10, 3)) * 0.3 b2 = jnp.zeros((3,)) def forward(W1, b1, W2, b2, x_in): h = jax.nn.tanh(jnp.dot(x_in, W1) + b1) return jnp.dot(h, W2) + b2 def pinball_loss(W1, b1, W2, b2, x_in, y_true): preds = forward(W1, b1, W2, b2, x_in) # (N, 3) err = y_true[:, None] - preds # (N, 3) loss = jnp.maximum(taus * err, (taus - 1.0) * err) return jnp.mean(loss) grad_fn = jax.grad(pinball_loss, argnums=(0, 1, 2, 3)) lr = 0.25 for step in range(280): gW1, gb1, gW2, gb2 = grad_fn(W1, b1, W2, b2, x, y) W1 = W1 - lr * gW1 b1 = b1 - lr * gb1 W2 = W2 - lr * gW2 b2 = b2 - lr * gb2 q_preds = forward(W1, b1, W2, b2, x) for i, tau in enumerate([0.10, 0.50, 0.90]): cov = float(jnp.mean(y <= q_preds[:, i])) print(f"Target quantile tau={tau:.2f} | Empirical coverage={cov:.3f}") plt.figure(figsize=(10, 4.2)) plt.scatter(x[:, 0], y, s=12, alpha=0.35, color="#666666", label="Observed Outcomes") plt.fill_between(x[:, 0], q_preds[:, 0], q_preds[:, 2], color="#3498db", alpha=0.20, label="Predicted 10% to 90% Band") plt.plot(x[:, 0], q_preds[:, 1], color="#3498db", lw=2.2, label="Predicted Median (q=0.50)") plt.plot(x[:, 0], q_preds[:, 0], color="#e74c3c", lw=1.4, ls="--", label="10th Percentile (Tail Risk)") plt.plot(x[:, 0], q_preds[:, 2], color="#27ae60", lw=1.4, ls="--", label="90th Percentile (Upside)") plt.xlabel("Forecast Horizon / Volatility Regime") plt.ylabel("Asset Return") plt.title("Multi-Quantile Neural Forecaster Trained with Pinball Loss") plt.legend(loc="upper left") plt.tight_layout() plt.show()