I would like to calculate Beta for a bunch of stocks without having to manually set up the equation for each stock.
Below is some sample code on which I would like to pass the names of the tickers to the x paramater in the cov() function while keeping the y and var() function variable constant:
ret <- c(1,2,1,3,1,4,5,10)
ret2 <- 2*ret
ret3 <- 2.5*ret
all_ret <- as.data.frame(cbind(ret,ret2, ret3))
ticks <- colnames(all_ret)
beta1 <- cov(x = all_ret$ret3, y = all_ret$ret) / var(all_ret$ret)
Is there a way to complete this with an apply function? something like:
sapply(ticks, function(x)
cov(x = all_ret$x, y = all_ret$ret) / var(all_ret$ret)
Please let me know how I can do this or if there is an easier way to do this, thank you for your help.
beta2 <- cov(x = all_ret, y = all_ret$ret) / var(all_ret$ret)