sql <- paste("SELECT gvkey,datadate,ni,at FROM comp.funda WHERE ni IS NOT NULL AND datadate>='2016-01-01'")
res <- dbSendQuery(wrds, sql)
fnd<- dbFetch(res, n = -1)
winsor<-
function (x, fraction=0.01){
lim <- quantile(x, probs=c(fraction, 1-fraction),na.rm = TRUE)
x[ x < lim[1] ] <- lim[1]
x[ x > lim[2] ] <- lim[2]
x}
library(dplyr)
library(zoo)
tmp <- fnd %>%
arrange(gvkey,datadate)%>%
group_by(gvkey)%>%
mutate(
roa = ni/lag(at,1)
) %>%
ungroup%>%
mutate(roa=winsor(roa,.01))%>%
group_by(gvkey)%>%
mutate(
roavol = rollapplyr(roa,5,sd,fill=NA)
)