Hello, I am trying to build a code in order to calculate the mean and variance of some stocks,
when I write this
get_stock_data3 <- function(stock_list, date_debut, date_fin){
for (stock_symbol in stock_list) {
stock_results <- tq_get(stock_symbol, from = date_debut, to = date_fin, get = "stock.prices")
stock_results <- as.numeric(unlist(stock_results[, 6]))
n <- length(stock_results)
stock_results$returns <- ((stock_results[2:n] -stock_results[1:(n-1)])/stock_results[1:(n-1)])
mean_returns <- mean(stock_results$returns, na.rm = TRUE)
sd_returns <- sd(stock_results$returns, na.rm = TRUE)
results_data <- tibble(Stock_symbol = stock_symbol, Mean_returns = mean_returns, SD_returns = sd_returns)
return(results_data)
}
}
when I write for example
stock_list <— c("AAPL", "MSFT",...)
resultstest<—get_stock_data3(stock_list, "2020-10-25","2021-10-25")
this program gives me the right answer but only for the first stock of the list.
any idea how to fix this problem ?
thank you very much