I am a little new to R. I assume that my mistake will be trivial for experienced ones.
I am trying to write an R program that will calculate beta for a number of stocks. Stock symbols are read from Input.csv, and data is loaded from yahoo. The code then performs a beta calculation cycle for each stock and outputs csv, summing the regressions.
I got a code to work when a one-time risk rate was accepted for all periods, but I believe that I may need to use the actual risk-free interest rate in each month to normalize excess income. I am having problems with this step. Xts successfully loads from FRED (GS20), but when revenue is deducted from security and market returns, it generates zero-length xts. This kills the program.
I believe this could be because dates are in different formats between FRED and Yahoo. I noticed that the getSymbols command ignores dates from-to. Any help would be appreciated.
require(PerformanceAnalytics)
require(quantmod)
require(car)
setwd("R Projects/Beta Test")
proxy <- read.csv("Input.csv",header=FALSE)[,1]
summary <- as.data.frame(matrix(0, ncol = 5, nrow = 0))
mar <- getSymbols("^GSPC", src = "yahoo", from = as.Date("2006-01-01"),
to = as.Date("2011-12-31"),auto.assign=FALSE)
riskFree <- getSymbols("GS20", src = "FRED", from = as.Date("2006-12-01"),
to = as.Date("2011-12-31"),auto.assign=FALSE)
for (n in proxy){
sec <- getSymbols(n, src = "yahoo", from = as.Date("2006-01-01"),
to = as.Date("2011-12-31"),auto.assign=FALSE)
sec.xsmonthly <- monthlyReturn(to.monthly(sec),type="log") - riskFree
mar.xsmonthly <- monthlyReturn(to.monthly(mar),type="log") - riskFree
sec.reg <- lm(sec.xsweekly ~ mar.xsmonthly + lag(mar.xsmonthly,-1))
summary[n,1] <- coef(sec.reg)[1]
summary[n,2] <- coef(sec.reg)[2]
summary[n,3] <- coef(sec.reg)[3]
summary[n,5]<-summary(sec.reg)$r.squared
}
summary[,4] <- summary[,2]+summary[,3]
colnames(summary) <- c("Alpha","Beta","Beta-Lag","Sum Beta","R-Squared")
write.csv(summary,file="output.csv")