SStatistics, Built

Stage III · Master's

Part 38 of 65

Time Series in Depth

Master'sstarts at this level53 min of film14 chaptersprerequisites: Part 17, Part 22

What changes when memory is long, the variance moves, or the state is hidden?

Hurst measures the Nile for a dam and finds that the rescaled range of its yearly minima grows like n to the 0.85, where white noise gives about a half. Part 17 assumed stationary series with short memory and constant variance, fully observed, and this part drops each assumption in turn. The periodogram is inconsistent until it is smoothed. A unit root gives the Dickey-Fuller statistic a Brownian limit, so the normal critical value rejects 45.6% of true random walks, and two independent walks regress on each other with a significant slope 77% of the time. GARCH lets the variance cluster on the DAX, and fractional differencing gives the Nile's long memory a model in which 663 years are worth about 3.5. Then the state is hidden: the Kalman filter tracks the Nile's level at Aswan and finds its fall into 1899, with smoothing, EM, particle filters and Hamilton's regimes after it. The part ends with VARs, the block bootstrap and how forecasters are evaluated without leakage.

What you need. The ACF, ARMA models and forecasting of Part 17, and likelihood (Part 22).

Hook
Hurst's Nile, 1951
Mathematics
spectra, unit roots and Dickey–Fuller, cointegration, GARCH, long memory, Kalman, VARs, particle filters
Built
statkit.ts (II)

What you will be able to do

Bachelor's

  • Explain Hurst's rescaled range and what an exponent well above one half says about a series.
  • Name the four things Part 17 assumed and recognize a path that breaks each.

Master's

  • Test for a unit root with the Dickey-Fuller statistic and its own critical values, and for cointegration with Engle-Granger.
  • Fit a GARCH(1,1) and forecast its variance h steps ahead.
  • Run the Kalman filter and the RTS smoother for a local-level model and estimate its two variances by the prediction-error likelihood.

PhD

  • Derive the hyperbolic decay of an ARFIMA's autocorrelations and the rate at which the variance of the mean falls under long memory.
  • Compare the EKF, the UKF and the bootstrap particle filter on a nonlinear state equation and say what each approximates.

Practice

  • Evaluate a forecaster by rolling origin with MASE against naive benchmarks, and recognize selection on the test outcomes as leakage.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 9 min · Master's 45 min · PhD 53 min · Practice 13 min.

  1. 0Hurst's NileBachelor's4 min
  2. 1What Part 17 assumedBachelor's3 min
  3. 2SpectraMaster's4 min
  4. 3Unit rootsMaster's4 min
  5. 4Spurious regression and cointegrationMaster's4 min
  6. 5VolatilityMaster's5 min
  7. 6Long memoryPhD4 min
  8. 7State space and the Kalman filterMaster's4 min
  9. 8Smoothing and learningMaster's4 min
  10. 9Nonlinear filtering and regimesPhD4 min
  11. 10VARs and Granger causalityMaster's4 min
  12. 11The block bootstrapMaster's3 min
  13. 12The forecasting frontierPractice3 min
  14. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.

Hurst's NileBachelor's4 min

Harold Edwin Hurst went to Egypt in 1906 and spent most of the next sixty years measuring the Nile. His question was practical: how big must a reservoir be to carry Egypt through a run of dry years, releasing the average flow every year? The answer depends on the range of the river's cumulative surplus and deficit. For independent finite-variance yearly increments, the typical range grows like the square root of the number of years. In 1951 Hurst reported that for the Nile, and for hundreds of other records of rivers, rainfall, tree rings and lake sediments, it grew faster, like the number of years to a power of about seven tenths or more.

Here is one of his records, from the Roda gauge on an island in Cairo: the yearly minimum level of the Nile from 622 to 1284, compiled by Prince Omar Toussoun in 1925. Six hundred and sixty-three years. Look at the long excursions: decades above the average, then decades below, at every scale. A series of independent years, or one with the short memory of Part seventeen's autoregressions, wanders back to its mean much faster.

Here we illustrate Hurst's construction using minimum water levels, not flow volumes. Add up each year's departure from the long-run mean: a cumulative level anomaly. For a flow-volume record, the analogous curve describes idealized storage while releasing the mean flow. The range of that curve summarizes cumulative deviations; for flow volumes under idealized operation it measures storage the reservoir needs. Divide it by the standard deviation to make it comparable across rivers: the rescaled range, R over S.

Compute R over S in blocks of every length, and plot it against the block length on log scales. The slope is Hurst's exponent, H. For the Nile's minima it is . White noise of the same length gives about , a little above one half in samples this short. Even an autoregression fitted to the Nile, with the same correlation between neighbouring years, gives only about . These summaries suggest persistent dependence; they do not by themselves prove a fractional model.

Benoit Mandelbrot and James Wallis named it the Joseph effect in 1968, after Pharaoh's dream of seven years of great plenty followed by seven years of famine. Persistence at every scale is now called long memory, and it breaks the short-memory models of Part seventeen. Hurst's analysis fed into the planning of the Aswan High Dam, built in the 1960s with storage for years of flow, not one.

Part seventeen's series were stationary, with short memory and constant variance, and everything was observed. This part asks what changes when the memory is long, or when a series wanders with no mean to return to. When the variance itself moves, as in financial markets. And when the thing we care about cannot be seen, only noisy measurements of it. The tools: spectra, unit-root tests, volatility models, long-memory models, the state space and the Kalman filter, and vector autoregressions.

Numbers: H = 0.85 vs 0.56

1What Part 17 assumedBachelor's3 min

Part seventeen built autoregressive and moving-average models, fitted them by Yule-Walker and least squares, and forecast with intervals. It assumed a constant mean and variance, autocorrelations that die away quickly, and a series we observe directly. This part lets each assumption go in turn.

Four seeded series. First, Part seventeen's world: an autoregression that forgets quickly and returns to its mean. A random walk: the same shocks, accumulated forever, so the series has no mean to return to and its variance grows without bound. Chapters three and four. A GARCH series: no correlation in the values at all, but calm stretches and storms, because the variance depends on recent shocks. Chapter five. And fractionally integrated noise: stationary, with a mean, but with excursions that last much longer than an autoregression's, the Nile's long memory. Chapter six.

Herman Wold proved in 1938 that every covariance-stationary square-integrable series, after removing its linearly deterministic part, is a moving average of past uncorrelated shocks, with weights that die away. A unit root is a series whose weights never die away: a shock today moves the series forever. Long memory has weights that do die away, but so slowly, like a power of the lag, that the autocorrelations cannot be added up. And GARCH keeps the shocks uncorrelated but not independent: their sizes are predictable even though their signs are not. Wold's theorem speaks only of correlations.

One thing every time-series method assumes quietly. We observe one realization: one Nile, one stock index, one history. Probability talks about averages over many possible histories. Ergodicity is the property that lets an average over time stand in for an average over realizations: the sample mean of one long series converges to the expected value. Stationarity with sufficient mixing is one route to ergodicity. Vanishing autocovariances suffice for mean convergence in mean square, but not for full ergodicity. Unit roots need different asymptotics, and long memory can make mean convergence very slow. Different methods in this part require different stationarity, ergodicity or nonstationary limit conditions. Leaving Part seventeen's world requires checking which conditions survive.

There is a fifth departure. The series we care about may be hidden: a position, a level, a state of the economy. We see only noisy measurements, and the state underneath must be inferred. Kalman's filter, in chapters seven to nine, does that by Gaussian conditioning, one step at a time. But first, a different way to look at any stationary series: one frequency at a time.

Numbers: four departures; ergodicity

2SpectraMaster's4 min

Gustav Herglotz's theorem says that every stationary autocovariance function is the Fourier transform of a non-decreasing function on the frequencies from minus a half to a half cycle per observation. When the autocovariances are summable, that function has a density, the spectrum, which is the Fourier transform of the autocovariances. For an autoregression it is the noise variance divided by the squared modulus of the autoregressive polynomial on the unit circle, with a peak at the frequency of any pseudo-cycle. The spectrum integrates to the variance: it says how the variance is shared among frequencies. It holds the same information as the autocorrelations, arranged by frequency rather than by lag.

Yearly sunspot numbers, 1700 to 2008. The apothecary Heinrich Schwabe noticed a cycle of about ten years in 1843, and in Part seventeen we fitted Yule's autoregression of 1927 to it. An autoregression of order two, fitted here, has a pseudo-period of years. Where in frequency does the variance live?

The natural estimate of the spectrum is the periodogram: the squared size of the series' Fourier coefficient at each frequency. For white noise, the true spectrum is flat, at one. With a hundred and twenty-eight observations, the periodogram scatters wildly around it. With sixteen times as many, it scatters just as wildly; there are just more points. Each interior positive-frequency ordinate is asymptotically the true spectrum times an exponential variable, with a standard deviation equal to its mean, however long the series. For white noise it is exactly unbiased; more generally it is asymptotically unbiased under regularity conditions, but inconsistent without smoothing. The cure is to average. Peter Welch, in 1967, cut the series into overlapping segments, tapered each to reduce leakage, and averaged their periodograms: the spread falls to .

The arithmetic: at distinct interior frequencies of a regular short-memory process, a periodogram ordinate is asymptotically the true spectrum times a chi-square on two degrees of freedom, halved, and different Fourier frequencies are nearly independent. Welch's averages reduce the variance, at the cost of resolution, because each segment is shorter. David Thomson's multitaper method of 1982 instead multiplies the whole series by several orthogonal tapers, the Slepian sequences that concentrate their energy best in a narrow band, and averages those periodograms. Either way it is Part twenty-nine's trade between bias and variance: spectral estimation is a smoothing problem.

The sunspot spectrum, on a log scale. The raw periodogram, in grey, has its highest point at years, surrounded by noise. Welch's estimate smooths it into a single clear peak near frequency zero point zero nine, about eleven years. The multitaper estimate agrees, with finer detail. And the two-parameter autoregression's spectrum puts a smooth peak in the same place: Yule's model is a smoothed spectrum.

The spectrum and the autocorrelation function are one object, written in two bases. Periodograms need smoothing, and an apparent peak needs a null spectrum to be judged against, or every noisy series seems to cycle. And the frequency view shows the next two departures at a glance: a random walk has no ordinary stationary spectrum; its formal frequency response diverges at zero. Stationary fractional long memory has a pole there that can still be integrated. Next, the series with no mean to return to.

Numbers: 11-year sunspot cycle

3Unit rootsMaster's4 min

Two series driven by the same shocks. In red, a random walk: each value is the last plus a shock, so every shock is permanent and the variance grows with time. In blue, an autoregression with coefficient point nine: shocks fade, slowly, and the series returns to zero. Over two hundred steps they can look alike. Whether a series like gross domestic product has a unit root decides whether a recession is ever made up, whether forecasts revert, and, chapter four, whether regressions on it mean anything.

David Dickey and Wayne Fuller's test, of 1979, regresses the change in the series on its last level, with lagged changes to absorb short-run dynamics. A unit root means the coefficient on the level is zero; a stationary series pulls back, with a negative coefficient. The catch: under the unit root, the usual t statistic does not converge to a normal. Scaled sums of a random walk converge to integrals of Brownian motion, by the functional central limit theorem that Part forty-four proves, and the statistic converges to a ratio of such integrals. Its distribution is skewed to the left, and its five percent point, with a constant in the regression, is minus two point eight six, not minus one point six four.

Twenty thousand random walks of length one hundred, each tested with a constant in the regression. In grey, the normal curve the ordinary t table assumes. The real distribution sits well to its left, centred near minus one and a half. A test that rejects the unit root when tau is below minus one point six four five rejects percent of the time when the unit root is true. James MacKinnon's critical value for this sample size, minus two point eight nine, is close to the simulated five percent point, .

Dickey and Fuller's null hypothesis is the unit root, so failing to reject it is weak evidence for it. A stationary series with coefficient nought point nine five is hard to tell from a random walk in a few decades of data, and the test's power is low. Denis Kwiatkowski, Peter Phillips, Peter Schmidt and Yongcheol Shin reversed the roles in 1992: their KPSS test takes stationarity as the null, and rejects when the partial sums of the deviations wander too far. Using both gives four rejection patterns. One may support a unit-root or stationary model, but neither outcome proves the null. Both rejected suggests misspecification; neither rejected means the data cannot tell.

A further complication. Pierre Perron showed in 1989 that a stationary series moving around a trend that shifts once looks, to the Dickey-Fuller test, like a unit root: the test mistakes one permanent change for an accumulation of permanent shocks. Allowing breaks at the 1929 crash and the 1973 oil shock, he rejected unit roots in many of Nelson and Plosser's series. Eric Zivot and Donald Andrews then let the data choose the break date, which changes the critical values again, because searching for the best break is another garden of forking paths. The honest conclusion for many economic series is that persistence is high, and its exact form is hard to pin down.

US quarterly data, 1959 to 2009. Log real gross domestic product: the Dickey-Fuller test, allowing a trend, cannot reject a unit root, and KPSS rejects trend-stationarity. This pattern is consistent with a unit root, as Charles Nelson and Charles Plosser argued for most US series in 1982. Unemployment, the Treasury-bill rate and inflation: neither test rejects. These tests with these deterministic terms and lag choices do not settle whether these series revert. The growth rate of GDP: Dickey-Fuller rejects the unit root decisively, and KPSS does not reject stationarity. Differencing a unit-root series gives a stationary one.

Numbers: 46% vs 5%

4Spurious regression and cointegrationMaster's4 min

Part seventeen met Yule's nonsense correlations of 1926. Here is their modern form. Two random walks, generated independently. Plot one against the other and fit a line. The line has a steep slope, a high R squared, and a t statistic that any journal would accept. Yet the two series have nothing to do with each other.

Five thousand such pairs. The green band holds the t statistics a five percent test would accept. The real statistics spread far beyond it: the test declares a significant relationship percent of the time. Clive Granger and Paul Newbold found seventy-six percent in 1974, and suggested a rule of thumb: be suspicious when R squared exceeds the Durbin-Watson statistic. Peter Phillips explained it in 1986: with two unit roots, the slope does not converge, and the t statistic grows like the square root of the sample size. More data makes the nonsense more significant.

But some wandering series really are tied together. Each has a unit root on its own; but some combination of them is stationary. Robert Engle and Clive Granger called such series cointegrated, in 1987. A drunk and her dog both wander, but the leash keeps them close. Cointegrated series obey an error-correction model: when they drift apart, the gap pulls them back. To test, estimate the combination by regression, and test its residuals for a unit root. Because the regression has already chosen the most stationary-looking combination, the critical values are stricter than Dickey and Fuller's: minus three point three seven for two series and a hundred observations. Engle and Granger shared the 2003 Nobel prize, Engle for chapter five.

Friedman's permanent-income theory suggests consumption and income should be tied: people spend a stable share of what they expect to earn. US log consumption and log disposable income, 1959 to 2009. Neither individual ADF test rejects a unit root under the displayed trend specification. The regression of one on the other has a slope of : one for one. The residual, the gap between consumption and income, wanders less, but it wanders.

When series are cointegrated, the regression has a surprising property. The slope converges to the truth at rate T rather than the square root of T, because any wrong slope leaves a residual that wanders off as a random walk, which least squares punishes heavily. James Stock called it super-consistency in 1987. Its limiting distribution can be mixed or nonstandard and nuisance-dependent, so ordinary least-squares standard errors and the usual t test on the slope is still wrong. Fully modified least squares, of Peter Phillips and Bruce Hansen, and dynamic least squares, of Stock and Mark Watson, correct it. And the error-correction coefficient says how quickly a gap between the series closes.

The Engle-Granger test on the residual gives minus , short of the critical value of minus three point three seven: it cannot reject that there is no cointegration. Søren Johansen's method of 1988 works with all the series at once, in a vector autoregression in levels, and estimates how many independent stationary combinations there are, from canonical correlations between changes and lagged levels. With consumption, income and investment, the trace test rejects zero relations, against a critical value of , and does not reject one. The sequential test selects one relation, barely; that is evidence under the chosen lag and deterministic specification, not proof of the rank. With two hundred quarters, cointegration tests, like unit-root tests, have little power, and the economics has to carry part of the argument.

Numbers: 77%; trace 30.2 vs 29.8

5VolatilityMaster's5 min

The German stock index, the DAX, at every close from July 1991 to August 1998. Its daily returns, in percent. They hover around zero with no visible pattern in their signs. But the size of the moves comes in clusters: calm months, then turbulent ones, as in late 1997 and the summer of 1998. The largest fall, almost ten percent in a day, came in August 1991, with the attempted coup in Moscow.

The autocorrelations of the returns, in grey, are inside the band of noise: this plot shows little linear predictability in returns; it does not rule out every form of predictability. But the autocorrelations of their absolute sizes, in red, are positive for weeks: a big move, of either sign, predicts more big moves. The returns' kurtosis is , three times the normal's: extreme days are far more common than a normal distribution allows. Robert Engle's test for this clustering, regressing squared returns on their own lags, rejects decisively. Benoit Mandelbrot had described the same facts in cotton prices in 1963: these are the stylized facts of financial returns.

The model writes each return as a mean plus a standard deviation that changes over time, times an independent shock. Engle's autoregressive conditional heteroskedasticity, ARCH, of 1982, made today's variance a weighted sum of recent squared shocks. He applied it to inflation in the United Kingdom. His student Tim Bollerslev's generalization of 1986, GARCH, adds yesterday's variance itself, so that one extra parameter gives a long, geometrically decaying memory. With positive omega, nonnegative coefficients and alpha plus beta below one, the stationary return process has a finite unconditional second moment. Its conditional variance forecasts revert at rate alpha plus beta per day; stationarity of the variance process in a stronger moment sense can require more.

Fitted to the DAX by maximum likelihood: alpha , beta . The red band is plus and minus two conditional standard deviations. It widens in the storms and narrows in the calms, following the returns. Alpha plus beta is : a burst of volatility halves in about trading days, three weeks. Values this close to one are typical of daily financial data.

GARCH also forecasts. The long-run variance is omega over one minus alpha minus beta: for the DAX, a daily standard deviation of about percent. The forecast of the variance h days ahead is the long-run level plus the current excess, shrunk by alpha plus beta for every day. A month of trading days ahead, of the one-day variance forecast's excess over the long-run level remains at horizon twenty-one. So volatility forecasts revert, geometrically, to the long-run level: the term structure of volatility that option prices and risk limits are built on.

Here is a retrospective diagnostic using parameters fitted to the whole record, not an out-of-sample backtest. A bank's one-day value at risk at one percent is the loss it should exceed on one day in a hundred. With a constant variance and a normal distribution, the DAX breaches it on percent of days overall, but on fewer than one in a hundred calm days and about three in a hundred turbulent ones: the breaches cluster, exactly when they hurt. With the fitted GARCH variance, the breach rates in these two volatility groups are closer. Equal group rates alone do not establish independent violations. Both still exceed one percent overall, consistent with heavier standardized tails and possible model misspecification relative to the normal. Student t innovations or empirical residual quantiles may help, but need fresh validation; robust location methods alone do not guarantee accurate tail risk.

The lesson is that uncorrelated is not independent: the sign of tomorrow's return is unpredictable, but its size is not. The family has grown: exponential GARCH lets falls raise volatility more than rises; stochastic volatility models; and realized volatility, measured from intraday prices. Stochastic volatility treats the variance as a hidden state, the subject of the filters in chapters seven to nine. Engle received the 2003 Nobel prize for methods of analyzing economic time series with time-varying volatility.

Numbers: α + β = 0.956

6Long memoryPhD4 min

Clive Granger and Roselyne Joyeux, in 1980, and Jonathan Hosking, in 1981, found a model with Hurst's behaviour: difference the series a fractional number of times. Differencing once gives a random walk's increments; differencing d times, with d between zero and a half, is defined by the binomial series. Its weights decay like a power of the lag. So do its autocorrelations: like the lag to the power two d minus one, rather than geometrically. For d below a half the series is stationary, but its autocorrelations sum to infinity, and Hurst's exponent is d plus a half. Combined with autoregressive and moving-average terms it is called ARFIMA.

The Nile minima's sample autocorrelations, in grey, for lags up to sixty years. They start near point six and stay positive for decades. An autoregression with the same lag-one correlation as the fractional reference, in blue, has forgotten within ten years. A fractionally integrated series with d equal to point four, in gold, decays like a power, and still remembers at lag sixty. The river looks like the gold curve.

Long memory is a statement about the lowest frequencies: near zero, the spectrum grows like the frequency to the power minus two d. So d can be estimated from the lowest frequencies alone, whatever the short-run dynamics. John Geweke and Susan Porter-Hudak, in 1983, regressed the log periodogram on the log of the frequency term. On the Nile minima their estimate moves from to as the number of frequencies changes: the bandwidth matters, as always. Peter Robinson's local Whittle estimator is more efficient: d is , with a standard error of , so Hurst's exponent is about .

The consequence is stark. With long memory, the variance of a sample mean shrinks like n to the power two d minus one, not like one over n. For the six hundred and sixty-three years of minima, the textbook standard error of the mean level is . If the fractional model with d of holds with the plug-in marginal variance, the model-based standard error is about , times larger. Six centuries of measurements carry about as much information about the long-run mean as independent years. That is what Hurst's reservoir was telling him.

Long memory turned up far from the Nile. Will Leland, Murad Taqqu, Walter Willinger and Daniel Wilson found in 1994 that Ethernet traffic is bursty at every time scale, from milliseconds to hours, which changed how networks were designed. Financial absolute returns have sometimes been found to have autocorrelations that decay more slowly than a short GARCH model predicts. That can motivate alternatives when estimated persistence is so close to one. Temperature records, river flows and inflation rates show it too. In each case, averages are less precise than independent-data formulas say, and averaging over longer periods helps less than one would hope.

A caveat. Occasional shifts in the mean, or regimes that change slowly, produce the same statistics. Francis Diebold and Atsushi Inoue showed in 2001 that switching models generate Hurst-like behaviour. With a single series, a fractional process and a stationary series with occasional breaks are hard to tell apart; the separate Aswan flow record fell abruptly around 1899, as chapter seven will show. Either way, the practical lesson stands: the long-run mean is far less certain than the textbook standard error claims.

Numbers: d = 0.41; n_eff = 3.5

7State space and the Kalman filterMaster's4 min

A state-space model has two equations. The state, which we cannot see, evolves linearly with Gaussian noise: a position and velocity, a river's underlying level, an economy's trend. We observe a linear function of it, plus noise. Before each observation, our belief about the state and the observation we expect are jointly Gaussian, assuming a Gaussian initial state and independent process and measurement noises. So after observing, the state's conditional distribution is Gaussian too, by the conditional-normal formula of Part five. The mean moves toward the observation by the gain K times the surprise, and the variance shrinks. That is the whole of the Kalman filter.

Watch it as ellipses. A target moves with nearly constant velocity; we measure only its position, with noise. The state is two-dimensional: position across, velocity up. Each step, the prediction carries the last ellipse forward. Position moves by the velocity, so the ellipse shears and grows. The measurement says only where the position is, a vertical band; it says nothing directly about velocity. The update is the intersection, in the Gaussian sense: an ellipse narrower in position, and, because the predicted position and velocity were correlated, narrower in velocity too. Velocity is learned without ever being measured. Step after step, the ellipses settle into a steady size, tracking the true state in gold.

In equations: predict the mean and covariance forward through the dynamics. Compare the observation with its prediction: the innovation, with its variance. Update by the gain. Rudolf Kálmán published the recursion in 1960; it needs only the last mean and covariance, not the whole history, which made it practical on the computers of the day. And an ignorable missing observation needs no measurement update: predict again, with greater uncertainty. Informative missingness requires modelling the observation process.

For the local level the gain is the predicted variance over the predicted variance plus the noise variance. After a few steps it settles to a steady state, a fixed number determined by the ratio of the two variances. And then the filter's update is a weighted average of the new observation and the old level: Part seventeen's simple exponential smoothing, exactly. John Muth noticed this in 1960. For the Nile the signal-to-noise ratio of gives a gain of . The state space explains why exponential smoothing works, and lets the likelihood choose its smoothing constant.

The Nile again, now its annual flow at Aswan from 1871 to 1970, the standard example of James Durbin and Siem Jan Koopman's textbook. The simplest state-space model, the local level, says the river has an underlying level that drifts as a random walk, and each year's flow is that level plus noise. Maximizing the likelihood gives a level variance of about fifteen hundred and a noise variance of about fifteen thousand: approximately the values in Durbin and Koopman's book, with a finite diffuse-prior approximation. The filtered level, in blue with its ninety percent band, follows the flows only slowly, discounting each year's surprise by the gain.

Using all the data, past and future, gives the smoothed level, in green, the subject of chapter eight. Its biggest one-year fall comes into 1899. Adding a permanent shift at 1899 to the model, the likelihood picks a fall of about three hundred, and the likelihood improvement statistic of is descriptive. The variances are held at their no-shift estimates, and the date was inspected in this same record, so this is not a calibrated likelihood-ratio test. Work on the first dam at Aswan began in 1898, and the climate of the basin became drier around the same time. This is evidence to investigate a level change, not causal attribution to the dam or a proof that the process broke.

Numbers: 1,469 / 15,099; K = 0.27

8Smoothing and learningMaster's4 min

The filter answers a real-time question: given everything up to now, where is the state? Afterwards we can ask a better one: given all the data, where was it? Herbert Rauch, Frank Tung and Charlotte Striebel's smoother of 1965 runs the filter forward, then a second pass backward, correcting each filtered mean by what the next smoothed value turned out to be. The smoothed variances are never larger than the filtered ones, because more data never hurts a Gaussian.

Durbin and Koopman's demonstration: hide two twenty-year stretches of the Nile's record. This illustration holds the noise variances at estimates from the complete record, so it is not an honest missing-data forecasting benchmark. The filter simply predicts through them, and the smoother then interpolates the level across each gap, using the years on both sides. Its band widens towards the middle of each gap, where the nearest data are furthest away, and narrows again at the edges. The deleted flows, in grey, scatter around the interpolated level as the noise variance says they should.

Where did the two variances come from? Any joint density factors into one-step-ahead conditional densities, and for a Gaussian state space each is the density of an innovation. So the filter computes the likelihood as a by-product, the prediction-error decomposition of Fred Schweppe in 1965. Maximizing it takes one filter pass per evaluation, the method of Part twenty-two. Or, as Robert Shumway and David Stoffer showed in 1982, treat the states as missing data and use the EM algorithm: smooth, then update the variances in closed form.

EM on the Nile, from a poor start. The likelihood rises with every iteration, as Part twenty-two proved it must: quickly at first, then slowly, EM's usual pace. After three hundred iterations it has reached the same variances as direct maximization. This run approaches the direct solution; EM in general can converge slowly or reach a local stationary point. It extends naturally to models with many parameters, where a direct search would struggle.

The state can hold many components at once: a level, a slope, a seasonal pattern, the effects of regressors or interventions. Andrew Harvey's structural time-series models of 1989 make each a small random walk, so that trends and seasons can evolve. One Kalman filter estimates them all together, handles missing observations, and delivers the likelihood. Every ARIMA model of Part seventeen can be written in state-space form too, so the state space is one framework for almost everything in this part.

The filter's first great application came within a year of its publication. Kálmán visited Stanley Schmidt at NASA's Ames Research Center, which was studying navigation for a voyage to the Moon. Schmidt's group linearized the equations of motion around the current estimate of the trajectory, creating the extended Kalman filter of the next chapter. Apollo's onboard navigation used it. Today descendants of Kálmán's filter run in satellite navigation, every phone, aircraft, and, as ensemble filters with millions of states, in weather forecasting.

Numbers: EM → MLE

9Nonlinear filtering and regimesPhD4 min

When the dynamics or the measurement are nonlinear, the state's distribution is no longer Gaussian, and the ellipses no longer tell the truth. The extended filter linearizes the functions at the current estimate and applies Kalman's equations. Simon Julier and Jeffrey Uhlmann's unscented filter, of 1997, instead pushes a few carefully placed sigma points through the nonlinearity and fits a Gaussian to where they land. And the particle filter of Neil Gordon, David Salmond and Adrian Smith, in 1993, met in Part twenty-seven, drops the Gaussian altogether: it carries thousands of samples forward, weights each by how well it explains the new observation, and resamples.

The standard test, used by Gordon and his colleagues: a state that swings between positive and negative values, observed through its square, so the sign is never measured directly. The truth is in gold. The extended filter, in red, often locks onto the wrong sign and stays there, because its linearization cannot represent two possibilities at once. The particle filter, in blue, can retain both modes. The plotted central quantile band spans them rather than splitting, and can include low-density states; its mean can lie between modes.

Over thirty simulated series: the extended filter's error is about . The unscented filter halves it. The particle filter cuts it to about , with a much larger particle population; no wall-time ratio is measured here. When the distribution is close to Gaussian, Kalman's equations or their extensions are cheaper and nearly as good.

The particle filter also gives a likelihood. The average of each step's unnormalized weights, multiplied over time, is an unbiased estimate of the likelihood of the parameters. Christophe Andrieu, Arnaud Doucet and Roman Holenstein showed in 2010 that plugging this noisy but unbiased estimate into a Metropolis-Hastings sampler still targets the exact posterior: particle Markov chain Monte Carlo. With a nonnegative unbiased likelihood estimate and the extended-state construction, its invariant parameter distribution is the exact posterior. Finite MCMC runs still require convergence checks. Stochastic volatility, epidemic models and animal populations are fitted this way: the ideas of Part twenty-seven, at scale.

A hidden state can also be discrete. James Hamilton's model of 1989 lets the economy switch between two regimes, recession and expansion, following a Markov chain. Growth has a different mean in each. The filter is the same recursion with two points instead of a Gaussian: predict the regime probabilities with the transition matrix, then reweight them by how likely this quarter's growth is under each. The product of the normalizing constants is the likelihood, maximized as before.

US real growth, quarter by quarter, annualized, 1959 to 2009. Hamilton's model finds one regime growing at about percent a year and another shrinking at about percent, lasting on average and quarters. The filtered probability of the low regime, in red, rises in the recessions that the National Bureau of Economic Research later dated by committee, in grey: an average of inside them and outside, filtered using GDP observations only up to each displayed quarter, but with parameters estimated from the entire sample. This is a retrospective filter, not a real-time forecast evaluation.

Numbers: RMSE 20.6 / 10.5 / 4.4

10VARs and Granger causalityMaster's4 min

Three US quarterly series, 1959 to 2009: inflation, unemployment, and the three-month Treasury-bill rate, which tracks the Federal Reserve's policy. They move together: the inflation of the 1970s, the high interest rates of the early 1980s that ended it, the recessions that followed. Which drives which?

A vector autoregression regresses each series on lags of all the series. Christopher Sims proposed it in 1980, in a paper called Macroeconomics and Reality, as an alternative to large models with what he called incredible restrictions. It is fitted by least squares, one equation at a time. Clive Granger's definition of 1969: x Granger-causes y if past x helps forecast y, given past y and the other included series; in a correctly specified linear VAR, an F test on x's lags in y's equation. Impulse responses trace how a shock to one variable moves all of them over time. Since the shocks are correlated, isolating one needs a decision: the Cholesky factorization assumes an ordering, in which later variables react to earlier ones within the quarter but not the reverse.

A VAR with four lags, a year of quarters. Inflation helps forecast unemployment and the T-bill rate; unemployment helps forecast the T-bill rate, as a central bank reacting to the economy would; and the T-bill rate helps forecast inflation. Unemployment does not help forecast inflation here, and the rate does not significantly help forecast unemployment. Granger causality is a statement about forecasting. A variable can Granger-cause another because both respond, at different speeds, to a third, or because people act today on what they expect tomorrow.

The responses to a surprise rise in the T-bill rate, interpreted as monetary tightening only under the recursive identifying assumptions, with the rate ordered last so that it can react to inflation and unemployment within the quarter. Unemployment rises, slowly, over two to three years, as textbooks say it should. But inflation rises too, at first. Sims noticed this price puzzle in 1992. The usual explanation is that the Federal Reserve raises rates when it sees inflation coming, from information the VAR does not have, so the 'shock' is partly a forecast. Adding information variables such as commodity prices has reduced the puzzle in some specifications; no such augmented fit is computed here. The identifying assumptions decide what an impulse response means.

Two more tools. The forecast-error variance decomposition says what share of each variable's forecast uncertainty, at each horizon, comes from each identified shock. Òscar Jordà's local projections of 2005 estimate impulse responses directly, regressing the outcome h periods ahead on today's shock, one horizon at a time, without iterating a VAR. With adequate lag controls, compatible identifying assumptions and suitable regularity, the two can target the same responses asymptotically. A fixed misspecified finite VAR need not agree with local projections. Both need the same thing to mean anything causal: a credible shock.

Vector autoregressions are honest forecasting machines with few restrictions. But their parameters multiply, the number of series squared times the number of lags, so in practice they are shrunk, Part twenty-five's idea, by priors such as Robert Litterman's Minnesota prior. Causal claims need identifying assumptions: orderings, signs of responses, or external instruments, the natural experiments of Part thirty-seven. Sims shared the 2011 Nobel prize with Thomas Sargent for empirical research on cause and effect in the macroeconomy.

Numbers: the price puzzle

11The block bootstrapMaster's3 min

Part sixteen's bootstrap resamples the observations independently, with replacement. Applied to a time series, it shuffles the order away: the resampled observations are conditionally independent draws from the empirical distribution, erasing the original serial dependence. So it estimates the variability the mean would have if the observations were independent. With positive autocorrelation, that is too small, just as the naive standard error was in Part seventeen.

The fix, published by Hans Künsch in 1989, is to resample blocks instead of points. Choose a block length, pick blocks of consecutive observations at random, and glue them together to make a series of the original length. Within each block the dependence survives; only at the joins is it broken. Dimitris Politis and Joseph Romano's stationary bootstrap of 1994 draws the block lengths at random, so that the resampled series are themselves stationary. The block length must grow with the sample, but slowly, about as the cube root of n for the variance of a mean.

One series of five hundred from an autoregression with coefficient a half. The ordinary bootstrap's standard error for the mean is . The moving-block and stationary bootstraps give about , close to Newey and West's estimate from Part seventeen and to the true value, . The ordinary bootstrap was off by a factor of the square root of three, the ratio that the autocorrelation implies.

Now try it on the Nile minima. With short memory, the block bootstrap's standard error rises with the block length and then levels off, once the blocks are longer than the memory. Here it keeps rising: with blocks of five years, with blocks of a century. The long-memory calculation of chapter six says about . These four lengths show no plateau. Under a fractional long-memory model the usual short-memory mean-bootstrap argument fails; this finite plot alone does not prove that no block is long enough. The block bootstrap assumes the memory is short, and that assumption, like every other in this part, has to be checked.

Choosing the block length is the bootstrap's own bias-variance trade. Too short, and the dependence is cut at too many joins, so the standard error is too small. Too long, and there are few distinct blocks, so it is noisy. Dimitris Politis and Halbert White proposed in 2004 a rule that chooses the length from the estimated autocorrelations. Alternatives include subsampling, which recomputes the statistic on shorter stretches of the series, and the sieve bootstrap, which fits a long autoregression and resamples its residuals. The usual short-memory versions need additional theory here. Subsampling with an appropriate long-memory rate, or specialized fractional bootstraps, can still be valid; the plain formulas shown are not justified if the Nile's minima do not respect.

Numbers: 0.055 vs 0.091

12The forecasting frontierPractice3 min

Part seventeen told the story of Spyros Makridakis's competitions, in which simple methods proved hard to beat. The fourth competition, in 2018, with a hundred thousand series, was won by Slawek Smyl's hybrid of exponential smoothing and a recurrent neural network. The fifth, in 2020, on Walmart's sales, was dominated by gradient-boosted trees, Part thirty-four's machinery, trained across thousands of related series at once. The lesson was that learning across many series pays, and that combinations often perform well; no method wins universally.

The next step borrows from language models: train one large model on a huge corpus of time series, then use it on new series without fitting anything. Nixtla's TimeGPT, Lag-Llama, Google's TimesFM, Amazon's Chronos and Salesforce's Moirai appeared in 2023 and 2024, and successors keep coming. Given a history, different models return point, quantile or distributional forecasts, without task-specific fitting. On public benchmarks they are often competitive with tuned statistical methods, and sometimes beaten by a seasonal naive forecast. The rankings change quickly; what does not change is how to evaluate them.

Honest evaluation has four rules. Use a rolling origin: fit on the data up to some time, forecast the next stretch, move the origin forward, repeat, and average. Use a scale-free error such as Rob Hyndman and Anne Koehler's MASE, the error relative to the seasonal naive forecast. Score the whole forecast distribution, by the continuous ranked probability score of Part twenty-four, and check interval coverage. And allow no leakage: nothing from the test period may touch training or tuning. For pretrained models that is hard to guarantee, because their training corpora may already contain the benchmark series.

A small honest evaluation, on Mauna Loa's carbon dioxide record: eleven origins, a year apart, each forecasting two years ahead. The naive forecast and the seasonal naive score above one. Adding last year's trend to the seasonal pattern brings it to . Holt-Winters exponential smoothing, from Part seventeen, scores . Any new method, pretrained or not, should be put through exactly this, on data it cannot have seen.

Leakage in miniature. Take the Holt-Winters forecast at the last origin and make fifty small random adjustments to it. Keep whichever scores best on the test period itself. Its error is , against the honest . This selected score is optimistic evidence: the adjustments were chosen using the test outcomes. Whether they improve a future period requires fresh data, which this example does not provide. It is Part twenty-eight's optimism of the training error, in time.

Big models change what is possible, not how to judge it. Rolling origins, scale-free errors, scores for the whole forecast distribution, no leakage, and strong simple baselines. And the structure of this part still matters: a forecaster that ignores a unit root, a volatility cluster, a break or long memory will be confidently wrong. Part sixty-four returns to statistics in the age of large models.

Numbers: MASE 0.48; leakage

Recap, problems, and the road aheadAll tracks3 min

Part thirty-eight in twelve lines. Hurst found the Nile's range growing faster than independence allows. Wold's theorem frames four ways to leave Part seventeen's world. The spectrum spreads a series' variance over frequencies, and its estimate must be smoothed; the sunspots cycle every eleven years. A unit root's test statistic is not normal, and Dickey and Fuller's tables replace the t table. Regressions of one random walk on another lie, unless the walks are cointegrated. GARCH lets the variance remember its past. Long memory makes the mean far less certain than it looks. Kalman's filter tracks a hidden state by Gaussian conditioning, step by step; the smoother uses the future, and the likelihood or EM learns the noise. Extended, unscented and particle filters handle nonlinearity, and Hamilton's filter finds recessions. Vector autoregressions forecast several series together, with causal claims only under identifying assumptions. And block bootstraps and honest evaluation keep the inference and the forecasts truthful.

A promise for later. This part handled dependence in time. Time has one dimension and one direction, the past, which is what makes filtering possible. Part thirty-nine moves to space, where dependence runs in every direction at once: variograms, kriging, which is the Kalman smoother's cousin, and point patterns.

Where it comes back. Part thirty-nine takes dependence into space. Part forty-one uses EM for missing data. Part forty-four proves the functional central limit theorem behind Dickey and Fuller. Part forty-seven studies non-standard limits. Part fifty-three uses Gaussian processes, the continuous cousins of state space models. Part fifty-eight makes sequential inference valid at every time. Part sixty treats nonstationarity as distribution shift. And Part sixty-four returns to large pretrained models.

Six problems, with full solutions in the README. The periodogram of white noise; the Dickey-Fuller numerator; GARCH's stationary variance and its ARMA form; the first autocorrelation of fractional noise; the Kalman gain for a local level and its steady state; and the long-run variance of an autoregressive mean. Pause here if you want to try them.

The books this part follows: Shumway and Stoffer; Hamilton's Time Series Analysis and Brockwell and Davis; Durbin and Koopman on state space methods; Beran on long memory, and Hyndman and Athanasopoulos on forecasting; with the papers from Hurst to Julier and Uhlmann.

Thirty-eight parts of sixty-five. A series remembers its past, sometimes for centuries, and the thing we care about is often hidden beneath it. Next, dependence in every direction: Part thirty-nine, space.

Where it goes next. Dependence in every direction, with kriging as its filter, is Part 39; EM returns for missing data in Part 41; Part 44 proves Donsker's theorem behind the Dickey-Fuller limit, Part 53 treats Gaussian processes, and Part 64 evaluates pretrained forecasters.

Key results

The part's results in one place, for revision.

Herglotz\(\displaystyle \gamma(h)=\int_{-\pi}^{\pi}e^{ih\omega}\,dF(\omega)\)
Dickey-Fuller limit (with a constant)\(\displaystyle t_{\hat\gamma}\Rightarrow\frac{\int_0^1\bar W\,dW}{\bigl(\int_0^1\bar W^2\,dr\bigr)^{1/2}},\qquad\allowbreak \bar W(r)=W(r)-\int_0^1 W(s)\,ds\)
GARCH(1,1) and its forecast\(\displaystyle \sigma_t^2=\omega+\alpha\varepsilon_{t-1}^2+\beta\sigma_{t-1}^2,\qquad\allowbreak E_t\sigma_{t+h}^2-\bar\sigma^2=(\alpha+\beta)^{h-1}(\sigma_{t+1}^2-\bar\sigma^2)\)
Long memory\(\displaystyle \rho(h)\sim c\,h^{2d-1},\qquad\allowbreak \operatorname{Var}(\bar X_n)\asymp n^{2d-1},\qquad\allowbreak H=d+\tfrac12\)
Kalman filter, local level\(\displaystyle K_t=\frac{P_{t\mid t-1}}{P_{t\mid t-1}+\sigma_v^2},\quad\allowbreak m_t=m_{t-1}+K_t(y_t-m_{t-1}),\quad\allowbreak P_{t+1\mid t}=(1-K_t)P_{t\mid t-1}+\sigma_w^2\)
Steady-state gain\(\displaystyle K=\tfrac12\bigl(\sqrt{q^2+4q}-q\bigr),\qquad\allowbreak q=\sigma_w^2/\sigma_v^2\)

Try it

Lab 38 · The unit-root test has its own distribution

Simulate 4,000 random walks of length 100 and 4,000 stationary AR(1) series, compute the t statistic of the autoregressive coefficient against its true value in each, and compare both histograms with the standard normal and with MacKinnon's Dickey-Fuller critical value.

Figure produced by Lab 38: The unit-root test has its own distribution
Produced by the lab below, seed 0, in 0.4 s.
python -m videos.stats.labs 38 needs numpy, scipy, matplotlib · download lab38.py · source on GitHub
random walk: 5% point of the t statistic       -2.88   (MacKinnon -2.89, normal -1.645)
random walk: mean of the t statistic           -1.51   (normal theory 0)
random walk: rejections at -1.645              45.0%   (nominal 5%)
random walk: rejections at MacKinnon's value   4.7%   (nominal 5%)
AR(1), phi = 0.5: 5% point of the t statistic  -1.94   (normal -1.645)
AR(1), phi = 0.5: rejections at -1.645         8.6%   (nominal 5%; the small-sample bias of phi-hat)
AR(1), phi = 0.5: rejections at |t| > 1.96     5.8%   (nominal 5%)

At a unit root the t statistic converges to a functional of Brownian motion, shifted well to the left of the normal: the normal cutoff rejects nearly half of all true random walks, and the Dickey-Fuller table restores the size. Away from the unit root the normal is close, apart from a small leftward shift that shrinks as T grows.
The code (69 lines; it asserts its own result)
"""Lab 38: simulate the Dickey-Fuller statistic and see the normal critical value fail at a unit root."""

import numpy as np
from scipy import stats

from videos.coursekit import labs
from explainer.stats.kit import ts

TITLE = "The unit-root test has its own distribution"
GOAL = ("Simulate 4,000 random walks of length 100 and 4,000 stationary AR(1) series, compute the t statistic of the "
        "autoregressive coefficient against its true value in each, and compare both histograms with the standard "
        "normal and with MacKinnon's Dickey-Fuller critical value.")
TASKS = [
    "Set phi to 0.95 and 0.99 in the stationary run. How large must T be before the normal approximation is usable?",
    "Regress one random walk on another, independent one (np.polyfit or ols) and count how often |t| > 1.96.",
    "Add a linear trend to the test (trend='ct') and compare the simulated 5% point with ts.df_critical(T, 0.05, 'ct').",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    T, reps, phi = 100, 4000, 0.5
    t_unit, t_stat = np.empty(reps), np.empty(reps)
    for r in range(reps):
        e = rng.standard_normal(T + 1)
        t_unit[r] = ts.adf(np.cumsum(e))["t"]  # H0: gamma = phi - 1 = 0, which is true
        x = np.empty(T + 1)
        x[0] = e[0] / np.sqrt(1 - phi ** 2)
        for i in range(1, T + 1):
            x[i] = phi * x[i - 1] + e[i]
        a = ts.adf(x)
        t_stat[r] = (a["gamma"] - (phi - 1)) / (a["gamma"] / a["t"])  # t against the true gamma = -0.5
    crit = ts.df_critical(T, 0.05, "c")
    q_unit, q_stat = np.quantile(t_unit, 0.05), np.quantile(t_stat, 0.05)
    rej_normal, rej_mack = np.mean(t_unit < -1.645), np.mean(t_unit < crit)
    rej_stat, rej_stat2 = np.mean(t_stat < -1.645), np.mean(np.abs(t_stat) > 1.96)

    lab = labs.Lab()
    lab.row("random walk: 5% point of the t statistic", f"{q_unit:.2f}   (MacKinnon {crit:.2f}, normal -1.645)")
    lab.row("random walk: mean of the t statistic", f"{t_unit.mean():.2f}   (normal theory 0)")
    lab.row("random walk: rejections at -1.645", f"{rej_normal:.1%}   (nominal 5%)")
    lab.row("random walk: rejections at MacKinnon's value", f"{rej_mack:.1%}   (nominal 5%)")
    lab.row("AR(1), phi = 0.5: 5% point of the t statistic", f"{q_stat:.2f}   (normal -1.645)")
    lab.row("AR(1), phi = 0.5: rejections at -1.645", f"{rej_stat:.1%}   (nominal 5%; the small-sample bias of phi-hat)")
    lab.row("AR(1), phi = 0.5: rejections at |t| > 1.96", f"{rej_stat2:.1%}   (nominal 5%)")
    lab.note = ("At a unit root the t statistic converges to a functional of Brownian motion, shifted well to the left "
                "of the normal: the normal cutoff rejects nearly half of all true random walks, and the Dickey-Fuller "
                "table restores the size. Away from the unit root the normal is close, apart from a "
                "small leftward shift that shrinks as T grows.")
    assert abs(q_unit - crit) < 0.12, "the simulated 5% point matches MacKinnon's"
    assert 0.40 < rej_normal < 0.51, "the normal critical value rejects about 45% of true unit roots"
    assert abs(rej_mack - 0.05) < 0.015, "MacKinnon's value has size 5%"
    assert abs(rej_stat2 - 0.05) < 0.025 and rej_stat < 0.14, "under stationarity the normal is about right"

    fig, ax = labs.figure(2, size=(11, 4.2), sharey=True)
    grid = np.linspace(-5, 4, 200)
    for a, t, name in ((ax[0], t_unit, "Random walk (phi = 1): the Dickey-Fuller law"),
                       (ax[1], t_stat, "Stationary AR(1), phi = 0.5: nearly normal")):
        a.hist(t, bins=np.linspace(-5, 4, 55), density=True, color=labs.BLUE, alpha=0.6, label="4,000 simulated t statistics")
        a.plot(grid, stats.norm.pdf(grid), color=labs.GOLD, label="standard normal")
        a.axvline(-1.645, color=labs.GOLD, ls="--", lw=1.2, label="normal 5% point, -1.645")
        a.set(title=name, xlabel="t statistic of the coefficient against its true value")
    ax[0].axvline(crit, color=labs.RED, ls="--", lw=1.2, label=f"MacKinnon 5% point, {crit:.2f}")
    ax[0].set_ylabel("density")
    ax[0].set_ylim(0, 0.72)
    ax[0].legend(loc="upper right")
    ax[1].legend(loc="upper right")
    lab.fig = fig
    return lab

Now change it

  1. Set phi to 0.95 and 0.99 in the stationary run. How large must T be before the normal approximation is usable?
  2. Regress one random walk on another, independent one (np.polyfit or ols) and count how often |t| > 1.96.
  3. Add a linear trend to the test (trend='ct') and compare the simulated 5% point with ts.df_critical(T, 0.05, 'ct').

Problems, with solutions

Try each problem before opening its solution.

  1. White-noise periodogram. For Gaussian white noise, show that periodogram ordinates at distinct interior positive Fourier frequencies are independent \(\sigma^2 \cdot\) Exp(1).

    Solution

    At an interior positive Fourier frequency f_j (excluding Nyquist), the cosine and sine sums are uncorrelated Gaussians with variance nσ²/2 each, and different interior positive j are orthogonal. So I(f_j) = (C² + S²)/n is σ²/2 times a χ²₂, that is σ² Exp(1), and the ordinates are independent. The zero and, for even n, Nyquist frequencies are exceptions: their real Gaussian transform gives a scaled χ²₁ rather than Exp(1).

  2. The Dickey–Fuller numerator. For \(\Delta x_t = \gamma x_{t-1} + \varepsilon_t\) with \(\gamma = 0\), show \(\frac{1}{T}\sum x_{t-1}\varepsilon_t = \frac{\sigma^2}{2}(x_T^2/(\sigma^2 T) - \hat\sigma^2/\sigma^2)\) approximately.

    Solution

    Squaring x_t = x_{t−1} + ε_t gives x_t² = x_{t−1}² + 2x_{t−1}ε_t + ε_t².

    • Summing, Σx_{t−1}ε_t = (x_T² − x_0² − Σε_t²)/2.
    • Divide by Tσ²: with x_0 = 0 this is ½(x_T²/(Tσ²) − σ̂²/σ²) → ½(W(1)² − 1) = ∫W dW.
  3. GARCH(1,1). For GARCH(1,1), show \(E\sigma_t^2 = \omega/(1-\alpha-\beta)\) and that \(\varepsilon_t^2\) follows an ARMA(1,1).

    Solution
    • Taking expectations of σ_t² = ω + αε_{t−1}² + βσ_{t−1}², with E ε² = E σ², gives Eσ² = ω/(1 − α − β).
    • Let ν_t = ε_t² − σ_t², a martingale difference. Then ε_t² = ω + (α + β)ε_{t−1}² + ν_t − βν_{t−1}, an ARMA(1,1).
  4. ARFIMA ρ₁. For ARFIMA\((0,d,0)\), show \(\rho_1 = d/(1-d)\).

    Solution

    From ρ_k = ∏(j − 1 + d)/(j − d), taking k = 1 gives ρ₁ = d/(1 − d). For d = 0.4 this is 0.67.

  5. Local-level gain. Local level: show the gain is \(K = P/(P + R)\), and find the steady-state \(P\) in terms of \(q/r\).

    Solution

    With H = 1, K = P(P + r)⁻¹ = P/(P + r).

    • The predicted variance recursion P' = P − P²/(P + r) + q has the steady state P² = q(P + r), so P = (q + √(q² + 4qr))/2.
    • For the Nile, with q/r = 0.097, K = 0.27.
  6. AR(1) mean. For an AR(1), show \(n\,\text{Var}(\bar X_n) \to \sigma_X^2 (1+\phi)/(1-\phi)\).

    Solution

    n Var(X̄) = γ₀ Σ_{|h|<n}(1 − |h|/n)φ^{|h|} → γ₀(1 + 2φ/(1 − φ)) = γ₀(1 + φ)/(1 − φ). For φ = 0.5 that is 3γ₀, so the i.i.d. SE is too small by √3.

Notes and sources

Where it comes back

  • Part 39: dependence in space; kriging.
  • Part 41: EM and missing data.
  • Part 44: Brownian motion and Donsker's theorem behind Dickey–Fuller.
  • Part 47: non-standard limits.
  • Part 53: Gaussian processes.
  • Part 58: sequential, anytime-valid inference.
  • Part 60: nonstationarity as distribution shift.
  • Part 64: pretrained forecasters, honestly.

Glossary

  • Rescaled range; Hurst exponent H: the range of cumulative deviations over the SD; its growth exponent.
  • Spectral density; periodogram; Welch; multitaper: the variance by frequency; its raw, inconsistent estimate; segment averaging; Slepian tapers.
  • Unit root; Dickey–Fuller; KPSS: a permanent-shock process; the test with a unit-root null; the test with a stationarity null.
  • Spurious regression; cointegration; error correction: significant-looking regressions between independent walks; a stationary combination of unit-root series; the pull back to it.
  • ARCH; GARCH; persistence: conditional variance driven by past squared shocks (and past variance); α + β.
  • Long memory; ARFIMA; d: autocorrelations decaying like a power; fractional differencing; H = d + ½.
  • State space; Kalman filter; RTS smoother; gain: hidden linear Gaussian dynamics; the forward recursion; the backward pass; the weight on the surprise.
  • Prediction-error decomposition; EM: the likelihood from innovations; Shumway–Stoffer's iteration.
  • EKF; UKF; particle filter; PMCMC: linearize; sigma points; weighted samples; particle likelihoods inside MCMC.
  • Markov switching: a discrete hidden regime (Hamilton).
  • VAR; Granger causality; impulse response; price puzzle: joint autoregression; forecasting improvement; dynamic effects of identified shocks; inflation rising after a tightening.
  • Block and stationary bootstraps: resampling blocks to keep dependence.
  • Rolling origin; MASE; leakage: honest forecast evaluation; a scale-free error; test information in training.

Sources

  • Long memory.
    • H. Hurst, Trans. ASCE 116 (1951); B. Mandelbrot & J. Wallis, Water Resour. Res. 4 (1968).
    • C. Granger & R. Joyeux, J. Time Ser. Anal. 1 (1980); J. Hosking, Biometrika 68 (1981).
    • J. Geweke & S. Porter-Hudak, J. Time Ser. Anal. 4 (1983); P. Robinson, Ann. Stat. 23 (1995).
    • F. Diebold & A. Inoue, J. Econometrics 105 (2001); W. Leland et al., IEEE/ACM Trans. Netw. 2 (1994).
    • J. Beran (1994); O. Toussoun (1925).
  • Spectra.
    • H. Wold (1938); P. Welch, IEEE Trans. Audio Electroacoust. 15 (1967); D. Thomson, Proc. IEEE 70 (1982).
  • Unit roots and cointegration.
    • D. Dickey & W. Fuller, JASA 74 (1979); J. MacKinnon (2010); D. Kwiatkowski, P. Phillips, P. Schmidt & Y. Shin, J. Econometrics 54 (1992).
    • C. Nelson & C. Plosser, J. Monet. Econ. 10 (1982); P. Perron, Econometrica 57 (1989); E. Zivot & D. Andrews, JBES 10 (1992).
    • C. Granger & P. Newbold, J. Econometrics 2 (1974); P. Phillips, J. Econometrics 33 (1986).
    • R. Engle & C. Granger, Econometrica 55 (1987); S. Johansen, J. Econ. Dyn. Control 12 (1988); J. Stock, Econometrica 55 (1987).
    • P. Phillips & B. Hansen, REStud 57 (1990); J. Stock & M. Watson, Econometrica 61 (1993).
  • Volatility.
    • B. Mandelbrot, J. Business 36 (1963); R. Engle, Econometrica 50 (1982); T. Bollerslev, J. Econometrics 31 (1986).
  • State space.
    • R. Kalman, J. Basic Eng. 82 (1960); H. Rauch, F. Tung & C. Striebel, AIAA J. 3 (1965); F. Schweppe, IEEE Trans. Inf. Theory 11 (1965).
    • R. Shumway & D. Stoffer, J. Time Ser. Anal. 3 (1982); J. Muth, JASA 55 (1960); A. Harvey, Forecasting, Structural Time Series Models and the Kalman Filter (1989).
    • J. Durbin & S. J. Koopman (2012); G. Cobb, Biometrika 65 (1978).
  • Nonlinear filtering.
    • S. Julier & J. Uhlmann (1997); N. Gordon, D. Salmond & A. Smith, IEE Proc. F 140 (1993).
    • C. Andrieu, A. Doucet & R. Holenstein, JRSS B 72 (2010); J. Hamilton, Econometrica 57 (1989).
  • VARs.
    • C. Granger, Econometrica 37 (1969); C. Sims, Econometrica 48 (1980), Eur. Econ. Rev. 36 (1992).
    • Ò. Jordà, AER 95 (2005).
  • Bootstrap.
    • H. Künsch, Ann. Stat. 17 (1989); D. Politis & J. Romano, JASA 89 (1994); D. Politis & H. White, Econometric Rev. 23 (2004).
  • Forecasting.
    • S. Makridakis et al., IJF 36 (2020), 38 (2022); R. Hyndman & A. Koehler, IJF 22 (2006).
    • A. Ansari et al. (Chronos, 2024); A. Das et al. (TimesFM, 2024); G. Woo et al. (Moirai, 2024); K. Rasul et al. (Lag-Llama, 2024); A. Garza & M. Mergenthaler-Canseco (TimeGPT, 2023). These are current as of the mid-2020s; check the latest benchmarks.
About this partfrom its README

Part 38 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the eighteenth part of Stage III, Master's. Part 17's series were stationary, with short memory and constant variance, and fully observed. This part lets each assumption go in turn:

  • spectra;
  • unit roots, spurious regression and cointegration;
  • volatility;
  • long memory;
  • the state space, with the Kalman filter, smoother and EM;
  • nonlinear filters and regime switching;
  • vector autoregressions;
  • the block bootstrap;
  • the forecasting frontier.

The part builds statkit.ts (II) and an instrument, the Kalman ellipses (KalmanEllipses): the predict and update steps as moving Gaussian ellipses, with the measurement as a band. Its real data are:

  • Toussoun's yearly minima of the Nile at Roda, 622–1284 (R's longmemo package, GPL ≥ 2);
  • the Nile's flow at Aswan, 1871–1970;
  • yearly sunspot numbers;
  • the DAX, 1991–1998 (R's EuStockMarkets);
  • US quarterly macro data, 1959–2009 (statsmodels).

It opens with Hurst (1951). The Nile minima's rescaled range grows like n^0.85. White noise of the same length gives 0.56 (0.48–0.63), and an AR(1) fitted to the Nile 0.69. The range of cumulative minimum-level anomalies is 10,647 level-years. These are gauge minima, not flow volumes: their cumulative range is a teaching analogue, not an actual reservoir capacity.

From there the part covers:

  • What Part 17 assumed. Four seeded departures from it: a random walk, GARCH, ARFIMA, a hidden level. Also Wold's decomposition and ergodicity.
  • Spectra.
    • Herglotz; the periodogram is exactly unbiased for white noise and asymptotically unbiased under suitable general short-memory conditions, but inconsistent without smoothing. For white noise its spread is 1.11 at n = 128 and 1.08 at n = 2,048; Welch's estimate brings it to 0.18.
    • Welch; multitaper.
    • The sunspot peak: periodogram 11.0 years, Welch 10.7, multitaper 10.7, Yule's AR(2) 10.9.
  • Unit roots.
    • Dickey–Fuller and its Brownian limit. Over 20,000 random walks the 5% point is −2.86, against MacKinnon's −2.89. The normal −1.645 rejects 45.6% of true unit roots.
    • KPSS.
    • US series: ADF nonrejection and KPSS rejection for log GDP are consistent with a unit root under these lag/deterministic specifications; unemployment, the T-bill rate and inflation cannot be told apart; GDP growth is stationary.
    • Perron's breaks.
  • Spurious regression and cointegration.
    • Two independent walks give |t| > 1.96 77% of the time (Granger & Newbold: 76%), with median R² 0.18.
    • Engle–Granger on log consumption and income: β̂ = 1.03, τ = −2.90 against −3.37, so it cannot reject.
    • Johansen with investment: trace 30.2 against 29.8 for rank 0, and 11.5 against 15.5 for rank 1, so the sequential test selects one relation, barely, under the chosen lag/deterministic specification. Neither rank selection nor unit-root nonrejection proves the null.
    • Super-consistency; FM-OLS and DOLS.
  • Volatility. DAX returns:
    • kurtosis 9.3; ARCH LM 70 (p ≈ 10⁻¹³);
    • GARCH(1,1) with α = 0.068, β = 0.888 (persistence 0.956, half-life 15 days);
    • In-sample 1% VaR diagnostics, with full-record parameter estimates and volatility groups defined by fitted conditional scale: constant variance 0.54% when calm and 2.91% when turbulent; GARCH 1.51% and 1.72%;
    • at horizon 21, about 0.41 of the one-day variance forecast's excess over its long-run level remains: the exponent is h−1, not h. Estimated tails and conditional calibration still need out-of-sample validation.
  • Long memory.
    • ARFIMA (Granger & Joyeux; Hosking).
    • GPH on the minima ranges from 0.40 to 0.58 by bandwidth; local Whittle gives d = 0.41 (0.06), so H ≈ 0.91.
    • With d = 0.41 the SE of the mean is 47.5 instead of 3.4: an effective sample of 3.5 of 663 years. This is an ARFIMA plug-in approximation using estimated d and marginal variance; it omits parameter uncertainty and does not establish that the true physical process is fractional.
    • Long memory elsewhere; breaks that mimic it.
  • Kalman.
    • Gaussian conditioning; the ellipses on a tracking example.
    • The Nile local level: MLE σ²_w = 1,469.0 and σ²_v = 15,099, matching Durbin & Koopman.
    • The steady-state gain is 0.27, which is exponential smoothing (Muth 1960).
    • The smoothed level's largest fall is into 1899; a shift there of −316 improves twice the log likelihood by 10.5 while holding variances at their no-shift estimates. The date was inspected in the same record: this is a descriptive fixed-nuisance comparison, not a calibrated likelihood-ratio test or causal attribution to a dam.
  • Smoothing and learning.
    • RTS.
    • Hidden years 1891–1910 and 1931–1950, using variances fitted to the full record. This illustrates smoothing with gaps rather than an honest missing-data forecast benchmark. Ignorable missingness is required to skip updates without modelling the observation process.
    • The prediction-error likelihood. The illustrated EM path raises the likelihood and approaches the direct solution (1,469 and 15,099). General EM theory guarantees nondecrease under exact steps, not convergence to a unique global maximum.
    • Structural time-series models; Apollo.
  • Nonlinear filtering.
    • Kitagawa–Gordon's benchmark, mean RMSE over 30 series: EKF 20.6, UKF 10.5, particle filter 4.4.
    • Particle central quantile intervals can span both modes; they do not split into a multimodal set, and their mean can lie between modes. No wall-time cost ratio was measured. PMCMC targets the exact invariant posterior under its nonnegative unbiased-likelihood construction; finite chains still need convergence diagnostics.
    • Hamilton's regimes in US growth: −1.1% and +4.1% a year, lasting 4 and 18 quarters. The low-regime probability averages 0.64 inside NBER recessions and 0.06 outside. Filtering uses past observations at each step but full-sample parameter estimates; this is retrospective, not a real-time forecast evaluation or a reproduction of Hamilton's full autoregressive model.
  • VARs. A VAR(4) of inflation, unemployment and the T-bill rate.
    • Conventional model-based Granger F tests (unadjusted p-values; persistence and misspecification can affect their calibration): inflation → unemployment p = 0.007, unemployment → T-bill p = 0.010, T-bill → inflation p = 0.038.
    • Responses to a rate shock: unemployment rises over 2–3 years; inflation rises at first (the price puzzle).
    • Variance decompositions; local projections. Agreement with VAR responses requires adequate lag controls, compatible identification and regularity, rather than any fixed finite VAR. Bootstrap bands are pointwise and conditional on the fitted model/order.
  • Block bootstrap.
    • AR(1) with φ = 0.5 and n = 500, SE of the mean: i.i.d. 0.055, moving-block 0.091, stationary 0.092, Newey–West 0.088, truth 0.089.
    • The Nile minima's block SE keeps rising with the block length (5.8 → 16.5), with no plateau in the four lengths tried. This finite plot does not prove long memory or rule out specialized long-memory bootstraps/subsampling with appropriate rates.
    • Choosing b.
  • Forecasting.
    • M4 and M5; pretrained forecasters.
    • Rolling-origin MASE on CO₂ (11 origins, 2 years ahead): naive 2.16, seasonal naive 1.80, seasonal naive plus trend 0.60, Holt–Winters 0.48.
    • Leakage: selecting among 50 tweaks on the test outcomes gives 0.15 against the untuned 0.19. There is no subsequent period available here to establish future performance. Overlapping 24-month evaluation windows are not eleven independent error estimates.

Data:

  • the Nile, its minima, the sunspots, the DAX, the macro series and CO₂ are the Museum's;
  • the rest are seeded simulations.

Built in this part:

  • statkit.ts (II) (explainer/stats/kit/ts.py), checked against statsmodels in tests/test_stats_kit_ts2.py:
    • Spectra and long memory: Hurst's R/S; the periodogram, Welch and multitaper; ARMA spectra; fractional differencing weights, the ARFIMA ACF and exact simulation (Davies–Harte); GPH and local Whittle.
    • Unit roots and cointegration: ADF with MacKinnon's critical values; KPSS; Engle–Granger; Johansen's trace.
    • Volatility: the ARCH LM test; GARCH(1,1) by maximum likelihood.
    • State space: the Kalman filter with missing data and its likelihood; RTS; local-level MLE and EM; EKF, UKF and a bootstrap particle filter; Hamilton's filter and its MLE.
    • Several series and resampling: VARs, Granger tests and orthogonalized impulse responses; the stationary bootstrap.
  • The Museum gains nile(), nile_minima(), eustock() and us_macro().
  • The Kalman ellipses (KalmanEllipses in explainer/stats/viz.py).

The Coverage Board gains seven rows:

Method Setting Achieved Verdict
Dickey–Fuller t, normal critical value (size) random walks, T = 100 44.7% broken
Dickey–Fuller t, MacKinnon's value (size) same 5.4% kept
KPSS, Bartlett long-run variance (size) AR(1), φ = 0.5, T = 200 5.2% kept
regression t-test, two random walks (size) independent walks, T = 100 77.1% broken
Engle–Granger, MacKinnon's values (size) same 4.6% kept
i.i.d. bootstrap 90% CI for the mean AR(1), φ = 0.5, n = 500 66.4% broken
moving-block bootstrap CI (blocks of 30) same 89.0% kept

Wold's representation applies to the purely nondeterministic square-integrable stationary component. Mean ergodicity from vanishing autocovariance is weaker than full ergodicity; nonstationary estimators use their own limit theory. Long-memory evidence and finite-sample summaries are kept separate from model assumptions.

Chapter notes
# Chapter Numbers
0 Hurst's Nile H = 0.85 vs 0.56
1 What Part 17 assumed four departures; ergodicity
2 Spectra 11-year sunspot cycle
3 Unit roots 46% vs 5%
4 Spurious regression and cointegration 77%; trace 30.2 vs 29.8
5 Volatility α + β = 0.956
6 Long memory d = 0.41; n_eff = 3.5
7 State space and the Kalman filter 1,469 / 15,099; K = 0.27
8 Smoothing and learning EM → MLE
9 Nonlinear filtering and regimes RMSE 20.6 / 10.5 / 4.4
10 VARs and Granger causality the price puzzle
11 The block bootstrap 0.055 vs 0.091
12 The forecasting frontier MASE 0.48; leakage
13 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Hurst (1951). The Nile, R/S, H well above ½; Toussoun's minima (622–1284).
  2. Upgrade card (Part 17).
  3. Spectra. Herglotz; the periodogram's inconsistency; Welch and multitaper; the sunspot cycle.
  4. Unit roots. Dickey–Fuller (1979) and its Brownian limit (Part 44 proves Donsker); KPSS (Board).
  5. Spurious regression and cointegration. Granger & Newbold (1974); Engle & Granger (1987); Johansen.
  6. Volatility. ARCH (Engle 1982); GARCH (Bollerslev 1986).
  7. Long memory. ARFIMA (Granger & Joyeux 1980; Hosking 1981).
  8. State space and Kalman (1960). Gaussian conditioning (KalmanEllipses); the Nile's flow 1871–1970 and its drop around 1899.
  9. Smoothing and learning. RTS; the prediction-error likelihood; EM (Shumway & Stoffer 1982); Apollo.
  10. Nonlinear filtering. EKF, UKF; particle filters (Part 27); regime switching (Hamilton 1989).
  11. VARs and Granger causality (Sims 1980; Granger 1969).
  12. Block bootstrap for series (Künsch 1989).
  13. Forecasting frontier. Pretrained forecasting models and honest evaluation (verify current models).
  14. Outro.

Built: statkit.ts (II). Data: the Nile; Toussoun; Yule's sunspots.

Build the film

python -m videos.stats.stats38.compute        # the part's numbers, into .cache/stats38
python tools/build.py stats38                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats38 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats38. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
OMP_NUM_THREADS=1 python -m videos.stats.stats38.compute   # once (a few minutes)
python tools/build.py stats38 -q l                         # fast 480p preview
python tools/build.py stats38                              # 1080p30 -> renders/stats38.mp4
python tools/qa_scene.py stats38 Kalman
python tools/lecture_length.py stats38 --floor 50