I am trying to calculate the idiosyncratic skewness for different funds in a panel data. Basically, I hope to regress the daily returns of a fund on the market return and the squared market return to obtain the residuals. Then calculate the skewness of the residuals using skewness(). However, I need to perform this calculation over a 20-day moving window, moving 1-day forward per step. I am thinking to write a function and rollapply the function for each fund in my panel data. However, I failed to obtain my expected results. The following codes generate a mock datatable.
library(dplyr)
library(zoo)
set.seed(123)
# Generate mock data
n <- 100
date_sequence <- seq(as.Date("2022-01-01"), by = "1 day", length.out = n)
fund_sequence <- rep(c("Fund_A", "Fund_B", "Fund_C"), each = n/3)
panel_data <- data.frame(
fund = rep(fund_sequence, each = n),
date = rep(date_sequence, times = 3),
returns = rnorm(n * 3),
market_returns = rnorm(n * 3)
)
# My own iKewness function
getIskewness <- function(x, y, z) {
aa <- residuals(lm(x ~ y + y^2))
aa <- skewness(aa, na.rm = TRUE)
return(aa)
}
## run a rolling regression
kk <- panel_data %>%
group_by(fund) %>%
arrange(date) %>%
mutate(Iskewness=rollapply(across(c(returns, market_returns)), width = 20,
FUN=getIskewness, x=returns, y=market_returns,
by.column = FALSE, align = "right", fill="NA")) %>%
arrange(fund, date)
I found the results are constant for each fund. What I expect is a variable changing daily because the function is supposed to be rollapplied over a 20-day moving window. Could anyone help me? Thanks!
There are a few problems:
skewnessis missing so set it tomeanfor purposes of allowing it to runrollapplycan be writtenrollapplyrwith an r on the end to avoidalign="right"getIskewnessappropriately with one argument).rollapplyarguments since that notation is reserved for non-rolling arguments passed toFUN=zargument is not used ingetIskewnesscbindinrollapplyrCode:
giving: