library(dplyr)
library(tidyr)
returns <- read.csv("https://empirical-economics.netlify.app/tutorials/datafiles/clean_energy_2016_daily.csv")
# tent weights: the DiD of the four means as a weighted sum of daily long-short returns
weights <- c(0, 0.2, 0.4, 0.6, 0.8, 1, 0.8, 0.6, 0.4, 0.2) # k = -5, ..., 4
for (benchmark in c("SPY", "IWO")) {
# one long-short return per day: clean-energy average minus the benchmark
long_short <- returns |>
filter(group == "clean" | ticker == benchmark) |>
summarise(ret = mean(ret), .by = c(group, date, k)) |>
pivot_wider(names_from = group, values_from = ret) |>
mutate(ls = clean - market) |>
arrange(k)
did_at <- function(centre) {
window <- filter(long_short, k >= centre - 5, k <= centre + 4)
sum(weights * window$ls)
}
estimate <- did_at(0)
# (c) Newey-West: variance of the weighted sum, w' Omega w, with Omega built from
# the Bartlett-weighted autocovariances (lag 5) of the daily long-short return
# over the estimation year (October 2015 to September 2016)
e <- long_short$ls[long_short$date >= "2015-10-01" & long_short$date <= "2016-09-30"]
autocov <- drop(acf(e, lag.max = 9, type = "covariance", plot = FALSE)$acf)
bartlett <- pmax(1 - (0:9) / 6, 0)
omega <- toeplitz(autocov * bartlett)
nw_se <- sqrt(drop(t(weights) %*% omega %*% weights))
# (d) placebo dates: the same DiD centred on every day from k = -275 to k = -26
placebo <- sapply(-275:-26, did_at)
cat(benchmark, "| estimate", round(estimate, 2), "| Newey-West se", round(nw_se, 2),
"| placebo sd", round(sd(placebo), 2),
"| share at or below", round(mean(placebo <= estimate), 3), "\n")
}