I am working with daily stock data and I am trying to compute the monthly betas in month t from daily stock data on t-11 month time window (e.g. the beta in Dec comprises daily stock data from Jan up to and including Dec). Additionally, I want to include a minimum of 150 observations in the regression equation. ->Link to data screenshot
I want to calculate the beta by computing the coefficients of a regression of excess stock returns on the excess market return over the past 12 months. My sample data lists the excess returns of each stock (the stock is classified by a number) and the market return mktrf in the last column.
I came up with the following code, but unfortunately I cannot find the error: I used width=252 for the past 12 months in days, but have not included prerequisite of a minimum of 150 observations in the code yet. I also have troubles with the NAs when the stock got delisted. I have searched the forum and I can only find the same code as I have in the answers, so I don't know what I'm doing wrong.
rollingbeta <- rollapply(joined_data,
width=252,
FUN = function(x) {
t = lm(formula=paste0(" ` ", x , " ` ~ mktrf"), data = x, na.rm=T);
return(t$coef) },
by.column=TRUE,
align="right")
Ideally, I wish to seek the output in the same data format as my input table.
Any ideas on this? Would appreciate any help!
Here is a sample created with dput:
structure(list(date = structure(c(16804, 16805, 16806, 16807, 16808, 16811, 16812, 16813, 16814, 16815), class = "Date"),
10001
= c(NA, -0.0132978723404255, 0.0148247978436657, 0.0146082337317397, 0.0196335078534031, 0.0346598202824133, 0.0235732009925558, 0, -0.0145454545454544, -0.0172201722017221),93436
= c(NA, 8.95215075422673e-05, -0.0196482119679542, -0.0154766252739225, -0.0215627173661025, -0.0149289099526067, 0.0101996632186674, -0.0460065723674811, 0.0293045779042485, -0.00577165583470751), mktrf = c(-0.0159, 0.0012, -0.0135, -0.0244, -0.0111, -6e-04, 0.0071, -0.0267, 0.0165, -0.0214)), row.names = c(NA, 10L), class = "data.frame")