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")