-
Notifications
You must be signed in to change notification settings - Fork 23
/
08_autocorrelation.Rmd
1576 lines (1272 loc) · 37.9 KB
/
08_autocorrelation.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Autocorrelation"
subtitle: "EC 421, Set 8"
author: "Edward Rubin"
date: "`r format(Sys.time(), '%d %B %Y')`"
output:
xaringan::moon_reader:
css: ['default', 'metropolis', 'metropolis-fonts', 'my-css.css']
# self_contained: true
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
---
class: inverse, middle
```{R, setup, include = F}
options(htmltools.dir.version = FALSE)
library(pacman)
p_load(
broom, here, tidyverse,
latex2exp, ggplot2, ggthemes, viridis, extrafont, gridExtra,
kableExtra,
dplyr,
lubridate,
magrittr, knitr, parallel
)
# Define pink color
red_pink <- "#e64173"
turquoise <- "#20B2AA"
grey_light <- "grey70"
grey_mid <- "grey50"
grey_dark <- "grey20"
# Dark slate grey: #314f4f
# Knitr options
opts_chunk$set(
comment = "#>",
fig.align = "center",
fig.height = 7,
fig.width = 10.5,
warning = F,
message = F
)
opts_chunk$set(dev = "svg")
options(device = function(file, width, height) {
svg(tempfile(), width = width, height = height)
})
# A blank theme for ggplot
theme_empty <- theme_bw() + theme(
line = element_blank(),
rect = element_blank(),
strip.text = element_blank(),
axis.text = element_blank(),
plot.title = element_blank(),
axis.title = element_blank(),
plot.margin = structure(c(0, 0, -0.5, -1), unit = "lines", valid.unit = 3L, class = "unit"),
legend.position = "none"
)
theme_simple <- theme_bw() + theme(
line = element_blank(),
panel.grid = element_blank(),
rect = element_blank(),
strip.text = element_blank(),
axis.text.x = element_text(size = 18, family = "STIXGeneral"),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
plot.title = element_blank(),
axis.title = element_blank(),
# plot.margin = structure(c(0, 0, -1, -1), unit = "lines", valid.unit = 3L, class = "unit"),
legend.position = "none"
)
theme_axes_math <- theme_void() + theme(
text = element_text(family = "MathJax_Math"),
axis.title = element_text(size = 22),
axis.title.x = element_text(hjust = .95, margin = margin(0.15, 0, 0, 0, unit = "lines")),
axis.title.y = element_text(vjust = .95, margin = margin(0, 0.15, 0, 0, unit = "lines")),
axis.line = element_line(
color = "grey70",
size = 0.25,
arrow = arrow(angle = 30, length = unit(0.15, "inches")
)),
plot.margin = structure(c(1, 0, 1, 0), unit = "lines", valid.unit = 3L, class = "unit"),
legend.position = "none"
)
theme_axes_serif <- theme_void() + theme(
text = element_text(family = "MathJax_Main"),
axis.title = element_text(size = 22),
axis.title.x = element_text(hjust = .95, margin = margin(0.15, 0, 0, 0, unit = "lines")),
axis.title.y = element_text(vjust = .95, margin = margin(0, 0.15, 0, 0, unit = "lines")),
axis.line = element_line(
color = "grey70",
size = 0.25,
arrow = arrow(angle = 30, length = unit(0.15, "inches")
)),
plot.margin = structure(c(1, 0, 1, 0), unit = "lines", valid.unit = 3L, class = "unit"),
legend.position = "none"
)
theme_axes <- theme_void() + theme(
text = element_text(family = "Fira Sans Book"),
axis.title = element_text(size = 18),
axis.title.x = element_text(hjust = .95, margin = margin(0.15, 0, 0, 0, unit = "lines")),
axis.title.y = element_text(vjust = .95, margin = margin(0, 0.15, 0, 0, unit = "lines")),
axis.line = element_line(
color = grey_light,
size = 0.25,
arrow = arrow(angle = 30, length = unit(0.15, "inches")
)),
plot.margin = structure(c(1, 0, 1, 0), unit = "lines", valid.unit = 3L, class = "unit"),
legend.position = "none"
)
theme_set(theme_gray(base_size = 20))
```
# Prologue
---
name: schedule
# Schedule
## Last Time
Midterm `+` Introduction to time series `+` Autocorrelation
## Today
Autocorrelation
## Upcoming
Assignment 3 soon.
---
layout: true
# .mono[R] showcase
---
name: r_showcase
## .mono[ggplot2]
I previously mentioned the .mono[R] package `ggplot2`.
Today, I'm going to show you a bit of the basics of `ggplot2`.
## Functions
I'm also going to tell you a bit about writing your own functions.
---
layout: true
# .mono[ggplot2]
---
name: ggplot2
```{R, gg data, echo = F}
# Load births data; drop totals; create time variable
birth_df <- read_csv("usa_birth_1933_2015.csv") %>%
janitor::clean_names() %>%
filter(month != "TOT") %>%
mutate(
month = as.numeric(month),
time = year + (month-1)/12
)
# Load days of months data
days_df <- read_csv("days_of_month.csv")
# Clean up days
days_lon <- gather(days_df, year, n_days, -Month)
days_lon <- janitor::clean_names(days_lon)
days_lon$year <- as.integer(days_lon$year)
# Join
birth_df <- left_join(
x = birth_df,
y = days_lon,
by = c("year", "month")
)
# Calculate 30-day equivalent births by month
birth_df %<>% mutate(
births_30day = births / n_days * 30
)
# Add post-ww2 indicator
birth_df %<>% mutate(post_ww2 = time > 1945 + 8/12)
```
The `ggplot` function `aes` arguments define variables from `data`.
```{R, gg1, fig.height = 5}
ggplot(data = birth_df, aes(x = time, y = births))
```
---
count: false
You can apply mathematical operators to the variables.
```{R, gg2, fig.height = 5}
ggplot(data = birth_df, aes(x = time, y = births/10000))
```
---
count: false
You add *geometries* (points, lines, *etc*.) layer by layer.
```{R, gg3, fig.height = 5}
ggplot(data = birth_df, aes(x = time, y = births/10000)) +
geom_point()
```
---
count: false
Color is easy.
```{R, gg4, fig.height = 5}
ggplot(data = birth_df, aes(x = time, y = births/10000)) +
geom_point(color = "deeppink")
```
---
count: false
You can even use variables to color.
```{R, gg5, fig.height = 5}
ggplot(data = birth_df, aes(x = time, y = births/10000)) +
geom_point(aes(color = post_ww2))
```
---
count: false
Add labels
```{R, gg6, fig.height = 4.75}
ggplot(data = birth_df, aes(x = time, y = births/10000)) +
geom_point() +
xlab("Time") + ylab("Births (10,000s)")
```
---
count: false
Change the theme...
```{R, gg7, fig.height = 4.5}
ggplot(data = birth_df, aes(x = time, y = births/10000)) +
geom_point() +
xlab("Time") + ylab("Births (10,000s)") +
theme_pander(base_size = 20)
```
---
count: false
Add other geometries—_e.g._, connect the dots (`line`) and a regression line
```{R, gg8, fig.height = 4}
ggplot(data = birth_df, aes(x = time, y = births/10000)) +
geom_line(color = "grey85") +
geom_point() +
geom_smooth(se = F, method = lm) +
xlab("Time") + ylab("Births (10,000s)") +
theme_pander(base_size = 20)
```
---
count: false
Compare births and its 9-month lag...
```{R, gg9, fig.height = 4}
ggplot(data = birth_df, aes(x = lag(births, 9)/10000, y = births/10000)) +
geom_line(color = "grey85") +
geom_point() +
geom_smooth(se = F) +
xlab("Births 9 months ago (10,000s)") + ylab("Births (10,000s)") +
theme_pander(base_size = 20)
```
---
layout: true
# Writing functions
---
name: functions
## Functions are everywhere
Everything you do in .mono[R] involves some sort of function, _e.g._,
- `mean()`
- `lm()`
- `summary()`
- `read_csv()`
- `ggplot()`
- `+`
The basic idea in .mono[R] is doing things to objects with functions.
---
## Functions can help
We write functions to make life easier. Instead of copying and pasting the same line of code a million times, you can write one function.
In .mono[R], you use the `function()` function to write functions.<sup>.pink[†]</sup>
.footnote[
.pink[†] Meta, right?
]
```{R, ex function 1, eval = F}
# Our first function
the_name <- function(arg1, arg2) {
# Insert code that involves arg1 and arg2 (this is where the magic happens)
}
```
- `the_name`: The name we are giving to our new function.
- `arg1`: The first argument of our function.
- `arg2`: The second argument of our function.
---
## Our first real function
Let's write a function that multiplies two numbers. (It needs two arguments.)
```{R, ex function 2}
# Create our function
the_product <- function(x, y) {
x * y
}
```
--
Did it work?
--
```{R, ex function 3}
the_product(7, 15)
```
.bigger[💪]
---
## Functions can do anything
... that you tell them.
If you are going to repeat a task (_e.g._, a simulation), then you have a good situation for writing your own function.
.mono[R] offers many functions (via its many packages), but you will sometimes find a scenario for which no one has written a function.
Now you know how to write your own.
```{R, ex function 4}
# An ad lib function
ad_lib <- function(noun1, verb1, noun2) {
paste("The next", noun1, "of our lecture", verb1, noun2)
}
```
---
```{R, ex function 5}
ad_lib(noun1 = "part", verb1 = "reviews", noun2 = "time series.")
```
---
layout: true
# Time series
## Review
---
class: inverse, middle
---
name: review
Changes to our model/framework.
- Our model now has $\color{#e64173}{t}$ subscripts for .hi[time periods].
- .hi[Dynamic models] allow .hi[lags] of explanatory and/or outcome variables.
- We changed our **exogeneity** assumption to .hi[contemporaneous exogeneity], _i.e._, $\mathop{\boldsymbol{E}}\left[ u_t \middle| X_t \right] = 0$
- Including .hi-orange[lags of outcome variables] can lead to .hi[biased coefficient estimates] from OLS.
- .hi-orange[Lagged explanatory variables] make .hi[OLS inefficient].
---
layout: false
class: inverse, middle
# Autocorrelation
---
layout: false
name: intro
# Autocorrelation
## What is it?
.hi[Autocorrelation] occurs when our disturbances are correlated over time, _i.e._, $\mathop{\text{Cov}} \left( u_t,\, u_s \right) \neq 0$ for $t\neq s$.
--
Another way to think about: If the *shock* from disturbance $t$ correlates with "nearby" shocks in $t-1$ and $t+1$.
--
*Note:* **Serial correlation** and **autocorrelation** are the same thing.
--
Why is autocorrelation prevalent in time-series analyses?
---
class: clear
.hi-slate[Positive autocorrelation]: Disturbances $\left( u_t \right)$ over time
```{R, positive auto u, echo = F, fig.height = 7.25}
# Number of observations
T <- 1e2
# Rho
rho <- 0.95
# Set seed and starting point
set.seed(1234)
start <- rnorm(1)
# Generate the data
ar_df <- tibble(
t = 1:T,
x = runif(T, min = 0, max = 1),
e = rnorm(T, mean = 0, sd = 2),
u = NA
)
for (x in 1:T) {
if (x == 1) {
ar_df$u[x] <- rho * start + ar_df$e[x]
} else {
ar_df$u[x] <- rho * ar_df$u[x-1] + ar_df$e[x]
}
}
ar_df %<>% mutate(y = 1 + 3 * x + u)
# Plot disturbances over time
ggplot(data = ar_df,
aes(t, u)
) +
geom_line(color = "grey85", size = 0.35) +
geom_point(color = red_pink, size = 2.25) +
ylab("u") +
xlab("t") +
# theme_pander(base_family = "Fira Sans Book", base_size = 20)
theme_axes_math
```
---
class: clear
.hi-slate[Positive autocorrelation]: Outcomes $\left( y_t \right)$ over time
```{R, positive auto y, echo = F, fig.height = 7.25}
# Plot outcomes over time
ggplot(data = ar_df,
aes(t, y)
) +
geom_line(color = "grey85", size = 0.35) +
geom_point(color = red_pink, size = 2.25) +
ylab("y") +
xlab("t") +
# theme_pander(base_family = "Fira Sans Book", base_size = 20)
theme_axes_math
```
---
class: clear
.hi-slate[Negative autocorrelation]: Disturbances $\left( u_t \right)$ over time
```{R, negative auto u, echo = F, fig.height = 7.25}
# Number of observations
T <- 1e2
# Rho
rho <- -0.95
# Set seed and starting point
set.seed(1234)
start <- rnorm(1)
# Generate the data
ar_df <- tibble(
t = 1:T,
x = runif(T, min = 0, max = 1),
e = rnorm(T, mean = 0, sd = 2),
u = NA
)
for (x in 1:T) {
if (x == 1) {
ar_df$u[x] <- rho * start + ar_df$e[x]
} else {
ar_df$u[x] <- rho * ar_df$u[x-1] + ar_df$e[x]
}
}
ar_df %<>% mutate(y = 1 + 3 * x + u)
# Plot disturbances over time
ggplot(data = ar_df,
aes(t, u)
) +
geom_line(color = "grey85", size = 0.35) +
geom_point(color = red_pink, size = 2.25) +
ylab("u") +
xlab("t") +
# theme_pander(base_family = "Fira Sans Book", base_size = 20)
theme_axes_math
```
---
class: clear
.hi-slate[Negative autocorrelation]: Outcomes $\left( y_t \right)$ over time
```{R, negative auto y, echo = F, fig.height = 7.25}
# Plot outcomes over time
ggplot(data = ar_df,
aes(t, y)
) +
geom_line(color = "grey85", size = 0.35) +
geom_point(color = red_pink, size = 2.25) +
ylab("y") +
xlab("t") +
# theme_pander(base_family = "Fira Sans Book", base_size = 20)
theme_axes_math
```
---
layout: true
# Autocorrelation
## In static time-series models
---
name: static_models
Let's start with a very common model: a static time-series model whose disturbances exhibit .hi[first-order autocorrelation], *a.k.a.* .pink[AR(1)]:
$$
\begin{align}
\text{Births}_t &= \beta_0 + \beta_1 \text{Income}_t + u_t
\end{align}
$$
where
$$
\begin{align}
\color{#e64173}{u_t} = \color{#e64173}{\rho \, u_{t-1}} + \varepsilon_t
\end{align}
$$
and the $\varepsilon_t$ are independently and identically distributed (*i.i.d.*).
--
.hi-purple[Second-order autocorrelation], or .purple[AR(2)], would be
$$
\begin{align}
\color{#6A5ACD}{u_t} = \color{#6A5ACD}{\rho_1 u_{t-1}} + \color{#6A5ACD}{\rho_2 u_{t-2}} + \varepsilon_t
\end{align}
$$
---
An .turquoise[AR(p)] model/process has a disturbance structure of
$$
\begin{align}
u_t = \sum_{j=1}^\color{#20B2AA}{p} \rho_j u_{t-j} + \varepsilon_t
\end{align}
$$
allowing the current disturbance to correlated with up to $\color{#20B2AA}{p}$ of its lags.
---
layout: false
name: ols_static
# Autocorrelation
## OLS
For **static models** or **dynamic models with lagged explanatory variables**, in the presence of autocorrelation
1. OLS provides .pink[**unbiased** estimates for the coefficients.]
1. OLS creates .pink[**biased** estimates for the standard errors.]
1. OLS is .pink[**inefficient**.]
*Recall:* Same implications as heteroskedasticity.
Autocorrelation get trickier with lagged outcome variables.
---
layout: true
# Autocorrelation
## OLS and lagged outcome variables
---
name: ols_adl
Consider a model with one lag of the outcome variable—ADL(1, 0)—model with AR(1) disturbances
$$
\begin{align}
\text{Births}_t = \beta_0 + \beta_1 \text{Income}_t + \beta_2 \text{Births}_{t-1} + u_t
\end{align}
$$
where
$$
\begin{align}
u_t = \rho u_{t-1} + \varepsilon_t
\end{align}
$$
--
**Problem:**
--
Both $\text{Births}_{t-1}$ (a regressor in the model for time $t$) and $u_{t}$ (the disturbance for time $t$) depend upon $u_{t-1}$. *I.e.*, a regressor is correlated with its contemporaneous disturbance.
--
**Q:** Why is this a problem?
--
<br>
**A:** It violates .pink[contemporaneous exogeneity]
--
, *i.e.*, $\mathop{\text{Cov}} \left( x_t,\,u_t \right) \neq 0$.
---
To see this problem, first write out the model for $t$ and $t-1$:
$$
\begin{align}
\text{Births}_t &= \beta_0 + \beta_1 \text{Income}_t + \beta_2 \text{Births}_{t-1} + u_t \\
\text{Births}_{t-1} &= \beta_0 + \beta_1 \text{Income}_{t-1} + \beta_2 \text{Births}_{t-2} + u_{t-1}
\end{align}
$$
and now note that $u_t = \rho u_{t-1} + \varepsilon_t$. Substituting...
$$
\begin{align}
\text{Births}_t &= \beta_0 + \beta_1 \text{Income}_t + \beta_2 \color{#6A5ACD}{\text{Births}_{t-1}} + \overbrace{\left( \rho \color{#e64173}{u_{t-1}} + \varepsilon_t \right)}^{u_t} \tag{1} \\
\color{#6A5ACD}{\text{Births}_{t-1}} &= \beta_0 + \beta_1 \text{Income}_{t-1} + \beta_2 \text{Births}_{t-2} + \color{#e64173}{u_{t-1}} \tag{2}
\end{align}
$$
In $(1)$, we can see that $u_t$ depends upon (covaries with) $\color{#e64173}{u_{t-1}}$.
<br> In $(2)$, we can see that $\color{#6A5ACD}{\text{Births}_{t-1}}$, a regressor in $(1)$, also covaries with $u_{t-1}$.
--
∴ This model violates our contemporaneous exogeneity requirement.
---
*Implications:* For models with **lagged outcome variables** and **autocorrelated disturbances**
1. The models .pink[**violate contemporaneous exogeneity**.]
1. OLS is .pink[**biased and inconsistent** for the coefficients.]
---
*Intuition?* Why is OLS inconsistent and biased when we violate exogeneity?
Think back to omitted-variable bias...
$$
\begin{align}
y_t &= \beta_0 + \beta_1 x_t + u_t
\end{align}
$$
When $\mathop{\text{Cov}} \left( x_t,\, u_t \right)\neq0$, we cannot separate the effect of $u_t$ on $y_t$ from the effect of $x_t$ on $y_t$. Thus, we get inconsistent estimates for $\beta_1$.
--
Similarly,
$$
\begin{align}
\text{Births}_t &= \beta_0 + \beta_1 \text{Income}_t + \beta_2 \text{Births}_{t-1} + \overbrace{\left( \rho u_{t-1} + \varepsilon_t \right)}^{u_t} \tag{1}
\end{align}
$$
we cannot separate the effects of $u_t$ on $\text{Births}_t$ from $\text{Births}_{t-1}$ on $\text{Births}_{t}$, because both $u_t$ and $\text{Births}_{t-1}$ depend upon $u_{t-1}$.
--
$\color{#e64173}{\hat{\beta}_2}$ .pink[is **biased** (w/ OLS).]
---
layout: true
# Autocorrelation and bias
## Simulation
---
name: ar2_simulation
To see how this bias can look, let's run a simulation.
$$
\begin{align}
y_t = 1 + 2 x_t + 0.5 y_{t-1} + u_t \\
u_t &= 0.9 u_{t-1} + \varepsilon_t
\end{align}
$$
One (easy) way generate 100 disturbances from AR(1), with $\rho = 0.9$:
```{R, arima.sim, eval = F}
arima.sim(model = list(ar = c(0.9)), n = 100)
```
--
We are going to run 10,000 iterations with $T=100$.
--
**Q:** Will this simulation tell us about *bias* or *consistency*?
--
<br>**A:** Bias. We would need to let $T\rightarrow\infty$ to consider consistency.
---
Outline of our simulation:
.pseudocode-small[
1. Generate T=100 values of x
1. Generate T=100 values of u
- Generate T=100 values of ε
- Use ε and ρ=0.9 to calculate u.sub[t] = ρ u.sub[t-1] + ε.sub[t]
1. Calculate y.sub[t] = β.sub[0] + β.sub[1] x.sub[t] + β.sub[2] y.sub[t-1] + u.sub[t]
1. Regress y on x; record estimates
Repeat 1–4 10,000 times
]
---
layout: false
class: clear
```{R, sim setup, echo = F}
# Define parameters
set.seed(1234)
rho <- 0.9
b0 <- 1
b1 <- 2
b2 <- 0.5
t <- 100
```
```{R, sim gen, echo = F, eval = F}
# Function for one iteration of the simulation
sim_fun <- function(x, rho, b0, b1, b2, t) {
# Start generating data (initialize y as 1)
# NOTE: u and u2 are both AR(1): u is manual; u2 uses canned function 'arima.sim'
data_x <- tibble(
e = rnorm(t),
u = rnorm(1),
u2 = arima.sim(model = list(ar = c(0.9)), n = t),
x = rnorm(t),
y = 1,
y2 = 1
)
# Calculate u and y, iteratively
for (j in 2:t) {
data_x$u[j] <- rho * data_x$u[j-1] + data_x$e[j]
data_x$y[j] <- b0 + b1 * data_x$x[j] + b2 * data_x$y[j-1] + data_x$u[j]
data_x$y2[j] <- b0 + b1 * data_x$x[j] + b2 * data_x$y2[j-1] + data_x$u2[j]
}
# Regression
lm(y2 ~ x + lag(y2), data = data_x) %>% tidy()
}
# Run the simulation 1,000 times
sim_df <- mclapply(
X = 1:1e4,
FUN = sim_fun,
mc.cores = 8,
rho = rho, b0 = b0, b1 = b1, b2 = b2, t = t
) %>% bind_rows()
# Save
saveRDS(
object = sim_df,
file = "sim.rds"
)
```
.pull-left[
.hi-slate[Distribution of OLS estimates,] $\hat{\beta}_2$
] .pull.right[
$y_t = 1 + 2 x_t + \color{#e64173}{0.5} y_{t-1} + u_t$
]
```{R, sim density b2, echo = F, fig.height = 6.75}
ggplot(data = readRDS("sim.rds") %>% filter(term == "lag(y2)"), aes(x = estimate)) +
geom_density(color = NA, fill = red_pink, alpha = 0.95) +
geom_vline(xintercept = b2, linetype = "solid") +
geom_vline(
xintercept =
readRDS("sim.rds") %>% filter(term == "lag(y2)") %>%
select(estimate) %>% unlist() %>% mean(),
linetype = "dashed") +
geom_hline(yintercept = 0) +
theme_pander(base_family = "Fira Sans Book", base_size = 20) +
labs(x = "Estimate", y = "Density")
```
---
layout: false
class: clear
.pull-left[
.hi-slate[Distribution of OLS estimates,] $\hat{\beta}_1$
] .pull.right[
$y_t = 1 + \color{#FFA500}{2} x_t + 0.5 y_{t-1} + u_t$
]
```{R, sim density b1, echo = F, fig.height = 6.75}
ggplot(data = readRDS("sim.rds") %>% filter(term == "x"), aes(x = estimate)) +
geom_density(color = NA, fill = "orange", alpha = 0.95) +
geom_vline(
xintercept =
readRDS("sim.rds") %>% filter(term == "x") %>%
select(estimate) %>% unlist() %>% mean(),
linetype = "dashed") +
geom_vline(xintercept = b1, linetype = "solid") +
geom_hline(yintercept = 0) +
theme_pander(base_family = "Fira Sans Book", base_size = 20) +
labs(x = "Estimate", y = "Density")
```
---
layout: false
class: inverse, middle
name: testing
# Testing for autocorrelation
---
layout: true
# Testing for autocorrelation
## Static models
---
name: testing_static
Suppose we have the **static model**,
$$
\begin{align}
\text{Births}_t = \beta_0 + \beta_1 \text{Income}_t + u_t \tag{A}
\end{align}
$$
and we want to test for an AR(1) process in our disturbances $u_t$.
--
.hi[Test for autocorrelation:] Test for correlation in the lags of our residuals:
--
$$
\begin{align}
e_t = \color{#e64173}{\rho} e_{t-1} + v_t
\end{align}
$$
--
Does $\color{#e64173}{\hat{\rho}}$ differ significantly from zero?
--
**Familiar idea:** Use residuals to learn about disturbances.
---
Specifically, to test for AR(1) disturbances in the static model
$$
\begin{align}
\text{Births}_t = \beta_0 + \beta_1 \text{Income}_t + u_t \tag{A}
\end{align}
$$
.pseudocode-small[
1\. Estimate $(\text{A})$ via OLS.
2\. Calculate residuals from the OLS regression in step 1.
3\. Regress the residuals on their lags (without an intercept).
<center>
e.sub[t] = ρ e.sub[t-1] + v.sub[t]
</center>
4\. Use a _t_ test to determine whether there is statistically significant evidence that ρ differs from zero.
5\. Rejecting H.sub[0] implies significant evidence of autocorrelation.
]
---
layout: false
class: clear, middle
For an example, let's return to our plot of negative autocorrelation.
---
class: clear
.hi-slate[Negative autocorrelation]: Disturbances $\left( u_t \right)$ over time
```{R, negative auto u 2, echo = F, fig.height = 7.25}
# Number of observations
T <- 1e2
# Rho
rho <- -0.95
# Set seed and starting point
set.seed(1234)
start <- rnorm(1)
# Generate the data
ar_df <- tibble(
t = 1:T,
x = runif(T, min = 0, max = 1),
e = rnorm(T, mean = 0, sd = 2),
u = NA
)
for (x in 1:T) {
if (x == 1) {
ar_df$u[x] <- rho * start + ar_df$e[x]
} else {
ar_df$u[x] <- rho * ar_df$u[x-1] + ar_df$e[x]
}
}
ar_df %<>% mutate(y = 1 + 3 * x + u)
# Plot disturbances over time
ggplot(data = ar_df,
aes(t, u)
) +
geom_line(color = "grey85", size = 0.35) +
geom_point(color = red_pink, size = 2.25) +
ylab("u") +
xlab("t") +
# theme_pander(base_family = "Fira Sans Book", base_size = 20)
theme_axes_math
```
---
layout: true
# Testing for autocorrelation
## Example: Static model and AR(1)
---
**Step 1:** Estimate the static model $\left( y_t = \beta_0 + \beta_1 x_t + u_t \right)$ with OLS
```{R, ex ar1 1}
reg_est <- lm(y ~ x, data = ar_df)
```
--
**Step 2:** Add the residuals to our dataset
```{R, ex ar1 2}
ar_df$e <- residuals(reg_est)
```
--
**Step 3:** Regress the residual on its lag (**no intercept**)
```{R, ex ar1 3}
reg_resid <- lm(e ~ -1 + lag(e), data = ar_df)
```
---
**Step 4:** _t_ test for the estimated $(\hat{\rho})$ coefficient in step 3.
```{R, ex ar1 4}
tidy(reg_resid)
```
--
That's a very small *p*-value—much smaller than 0.05.
--
.hi[Reject H.sub[0]] (H.sub[0] was $\rho=0$, _i.e._, no autocorrelation).
--
**Step 5:** Conclude. Statistically significant evidence of autocorrelation.
---
layout: true
# Testing for autocorrelation
## Example: Static model and AR(3)
---
What if we wanted to test for AR(3)?
- We add more lags of residuals to the regression in *Step 3*.
- We **jointly** test the significance of the coefficients (_i.e._, $\text{LM}$ or $F$).
Let's do it.
---
**Step 1:** Estimate the static model $\left( y_t = \beta_0 + \beta_1 x_t + u_t \right)$ with OLS
```{R, ex ar3 1}
reg_est <- lm(y ~ x, data = ar_df)
```
--
**Step 2:** Add the residuals to our dataset
```{R, ex ar3 2}
ar_df$e <- residuals(reg_est)
```
--
**Step 3:** Regress the residual on its lag (**no intercept**)
```{R, ex ar3 3}
reg_ar3 <- lm(e ~ -1 + lag(e) + lag(e, 2) + lag(e, 3), data = ar_df)
```
--
*Note:* `lag(v, n)` from `dplyr` takes the .mono[n].super[th] lag of the variable .mono[v].
---
**Step 4:** Calculate the $\text{LM} = n\times R_e^2$ test statistic—distributed $\chi_k^2$.
<br>
$k$ is the number of regressors in the regression in *Step 3* (here, $k=3$).