with_progress({
# Initialize the progress bar
pb <- progressor(along = unique(pct_women_exec$ticker))
# Precompute unique tickers
unique_tickers <- unique(pct_women_exec$ticker)
# Use lapply to fit models for each ticker
fitted_models <- lapply(unique_tickers, function(ticker) {
# Subset the data and external regressors for the current ticker
y <- pct_women_exec[pct_women_exec$ticker == ticker, "ret.RF"]
X1 <- data.frame(Mkt.RF = pct_women_exec[pct_women_exec$ticker == ticker, "Mkt.RF"])
X2 <- data.frame(event_dummy = pct_women_exec[pct_women_exec$ticker == ticker, "event_dummy"])
X2 <- as.matrix(X2)
X3 <- data.frame(SMB = pct_women_exec[pct_women_exec$ticker == ticker, "SMB"])
X4 <- data.frame(HML = pct_women_exec[pct_women_exec$ticker == ticker, "HML"])
X <- cbind(as.matrix(X1), X2, as.matrix(X3), as.matrix(X4))
# Define the specifications
spec <- ugarchspec(variance.model = list(model = "sGARCH", external.regressors=X2), mean.model = list(armaOrder= c(0, 0), include.mean = TRUE, external.regressors=X))
# Fitting the model
fit <- ugarchfit(data=y, spec=spec, solver="hybrid", scale = FALSE)
#Extracting residuals and sd of sigma
resid <- residuals(fit)
sigma_sd <- sd(sigma(fit))
# Perform OLS assumptions tests
# Normality test
jb_test <- jarque.bera.test(resid)
sw_test <- shapiro.test(resid)
# Autocorrelation test
lj_test <- Box.test(resid, lag = 10, type = "Ljung-Box")
bg_test <- bgtest(fit, order = 1)
# Heteroscedasticity test
wh_test <- bptest(resid ~ 1, varformula = ~ fitted(fit)^2)
bp_test <- bptest(fit, studentize = FALSE)
# Add test results as attributes of the fit object
fit@jb_test <- jb_test
fit@sw_test <- sw_test
fit@lj_test <- lj_test
fit@bg_test <- bg_test
fit@wh_test <- wh_test
fit@bp_test <- bp_test
# Check the output
convergence(fit)
coef(fit)
# Update the progress bar
pb()
# Return the fitted model
return(fit)
})
})
Why would the code return me an error here? I feel like I have tried everything to pass all of these tests to the fit object. Residuals and sd of sigma are correctly being extracted as values are being pulled for the first ticker before the loop returns an error.