SStatistics, Built

Stage II · Bachelor's: Methods

Part 17 of 65

Time Series

Bachelor'sstarts at this level51 min of film12 chaptersprerequisites: Part 7, Part 12

How do you do statistics when each observation remembers the last?

In 1926 Yule shows that Church of England marriages and mortality in England and Wales correlate at 0.95 over 1866 to 1911, and at 0.02 once each series is differenced; a year later he explains the sunspot cycle with a pendulum pelted by peas. The part builds the language for such data: stationarity, the correlogram, and the price of memory, which makes 100 observations of an AR(1) with correlation 0.7 worth about 18. AR, MA and ARMA models are read from their roots against the unit circle, and complex roots give the pseudo-cycles of Slutsky and of Yule's sunspot AR(2). Box and Jenkins's cycle of identification, estimation and checking leads to forecasts whose intervals widen, to the decomposition of the Mauna Loa record and to Holt-Winters smoothing. The part returns to Yule: two independent random walks pass a slope test three times in four, and differencing repairs it. It closes with the M-competitions, where simple methods and combinations are hard to beat.

What you need. Stage I of this series, and least squares from Part 12; complex numbers for the roots.

Hook
Yule's nonsense correlation, 1926
Mathematics
stationarity, ARMA, ACF/PACF, Box–Jenkins, forecasting, smoothing, seasonality
Built
statkit.ts (I)

What you will be able to do

Bachelor's

  • Read a correlogram with its bands, and tell white noise, an autoregression and a random walk apart.
  • Explain why the correlation of two trending series says little, and what differencing does.

Master's

  • Check stationarity and invertibility of an ARMA model from its roots, and compute the period of an AR(2) with complex roots.
  • Fit an autoregression by Yule-Walker or least squares, check its residuals with Ljung-Box, and forecast with intervals.

PhD

  • Derive the variance of the mean of a stationary series from its autocovariances, and state why the t statistic of a regression between independent random walks does not settle as n grows.

Practice

  • Score forecasts by MASE on a held-out stretch against the naive and seasonal-naive benchmarks.
  • Report a mean or a trend from autocorrelated data with a standard error that allows for the dependence.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 31 min · Master's 51 min · PhD 51 min · Practice 39 min.

  1. 0Nonsense correlations, 1926Bachelor's4 min
  2. 1Stationarity and the ACFBachelor's5 min
  3. 2AR, MA, ARMABachelor's5 min
  4. 3Pseudo-cyclesMaster's4 min
  5. 4IdentificationMaster's4 min
  6. 5EstimationMaster's4 min
  7. 6ForecastingBachelor's5 min
  8. 7Trend and seasonalityBachelor's4 min
  9. 8Exponential smoothingPractice5 min
  10. 9Spurious regressionBachelor's4 min
  11. 10The M-competitionsPractice4 min
  12. 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.

Nonsense correlations, 1926Bachelor's4 min

In January 1926 George Udny Yule gave his presidential address to the Royal Statistical Society. His title was a question: why do we sometimes get nonsense correlations between time series? Every method in this course so far has assumed that the observations are independent, or at least exchangeable. An ordered time series generally lacks that permutation symmetry. This year looks like last year; each observation remembers the one before. This part is about what goes wrong when we forget that, and what to do instead.

His first example. In red, the standardized death rate in England and Wales, every year from 1866 to 1911. In blue, the share of marriages performed in the Church of England, per thousand marriages. The correlation is point nine five. Yule computed point nine five one two from the original figures. Taken at face value, the fewer church weddings, the fewer deaths. Nobody believes that, and Yule didn't. But he wanted to know why the correlation is so high, and whether a significance test would have warned us.

Plotted against each other, the forty-six years lie almost on a line. But look at the changes from one year to the next. A simple contemporaneous link would suggest that a year with an unusual drop in church weddings should bring an unusual drop in deaths. The correlation of the changes is point oh two: little linear association in these changes. Both series simply drift downward over the half-century, for unrelated reasons, and shared trends can create strong level correlations without a direct relationship. Differencing does not by itself settle causality. The forty-six years aren't forty-six independent observations. They're closer to one observation each of two trends.

Yule then did an experiment, by hand, with shuffled cards. Take two series of forty-six independent random numbers, unrelated to each other, and correlate them. Twenty thousand pairs: the correlations cluster near zero, and beyond plus or minus a half only four times in ten thousand. Now make each series a random walk, each step adding a fresh random number to the last value, like a drunkard's path. Here's one pair. The two walks are still completely independent, but their correlation can be almost anything: beyond plus or minus a half in thirty-nine percent of pairs. Series that wander produce large correlations by chance. The usual test, built for independent observations, would call most of them significant.

The next year Yule offered a model for series like these, with a famous image. A pendulum left to itself swings in a slowly damped rhythm. Now imagine boys with pea-shooters hitting it at random. Each pea knocks it a little, so the swing never dies away and never repeats exactly. In symbols, this year's position is a multiple of last year's, minus a multiple of the year before's, plus a fresh random shock: an autoregression. Yule fitted it to the yearly sunspot numbers from 1749 to 1924, and found the pendulum's natural period: about ten and a half years, the sunspot cycle. Here it is swinging. That model, and its relatives, are what this part builds.

Numbers: r = 0.9515 (Yule 0.9512), differences 0.0185; random walks |r| > 0.5 in 39%, noise 0.04%

1Stationarity and the ACFBachelor's5 min

If every observation depends on the past, what can we estimate at all? We need something that doesn't change over time. First, the mean is the same at every time: no drift in the level. Second, the covariance between two observations depends only on how far apart they are, the lag h, not on when they occur. With finite second moments, a series with these properties is weakly stationary: it moves, but its statistical character doesn't age. For positive variance, dividing by it gives the autocorrelation function, rho of h: the correlation of the series with itself h steps back. The simplest stationary series is white noise: zero mean, and no correlation at any lag. It's the raw material, the random shocks, from which every other model in this part is built.

Three series of two hundred steps, and beside each its sample autocorrelations at lags one to twenty. White noise: the series is pure jitter, and its autocorrelations stay inside the dashed bands, which mark what chance alone produces. An autoregression, each value point eight of the last plus a shock: the series wanders in slow swells, and its autocorrelations decay geometrically, point eight, point six four, point five one, close to the theoretical values marked by dots. A random walk: each value is the last plus a shock, the case phi equals one. It has no pull toward a fixed mean, its sample autocorrelations die away only slowly, and it isn't stationary at all: its variance grows with time.

The sample autocovariance averages the products of deviations h steps apart, dividing by n rather than n minus h, which keeps the whole function a valid covariance. Divide by the sample variance for the sample autocorrelation. For IID noise with suitable moments, the standard Bartlett approximation says, from 1946 that each sample autocorrelation is approximately normal with variance one over n. Hence the bands at plus or minus two over root n. With twenty lags, about one bar in twenty will cross them by chance alone, so these are pointwise, not simultaneous bands; one marginal crossing among many is weak evidence by itself.

Here is the first casualty of dependence: the standard error of the mean. Part 5's variance of a sum includes every covariance. For a stationary series it's the iid formula, gamma nought over n, times a bracket containing all the autocorrelations. For an autoregression with coefficient rho, the bracket sums to about one plus rho over one minus rho. With rho equal to point seven, that's five point six seven: the mean's variance is nearly six times what the iid formula says, and its standard error nearly two and a half times. Put differently, a hundred observations carry the information of seventeen and a half independent ones: the effective sample size. Positive correlation means each new observation mostly repeats the last.

One series of a hundred from such an autoregression, with true mean zero. Its sample mean is minus point two seven. The iid standard error is point one four five, and the t-interval only just reaches zero: it all but declares the mean negative. Whitney Newey and Kenneth West, in 1987, estimated the bracket directly, adding up the first few sample autocovariances with weights that taper off: a heteroskedasticity and autocorrelation consistent, or HAC, standard error, here point two six. Or resample in blocks. Hans Künsch's moving-block bootstrap of 1989 glues together random blocks of ten consecutive observations, so within-block dependence survives: point three oh. The interval uses the basic bootstrap, as on the Board. The true standard deviation of the mean, which we can compute for this model, is point three three. Both corrections are nearer the truth, and both still fall short here. HAC and block-bootstrap consistency require short-memory regularity and tuning that grows suitably with sample size.

The Coverage Board: ten thousand such series, each with a ninety-five percent interval for the mean. The iid t-interval covers fifty-eight percent: badly broken, as the inflation factor predicted. Newey–West covers eighty-one percent: much better, still broken, because with a hundred observations it can't see enough lags to estimate the whole bracket. The block bootstrap, eighty-four percent, broken for the same reason: blocks of ten cut the longer-range dependence. Dependence is expensive. The corrections help, but a hundred correlated observations simply don't contain much information about the mean.

Numbers: bands ±0.14 (n = 200); inflation 5.67, n_eff 17.6; one series: iid SE 0.145, NW 0.260, block 0.303, true 0.329; Board 58.1%, 81.2%, 84.2%

2AR, MA, ARMABachelor's5 min

Autoregressive and moving-average models. The autoregression of order one: this period's value is phi times the last, plus a fresh shock. Substitute for the last value, and again, and again: the series is a weighted sum of all the past shocks, with weights one, phi, phi squared. Every observation carries a fading memory of every shock before it. The variance is a geometric series, sigma squared over one minus phi squared, and the autocorrelation at lag h is phi to the h: memory decays geometrically. All of this needs phi between minus one and one, so that old shocks fade. Otherwise the sum doesn't converge.

A gallery, each with a simulated path and its theoretical autocorrelations. Phi equal to point nine: long, slow swells, and correlations that fade slowly. Phi equal to minus point nine: the series flips sign almost every step, and the correlations alternate. A moving average of order one, the current shock plus point eight of the previous one. Its memory is exactly one step long: the autocorrelation at lag one is theta over one plus theta squared, point four nine, and every later lag is zero. And a mixture, an ARMA of order one and one: an autoregressive decay that starts from a lag-one value set by the moving-average part. Different memories, different fingerprints in the autocorrelation function.

Feed the same sixty shocks into three autoregressions. With phi equal to a half, the series hugs zero: each shock is half forgotten by the next step. With phi equal to one, nothing is forgotten: the random walk, which has no mean reversion, and whose variance grows without limit. Part 38 will test for this unit root. With phi just above one, each step amplifies the last, and the series explodes. Only the first converges from this zero start to a causal stationary law.

There's a single test for all autoregressions. Write the coefficients as a polynomial, one minus phi one z, minus phi two z squared, and so on. A causal stationary AR solution, driven by innovations orthogonal to its past, exists exactly when every root of that polynomial lies outside the unit circle in the complex plane. For an AR one with phi a half, the root is at two: comfortably outside. Phi of point nine puts it at one point one one, close to the edge: long memory. Phi of one puts it on the circle: the unit root of the random walk. Yule's sunspot model has a pair of complex roots, one point oh three plus or minus point six nine i, of modulus one point two four: outside, so stationary. Complex roots mean oscillation, and that's chapter three.

For the AR two, the roots condition draws a picture in the plane of the two coefficients. The model is stationary inside a triangle, bounded by three lines. Below the parabola, phi one squared plus four phi two less than zero, the roots are complex, and the series oscillates. Yule's sunspot fit sits here: inside the triangle, below the parabola, a damped oscillation kept alive by its shocks.

Moving averages have a subtlety of their own. An MA one is the current shock plus theta times the last. Its lag-one autocorrelation is theta over one plus theta squared, and that's the same for theta and one over theta: point five and two give identical autocorrelations, so autocorrelations alone cannot distinguish them. For Gaussian shocks their full laws agree after rescaling the innovation variance. With theta inside the unit interval, the shocks can be rebuilt from the observed past, a convergent sum. That's invertibility, and the rule is the mirror of stationarity: the moving-average polynomial's roots must lie outside the unit circle. By convention we always choose the invertible version.

In general an ARMA of orders p and q combines both: a polynomial in the backshift operator on the series, and another on the shocks. For a causal stable model, the centred series is an infinite moving average of shocks, with weights psi from dividing one polynomial by the other. For the ARMA one-one of the gallery: one, one point two, point eight four, point five eight eight, decaying. Herman Wold proved in 1938 that every finite-variance weakly stationary series can be written as a linearly deterministic part, predictable from its infinite past, plus an infinite moving average of uncorrelated innovations. The deterministic part need not be a nonrandom path. ARMA models are a way of approximating that infinite list of weights with a handful of parameters.

Numbers: MA(1) ρ(1) = 0.49; sunspot roots 1.03 ± 0.69i, modulus 1.24; ARMA(1,1) ψ = 1, 1.2, 0.84, 0.588

3Pseudo-cyclesMaster's4 min

Take an AR two whose polynomial has complex roots. Its autocorrelation function is a damped cosine: correlations that swing positive and negative while shrinking by a factor r each step, where r is the square root of minus phi two. It's the free swing of Yule's pendulum. The frequency comes from the angle of the roots: cos omega equals phi one over twice the square root of minus phi two. For phi one equal to one point three and phi two minus point six, r is point seven seven five and the period is ten point nine steps.

Here's three hundred steps of it. There's an unmistakable rhythm: rises and falls, about eleven steps apart. But no two cycles are alike. Heights vary, lengths vary, and every so often the rhythm almost disappears before a run of shocks revives it. The sample autocorrelations trace the damped cosine, close to the theory. These are pseudo-cycles: regular enough to see, irregular enough that no clock is driving them. A pendulum and some peas are all it takes.

The same year, in Moscow, Eugen Slutsky made a related discovery. Start with pure white noise: independent shocks, no rhythm at all. Replace each value by the sum of the last ten. Waves appear: smooth rises and falls with something like a period, which Slutsky compared with the English business cycle of the nineteenth century, and found an uncomfortable resemblance. His paper was called The summation of random causes as the source of cyclic processes. The lesson cuts both ways. Averaging random shocks can produce apparent waves, so a cycle in the data doesn't prove a periodic cause; and smoothing a series yourself can manufacture waves that weren't there.

Now Yule's data: the yearly sunspot numbers from 1749 to 1924, a hundred and seventy-six years. The famous cycle is there, about eleven years from peak to peak, with peaks of very different heights. Fitting an AR two by least squares gives coefficients one point three three six and minus point six five oh, with standard errors near point oh six. The implied period is ten point six years, and the damping factor point eight one a year. Yule's own estimates were one point three four and minus point six five: a close agreement with a modern fit to the statsmodels record over his year window.

How good is the pendulum? Compare the sunspots' sample autocorrelations with those the fitted AR two implies. The dots are the model. Over the first cycle they agree closely: the fall to negative correlation around lag five, the return. But the data stay correlated at about point five a full cycle later, at lags ten and eleven, where the model has almost forgotten: point one. The real sunspot cycle is more regular than an AR two allows; its pendulum is damped too quickly. Chapter five will let the data choose a longer memory.

So: complex roots give a damped oscillation in the autocorrelations, and random shocks keep it alive, so the cycles vary in height and length. A cycle in the data doesn't prove a periodic cause, and averaging noise can make one. Yule and Slutsky's picture, random shocks driving a resonant system, became the standard model of business cycles in economics, and it fits lynx and hare counts, river flows and sunspots alike.

Numbers: (1.3, −0.6): r = 0.775, period 10.9; sunspots LS (1.336, −0.650), SE 0.058, period 10.6 years; ACF at lag 10–11: 0.5 vs 0.1 implied

4IdentificationMaster's4 min

The autocorrelation function has a partner. Fit the best linear predictor of the series from its last h values. Its last coefficient, phi h h, is the partial autocorrelation at lag h. It's the correlation between the series and its value h steps back, after removing what the observations in between explain, much as Part 12's partial regression coefficients did. The Durbin–Levinson recursion computes them all from the autocorrelations. For an AR of order p, once the p previous values are known, older ones add nothing, so the partial autocorrelation is exactly zero beyond lag p.

For minimal causal, invertible ARMA models with no cancelling factors, this gives theoretical fingerprints. An autoregression of order p: its autocorrelations tail off gradually, and its partial autocorrelations cut off sharply after lag p. A moving average of order q: the reverse. Its autocorrelations cut off after lag q, since shocks more than q steps apart share nothing, and its partial autocorrelations tail off. A mixed model: both tail off. White noise: both are zero. The symmetry isn't an accident. An autoregression is an infinite moving average, and an invertible moving average is an infinite autoregression.

Two simulated series of three hundred, and their four correlograms. An AR two: the autocorrelations swing and fade, a damped wave, while the partial autocorrelations are large at lags one and two, point seven nine and minus point six five, then drop inside the bands and stay there. An MA two: two large autocorrelations, and then nothing beyond the bands, apart from one bar at lag three that only just crosses, as one in twenty will. Its partial autocorrelations don't stop cleanly: in theory they decay forever, and here they leave small values of both signs. On real data the cut-offs are rarely this clean, but the signatures usually narrow the choice to a few candidates.

The sunspots. The autocorrelation function is a damped wave with a period near eleven: the signature of an autoregression with complex roots. The partial autocorrelations are large at lags one and two, point eight one and minus point six four, then small, with a few bars near the edge of the bands around lags six to eight. So the candidates are Yule's AR two, or a longer autoregression that also catches those later lags, and with them the cycle's regularity. Choosing between them is the next chapter's job.

In 1970 George Box and Gwilym Jenkins turned this into a method, in a book that made ARMA models standard practice. Identify a few candidate models from plots and correlograms. Estimate them. Check the residuals: if the model has captured the dependence, what's left should be white noise. If it isn't, go back and try again. Only then forecast. It's an iterative, modest method, and it embodies Box's famous remark that all models are wrong, but some are useful.

What about series that wander, like the random walk, or trend? Box and Jenkins's answer was to difference them. The first difference is the change from one period to the next. A random walk's differences are just its shocks: white noise. If the d-th differences of a series are a stationary ARMA, the series is called ARIMA, the I for integrated. That's what we did to Yule's marriages and deaths in the hook: their changes had little contemporaneous linear correlation. Whether a series really needs differencing is a question for a test, and Part 38 has it.

Numbers: simulated PACF 0.79, −0.65; sunspot PACF 0.81, −0.64

5EstimationMaster's4 min

How did Yule estimate his coefficients? Multiply the AR two by the value one step back and take expectations, then do the same with the value two steps back. Out come two equations linking the coefficients to the autocorrelations. In matrix form, the autocorrelation matrix times the coefficients equals the vector of autocorrelations: the Yule–Walker equations, after Yule and Gilbert Walker, who used them on air pressure in 1931. Plug in the sample autocorrelations of the sunspots, point eight one and point four three, and solve: one point three two six and minus point six four two. It's Part 9's method of moments, for a series.

The other natural method is Part 12's least squares, with the series' own past as the regressors. Here's each year's sunspot number against the year before's. Regressing on two lags gives one point three three six and minus point six five oh, very close to Yule–Walker. With Gaussian shocks this is the maximum likelihood estimate, conditional on the first two values, so the asymptotic theory of Part 9 supplies standard errors. Moving-average terms are harder, because the shocks they depend on aren't observed. They have to be reconstructed as the fit proceeds, which takes an iterative optimizer or the Kalman filter of Part 38.

How many lags? Hirotugu Akaike's information criterion, from 1973, balances fit against size: on a common sample, take its size times the log mean squared residual, plus twice the number of fitted mean parameters. A common constant includes the innovation-variance penalty. Smaller is better. For the sunspots, over orders zero to twelve: zero and one lag are hopeless. The minimum is at order eight. Yule's AR two is four point nine units worse: a real difference, but not a crushing one. Part 28 explains what such differences mean; for now, AIC prefers the longer memory that chapter three found missing.

Then check. If the model has captured the dependence, its residuals should be white noise, with autocorrelations inside the bands. The AR two's residuals are nearly clean, but there's a bump at lag eleven, just outside the band: the cycle-length memory it couldn't represent. The AR eight's residuals show nothing.

One test can summarize a whole correlogram. Greta Ljung and George Box's Q statistic adds up the squared residual autocorrelations over the first h lags, with weights that improve its small-sample behaviour. If the residuals are white noise, Q is approximately chi-squared, with one degree of freedom subtracted for each fitted AR or MA coefficient. For a model chosen after looking at these data, read the p-values as descriptive checks. For the AR two, Q over twenty lags is twenty-four point one, p equals point one five: it passes, the lag-eleven bump diluted among twenty lags. For the AR eight, p equals point four eight. Both pass. A portmanteau test like this one is a coarse net: passing it doesn't make a model right.

So: under regular stable autoregressive assumptions, Yule–Walker and least squares approach the same target. AIC chooses how much memory to keep. Residual checks catch what a model has missed, though summary tests like Ljung–Box are coarse. Yule's AR two has three parameters and a physical story; the AR eight has nine, and fits better. Which is better in the sense that matters? The honest referee is prediction of data the model hasn't seen.

Numbers: YW (1.326, −0.642); AIC best p = 8, p = 2 is 4.9 higher; Ljung–Box Q(20) = 24.1 (p = 0.15) and 11.6 (p = 0.48)

6ForecastingBachelor's5 min

The best forecast, in mean squared error, is the conditional mean of the future given the past. For the Gaussian innovation models used here, future shocks have conditional mean zero, so it is easy to compute: run the model's recursion forward, setting every future shock to its mean, zero. For an AR one, the forecast h steps ahead is the current deviation from the mean, shrunk by phi to the h. As h grows, the forecast returns to the mean: memory fades. Its error is made of the shocks that will arrive between now and then, weighted by the psi weights of chapter two, so its variance is sigma squared times the sum of the first h squared weights.

For an AR one with phi point eight, here's the forecast's standard error against the horizon. One step ahead it's just sigma, the size of a single shock. It grows with the horizon, and levels off at the standard deviation of the series itself, one point six seven sigma. Far enough ahead, the past tells us nothing: the forecast is the mean, and its interval is the series' ordinary range. Stable causal ARMA models with decaying impulse weights behave this way; a stationary deterministic component can remain predictable. A random walk, whose variance has no limit, has intervals that widen forever.

For a random walk the story is different. The next step is equally likely to go up or down, so the best forecast for every horizon is simply the last value: no change. But the errors accumulate, one shock per step, so the forecast's standard error is sigma times the square root of h, and the interval keeps widening without limit. This is the naive forecast that every method must beat. For stock prices and exchange rates, which behave much like random walks, it is notoriously hard to beat.

Now the sunspots. Stand in 1924, at the end of Yule's data, with everything before it to fit. The AR two forecasts one damped swing up from the low of 1924, peaking a little above fifty, and then settles to the mean of forty-four. The band is the ninety-five percent forecast interval, widening quickly to the full range of the series, and below zero, which a sunspot count cannot be: the normal shocks are only an approximation. In grey, what actually happened: three full cycles, with a peak of a hundred and fifty-two in 1947. The AR two caught the first rise, and after that it only knew the mean.

The AR eight, chosen by AIC, forecasts more. From the same 1924 low, it predicts a rise to about seventy by 1927, close to the real seventy-eight of 1928, then a fall, and then a second, smaller cycle. Its swings also fade toward the mean, but more slowly: it remembers the eleven-year rhythm. Neither model saw the great peak of 1947 coming. No linear model can predict the height of a cycle that far ahead: the shocks that will build it haven't happened yet.

How to score forecasts fairly across series of different scales? Rob Hyndman and Anne Koehler's mean absolute scaled error divides the forecast's average absolute error by the average one-step change within the training data, so below one beats the naive forecast's typical in-sample error. Over the first eleven years, one full cycle, the naive forecast, the 1924 value carried forward, scores one point six nine. The long-run mean, one point three eight. Yule's AR two, one point two oh. And the AR eight, point five eight: half the AR two's error. Here the extra memory that AIC chose was worth having.

Some cautions. Forecast intervals assume the model is right and its parameters known. Estimated parameters add error, which refitting simulated training histories and adding new future shocks in Part 16's parametric bootstrap, can include. Normal shocks gave intervals that went below zero; sunspot numbers are skewed, and a square-root transformation is often used. Of the thirty-one years forecast, eighty-seven percent of the outcomes fell inside the AR two's ninety-five percent bands, and ninety percent inside the AR eight's: short of the promise, though thirty-one correlated years are a small test. Above all, score forecasts on data the model never saw.

Numbers: AR(1) φ = 0.8: SE → 1.67σ; MASE over 1925–35: naive 1.69, mean 1.38, AR(2) 1.20, AR(8) 0.58; 87% and 90% of 31 outcomes inside the 95% bands

7Trend and seasonalityBachelor's4 min

In 1958 Charles David Keeling began measuring carbon dioxide in the air on Mauna Loa, a Hawaiian volcano three thousand four hundred metres up, far from local sources. Here are monthly averages, with historical gaps interpolated, to the end of 2001. Two things are obvious at once. The level rises, from three hundred and sixteen parts per million in 1959 to three hundred and seventy-one in 2001. And it waves, up and down, every year. Neither a trend nor a season is stationary. To model the series, first take it apart.

The classical decomposition writes the series as a trend, plus a seasonal pattern, plus a remainder. Estimate the trend with a moving average spanning exactly one year: thirteen months centred on each point, with half weight on the two ends, so every calendar month counts equally and the seasonal wave cancels. Subtract the trend, and average what's left for each calendar month: twelve numbers, adjusted to sum to zero, the seasonal figure. What remains is the remainder. If the decomposition has worked, it should look like a stationary series, ready for chapter two's models.

Here's the result, as four panels on a common time axis. The data. The trend: smooth, and steepening. The seasonal component: the same wave each year, about six parts per million from trough to peak. And the remainder: small wiggles with a standard deviation of a quarter of a part per million. It still has some memory, and an ARMA model could describe it, but the trend and the season carry nearly everything.

The seasonal figure, month by month. The air holds the most carbon dioxide in May, nearly three parts per million above the trend, and the least in September and October, about three below. It's the breathing of the northern hemisphere's vegetation, which has most of the planet's land: plants draw carbon dioxide in as they grow through the summer, and decay and respiration release it through the winter. A statistical decomposition, read the right way, shows a planet breathing.

The trend deserves its own look. In the first decade it rose about three quarters of a part per million a year. In the last decade of the record, one point six four: more than twice as fast. The growth is accelerating, so a straight-line trend fitted to the whole record would forecast too low. Any trend we extrapolate is an assumption about the future, and the forecasting methods of the next chapter let the trend's slope adapt as the data arrive.

Is the remainder really just noise? Chapter five's check says no. Its autocorrelation at lag one is point four: successive residuals still have linear dependence. And there's a wave in the correlogram, negative around lags four to seven and positive again at a year. The Ljung–Box statistic is enormous. This Q is descriptive: estimating and removing the trend and season itself induces dependence, so its usual white-noise chi-squared calibration does not directly apply. A changing seasonal pattern is another possible explanation, and twelve fixed numbers may miss it. Methods that let the season evolve, and an ARMA model for what's left, do better.

Some variations. When the seasonal swing grows with the level, as in retail sales, a multiplicative model may be useful; with positive observations, logarithms turn its components into additive terms. STL, from Robert Cleveland and colleagues in 1990, replaces the moving averages with local regressions and lets the seasonal pattern change slowly over the years. Statistical agencies use the X-11 and X-13 programs to seasonally adjust unemployment and output figures, the series you read in the news, with the estimated season removed. But a decomposition describes the past. To forecast, we need a model of how the level, the slope and the season move.

Numbers: 316 → 371 ppm; seasonal May +2.9, October −3.2; trend 0.75 → 1.64 ppm/yr; remainder SD 0.27, ρ̂(1) = 0.40

8Exponential smoothingPractice5 min

In the 1950s, operations researchers forecasting inventories for the US Navy and for factories needed something simpler than Box and Jenkins. Robert Brown and Charles Holt proposed simple exponential smoothing: keep a running level, and each period move it a fraction alpha of the way toward the new observation. The forecast for every future period is the current level. Unrolled, the level is a weighted average of the observed history plus a diminishing initialization term, with weights that fall off geometrically, by a factor one minus alpha per period: recent data count most, and the past is forgotten gracefully. Alpha near one tracks the latest value; alpha near zero averages over a long history.

Here is Yule's mortality series again, with exponential smoothing's one-step-ahead forecasts. With alpha point three, the forecast is smooth, but it lags behind the steady fall in deaths. With alpha point eight it follows each year closely, noise and all. Either way the forecast trails a trend: simple smoothing assumes a level that wanders, not one that slopes. It needs a second component.

Holt added a slope, and his student Peter Winters a season, in 1960. The level is smoothed as before, after removing the seasonal effect for this month. The slope is smoothed too: a running average of how much the level changes each period, with its own smoothing constant beta. And each calendar month's seasonal effect is updated, with constant gamma, whenever that month comes round. The forecast h periods ahead is the level, plus h times the slope, plus the right month's seasonal effect. Three smoothing constants, chosen to minimize the one-step forecast errors on the past.

Let's forecast Keeling's curve. Fit Holt–Winters to the record up to the end of 1997, and forecast the next four years, month by month. The fitted constants: alpha about a half, beta point oh one, gamma about a half. The tiny beta means the slope is estimated from a long stretch of history, while level and season adapt quickly. For comparison, the seasonal naive forecast simply repeats the last year's values. And here's what was recorded. Holt–Winters tracks it closely for four years; the seasonal naive forecast, with no trend, falls steadily behind.

The scores, as mean absolute scaled errors, scaled this time by the seasonal naive forecast's in-sample error. Simple smoothing, a flat line with no trend or season: four point five three. The seasonal naive forecast: four point oh two, because the series has climbed since last year. Adding the average yearly rise to it: one point five three. Holt–Winters: point seven eight. Each component the model represents, the season, then the trend, cuts the error substantially.

One small change to Holt's method has a remarkable record. Holt's forecast extends today's slope forever, in a straight line. Over long horizons that's usually too bold: growth rarely continues unchecked. Everette Gardner and Ed McKenzie, in 1985, multiplied the slope's contribution by a damping factor phi at each step ahead, so the forecast trend fades and the forecast levels off. With phi point nine five it bends gently; with point eight five, sooner. This damped trend was among the most accurate methods in the M3 competition, and it's now a standard benchmark.

Is this ad hoc? Less than it looks. John Muth showed in 1960 that simple exponential smoothing gives the optimal forecast for a particular model, an ARIMA zero one one, which is a random walk observed with noise: the smoothing constant is set by the ratio of the two variances. In 2002 Rob Hyndman and colleagues showed that the standard exponential smoothing methods can be represented as forecasts of state-space models, the ETS family, for error, trend and season. So smoothing methods have likelihoods, prediction intervals and information criteria, like everything else in this part.

Numbers: Holt–Winters α = 0.51, β = 0.01, γ = 0.50; MASE 4.53 (flat), 4.02 (seasonal naive), 1.53 (+ drift), 0.78 (Holt–Winters)

9Spurious regressionBachelor's4 min

Yule's nonsense correlations have a modern name: spurious regression. Here are two random walks of a hundred steps, generated completely independently. Regress one on the other by Part 12's least squares. The slope's t statistic is minus thirteen point two. R squared is point six four, and the nominal p-value is about two times ten to the minus twenty-three. And the two series have nothing to do with each other.

Was that a fluke? If the regression assumptions held, the t statistic would follow Student's t distribution, in grey, and exceed one point nine eight only five percent of the time. Here are five thousand pairs of independent random walks. The t statistics are spread over a range ten times wider. Seventy-five percent of them are significant at the five percent level. Half exceed four point four. Clive Granger and Paul Newbold ran this experiment in 1974 and warned econometricians that many published regressions between trending economic series were nonsense.

Why does it happen? The true slope is zero, so the regression's error term is just the second walk itself, minus a constant. That error is a random walk: not independent, not even stationary. The usual standard error assumes independent errors, and with errors this persistent it's far too small, the problem of chapter one, in its most extreme form. Peter Phillips proved in 1986 that the t statistic doesn't settle down to any distribution: it grows like the square root of n. More data makes the nonsense more significant, not less.

There's a warning light. James Durbin and Geoffrey Watson's statistic of 1950 compares the squared changes in the residuals with their squares: roughly two times one minus their lag-one autocorrelation. Independent residuals give a value near two. In the random-walk regressions, the median is point one five: the residuals hardly change from one step to the next. Granger and Newbold's rule of thumb: when R squared exceeds the Durbin–Watson statistic, suspect a spurious regression. In our example, R squared point six four, Durbin–Watson point two nine.

The cure is the one Box and Jenkins used: difference. Regress the changes in one series on the changes in the other. For random walks, the differences are white noise, and the regression assumptions hold. The t statistics now follow Student's t, and five point four percent exceed the critical value, as they should. There's one important exception. Sometimes two wandering series really are tied together, so that a combination of them is stationary, like a drunk and her dog on a lead. Robert Engle and Granger developed the theory of this cointegration in 1987; it was the work for which Granger shared the 2003 Nobel prize in economics. Part 38 tests for it.

The Coverage Board, ten thousand pairs of walks of a hundred. The slope's t-test in levels has a size of seventy-seven percent where five was promised: the worst row the Board has seen since the bootstrap of a maximum. In differences, five point oh percent: kept.

So: regressing one trending series on another proves nothing by itself. Look at the residuals; a Durbin–Watson statistic far below two is a red flag. Difference, or model the dependence, before believing a test. Yule's marriages and deaths showed it in 1926: point nine five in levels, point oh two in changes. The trap is everywhere. Common trends can create misleading association between unrelated series: in a famous joke, global temperatures with the falling number of pirates.

Numbers: example t = −13.2, R² = 0.64, DW = 0.29; 75% significant; median R² 0.17, DW 0.15; differences 5.4%; Board 76.7%, 5.0%

10The M-competitionsPractice4 min

In 1979 Spyros Makridakis and Michèle Hibon compared forecasting methods on a hundred and eleven real series, holding out the last observations of each. Their finding was awkward: the sophisticated methods, Box–Jenkins included, were not more accurate than simple ones. The discussants at the Royal Statistical Society objected that the methods must have been misapplied. So Makridakis invited the experts to forecast the series themselves. The M-competition of 1982 used a thousand and one series; M3, in 2000, three thousand and three; M4, in 2018, a hundred thousand.

The conclusions held up through every round. Sophisticated methods aren't necessarily more accurate than simple ones. Which method wins depends on how accuracy is measured and how far ahead. Averaging the forecasts of several methods beats most of the methods being averaged. And simple benchmarks, exponential smoothing with a damped trend especially, are very hard to beat. In M4, the top entries combined statistical models with machine learning, and pure machine-learning entries did poorly: a lesson Part 19 will return to.

We can run a small competition of our own. Sixty-three series: sixty simulated, some stationary, some random walks, some with trends, plus Yule's two series and the sunspots since 1900. Hold out the last six values of each and forecast them five ways. The naive forecast, the last value carried forward. The drift method, which continues the average step. Simple exponential smoothing. An autoregression with its order chosen by AIC. And the plain average of the last three. On average scaled error, four of them are within two percent of each other. The combination comes first, about three percent better than its best component.

Rank the five methods on each series and average. The combination's mean rank is two point five nine; every single method is near three. It's rarely the best on any one series, but it's rarely bad. Judged by the median error instead, the drift method comes first. The competitions' second lesson, reproduced in miniature: the ranking depends on the measure.

Why does averaging work? Average two forecasts, and you average their errors. By Part 5, the variance of the average depends on how correlated the errors are. For unbiased errors with equal variance, the combined variance is sigma squared times one plus rho over two, never more than either alone, and less whenever their errors aren't perfectly correlated. With a correlation of a half, a quarter of the error variance disappears. John Bates and Clive Granger made the case in 1969. Different methods make different mistakes, and averaging lets them cancel: the same principle as averaging observations, applied to opinions.

How should a method be chosen for a single series, without a competition? With cross-validation, adapted to time. Fit on the data up to some origin and score the forecasts of the next few values. Then roll the origin forward, refit, and score again, and average the scores. Every forecast uses only the past, as a real one would. Part 16's random folds would scatter future observations into the fitting set and make evaluation of future forecasting too optimistic. It need not affect every method equally. Holding out the end of each series is exactly what the competitions did.

The lessons for practice. Judge forecasts on data held out, never on the fit. Always compare with naive benchmarks: the last value, or last year's value. A method that can't beat them isn't worth its complexity. Models are tools, and the one that fits the past best isn't always the one that forecasts best. When unsure, combine. And report intervals, which the later competitions scored too: a forecast without its uncertainty invites false confidence.

Numbers: 63 series, 6 ahead: mean MASE 1.84, 1.84, 1.86, 1.83, combination 1.78; mean rank 2.59 for the combination

Recap, problems, and the road aheadAll tracks3 min

Part seventeen in fourteen lines. Yule showed that series which merely drift correlate by nonsense. Stationarity makes a series' dependence stable, and the autocorrelation function, with Bartlett's bands, measures it. Positive autocorrelation usually reduces the effective sample size of a mean; negative correlation can increase it. HAC standard errors and block bootstraps partly repair the mean's interval. Autoregressions and moving averages build memory out of shocks, and the roots of a polynomial decide whether that memory fades. Complex roots make pseudo-cycles, and so, Slutsky showed, does averaging noise. The ACF and PACF are fingerprints; Box and Jenkins turned them into a cycle of identifying, estimating and checking, with Yule–Walker, AIC and Ljung–Box as tools. Stable causal ARMA forecasts return to the mean and their intervals widen. Trend and season can be taken apart, and exponential smoothing forecasts them. Regressions between wandering series need a dependence model: differencing can help, while cointegration can make a levels relationship meaningful. And when unsure, combine forecasts.

Where it comes back. Part 19's cross-validation must respect time, with rolling forecast origins. Part 38 takes time series in depth: the Kalman filter and state-space models, spectra, tests for unit roots, cointegration and volatility models. Part 39 meets dependence in space instead of time. Part 44 builds the probability of dependent sequences, martingales and mixing. Part 58 monitors a stream of data with guarantees at every moment. And Part 64 asks what machine learning has changed in forecasting.

Six problems, with full solutions in the README. An AR one's moments and forecast; a bound on an MA one's autocorrelation; an effective sample size; stationarity from roots; the Yule–Walker equations; and the weights of exponential smoothing. Pause here if you want to try them.

The books and papers this part follows: Box and Jenkins, now in its fifth edition; Brockwell and Davis; Hyndman and Athanasopoulos's free online text; Shumway and Stoffer; with the papers from Yule and Slutsky to Newey, West and the M-competitions.

Seventeen parts of sixty-five, the seventh of Stage II. We can now handle data that remember their past. But every part so far has trusted that the data were a fair sample of something. In 1936 the Literary Digest mailed ten million ballots, received two point four million back, and predicted that Alf Landon would beat Franklin Roosevelt. Roosevelt won forty-six of forty-eight states. Part 18: who did you ask?

Where it goes next. Rolling-origin evaluation returns in Part 19; spectra, unit-root tests, cointegration, GARCH and the Kalman filter are Part 38; dependence in space is Part 39, and martingales and mixing are Part 44.

Key results

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

The mean of an AR(1)\(\displaystyle \operatorname{Var}(\bar X)\approx\frac{\sigma_X^2}{n}\cdot\frac{1+\rho}{1-\rho},\qquad\allowbreak n_{\text{eff}}=n\,\frac{1-\rho}{1+\rho}\)
Stationarity (causality)\(\displaystyle \phi(z)=1-\phi_1z-\dots-\phi_pz^p\neq 0\quad\allowbreak \text{for }\allowbreak \text{all }|z|\le 1\)
AR(2) pseudo-cycle\(\displaystyle \phi_1^2+4\phi_2<0:\quad\allowbreak \rho(h)=(-\phi_2)^{h/2}\,\frac{\cos(h\omega-\psi)}{\cos\psi},\quad\allowbreak \cos\omega=\frac{\phi_1}{2\sqrt{-\phi_2}}\)
Yule-Walker\(\displaystyle \rho(h)=\phi_1\rho(h-1)+\dots+\phi_p\rho(h-p),\qquad\allowbreak h=1,\dots,p\)
AR(1) forecast\(\displaystyle \hat X_{n+h}=\mu+\phi^{h}(X_n-\mu),\qquad\allowbreak \operatorname{Var}(X_{n+h}-\hat X_{n+h})=\sigma^2\,\frac{1-\phi^{2h}}{1-\phi^{2}}\)
Exponential smoothing\(\displaystyle \ell_t=\alpha y_t+(1-\alpha)\ell_{t-1}=\alpha\sum_{j\ge 0}(1-\alpha)^{j}y_{t-j}\quad\allowbreak (\text{up }\allowbreak \text{to }\allowbreak \text{the }\allowbreak \text{starting }\allowbreak \text{value})\)

Try it

Lab 17 · Statistics on series that remember

Simulate an AR(1) with rho = 0.7 four thousand times and compare the spread of its mean with the iid formula and with (1 + rho)/(1 - rho); then regress two thousand independent random walks on one another, in levels and in differences, and count the 'significant' slopes.

Figure produced by Lab 17: Statistics on series that remember
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.stats.labs 17 needs numpy, scipy, matplotlib · download lab17.py · source on GitHub
AR(1), rho = 0.7, n = 100: sd of the mean            0.330   (theory 0.329)
mean SE: iid formula / Newey-West                    0.136 / 0.229
variance inflation over the iid formula              5.84   ((1 + rho)/(1 - rho) = 5.67; n_eff = 17.6)
95% interval covers: iid t / Newey-West              57.8% / 78.7%
two independent walks, n = 100: slope 'significant'  levels 75.4%   differences 5.0%   (nominal 5%)
share of pairs with |r| > 0.5 in levels              38.6%

Positive autocorrelation leaves the mean unbiased but makes 100 observations worth about 18, and two unrelated random walks pass a slope test three times in four; differencing brings the test back to 5%.
The code (84 lines; it asserts its own result)
"""Lab 17: what memory does to the mean of a series, and to the regression of one random walk on another."""

import numpy as np
from scipy import signal, stats

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

TITLE = "Statistics on series that remember"
GOAL = ("Simulate an AR(1) with rho = 0.7 four thousand times and compare the spread of its mean with the iid formula "
        "and with (1 + rho)/(1 - rho); then regress two thousand independent random walks on one another, in levels "
        "and in differences, and count the 'significant' slopes.")
TASKS = [
    "Set rho = -0.5. Is the iid interval now too narrow or too wide, and what is the effective sample size?",
    "Replace the random walks by AR(1) series with phi = 0.9. How much of the spurious significance remains?",
    "Use ts.block_bootstrap_means with blocks of 10 on one AR(1) series and compare its SE with the three in the table.",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. the mean of an AR(1): n observations are worth n (1 - rho)/(1 + rho)
    n, reps, rho = 100, 4000, 0.7
    e = rng.standard_normal((reps, n + 200))
    x = signal.lfilter([1.0], [1.0, -rho], e, axis=1)[:, 200:]  # x_t = rho x_{t-1} + e_t, after a burn-in
    means = x.mean(1)
    sd_true = means.std(ddof=1)
    se_iid = x.std(axis=1, ddof=1) / np.sqrt(n)
    se_nw = np.array([ts.newey_west_se(row) for row in x[:1000]])
    k = np.arange(1, n)
    inflation_n = 1 + 2 * np.sum((1 - k / n) * rho ** k)  # exact for n = 100; tends to (1 + rho)/(1 - rho)
    sd_theory = np.sqrt(inflation_n / (1 - rho ** 2) / n)
    tcrit = stats.t.ppf(0.975, n - 1)
    cover_iid = np.mean(np.abs(means) < tcrit * se_iid)
    cover_nw = np.mean(np.abs(means[:1000]) < 1.96 * se_nw)
    ratio = (sd_true / np.sqrt(np.mean(se_iid ** 2))) ** 2
    lab.row("AR(1), rho = 0.7, n = 100: sd of the mean", f"{sd_true:.3f}   (theory {sd_theory:.3f})")
    lab.row("mean SE: iid formula / Newey-West", f"{se_iid.mean():.3f} / {se_nw.mean():.3f}")
    lab.row("variance inflation over the iid formula", f"{ratio:.2f}   ((1 + rho)/(1 - rho) = {(1 + rho) / (1 - rho):.2f}; "
            f"n_eff = {ts.ar1_neff(n, rho):.1f})")
    lab.row("95% interval covers: iid t / Newey-West", f"{cover_iid:.1%} / {cover_nw:.1%}")
    assert abs(sd_true / sd_theory - 1) < 0.05, "the spread of the mean follows the autocovariances"
    assert 4.3 < ratio < 7.0, "the iid variance is too small by about (1 + rho)/(1 - rho)"
    assert 0.50 < cover_iid < 0.66 and cover_iid + 0.12 < cover_nw < 0.93, "iid breaks; HAC repairs part of it"

    # 2. spurious regression: independent random walks
    m, pairs = 100, 2000
    a = np.array([ts.random_walk(m, rng) for _ in range(pairs)])
    b = np.array([ts.random_walk(m, rng) for _ in range(pairs)])

    def slope_t(u, v):
        u, v = u - u.mean(1, keepdims=True), v - v.mean(1, keepdims=True)
        r = (u * v).sum(1) / np.sqrt((u * u).sum(1) * (v * v).sum(1))
        return r * np.sqrt((u.shape[1] - 2) / (1 - r * r)), r

    t_lev, r_lev = slope_t(a, b)
    t_dif, _ = slope_t(np.diff(a, axis=1), np.diff(b, axis=1))
    rej_lev = np.mean(np.abs(t_lev) > stats.t.ppf(0.975, m - 2))
    rej_dif = np.mean(np.abs(t_dif) > stats.t.ppf(0.975, m - 3))
    lab.row("two independent walks, n = 100: slope 'significant'", f"levels {rej_lev:.1%}   differences {rej_dif:.1%}   (nominal 5%)")
    lab.row("share of pairs with |r| > 0.5 in levels", f"{np.mean(np.abs(r_lev) > 0.5):.1%}")
    assert rej_lev > 0.68, "three quarters of unrelated walks look related"
    assert 0.03 < rej_dif < 0.075, "differencing restores the test's size"
    lab.note = ("Positive autocorrelation leaves the mean unbiased but makes 100 observations worth about 18, and two "
                "unrelated random walks pass a slope test three times in four; differencing brings the test back to 5%.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    grid = np.linspace(-1.3, 1.3, 200)
    ax[0].hist(means, bins=60, density=True, color=labs.BLUE, alpha=0.6, label="4,000 means of an AR(1)")
    ax[0].plot(grid, stats.norm.pdf(grid, 0, se_iid.mean()), color=labs.RED, label="normal with the iid SE")
    ax[0].plot(grid, stats.norm.pdf(grid, 0, sd_theory), color=labs.GREEN, label="normal with the true sd")
    ax[0].set(title="The mean of 100 remembered observations", xlabel="sample mean (truth 0)", ylabel="density")
    ax[0].legend(loc="upper left")
    bins = np.linspace(-30, 30, 61)
    ax[1].hist(np.clip(t_lev, -30, 30), bins=bins, density=True, color=labs.RED, alpha=0.6, label=f"levels: {rej_lev:.0%} beyond ±2")
    ax[1].hist(t_dif, bins=bins, density=True, color=labs.GREEN, alpha=0.6, label=f"differences: {rej_dif:.0%} beyond ±2")
    ax[1].axvline(-1.98, color=labs.MUTED, ls="--")
    ax[1].axvline(1.98, color=labs.MUTED, ls="--")
    ax[1].set(title="Slope t statistics for two independent random walks", xlabel="t (clipped at ±30)", ylabel="density")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Set rho = -0.5. Is the iid interval now too narrow or too wide, and what is the effective sample size?
  2. Replace the random walks by AR(1) series with phi = 0.9. How much of the spurious significance remains?
  3. Use ts.block_bootstrap_means with blocks of 10 on one AR(1) series and compare its SE with the three in the table.

Problems, with solutions

Try each problem before opening its solution.

1. An AR(1). AR(1) with \(\phi = 0.6\), \(\mu = 0\): \(\rho(2)\), \(\mathrm{Var}(X_t)/\sigma^2\), and the 2-step forecast and its SE from \(x_n = 5\).

Solution

ρ(2) = φ² = 0.36. Var(Xₜ) = σ²/(1 − φ²) = σ²/0.64 = 1.5625σ². The two-step forecast is φ²xₙ = 0.36 × 5 = 1.8, with error eₙ₊₂ + φeₙ₊₁, so its SE is σ√(1 + φ²) = σ√1.36 ≈ 1.166σ.

2. An MA(1)'s autocorrelation. Show that an MA(1) has \(|\rho(1)| \le \tfrac12\), with equality only at \(\theta = \pm 1\).

Solution

ρ(1) = θ/(1 + θ²). Since (1 − |θ|)² ≥ 0, 1 + θ² ≥ 2|θ|, so |ρ(1)| ≤ ½, with equality only when |θ| = 1. The population lag-one ACF cannot exceed ½ in magnitude under this MA(1) model. A sample ACF can exceed the bound through sampling error, so a single observed spike does not rule out the model.

3. An effective sample size. The effective sample size of the mean of 200 observations from an AR(1) with \(\rho = 0.5\).

Solution

For large n, n_eff ≈ n(1 − ρ)/(1 + ρ) = 200 × 0.5/1.5 ≈ 66.7. The mean's SE is about √3 ≈ 1.73 times the iid formula.

4. Is it stationary? Is the AR(2) with \(\phi_1 = 0.5\), \(\phi_2 = 0.3\) stationary? Find its roots.

Solution

φ(z) = 1 − 0.5z − 0.3z². Its roots solve 0.3z² + 0.5z − 1 = 0: z = (−0.5 ± √(0.25 + 1.2))/0.6, that is z ≈ 1.174 and z ≈ −2.840. Both lie outside the unit circle, so the model is causal and stationary with the model innovations. The triangle agrees: φ₁ + φ₂ = 0.8 < 1, φ₂ − φ₁ = −0.2 < 1 and |φ₂| < 1. The roots are real (φ₁² + 4φ₂ = 1.45 > 0), so there is no complex-root pseudo-cycle; a negative real root can still contribute alternating signs.

5. Yule–Walker for an AR(2). Yule–Walker for an AR(2), given \(\hat\rho_1 = 0.7\) and \(\hat\rho_2 = 0.5\).

Solution

Solving ρ₁ = φ₁ + φ₂ρ₁ and ρ₂ = φ₁ρ₁ + φ₂ gives φ₁ = ρ₁(1 − ρ₂)/(1 − ρ₁²) and φ₂ = (ρ₂ − ρ₁²)/(1 − ρ₁²).

  • φ₁: 0.7 × 0.5/0.51 ≈ 0.686.
  • φ₂: (0.5 − 0.49)/0.51 ≈ 0.020.

The second lag adds almost nothing: these autocorrelations are close to an AR(1)'s (0.7, 0.49).

6. The weights of exponential smoothing. Show that simple smoothing's weights sum to 1, and that the average age of the data they weight is \((1 - \alpha)/\alpha\).

Solution

Σⱼ α(1 − α)ʲ = α/(1 − (1 − α)) = 1. Their average age is Σⱼ jα(1 − α)ʲ = α(1 − α)/α² = (1 − α)/α: 2.33 periods for α = 0.3, 0.25 for α = 0.8.

Notes and sources

Where it comes back

Idea Returns in
time-series cross-validation, rolling origins 19
spectra, unit-root tests, cointegration, GARCH, the Kalman filter 38
dependence in space 39
martingales, mixing, ergodic theorems 44
monitoring a stream with anytime-valid guarantees 58
forecasting with machine learning 64
the Coverage Board every part; 65

Glossary

  • Time series: observations indexed by time, usually dependent.
  • (Weak) stationarity: a constant mean and a covariance γ(h) depending only on the lag h.
  • Autocorrelation function (ACF), ρ(h): the correlation of a series with itself h steps back.
  • Partial autocorrelation (PACF), α(h): the last coefficient of the best AR(h) predictor; the correlation at lag h after removing the lags in between.
  • White noise: uncorrelated shocks with mean 0 and constant variance.
  • Correlogram; Bartlett's bands: a sample ACF plot; ±2/√n are approximate pointwise 95% reference bands under IID noise with suitable moments, not simultaneous limits for arbitrary uncorrelated noise.
  • Effective sample size: the number of independent observations carrying the same information about the mean.
  • HAC (Newey–West) standard error: an SE built from weighted sample autocovariances.
  • Moving-block bootstrap: resampling blocks of consecutive observations to keep their dependence.
  • AR(p), MA(q), ARMA(p, q): autoregressive, moving-average and mixed models built from shocks.
  • ψ weights; Wold decomposition: a finite-variance weakly stationary series is a linearly deterministic component plus an MA(∞) of uncorrelated innovations.
  • Causal stationary and invertible: AR and MA polynomial roots outside the unit circle.
  • Unit root; random walk: φ = 1; shocks never fade and the variance grows without limit.
  • Pseudo-cycle: a quasi-periodic swing from complex roots, with varying amplitude and length.
  • Box–Jenkins cycle: identify, estimate, check, forecast.
  • Differencing; ARIMA(p, d, q): modelling the d-th differences as an ARMA.
  • Yule–Walker equations: moment equations linking AR coefficients to autocorrelations.
  • AIC: n log σ̂² + 2(number of parameters); smaller is better.
  • Ljung–Box Q: a portmanteau test that residual autocorrelations are all zero.
  • MASE: mean absolute error scaled by the in-sample error of a naive forecast.
  • Classical decomposition; seasonal figure: trend by a centred moving average, season by monthly averages.
  • Exponential smoothing; Holt–Winters; damped trend: forecasts from smoothed level, slope and season.
  • Spurious regression: a significant regression between independent nonstationary series.
  • Durbin–Watson statistic: ≈ 2(1 − ρ̂₁) of the residuals; far below 2 signals autocorrelation.
  • Cointegration: nonstationary series with a stationary combination.
  • Forecast combination: averaging forecasts so that their errors partly cancel.
  • Rolling-origin evaluation: cross-validation for time, always forecasting from the past.

Sources

  • Yule, Slutsky and the founders.
    • G. U. Yule, JRSS 89 (1926), 1–63; Phil. Trans. R. Soc. A 226 (1927), 267–298.
    • E. Slutsky, Problems of Economic Conditions 3 (1927; English in Econometrica 5, 1937).
    • G. Walker, Proc. R. Soc. A 131 (1931); H. Wold, A Study in the Analysis of Stationary Time Series (1938).
    • M. Bartlett, JRSS Suppl. 8 (1946); J. Durbin & G. Watson, Biometrika 37 (1950).
  • Models and methods.
    • G. Box & G. Jenkins, Time Series Analysis: Forecasting and Control (1970); G. Ljung & G. Box, Biometrika 65 (1978); H. Akaike, in 2nd Int. Symp. Information Theory (1973).
    • R. Brown, Statistical Forecasting for Inventory Control (1959); C. Holt, ONR memorandum 52 (1957; reprinted IJF 20, 2004); P. Winters, Management Science 6 (1960); J. Muth, JASA 55 (1960).
    • E. Gardner & E. McKenzie, Management Science 31 (1985); R. Hyndman, A. Koehler, R. Snyder & S. Grose, IJF 18 (2002); R. Hyndman & A. Koehler, IJF 22 (2006).
    • R. Cleveland, W. Cleveland, J. McRae & I. Terpenning, J. Official Statistics 6 (1990).
    • W. Newey & K. West, Econometrica 55 (1987); H. Künsch, Ann. Stat. 17 (1989).
  • Spurious regression and forecasting practice.
    • C. Granger & P. Newbold, J. Econometrics 2 (1974); P. Phillips, J. Econometrics 33 (1986); R. Engle & C. Granger, Econometrica 55 (1987).
    • J. Bates & C. Granger, Oper. Res. Q. 20 (1969); S. Makridakis & M. Hibon, JRSS A 142 (1979); S. Makridakis et al., J. Forecasting 1 (1982); IJF 16 (2000); IJF 36 (2020).
  • Books.
    • G. Box, G. Jenkins, G. Reinsel & G. Ljung, Time Series Analysis (5th ed., 2015); P. Brockwell & R. Davis, Introduction to Time Series and Forecasting (3rd ed., 2016); R. Hyndman & G. Athanasopoulos, Forecasting: Principles and Practice (3rd ed., 2021); R. Shumway & D. Stoffer, Time Series Analysis and Its Applications (4th ed., 2017).
  • Data. K. Hipel & A. McLeod's time-series collection (StatLib), roberts/yule1.1, yule2.1; the sunspot and CO₂ datasets in statsmodels.
About this partfrom its README

Part 17 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage II, Bachelor's: Methods. Every method so far assumed independent, or at least exchangeable, observations. This part asks what to do when each observation remembers the last.

It opens with Yule's presidential address of 1926: Church of England marriages and mortality in England and Wales, 1866–1911, correlate at r = 0.95 in levels and 0.02 in year-on-year changes. Independent random walks of 46 steps reach |r| > 0.5 in 39% of pairs, against 0.04% for independent noise. Then Yule's pendulum pelted with peas (1927).

From there the part covers:

  • Stationarity and the ACF. White noise, an AR(1) and a random walk side by side with their correlograms; Bartlett's bands. The variance of an autocorrelated mean: inflation (1 + ρ)/(1 − ρ) = 5.67 at ρ = 0.7, an effective sample size of 17.6 from 100. Newey–West and the basic moving-block bootstrap; three Board rows.
  • AR, MA, ARMA. The AR(1) as an MA(∞); a gallery of four models; φ = 0.5, 1 and 1.08 on the same shocks; roots outside the unit circle on the RootPlane; the AR(2) stationarity triangle and its parabola of complex roots; MA invertibility; Wold's theorem.
  • Pseudo-cycles. The damped-cosine ACF of complex roots; Slutsky's summed shocks; Yule's sunspot AR(2), (1.336, −0.650), period 10.6 years; where the AR(2) falls short of the data's ACF.
  • Identification. The PACF; the table of signatures; simulated AR(2) and MA(2); the sunspots' correlograms; the Box–Jenkins cycle; differencing and ARIMA.
  • Estimation. Yule–Walker and least squares; AIC over orders 0–12 (best: 8); residual correlograms; Ljung–Box.
  • Forecasting. Best linear prediction; widening intervals; the random walk's "no change"; the sunspots of 1925–1955 forecast from 1924 by AR(2) and AR(8); MASE; cautions.
  • Trend and seasonality. Keeling's Mauna Loa record; the classical decomposition in four panels; the seasonal figure (May +2.9, October −3.2 ppm); the accelerating trend (0.75 → 1.64 ppm a year); the remainder's leftover memory; STL and X-13.
  • Exponential smoothing. Brown and Holt's level; Yule's mortality smoothed; Holt–Winters forecasting CO₂ for 1998–2001 (MASE 0.78 vs 4.02 for the seasonal naive); the damped trend; Muth and ETS.
  • Spurious regression. Two independent walks with t = −13.2; Granger and Newbold's experiment (75% significant); Phillips's √n; Durbin–Watson and the R² > DW rule; differencing; cointegration; two Board rows.
  • The M-competitions. Makridakis and Hibon (1979) to M4 (2018); a 63-series competition of our own, in which the combination wins on average; Bates and Granger; rolling-origin evaluation.

Every number on screen is computed in compute.py or inline in a scene:

  • Yule's series (as Hipel and McLeod read them from his graph), the sunspots and the Mauna Loa CO₂ record (as statsmodels ships them) come from the Museum;
  • everything else is a seeded simulation.

Built in this part:

  • statkit.ts (I) (explainer/stats/kit/ts.py), checked against statsmodels in tests/test_stats_kit_ts.py:
    • the sample ACVF, ACF and PACF (Durbin–Levinson);
    • ARMA simulation, AR and MA roots, ψ weights, the theoretical ACF, the AR(2) period;
    • Yule–Walker, conditional least squares, AIC over AR orders, Ljung–Box;
    • AR forecasts with intervals, simple exponential smoothing, additive Holt–Winters with fitted constants, classical decomposition, MASE;
    • the AR(1) effective sample size, the Newey–West SE and the moving-block bootstrap.
  • The correlogram (Correlogram in explainer/stats/viz.py): ACF or PACF bars with Bartlett's bands, the bars outside them lit, and theoretical values as dots.
  • The root plane (RootPlane): the unit circle with polynomial roots coloured by side.
  • Yule's pendulum (YulePendulum): a pendulum whose swing follows a series.

The Coverage Board gains five rows, R = 10,000.

Method Setting Kind Achieved Verdict
iid t-interval, the mean AR(1), ρ = 0.7, n = 100 coverage 58.07% broken
Newey–West (HAC), the mean AR(1), ρ = 0.7, n = 100 coverage 81.17% broken
moving-block bootstrap (blocks of 10), the mean AR(1), ρ = 0.7, n = 100 coverage 84.15% broken
slope t-test, levels two independent random walks, n = 100 size 76.68% broken
slope t-test, differences two independent random walks, n = 100 size 5.04% kept
Chapter notes
# Chapter Numbers
0 Nonsense correlations, 1926 r = 0.9515 (Yule 0.9512), differences 0.0185; random walks |r| > 0.5 in 39%, noise 0.04%
1 Stationarity and the ACF bands ±0.14 (n = 200); inflation 5.67, n_eff 17.6; one series: iid SE 0.145, NW 0.260, block 0.303, true 0.329; Board 58.1%, 81.2%, 84.2%
2 AR, MA, ARMA MA(1) ρ(1) = 0.49; sunspot roots 1.03 ± 0.69i, modulus 1.24; ARMA(1,1) ψ = 1, 1.2, 0.84, 0.588
3 Pseudo-cycles (1.3, −0.6): r = 0.775, period 10.9; sunspots LS (1.336, −0.650), SE 0.058, period 10.6 years; ACF at lag 10–11: 0.5 vs 0.1 implied
4 Identification simulated PACF 0.79, −0.65; sunspot PACF 0.81, −0.64
5 Estimation YW (1.326, −0.642); AIC best p = 8, p = 2 is 4.9 higher; Ljung–Box Q(20) = 24.1 (p = 0.15) and 11.6 (p = 0.48)
6 Forecasting AR(1) φ = 0.8: SE → 1.67σ; MASE over 1925–35: naive 1.69, mean 1.38, AR(2) 1.20, AR(8) 0.58; 87% and 90% of 31 outcomes inside the 95% bands
7 Trend and seasonality 316 → 371 ppm; seasonal May +2.9, October −3.2; trend 0.75 → 1.64 ppm/yr; remainder SD 0.27, ρ̂(1) = 0.40
8 Exponential smoothing Holt–Winters α = 0.51, β = 0.01, γ = 0.50; MASE 4.53 (flat), 4.02 (seasonal naive), 1.53 (+ drift), 0.78 (Holt–Winters)
9 Spurious regression example t = −13.2, R² = 0.64, DW = 0.29; 75% significant; median R² 0.17, DW 0.15; differences 5.4%; Board 76.7%, 5.0%
10 The M-competitions 63 series, 6 ahead: mean MASE 1.84, 1.84, 1.86, 1.83, combination 1.78; mean rank 2.59 for the combination
11 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Yule (1926, 1927). C of E marriages vs mortality, r ≈ 0.95; AR(2) for sunspots.
  2. Stationarity and the ACF. White noise; the effective sample size of an autocorrelated mean (Board).
  3. AR, MA, ARMA. Causality and invertibility from roots; the unit circle.
  4. Pseudo-cycles. AR(2) complex roots; Slutsky (1927).
  5. Identification. ACF/PACF signatures; Box & Jenkins (1970).
  6. Estimation. Yule–Walker; least squares; Ljung–Box.
  7. Forecasting. Best linear prediction; widening intervals; MASE.
  8. Trend and seasonality. Decomposition; STL; Mauna Loa CO₂.
  9. Exponential smoothing. Holt–Winters.
  10. Spurious regression, first look. Two random walks "correlate" (Board).
  11. The M-competitions' lesson. Simple methods and combinations are hard to beat.
  12. Outro.

Built: statkit.ts (I). Data: Yule (1926); NOAA CO₂.

Build the film

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

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

Build it
python -m videos.stats.stats17.compute         # once (about a minute; cached in .cache/stats17)
python tools/build.py stats17 -q l             # fast 480p preview
python tools/build.py stats17                  # 1080p30 -> renders/stats17.mp4
python tools/qa_scene.py stats17 Forecast
python tools/lecture_length.py stats17 --floor 50