-1

Hi i am trying to calculate a stocks beta using r. Beta is defined as the covariance of the returns of the equity and the returns of the benchmark divided variance of the returns of the security.

I am getting a number that is not the beta, but i do not know why.

 #Inputs
library(tidyr)
library(dplyr)
library(quantmod)
library(lubridate)
library(ggplot2)

ticker <- "TSLA"
base_index <- "SPY"
startdate <- "2016-01-01"

betadata <- new.env()
getSymbols( ticker, env = betadata, src = "yahoo",
            from = as.Date(startdate),  to = Sys.Date())
getSymbols(base_index, env = betadata, src = "yahoo",
           from = as.Date(startdate),  to = Sys.Date())

TX <- get(ticker, envir = betadata)
IX <- get(base_index, envir = betadata)
TX <- data.frame(TX[,4])
IX <- data.frame(IX[,4])
df_1 <- cbind(TX,IX)
df_2 <- mutate(df_1,date= ymd(rownames(df_1))) 
write.csv(df_2,"outputfile.csv")
df_1 <- df_1 %>% 
  mutate(return_T = ((df_1[,1]-lag(df_1[,1]))/lag(df_1[,1]))*100) %>%
  mutate(return_I = ((df_1[,2]-lag(df_1[,2]))/lag(df_1[,2]))*100)

df_lm <- lm(return_I ~ return_T, data= df_1)
summary(df_lm)

beta <- cov(df_1$return_T,df_1$return_I,
            use = "complete.obs")/var(df_1$return_T, use = "complete.obs")

print(beta)

ggplot(df_1, aes(y=return_I,x=return_T)) +
  geom_point()+ 
  geom_smooth(method = "lm")
Rob
  • 1
  • 3
  • library(tidyr) library(dplyr) library(quantmod) library(lubridate) library(ggplot2) – Rob Nov 08 '17 at 18:18
  • To reiterate @KenWhite's sentiments, you really ought to read [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) to figure out what is expected of a minimal reproducible example for questions on stack overflow – duckmayr Nov 08 '17 at 18:37
  • let's cool our jets_ the code will pull variables, I forgot to include the packages at the top, so I put them in a comment. – Rob Nov 08 '17 at 19:39
  • @Rob I think you can edit the question to paste in the code that was lacking. If the goal is to obtain beta (and not to show that you know how to calculate it or something like that), there might be packages that will calculate it for you. – Robert Dodier Nov 08 '17 at 19:46
  • 1
    To @RobertDodier's point: take a look at `PerformanceAnalytics::CAPM.beta()` and [related SO question](https://stackoverflow.com/questions/32186233/r-calculating-a-stocks-beta-using-performanceanalytics-capm-beta-function-or). – Artem Sokolov Nov 08 '17 at 19:55

1 Answers1

1

The formula of the beta uses the variance of the benchmark, not the one of the stock, as a denominator. So in your code return_I and return_T have to be inverted in the following lines, like this:

df_lm <- lm(return_T ~ return_I, data= df_1)

and

beta <- cov(df_1$return_T,df_1$return_I,
            use = "complete.obs")/var(df_1$return_I, use = "complete.obs")
Vincent K
  • 568
  • 5
  • 9