library(BatchGetSymbols)
library(tidyverse)

tickers <- GetSP500Stocks()$Tickers
first_date <- Sys.Date() - 3*365
last_date  <- Sys.Date()

df_stocks <- BatchGetSymbols(tickers = tickers, 
                             first.date = first_date, 
                             last.date = last_date)[[2]]

df_sp500 <- BatchGetSymbols(tickers =  '^GSPC', 
                            first.date = first_date, 
                            last.date = last_date)[[2]]

idx <- match(df_stocks$ref.date, df_sp500$ref.date)
df_stocks$ret_mkt <- df_sp500$ret.closing.prices[idx]

# calculate beta for each stock
estimate_beta <- function(df) {
  # Function to estimate beta from dataframe of stocks returns
  #
  # Args:
  #   df - Dataframe with columns ret and ret.sp500
  #
  # Returns:
  #   The value of beta

  my_model <- lm(data = df, 
                 formula = ret.adjusted.prices ~ ret_mkt)

  return(coef(my_model)[2])
}

my_betas <- by(data = df_stocks, 
               INDICES = df_stocks$ticker, 
               FUN = estimate_beta)

glimpse(my_betas)

# solution
p <- ggplot(tibble(betas = my_betas), aes(x = betas)) + 
  geom_histogram()

print(p)
# none
#my_answers <- make_random_answers(my_sol)
my_answers <- rep(NA, 5)

type_question <- 'string'
ex_name <- 'models 11 04'

Question

Utilize função BatchGetSymbols::GetSP500Stocks para baixar dados de todas ações pertencentes ao atual índice SP500 para os últimos três anos. Usando o SP500 como o índice de mercado, calcule o beta para cada uma das ações. Apresente o histograma dos betas estimados. Note que os retornos do SP500 ('^GSPC') não estão disponíveis na base de dados original e devem ser baixados e agregados a base de dados original.

Solution


Meta-information

extype: r type_question exsolution: r mchoice2string(c(TRUE, FALSE, FALSE, FALSE, FALSE), single = TRUE) exname: r ex_name exshuffle: TRUE



msperlin/adfeR documentation built on March 26, 2021, 3:05 a.m.