Slides compress; these notes explain. Written as continuous prose, they motivate time-series econometrics from familiar macro and finance variables (disposable income, interest rates), then develop the framework, processes, stationarity, white noise, dependence, with every derivation and piece of intuition written out, not bulleted.
What these materials cover
- Why time series needs its own framework: examples from macro and finance
- Processes, realisations and the meaning of stationarity, in prose
- White noise and measuring dependence
- MA and AR foundations with full derivations
- Designed to be read alongside lectures 1 and 2
- Six example series from free data, with code in Python, R, Stata and EViews (below)
Download
Free to download and use for personal study. Written for my own university teaching; shared here as evidence of teaching style and depth.
Typed lecture notes: weeks 1–2 (PDF) TeX source (week 1, postgraduate edition) (.tex)
Six time series, and the code to draw them
Each chart in the opening chapter of the notes shows one feature a time-series model has to handle: forecast uncertainty that grows with the horizon, returns that are hard to predict but whose volatility changes, a smooth trend, strong persistence, a seasonal pattern, and a mean that shifts over time. All six use free data. The code below draws them, so you can change the dates or swap in another series and check whether the same features appear. The charts here come from the Python script; the R, Stata and EViews scripts take the same steps.






The data
- uk-cpi-inflation-d7g7.csv: UK CPI inflation, % on a year earlier, monthly from 1989. Source: ONS series D7G7.
- ftse-daily-1991-1998.csv: FTSE 100 daily closing values, 1991 to 1998. Source: R datasets package, EuStockMarkets.
- us-population-1790-1990.csv: US population at each census, millions. Source: US Census Bureau.
- uk-unemployment-rate-mgsx.csv: UK unemployment rate, aged 16 and over, seasonally adjusted. Source: ONS series MGSX.
- uk-retail-sales-j5ah.csv: UK retail sales index, value, not seasonally adjusted. Source: ONS series J5AH.
- uk-bank-rate-1987-2017.csv: UK Bank Rate at the end of each month. Source: Bank of England.
ONS series are used under the Open Government Licence v3.0. The forecast fan is a simple AR(1) fitted by least squares; Section 2 of the notes explains the model and Lecture 4 the forecasts.
The code
# Time series examples: six charts from freely available data
# Dr Nicky Grant, drnickygrant.com. Companion to the ECON30401 lecture notes, weeks 1 and 2.
# Needs: pandas, numpy, matplotlib, scipy (pip install pandas numpy matplotlib scipy)
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
# Clean copies of each series, with their sources, are kept on the site.
BASE = os.environ.get("TS_DATA", "https://www.drnickygrant.com/teaching/data/")
OUT = os.environ.get("TS_OUT", ".")
plt.rcParams.update({"font.family": "DejaVu Serif", "font.size": 11,
"axes.spines.top": False, "axes.spines.right": False})
def monthly(file):
"""Read a month,value file and index it by month."""
d = pd.read_csv(BASE + file)
d.index = pd.PeriodIndex(d["month"], freq="M").to_timestamp()
return d.iloc[:, 1]
def save(fig, name):
fig.tight_layout()
fig.savefig(os.path.join(OUT, name), dpi=200)
plt.close(fig)
# 1. UK CPI inflation to August 2016 with a fan of AR(1) forecasts (ONS series D7G7)
cpi = monthly("uk-cpi-inflation-d7g7.csv")
y = cpi[:"2016-08"].to_numpy()
X = np.column_stack([np.ones(len(y) - 1), y[:-1]])
(c, phi), *_ = np.linalg.lstsq(X, y[1:], rcond=None) # OLS of y_t on 1 and y_{t-1}
resid = y[1:] - X @ np.array([c, phi])
sigma = np.sqrt(resid @ resid / (len(resid) - 2))
H = 36 # forecast three years ahead
mean, var, f, se = y[-1], 0.0, [], []
for h in range(H):
mean = c + phi * mean # E[Y_{T+h} | Y_T]
var = sigma**2 + phi**2 * var # forecast-error variance
f.append(mean); se.append(np.sqrt(var))
f, se = np.array(f), np.array(se)
months = pd.date_range("2016-08-01", periods=H + 1, freq="MS")
fig, ax = plt.subplots(figsize=(6.2, 4.6))
hist = cpi["2012-01":"2016-08"]
ax.plot(hist.index, hist, color="#b22222", lw=1.6)
for share, colour in [(0.90, "#f6c7b6"), (0.60, "#ef9a84"), (0.30, "#e06650")]:
z = norm.ppf(0.5 + share / 2)
ax.fill_between(months, np.r_[y[-1], f - z * se], np.r_[y[-1], f + z * se], color=colour, lw=0)
ax.axvspan(months[0], months[-1], color="0.93", zorder=-1)
ax.axhline(2, color="0.4", lw=0.8, ls="--")
ax.set_ylabel("% change on a year earlier")
ax.set_title("UK CPI inflation and an AR(1) forecast fan", fontsize=11)
save(fig, "fig1-uk-cpi-forecast-fan.png")
# 2. Daily FTSE 100 returns, 1991 to 1998 (R datasets package, EuStockMarkets)
ftse = pd.read_csv(BASE + "ftse-daily-1991-1998.csv")
ret = 100 * np.log(ftse["ftse"]).diff()
fig, ax = plt.subplots(figsize=(7.6, 3.0))
ax.plot(ftse["time"], ret, color="k", lw=0.5)
ax.axhline(0, color="0.5", lw=0.6)
ax.set_ylabel("log return, %")
ax.set_xlabel("Daily FTSE 100 returns, 1991 to 1998")
save(fig, "fig2-ftse-daily-returns.png")
# 3. US population at each census, 1790 to 1990 (US Census Bureau)
pop = pd.read_csv(BASE + "us-population-1790-1990.csv")
fig, ax = plt.subplots(figsize=(6.0, 4.2))
ax.plot(pop["year"], pop["population_millions"], "s-", color="k", ms=4, mfc="white", lw=0.9)
ax.set_ylabel("millions")
ax.set_xlabel("US population at each census, 1790 to 1990")
save(fig, "fig3-us-population.png")
# 4. UK unemployment rate, monthly (ONS series MGSX)
u = monthly("uk-unemployment-rate-mgsx.csv")
fig, ax = plt.subplots(figsize=(6.0, 4.2))
ax.plot(u.index, u, color="k", lw=0.9)
ax.set_ylabel("%")
ax.set_xlabel("UK unemployment rate, monthly")
save(fig, "fig4-uk-unemployment.png")
# 5. UK retail sales, value, not seasonally adjusted, 2010 to 2019 (ONS series J5AH)
r = monthly("uk-retail-sales-j5ah.csv")["2010-01":"2019-12"]
fig, ax = plt.subplots(figsize=(6.0, 4.2))
ax.plot(r.index, r, "s-", color="k", ms=2.5, mfc="white", lw=0.8)
ax.set_ylabel("index")
ax.set_xlabel("UK retail sales, monthly, not seasonally adjusted")
save(fig, "fig5-uk-retail-sales.png")
# 6. UK Bank Rate at the end of each month, 1987 to 2017 (Bank of England)
br = monthly("uk-bank-rate-1987-2017.csv")
fig, ax = plt.subplots(figsize=(6.0, 3.3))
ax.step(br.index, br, where="post", color="#0f5c5c", lw=1.4)
ax.set_ylabel("%")
ax.set_xlabel("UK Bank Rate, 1987 to 2017")
save(fig, "fig6-uk-bank-rate.png")
print("Six charts written to", os.path.abspath(OUT))
# Time series examples: six charts from freely available data
# Dr Nicky Grant, drnickygrant.com. Companion to the ECON30401 lecture notes, weeks 1 and 2.
# Base R only: no packages needed.
base <- "https://www.drnickygrant.com/teaching/data/"
monthly <- function(file) { # read a month,value file and add a date column
d <- read.csv(paste0(base, file))
d$date <- as.Date(paste0(d$month, "-01"))
d
}
open_png <- function(name, w = 6.2, h = 4.4) png(name, width = w, height = h, units = "in", res = 200)
# 1. UK CPI inflation to August 2016 with a fan of AR(1) forecasts (ONS series D7G7)
cpi <- monthly("uk-cpi-inflation-d7g7.csv")
y <- cpi$cpi_inflation[cpi$date <= as.Date("2016-08-01")]
fit <- lm(y[-1] ~ y[-length(y)]) # OLS of y_t on 1 and y_{t-1}
c0 <- coef(fit)[1]; phi <- coef(fit)[2]; sigma <- summary(fit)$sigma
H <- 36; f <- se <- numeric(H); m <- tail(y, 1); v <- 0
for (h in 1:H) {
m <- c0 + phi * m # E[Y_{T+h} | Y_T]
v <- sigma^2 + phi^2 * v # forecast-error variance
f[h] <- m; se[h] <- sqrt(v)
}
fdates <- seq(as.Date("2016-08-01"), by = "month", length.out = H + 1)
hist <- cpi[cpi$date >= as.Date("2012-01-01") & cpi$date <= as.Date("2016-08-01"), ]
open_png("fig1-uk-cpi-forecast-fan.png")
plot(hist$date, hist$cpi_inflation, type = "n", xlim = range(c(hist$date, fdates)), ylim = c(-1.5, 4),
xlab = "", ylab = "% change on a year earlier", main = "UK CPI inflation and an AR(1) forecast fan")
for (band in list(list(0.90, "#f6c7b6"), list(0.60, "#ef9a84"), list(0.30, "#e06650"))) {
z <- qnorm(0.5 + band[[1]] / 2)
upper <- c(tail(y, 1), f + z * se); lower <- c(tail(y, 1), f - z * se)
polygon(c(fdates, rev(fdates)), c(upper, rev(lower)), col = band[[2]], border = NA)
}
lines(hist$date, hist$cpi_inflation, col = "firebrick", lwd = 2)
abline(h = 2, lty = 2, col = "grey40")
dev.off()
# 2. Daily FTSE 100 returns, 1991 to 1998 (R datasets package, EuStockMarkets)
ftse <- read.csv(paste0(base, "ftse-daily-1991-1998.csv"))
ret <- 100 * diff(log(ftse$ftse))
open_png("fig2-ftse-daily-returns.png", 7.6, 3.0)
plot(ftse$time[-1], ret, type = "l", lwd = 0.5, xlab = "Daily FTSE 100 returns, 1991 to 1998", ylab = "log return, %")
abline(h = 0, col = "grey50")
dev.off()
# 3. US population at each census, 1790 to 1990 (US Census Bureau)
pop <- read.csv(paste0(base, "us-population-1790-1990.csv"))
open_png("fig3-us-population.png", 6.0, 4.2)
plot(pop$year, pop$population_millions, type = "o", pch = 0,
xlab = "US population at each census, 1790 to 1990", ylab = "millions")
dev.off()
# 4. UK unemployment rate, monthly (ONS series MGSX)
u <- monthly("uk-unemployment-rate-mgsx.csv")
open_png("fig4-uk-unemployment.png", 6.0, 4.2)
plot(u$date, u$unemployment_rate, type = "l", xlab = "UK unemployment rate, monthly", ylab = "%")
dev.off()
# 5. UK retail sales, value, not seasonally adjusted, 2010 to 2019 (ONS series J5AH)
r <- monthly("uk-retail-sales-j5ah.csv")
r <- r[r$date >= as.Date("2010-01-01") & r$date <= as.Date("2019-12-01"), ]
open_png("fig5-uk-retail-sales.png", 6.0, 4.2)
plot(r$date, r$retail_sales_index, type = "o", pch = 0, cex = 0.5,
xlab = "UK retail sales, monthly, not seasonally adjusted", ylab = "index")
dev.off()
# 6. UK Bank Rate at the end of each month, 1987 to 2017 (Bank of England)
br <- monthly("uk-bank-rate-1987-2017.csv")
open_png("fig6-uk-bank-rate.png", 6.0, 3.3)
plot(br$date, br$bank_rate, type = "s", col = "#0f5c5c", lwd = 2, xlab = "UK Bank Rate, 1987 to 2017", ylab = "%")
dev.off()
* Time series examples: six charts from freely available data
* Dr Nicky Grant, drnickygrant.com. Companion to the ECON30401 lecture notes, weeks 1 and 2.
* Stata 14 or later.
global base "https://www.drnickygrant.com/teaching/data"
set scheme s1mono
* 1. UK CPI inflation to August 2016 with a fan of AR(1) forecasts (ONS series D7G7)
import delimited using "$base/uk-cpi-inflation-d7g7.csv", clear varnames(1)
gen m = monthly(month, "YM")
format m %tm
tsset m
keep if m <= tm(2016m8)
regress cpi_inflation L.cpi_inflation // OLS of y_t on 1 and y_{t-1}
scalar c0 = _b[_cons]
scalar phi = _b[L.cpi_inflation]
scalar s2 = e(rmse)^2
tsappend, add(36) // three years ahead
gen f = cpi_inflation if m == tm(2016m8)
gen v = 0 if m == tm(2016m8)
replace f = c0 + phi*f[_n-1] if m > tm(2016m8) // E[Y_{T+h} | Y_T], built one month at a time
replace v = s2 + phi^2*v[_n-1] if m > tm(2016m8) // forecast-error variance
gen se = sqrt(v)
foreach p in 30 60 90 {
local z = invnormal(0.5 + `p'/200)
gen lo`p' = f - `z'*se
gen hi`p' = f + `z'*se
}
twoway (rarea hi90 lo90 m, color("246 199 182") lwidth(none)) ///
(rarea hi60 lo60 m, color("239 154 132") lwidth(none)) ///
(rarea hi30 lo30 m, color("224 102 80") lwidth(none)) ///
(line cpi_inflation m if m >= tm(2012m1), lcolor(cranberry) lwidth(medthick)), ///
yline(2, lpattern(dash)) legend(off) xtitle("") ytitle("% change on a year earlier") ///
title("UK CPI inflation and an AR(1) forecast fan")
graph export "fig1-uk-cpi-forecast-fan.png", replace width(1240)
* 2. Daily FTSE 100 returns, 1991 to 1998 (R datasets package, EuStockMarkets)
import delimited using "$base/ftse-daily-1991-1998.csv", clear varnames(1)
tsset obs
gen ret = 100*(ln(ftse) - ln(L.ftse))
twoway line ret time, lwidth(vthin) yline(0) ytitle("log return, %") xtitle("Daily FTSE 100 returns, 1991 to 1998")
graph export "fig2-ftse-daily-returns.png", replace width(1520)
* 3. US population at each census, 1790 to 1990 (US Census Bureau)
import delimited using "$base/us-population-1790-1990.csv", clear varnames(1)
twoway connected population_millions year, msymbol(Sh) ytitle("millions") xtitle("US population at each census, 1790 to 1990")
graph export "fig3-us-population.png", replace width(1200)
* 4. UK unemployment rate, monthly (ONS series MGSX)
import delimited using "$base/uk-unemployment-rate-mgsx.csv", clear varnames(1)
gen m = monthly(month, "YM")
format m %tm
tsset m
tsline unemployment_rate, ytitle("%") xtitle("UK unemployment rate, monthly")
graph export "fig4-uk-unemployment.png", replace width(1200)
* 5. UK retail sales, value, not seasonally adjusted, 2010 to 2019 (ONS series J5AH)
import delimited using "$base/uk-retail-sales-j5ah.csv", clear varnames(1)
gen m = monthly(month, "YM")
format m %tm
keep if inrange(m, tm(2010m1), tm(2019m12))
twoway connected retail_sales_index m, msymbol(Sh) msize(vsmall) ytitle("index") ///
xtitle("UK retail sales, monthly, not seasonally adjusted")
graph export "fig5-uk-retail-sales.png", replace width(1200)
* 6. UK Bank Rate at the end of each month, 1987 to 2017 (Bank of England)
import delimited using "$base/uk-bank-rate-1987-2017.csv", clear varnames(1)
gen m = monthly(month, "YM")
format m %tm
twoway line bank_rate m, connect(stairstep) ytitle("%") xtitle("UK Bank Rate, 1987 to 2017")
graph export "fig6-uk-bank-rate.png", replace width(1200)
' Time series examples: six charts from freely available data
' Dr Nicky Grant, drnickygrant.com. Companion to the ECON30401 lecture notes, weeks 1 and 2.
' EViews 10 or later. Each block opens its own workfile.
%base = "https://www.drnickygrant.com/teaching/data/"
' 1. UK CPI inflation to August 2016 with a fan of AR(1) forecasts (ONS series D7G7)
wfopen(type=text) {%base}uk-cpi-inflation-d7g7.csv @freq m 1989m01
pagestruct(end=2019m08)
smpl 1989m01 2016m08
equation eq_ar1.ls cpi_inflation c cpi_inflation(-1) ' OLS of y_t on 1 and y_{t-1}
smpl 2016m09 2019m08
eq_ar1.forecast cpi_f cpi_se ' dynamic forecast and its standard error
smpl 2016m08 2016m08
cpi_f = cpi_inflation
cpi_se = 0
smpl 2016m08 2019m08
for %p 30 60 90
!z = @qnorm(0.5 + {%p}/200)
series lo{%p} = cpi_f - !z*cpi_se
series hi{%p} = cpi_f + !z*cpi_se
next
smpl 2012m01 2019m08
group fan cpi_inflation lo90 lo60 lo30 hi30 hi60 hi90
freeze(g1) fan.line ' the bands are drawn as lines; shade them in the graph options if you like
g1.addtext(t) UK CPI inflation and an AR(1) forecast fan
g1.save(t=png, u=in, w=6.2, h=4.4) fig1-uk-cpi-forecast-fan
' 2. Daily FTSE 100 returns, 1991 to 1998 (R datasets package, EuStockMarkets)
wfopen(type=text) {%base}ftse-daily-1991-1998.csv @freq u 1
series ret = 100*dlog(ftse)
freeze(g2) ret.line
g2.save(t=png, u=in, w=7.6, h=3) fig2-ftse-daily-returns
' 3. US population at each census, 1790 to 1990 (US Census Bureau)
wfopen(type=text) {%base}us-population-1790-1990.csv @freq u 1
group pop year population_millions
freeze(g3) pop.xyline
g3.save(t=png, u=in, w=6, h=4.2) fig3-us-population
' 4. UK unemployment rate, monthly (ONS series MGSX)
wfopen(type=text) {%base}uk-unemployment-rate-mgsx.csv @freq m 1971m02
freeze(g4) unemployment_rate.line
g4.save(t=png, u=in, w=6, h=4.2) fig4-uk-unemployment
' 5. UK retail sales, value, not seasonally adjusted, 2010 to 2019 (ONS series J5AH)
wfopen(type=text) {%base}uk-retail-sales-j5ah.csv @freq m 1996m01
smpl 2010m01 2019m12
freeze(g5) retail_sales_index.line
g5.save(t=png, u=in, w=6, h=4.2) fig5-uk-retail-sales
' 6. UK Bank Rate at the end of each month, 1987 to 2017 (Bank of England)
wfopen(type=text) {%base}uk-bank-rate-1987-2017.csv @freq m 1987m01
freeze(g6) bank_rate.line
g6.save(t=png, u=in, w=6, h=3.3) fig6-uk-bank-rate
What students say
“Nicky is an excellent econometrics tutor. He explains complex concepts clearly and makes them much easier to understand.”
“I was completely lost in my economics class, and then I started working Nicky and he totally saved me. He was excellent at explaining the material and extremely accommodating to meet with me many times despite us being in different time zones! Highly recommend working with Nicky!”
“Nicky is a very good and thorough teacher. He has excellent knowledge of econometrics and takes the time to work through your questions. Highly recommended!”
“Really great tutor! Encouraging, knowledgeable, friendly”
“Very good lesson, Nicky is very helpful.”
“Very helpful and clear.”
“I gather it was very useful, thank you!”
“Fantastic!”
Who this is for
Students who learn better from prose than slides, and revision readers who want the full argument, not the compressed version.
Related free resources
- Time Series Econometrics, full study-note hub
- Time series econometrics: a complete guide, study note
- Lecture 1 slides (the compressed version)
- All teaching materials, notes, exercises and solutions
One-to-one help
For help with this material, or the module it belongs to, see econometrics tuition or university economics tuition. The first consultation is free, with no obligation.
Free worked video lectures: @unientryTMUA on YouTube.
