Thanks, this is totally outside my area but it looks like a start for someone who knows a bit about it. However we need to know what R packages you have loaded. For example when I ran your code I get an error could not find function "tq_get". I do not see it in the PerformanceAnalytics package and in the PortfolioAnalytics package that you mention. BTW' are you loading either of them?
I think we, also need some sample data. You say you have two data sets. We probably need data from both.
A handy way to supply some sample data is the dput() function. In the case of a large dataset something like dput(head(mydata, 100)) should supply the data we need. Just do dput(mydata) where mydata is your data. Copy the output and paste it here.
BTW your code is a bit messy here. I think you have a few ``` in the wrong spots.
I think this is what you intended.
get_stock_data <- function(stock_list, date_debut, date_fin){
stock_list_df <- vector(length = length(stock_list), 'list')
i = 1
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 )
stock_list_df[[i]] <- results_data
i <- i + 1
# return(results_data)
}
return(do.call("rbind", stock_list_df))
}
#creation d'une liste de stocks
stock_list <- c("AAPL", "MSFT","TSLA", "AMZN", "GOOG", "JPM", "PFE", "BLK", "IBM", "NKE")
#appel de la fonction pour les stocks et les donner
results_stocks <- get_stock_data(stock_list, "2022-01-01", "2023-01-01")
# Nombre de portefeuilles à créer
num_portfolios <- 10
# Initialisation d'une matrice pour stocker les poids des portefeuilles
portfolio_weights <- matrix(0, ncol = length(stock_list), nrow = num_portfolios)
# Boucle pour créer chaque portefeuille
for (i in 1:num_portfolios) {
# Génération aléatoire des poids de chaque stock
weights <- runif(length(stock_list))
# Normalisation des poids pour que la somme soit égale à 1
weights <- weights / sum(weights)
Stockage des poids dans la matrice
portfolio_weights[i, ] <- weights
}
# Conversion de la matrice des poids en un data.frame
portfolio_weights_df <- as.data.frame(portfolio_weights)
# Ajout des noms de colonnes pour chaque stock
colnames(portfolio_weights_df) <- stock_list