这里总新手,在尝试编写函数来计算股票的无杠杆beta时遇到错误问题。
继续获得返回协方差的NA,我认为这可能是使用错误对象类的问题
非常感谢任何帮助
library(tidyr)
library(dplyr)
library(quantmod)
library(lubridate)
library(ggplot2)
betadata <- new.env()
ticker <- "GS"
base_index <- "DJI"
startdate <- "2016-01-01"
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])) %>%
mutate(return_I = (df_1[,2]-lag(df_1[,2]))/lag(df_1[,2]))
df_lm <- lm(return_T ~ return_I, data= df_1)
summary(df_lm)
beta <- cov(df_1$return_T,df_1$return_I)
print(beta)
答案 0 :(得分:0)
df_1$return_T
和df_1$return_I
包含NA
个。使用
beta <- cov(df_1$return_T,df_1$return_I, use = "complete.obs")
print(beta)
[1] 7.300298e-05