Econometrics · Week 9
Serial correlation序列相關
In a time series, this month is rarely independent of last month. If more accidents than expected happened in March, more than expected probably happened in April too. Week 8 dealt with errors whose variances differ; this week deals with errors that are correlated with each other over time. The plan is the same: what goes wrong, how to see it, how to test for it, and how to repair the standard errors.
在時間序列中,這個月的情況很少與上個月無關。如果三月份的交通意外比預期多,四月份很可能也比預期多。第 8 週處理方差各不相同的誤差;本週處理隨時間互相相關的誤差。思路一樣:會出現甚麼問題、怎樣觀察、怎樣檢定,以及怎樣修正標準誤。
- Reading time 閱讀時間
- About 50 minutes
- Data 數據
traffic2- Code 程式碼
- R, Python
What serial correlation is甚麼是序列相關
Assumption A4 has two parts. Week 8 relaxed the first, equal variances. This week relaxes the second: no serial correlation, for . We write rather than because the observations are periods in time, in order. When the errors are serially correlated (or autocorrelated), the off-diagonal entries of their covariance matrix are no longer zero:
假設 A4 有兩部分。第 8 週放寬了第一部分,即方差相等。本週放寬第二部分:沒有序列相關,即對 有 。這裏用 而不是 ,因為觀測值是按時間順序排列的時期。當誤差序列相關(或自相關)時,其協方差矩陣的非對角元素不再是零:
In cross sections drawn at random, there is no natural order and no reason for one person’s error to predict another’s. In time series it is the rule rather than the exception: shocks such as a wet winter, a recession or a new law last longer than one period, and anything the model leaves out that moves slowly over time ends up in several consecutive errors.
在隨機抽取的橫截面數據中,觀測值沒有自然的次序,一個人的誤差也沒有理由能預測另一個人的誤差。但在時間序列中,序列相關是常態而非例外:多雨的冬季、經濟衰退或新法例等衝擊都會持續超過一個時期;模型遺漏的任何緩慢變化的因素,都會同時出現在連續幾期的誤差之中。
A model of it: AR(1) errors一個模型:AR(1) 誤差
The simplest model of serial correlation is the first-order autoregressive process, AR(1): each error carries over a fraction of the previous one and adds a fresh shock.
最簡單的序列相關模型是一階自回歸過程 AR(1):每期誤差承接上一期誤差的 部分,再加上新的衝擊。
If the process is stable: its variance does not change over time and shocks fade away. Then, for every lag ,
如果 ,過程是穩定的:方差不隨時間改變,衝擊會逐漸消失。於是對每個滯後期 ,
so the correlation between errors periods apart is . Unless , every pair of errors is correlated, and A4(b) fails. The correlation decays geometrically with distance: with it is 0.7 one period apart, 0.49 two periods apart and 0.03 ten periods apart.
所以相隔 期的誤差之間的相關係數是 。除非 ,否則每一對誤差都相關,A4(b) 不成立。相關程度隨距離以幾何級數遞減:當 時,相隔一期為 0.7,相隔兩期為 0.49,相隔十期為 0.03。
Show every step 顯示完整推導
Variance. Stability means . The new shock is independent of the past, so of :
方差。穩定表示 。新衝擊 與過去獨立,所以也與 獨立:
This is positive only if , which is why stability needs .
只有當 時它才是正數,這正是穩定性需要 的原因。
Covariance. Substitute the AR(1) equation into itself times:
協方差。把 AR(1) 方程代入自身 次:
The shocks all come after and are independent of it, so only the first term contributes:
衝擊 都發生在 之後,與它獨立,所以只有第一項有貢獻:
Dividing by gives the autocorrelation .
除以 便得到自相關係數 。
Move the slider. At φ = 0 the series is white noise that crosses zero constantly. As φ rises it wanders: long runs above zero, then long runs below. At 0.99 it barely returns to zero in 300 periods, and its correlogram stays high far out.
拖動滑桿。φ = 0 時,序列是不斷穿越零的白噪音。φ 上升時,序列開始游走:長時間高於零,然後長時間低於零。到了 0.99,序列在 300 期內幾乎不回到零,相關圖也一直維持在高位。
The series 序列
Its correlogram 相關圖
Sample ACF 樣本自相關Theory ±1.96/√n
- Lag-1 sample autocorrelation 一階樣本自相關
- –
- Lags outside the band 超出範圍的滯後期
- –
- sd of uₜ, theory uₜ 的理論標準差
- –
- True se of a mean vs usual 均值的真實標準誤相對一般
- –
Each series is with the same 300 standard normal shocks , so only changes between pictures. The last figure is , the factor derived in Section 3: how much the true standard error of a sample mean exceeds the one that assumes no serial correlation.
每個序列都是 ,並使用同一組 300 個標準正態衝擊 ,所以圖與圖之間只有 改變。最後一個數字是第 3 節推導的因子 :樣本均值的真實標準誤比假設沒有序列相關的標準誤大多少倍。
What it does to OLS序列相關對 OLS 的影響
The consequences mirror those of heteroskedasticity:
其後果與異方差的情況相同:
OLS is still unbiased, as long as A1–A3 hold.
OLS 仍然無偏,只要 A1–A3 成立。
Its variance is not σ²(X′X)⁻¹ but the sandwich , so the usual standard errors, t tests and F tests are wrong.
它的方差不是 σ²(X′X)⁻¹,而是三文治形式 ,所以一般的標準誤、t 檢定和 F 檢定都是錯的。
OLS is no longer BLUE.
OLS 不再是 BLUE。
Which way are the usual standard errors wrong? Take the simplest case, estimating a mean, so the only regressor is the constant. With AR(1) errors, for large n,
一般標準誤錯在哪個方向?考慮最簡單的情況,估計均值,即唯一的解釋變數是常數。在 AR(1) 誤差下,當 n 很大時,
The usual formula is . With , close to the first autocorrelation in the example below, the factor is : the true variance is 4.6 times what the usual formula says, and the true standard error times as large. Positive serial correlation makes consecutive errors repeat each other, so correlated observations carry less information than independent ones.
一般公式是 。當 (接近下文例子中的一階自相關)時,因子是 :真實方差是一般公式的 4.6 倍,真實標準誤則是 倍。正序列相關令相鄰誤差互相重複,所以 個相關觀測值所含的資訊少於 個獨立觀測值。
Show every step: the variance with AR(1) errors 顯示完整推導:AR(1) 誤差下的方差
Simple regression. The OLS slope is with . The variance of a sum includes every covariance:
簡單回歸。OLS 斜率是 ,其中 。總和的方差包含所有協方差:
The first term is the usual formula. The second is extra. If the regressor is itself positively autocorrelated, as trends and most economic series are, and , the inner sums are positive, so the true variance is larger and the usual standard error is too small.
第一項就是一般公式,第二項是額外部分。如果解釋變數本身正自相關(趨勢和大部分經濟序列都是如此),而且 ,內層的總和便是正數,所以真實方差較大,一般標準誤偏小。
The mean. Put . There are pairs periods apart, so
均值。設 。相隔 期的配對共有 對,所以
As grows, the weights approach 1 and the sum approaches , so the bracket becomes
當 增大,權重 趨向 1,總和趨向 ,所以括號變成
The declining weights 1 − j/n reappear in Section 7: the Newey–West estimator uses the same shape.
遞減權重 1 − j/n 會在第 7 節再次出現:Newey–West 估計量正是使用相同形狀的權重。
The line graph of the residuals殘差的折線圖
Example. The traffic2 data record the number of traffic accidents in California each month from January 1981 to December 1989, 108 months. As in the lecture’s tourism example, regress the log of the monthly total on a linear time trend and eleven month dummies (January is the base):
例子。traffic2 數據記錄了 1981 年 1 月至 1989 年 12 月加州每月的交通意外數目,共 108 個月。與課堂的旅遊例子一樣,把每月總數的對數對線性時間趨勢和十一個月份虛擬變數(一月為基準)做回歸:
The trend is per month, about 3.4% more accidents a year, and . We cannot see the errors, but the residuals stand in for them. Plot them in time order:
趨勢為每月 ,即每年交通意外約多 3.4%,。我們看不到誤差,但可以用殘差 代替。按時間順序把它們畫出來:
Above the fitted value 高於擬合值Below 低於擬合值
The residuals move in long waves: positive in 11 of the 12 months of 1981, negative in most months of 1982 to 1984, positive in every month of 1986 and 1987, and negative in every month of 1989. Independent errors would cross zero about every second month. These residuals change sign only 25 times in 107 steps, compared with about 53 expected without serial correlation.
殘差呈長波動:1981 年 12 個月中有 11 個月為正,1982 至 1984 年大部分月份為負,1986 及 1987 年每個月都為正,1989 年每個月都為負。獨立的誤差大約每兩個月便會穿越零一次。這些殘差在 107 步中只改變正負號 25 次,而沒有序列相關時預期約為 53 次。
The correlogram相關圖
A correlogram puts numbers on the picture. The autocorrelation function (ACF) gives the sample correlation between the residuals and their own past values periods earlier:
相關圖把圖像量化。自相關函數(ACF)給出殘差與 期前自身數值之間的樣本相關係數:
If the errors are not serially correlated, each is approximately normal with mean zero and standard deviation . So outside rejects at the 5% level.
如果誤差沒有序列相關,每個 大約服從均值為零、標準差為 的正態分佈。所以 落在 之外,便在 5% 水平下拒絕 。
The partial autocorrelation function (PACF) asks a sharper question: does lag help once lags 1 to are accounted for? Its value at lag is the last coefficient in the regression of on :
偏自相關函數(PACF)問一個更精確的問題:在考慮了滯後 1 至 期之後,滯後 期是否仍有幫助?它在滯後 的值,就是把 對 回歸時最後一個係數 :
For an AR(1) process the ACF decays gradually, as φʲ, but the PACF cuts off after lag 1: once last period is known, earlier periods add nothing. In general an AR(p) process has a PACF that cuts off after lag p, which makes the PACF the tool for choosing p.
AR(1) 過程的 ACF 按 φʲ 逐漸遞減,但 PACF 在滯後 1 期之後便截斷:知道上一期之後,更早的時期不再提供額外資訊。一般而言,AR(p) 過程的 PACF 在滯後 p 期之後截斷,所以 PACF 是選擇 p 的工具。
The shaded band is . Bars that leave it are drawn in a darker colour.
陰影帶為 。超出範圍的柱以較深顏色顯示。
All twelve autocorrelations lie outside the bands, starting at 0.644 and declining slowly, so we reject for every . The partial autocorrelations at lags 1 (0.644) and 2 (0.354) are outside; lag 3 (0.139) and beyond are inside. This suggests the errors follow an AR(2) process,
全部十二個自相關係數都落在範圍之外,由 0.644 開始緩慢下降,所以對每個 都拒絕 。偏自相關係數在滯後 1 期(0.644)和 2 期(0.354)落在範圍之外;滯後 3 期(0.139)及以後都在範圍之內。這表示誤差服從 AR(2) 過程:
The Breusch–Godfrey testBreusch–Godfrey 檢定
The Breusch–Godfrey (BG) test checks all lags up to at once. Suppose the errors follow an AR() process,
Breusch–Godfrey(BG)檢定一次過檢查直至 期的所有滯後期。假設誤差服從 AR() 過程,
and test against the alternative that at least one is not zero. Choose to match the frequency of the data: 1 or 2 for annual data, 4 for quarterly, 12 for monthly, so that the test can pick up a relation with the same season last year.
並檢定 ,備擇假設是至少有一個不為零。 應配合數據頻率:年度數據取 1 或 2,季度取 4,月度取 12,讓檢定能捕捉與去年同一季節的關係。
Fit the model 估計模型
Run OLS and save the residuals .
進行 OLS 估計並保存殘差 。
Auxiliary regression 輔助回歸
Keep its . Including the regressors matters: it makes the test valid even when they are not strictly exogenous.
記下它的 。加入解釋變數很重要:即使它們不是嚴格外生的,檢定仍然有效。
Test statistic 檢定統計量
Decide 作出結論
Reject if BG exceeds the critical value. Equivalently, use the usual F test of the lag coefficients.
如果 BG 超過 的臨界值便拒絕。也可以對 個滯後係數做一般的 F 檢定。
Why n − q? The first periods have no complete set of lagged residuals: does not exist, so period 1 has no first lag, period 2 no second lag, and so on. The auxiliary regression uses only periods to . Some software instead sets the missing lags to zero, keeps all periods and reports . That changes both and , but both versions have the same large-sample distribution.
為甚麼用 n − q?最初 期沒有完整的滯後殘差: 並不存在,所以第 1 期沒有一階滯後,第 2 期沒有二階滯後,如此類推。輔助回歸只用第 至第 期。有些軟件則把缺失的滯後值設為零,保留全部 期並報告 。這會同時改變 和 ,但兩個版本在大樣本中的分佈相同。
Example. With monthly data, take . The auxiliary regression of the residual on the trend, the eleven month dummies and twelve lagged residuals uses months and has :
例子。月度數據取 。把殘差對趨勢、十一個月份虛擬變數和十二個滯後殘差回歸,使用 個月,:
The p-value is . The zero-filled version, which Python’s acorr_breusch_godfrey() and R’s lmtest::bgtest() report, gives : same conclusion. The result does not hinge on :
p 值為 。Python 的 acorr_breusch_godfrey() 和 R 的 lmtest::bgtest() 所報告的補零版本得出 :結論相同。結果並不取決於 :
| 5% critical value 5% 臨界值 | |||
|---|---|---|---|
| 1 | 0.488 | 52.17 | 3.84 |
| 2 | 0.563 | 59.70 | 5.99 |
| 3 | 0.573 | 60.12 | 7.81 |
| 12 | 0.580 | 55.66 | 21.03 |
Every version rejects with a p-value below 0.000001.
所有版本都以低於 0.000001 的 p 值拒絕。
HAC standard errorsHAC 標準誤
As in Week 8, we can keep the OLS estimates and fix only their standard errors. Whitney Newey and Kenneth West (1987) proposed an estimator of the sandwich that is consistent when the errors are serially correlated, heteroskedastic, or both: the HAC (heteroskedasticity and autocorrelation consistent) covariance matrix,
與第 8 週一樣,我們可以保留 OLS 估計值,只修正它們的標準誤。Whitney Newey 和 Kenneth West(1987)提出了一個三文治形式的估計量,在誤差序列相關、異方差或兩者兼有時都具一致性:HAC(異方差及自相關一致)協方差矩陣,
The first sum is White’s heteroskedasticity-robust term from Week 8. The second adds the covariances between errors up to periods apart, each estimated by products of residuals. The declining Bartlett weights give distant lags less say and guarantee that the variance estimate is never negative.
第一個總和是第 8 週 White 的異方差穩健項。第二個總和加入相隔最多 期的誤差之間的協方差,每項都以殘差乘積估計。遞減的 Bartlett 權重 令較遠的滯後期影響較小,並保證方差估計值永不為負。
Choosing L. L must grow with the sample, but slowly. A common rule of thumb is , which gives for . Results should not change much for nearby values.
選擇 L。L 必須隨樣本增大,但要增得慢。常用的經驗法則是 ,當 時得出 。在相近的數值之間,結果不應有太大變化。
| Estimate | Usual | HAC | |||
|---|---|---|---|---|---|
| se | se | ||||
t 趨勢 | 0.002747 | 0.000161 | 17.06 | 0.000279 | 9.86 |
feb 二月 | −0.0427 | 0.0244 | −1.75 | 0.0175 | −2.44 |
aug 八月 | 0.0540 | 0.0245 | 2.21 | 0.0277 | 1.95 |
dec 十二月 | 0.0962 | 0.0245 | 3.92 | 0.0298 | 3.23 |
Newey–West with L = 4 lags and no small-sample adjustment. The other eight month dummies are in the code output.
Newey–West,L = 4 個滯後期,沒有小樣本調整。其餘八個月份虛擬變數見程式碼輸出。
The trend’s standard error rises by 73%, and its t statistic falls from 17.1 to 9.9. That matches Section 3: a trend is as autocorrelated as a regressor can be, and the errors are positively autocorrelated, so the usual formula understated the uncertainty. The trend is still clearly significant. HAC standard errors are not always larger, though. For February the standard error falls and the effect becomes significant at 5%; for August it rises and the effect is no longer significant at 5%.
趨勢的標準誤增加了 73%,t 統計量由 17.1 降至 9.9。這與第 3 節一致:趨勢是自相關程度最高的解釋變數,而誤差正自相關,所以一般公式低估了不確定性。趨勢仍然明顯顯著。不過 HAC 標準誤並非總是較大。二月份的標準誤下降,效應在 5% 水平下變得顯著;八月份的標準誤上升,效應在 5% 水平下不再顯著。
Two failures of A4 side by side並排比較 A4 的兩種失效
Heteroskedasticity and serial correlation are the two ways A4 can fail. The treatment is parallel:
異方差和序列相關是 A4 失效的兩種方式。處理方法互相對應:
| Heteroskedasticity (Week 8) 異方差(第 8 週) | Serial correlation (Week 9) 序列相關(第 9 週) | |
|---|---|---|
| Breaks 違反 | A4(a): equal variances A4(a):方差相等 | A4(b): zero covariances A4(b):協方差為零 |
| Typical data 常見數據 | Cross sections 橫截面數據 | Time series 時間序列 |
| OLS estimates OLS 估計值 | Unbiased if A1–A3 hold; no longer BLUE A1–A3 成立時無偏;不再是 BLUE | |
| Look at 觀察 | Residuals against regressors 殘差對解釋變數 | Residuals over time; correlogram 殘差隨時間變化;相關圖 |
| Test 檢定 | Breusch–Pagan, White | Breusch–Godfrey |
| Fix the standard errors 修正標準誤 | Robust (HC) 穩健(HC) | Newey–West (HAC), which also covers heteroskedasticity Newey–West(HAC),同時處理異方差 |
Reproduce the results自己重現結果
The data come with the free wooldridge package. The R code computes the Breusch–Godfrey test and the Newey–West standard errors by hand; lmtest::bgtest() and sandwich::NeweyWest() give the same results in one line each.
數據收錄在免費的 wooldridge 套件中。R 程式碼親手計算 Breusch–Godfrey 檢定和 Newey–West 標準誤;lmtest::bgtest() 和 sandwich::NeweyWest() 各用一行便可得出相同結果。
library(wooldridge)
# Log of monthly traffic accidents in California, 1981-1989
f <- ltotacc ~ t + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec
m <- lm(f, data = traffic2)
summary(m) # trend 0.002747, se 0.000161
# Line graph and correlogram of the residuals
e <- resid(m); n <- length(e)
plot(e, type = "l"); abline(h = 0)
acf(e, lag.max = 12) # 0.644, 0.622, 0.558, ...
pacf(e, lag.max = 12) # 0.644, 0.354, 0.139, ...
# Breusch-Godfrey with q = 12: lm() drops the 12 rows with missing lags
q <- 12
lags <- sapply(1:q, function(j) c(rep(NA, j), e[1:(n - j)]))
aux <- lm(e ~ model.matrix(m)[, -1] + lags)
bg <- (n - q) * summary(aux)$r.squared
c(bg, qchisq(0.95, q), pchisq(bg, q, lower.tail = FALSE)) # 55.66 > 21.03
# Newey-West (HAC) standard errors with L = 4 lags, by hand
X <- model.matrix(m); L <- 4
S <- crossprod(X * e)
for (j in 1:L) {
G <- crossprod(X[(j + 1):n, ] * e[(j + 1):n], X[1:(n - j), ] * e[1:(n - j)])
S <- S + (1 - j / (L + 1)) * (G + t(G))
}
bread <- solve(crossprod(X))
hac <- sqrt(diag(bread %*% S %*% bread))
cbind(usual = coef(summary(m))[, 2], hac, t_hac = coef(m) / hac)
# trend: se 0.000161 -> 0.000279, t 17.06 -> 9.86
# Same as sandwich::NeweyWest(m, lag = 4, prewhite = FALSE)
# pip install wooldridge statsmodels
import numpy as np
import statsmodels.formula.api as smf
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.stats.diagnostic import acorr_breusch_godfrey
import wooldridge as wd
traffic = wd.data("traffic2") # monthly, California, 1981-1989
months = " + ".join(["feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"])
m = smf.ols("ltotacc ~ t + " + months, data=traffic).fit()
print(m.params["t"], m.bse["t"]) # 0.002747, se 0.000161
# Correlogram of the residuals
e = m.resid.to_numpy()
n = len(e)
print(acf(e, nlags=12)[1:].round(3)) # 0.644, 0.622, 0.558, ...
print(pacf(e, nlags=12, method="ldb")[1:].round(3)) # 0.644, 0.354, 0.139, ...
print(1.96 / np.sqrt(n)) # bands at +/- 0.189
# Breusch-Godfrey with q = 12, dropping the first 12 months
q = 12
lags = np.column_stack([np.r_[np.full(j, np.nan), e[:-j]] for j in range(1, q + 1)])
traffic[[f"e_lag{j}" for j in range(1, q + 1)]] = lags
traffic["e"] = e
aux = smf.ols("e ~ t + " + months + " + " + " + ".join(f"e_lag{j}" for j in range(1, q + 1)),
data=traffic).fit() # rows with missing lags are dropped
print((n - q) * aux.rsquared) # BG = 96 x 0.580 = 55.66
print(acorr_breusch_godfrey(m, nlags=q)[:2]) # zero-filled version: n R^2 = 57.55
# Newey-West (HAC) standard errors with 4 lags
hac = smf.ols("ltotacc ~ t + " + months, data=traffic).fit(cov_type="HAC", cov_kwds={"maxlags": 4})
print(hac.bse["t"], hac.tvalues["t"]) # se 0.000279, t = 9.86
Check your understanding自我測驗
-
The errors follow an AR(1) process with and . What are and ?
誤差服從 、 的 AR(1) 過程。 和 是多少?
Answer 答案
and .
,。
-
A residual correlogram shows a slowly decaying ACF and a PACF with one large spike at lag 1. What process do the errors seem to follow?
殘差相關圖顯示 ACF 緩慢遞減,PACF 只在滯後 1 期有一個大尖峰。誤差看來服從甚麼過程?
Answer 答案
AR(1): the partial autocorrelations cut off after lag 1, and the autocorrelations decay like φʲ.
AR(1):偏自相關在滯後 1 期之後截斷,自相關則按 φʲ 遞減。
-
With quarterly data on quarters, a BG test with gives an auxiliary of 0.12 on the usable observations. Do you reject at 5%?
用 個季度的季度數據, 的 BG 檢定在可用觀測值上得出輔助回歸 為 0.12。在 5% 水平下是否拒絕?
Answer 答案
, below the critical value 9.49. Do not reject at 5%, though it is close (p ≈ 0.058).
,低於 的臨界值 9.49。在 5% 水平下不拒絕,但很接近(p ≈ 0.058)。
-
A researcher regresses on and finds serially correlated residuals. Why is this worse than serial correlation in a model with only a trend?
一位研究員把 對 回歸,發現殘差序列相關。為甚麼這比只有趨勢的模型出現序列相關更嚴重?
Answer 答案
With a trend, OLS is still unbiased and only the standard errors need fixing. With as a regressor, a serially correlated error is correlated with , which is part of . The regressor is correlated with the error, A3 fails, and the coefficient itself is biased. HAC standard errors cannot fix that.
在只有趨勢的模型中,OLS 仍然無偏,只需修正標準誤。當 是解釋變數時,序列相關的誤差 與 相關,而 是 的一部分。解釋變數與誤差相關,A3 不成立,係數本身便有偏誤。HAC 標準誤無法修正這個問題。
-
Errors follow an AR(1) process with . Roughly how many independent observations is a sample of 200 worth when estimating a mean?
誤差服從 的 AR(1) 過程。估計均值時,200 個觀測值大約相當於多少個獨立觀測值?
Answer 答案
The variance of the mean is times the independent-sample formula, so 200 correlated observations are worth about independent ones.
均值的方差是獨立樣本公式的 倍,所以 200 個相關觀測值大約只相當於 個獨立觀測值。
Sources and acknowledgement 資料來源與鳴謝
- Lecture materials for Introductory Econometrics (ETC2410) by Associate Professor Didier Nibbering, Department of Econometrics and Business Statistics, Monash Business School.
- Jeffrey M. Wooldridge, Introductory Econometrics: A Modern Approach, Chapters 10.5, 12.1–12.3 and 12.5.
- Whitney K. Newey and Kenneth D. West (1987), “A simple, positive semi-definite, heteroskedasticity and autocorrelation consistent covariance matrix”, Econometrica 55(3), 703–708.
- Data: traffic2, distributed with the textbook and in the wooldridge R package. All estimates on this page were computed from it.
Any errors are our own.