-
Notifications
You must be signed in to change notification settings - Fork 0
/
VAR_External_Instrument_ECB.Rmd
335 lines (241 loc) · 7.76 KB
/
VAR_External_Instrument_ECB.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
---
title: "VAR_External_Instrument_ECB"
author: "MandarPriya_Phatak"
date: "`r Sys.Date()`"
output:
word_document:
toc: yes
toc_depth: '2'
html_document:
toc: yes
toc_depth: '2'
df_print: paged
pdf_document:
latex_engine: xelatex
toc: yes
toc_depth: '2'
---
```{r setup}
knitr::opts_chunk$set(cache = TRUE, cache.lazy = FALSE, warning = FALSE,
message = FALSE,echo = TRUE, dpi = 360, warning = FALSE,
fig.width = 10, fig.height = 9)
```
# prequisite libraries
```{r}
library(tidyquant)
library(tidyverse)
library(Matrix)
library(readxl)
library(dplyr)
library(broom)
library(modeltime)
library(readr)
library(vars)
library(svars)
```
# reading the data
```{r}
data <- read_csv("data_final.csv")
data |> head()
```
## Data exploration using skimr
```{r}
library(skimr)
data_var <- data |>
dplyr::select(-date,-ois_1y)
skim(data = data_var)
```
```{r}
library(DataExplorer)
DataExplorer::create_report(data = data_var)
```
```{r}
## Selecting the number of lags, and no intercept
VARselect(data_var, lag.max = 12,type = "none")
```
## We can see that number of lags based on bic is 2
```{r}
# VAR model without constant
var <- vars::VAR(data_var,lag.max = 12,ic = "SC",type = "none")
## Residual
res = data.frame(residuals(var))
## Instrument
instrument <-(data[,"ois_1y"])
instrument <- instrument[3:nrow(instrument), , drop = FALSE]
## Aligining the dependent based on ordering
# Extract column names from the residuals dataframe
seriesnames <- colnames(res)
origorder <- seriesnames
# Check if the dependent variable (assuming "ffr") is in the residuals
dependent <- "de1y"
if (dependent %in% seriesnames) {
# Reorder columns to put dependent first
seriesnames <- seriesnames[seriesnames != dependent]
seriesnames <- c(dependent, seriesnames)
# Reorder the columns in res
res <- res[, seriesnames]
} else {
stop(paste("The series you are trying to instrument (", dependent, ") is not a series in the residual dataframe.", sep =""))
}
## combining the instrument with the residual
res[,"instrument"] <- instrument
# Create matrix u from the reordered residuals
u <- as.matrix(res[, seriesnames])
# Remove rows with NA values in the instrument column
u <- u[!is.na(res$instrument), ]
print("Step 2 completed: Residual matrix created.")
print(dim(u))
## Intermediate steps
# Useful constants
T <- nrow(u)
k <- ncol(u)
p <- 2
# Some necessary parts of the covariance matrix
gamma <- (1 / (T - k*p - 1)) * t(u) %*% u
gamma_11 <- gamma[1,1]
gamma_21 <- matrix(gamma[2:nrow(gamma), 1], c(k-1,1))
gamma_22 <- matrix(gamma[2:nrow(gamma), 2:nrow(gamma)], c(k-1,k-1))
## First and Second stage regression
# First stage regression
firststage <- lm(de1y ~ instrument, data = res)
res[names(predict(firststage)), "fs"] <- predict(firststage)
print("Step 4 completed: First stage regression performed.")
print(summary(firststage))
# Now get the second-stage coefficients
coefs <- rep(0, k)
names(coefs) <- seriesnames
for (i in 1:k) {
s <- seriesnames[i]
if (s != "de1y") { # Using "d" as the instrumented variable
secondstage <- lm(as.formula(paste(s, " ~ fs")), res)
coefs[i] <- secondstage$coefficients["fs"]
} else {
coefs[i] <- 1
}
}
print("Step 5 completed: Second stage regression performed.")
print(coefs)
## Identitfying the factor
s21_on_s11 <- matrix(coefs[2:k], c(k-1,1))
Q <- (s21_on_s11 * gamma_11) %*% t(s21_on_s11) - (gamma_21 %*% t(s21_on_s11) + s21_on_s11 %*% t(gamma_21)) + gamma_22
s12s12 <- t(gamma_21 - s21_on_s11 * gamma_11) %*% solve(Q) %*% (gamma_21 - s21_on_s11 * gamma_11)
s11_squared <- gamma_11 - s12s12
sp <- as.numeric(sqrt(s11_squared))
print("Step 6 completed: Intermediate matrices calculated.")
print("sp value:")
print(sp)
result <- sp * coefs[origorder]
print("Step 7 completed: Final result calculated.")
print("Final result:")
print(result)
## IRFs plot
ma_representation <- Phi(var, 50)
irfs <- apply(ma_representation, 3, function(x) x %*% result)
irfs <- as.data.frame(t(irfs))
colnames(irfs) <- names(result)
irfs <- mutate(irfs, horizon = 0:50)
irfs <- gather(irfs, key = variable, value = response, -horizon)
ggplot(irfs, aes(x = horizon, y = response, group = variable, color = variable)) + geom_line()
```
### Checking with Robust Errors:- using vcovHAC, waldtest
```{r}
library(sandwich)
library(lmtest)
var <- vars::VAR(data_var, lag.max = 12, ic = "SC", type = "none")
res = data.frame(residuals(var))
```
```{r}
instrument <- (data[,"ois_1y"])
instrument <- instrument[3:nrow(instrument), , drop = FALSE]
```
```{r}
# Extract column names from the residuals dataframe
seriesnames <- colnames(res)
origorder <- seriesnames
# Check if the dependent variable (assuming "ffr") is in the residuals
dependent <- "de1y"
if (dependent %in% seriesnames) {
# Reorder columns to put dependent first
seriesnames <- seriesnames[seriesnames != dependent]
seriesnames <- c(dependent, seriesnames)
# Reorder the columns in res
res <- res[, seriesnames]
} else {
stop(paste("The series you are trying to instrument (", dependent, ") is not a series in the residual dataframe.", sep =""))
}
res[,"instrument"] <- instrument
# Create matrix u from the reordered residuals
u <- as.matrix(res[, seriesnames])
# Remove rows with NA values in the instrument column
u <- u[!is.na(res$instrument), ]
print("Step 2 completed: Residual matrix created.")
print(dim(u))
```
```{r}
# Useful constants
T <- nrow(u)
k <- ncol(u)
p <- 2
# Some necessary parts of the covariance matrix
gamma <- (1 / (T - k*p - 1)) * t(u) %*% u
gamma_11 <- gamma[1,1]
gamma_21 <- matrix(gamma[2:nrow(gamma), 1], c(k-1,1))
gamma_22 <- matrix(gamma[2:nrow(gamma), 2:nrow(gamma)], c(k-1,k-1))
# First stage regression
firststage <- lm(de1y ~ instrument, data = res)
res[names(predict(firststage)), "fs"] <- predict(firststage)
print("Step 4 completed: First stage regression performed.")
print(summary(firststage))
# Calculate robust standard errors for first stage
robust_se_first <- sqrt(diag(vcovHAC(firststage)))
print("Robust standard errors for first stage:")
print(robust_se_first)
# Calculate robust F-statistic
robust_f <- waldtest(firststage, vcov = vcovHAC(firststage))
print("Robust F-statistic:")
print(robust_f)
```
```{r}
# Now get the second-stage coefficients
coefs <- rep(0, k)
names(coefs) <- seriesnames
robust_se_second <- list()
for (i in 1:k) {
s <- seriesnames[i]
if (s != "de1y") { # Using "d" as the instrumented variable
secondstage <- lm(as.formula(paste(s, " ~ fs")), res)
coefs[i] <- secondstage$coefficients["fs"]
# Calculate robust standard errors for second stage
robust_se_second[[s]] <- sqrt(diag(vcovHAC(secondstage)))
print(paste("Robust standard errors for", s, "in second stage:"))
print(robust_se_second[[s]])
} else {
coefs[i] <- 1
}
}
print("Step 5 completed: Second stage regression performed.")
print(coefs)
```
```{r}
s21_on_s11 <- matrix(coefs[2:k], c(k-1,1))
Q <- (s21_on_s11 * gamma_11) %*% t(s21_on_s11) - (gamma_21 %*% t(s21_on_s11) + s21_on_s11 %*% t(gamma_21)) + gamma_22
s12s12 <- t(gamma_21 - s21_on_s11 * gamma_11) %*% solve(Q) %*% (gamma_21 - s21_on_s11 * gamma_11)
s11_squared <- gamma_11 - s12s12
sp <- as.numeric(sqrt(s11_squared))
print("Step 6 completed: Intermediate matrices calculated.")
print("sp value:")
print(sp)
result <- sp * coefs[origorder]
print("Step 7 completed: Final result calculated.")
print("Final result:")
print(result)
```
```{r}
ma_representation <- Phi(var, 50)
irfs <- apply(ma_representation, 3, function(x) x %*% result)
irfs <- as.data.frame(t(irfs))
colnames(irfs) <- names(result)
irfs <- mutate(irfs, horizon = 0:50)
irfs <- gather(irfs, key = variable, value = response, -horizon)
ggplot(irfs, aes(x = horizon, y = response, group = variable, color = variable)) + geom_line()
```