I am trying to fetch data for some stocks using quantmod and it worked when I did for just 1 stock. But when I try to automate it for list of multiple Stock Symbols then I am not getting the results
Below Code works for getting just 1 Stock Symbol data by making it Static:
library(tidyverse)
library(quantmod)
# Creating Empty dataframe to collect final results
df_append <- setNames(data.frame(matrix(ncol = 8, nrow = 0)),
c("Date", "Symbol", "Open","High","Low","Close","Volume","Adjusted"))
fetch_stock_data_fn <- function(){
# Fetching Stock data for each symbol
df_quant <- quantmod::getSymbols(Symbols = "SHREECEM.NS", src="yahoo",
from = "2021-05-01",auto.assign = F) %>%
# converting time series to dataframe
data.frame(as.matrix(.), Date=time(.), row.names = NULL) %>%
# Adding Symbol Column
mutate(Symbol = "SHREECEM.NS",
Symbol = str_remove(Symbol, ".NS")) %>%
select(Date,Symbol,everything())
# Removing String from Column Names
for (col in 3: ncol(df_quant)){
colnames(df_quant)[col] <- str_remove(colnames(df_quant)[col],"SHREECEM.NS.")
}
# Selecting Required columns only
df_quant <- df_quant %>%
select(Date:Adjusted)
# Append data to final dataframe
df_append <- rbind(df_append,df_quant)
return(df_append)
}
fetch_stock_data_fn()
Now when I try to modify this to accept stock symbol names for multiple symbols then I am not getting results. I think I am close to the solution but probably messing up with names in quotes while passing them as argument in the function call:
library(tidyverse)
library(quantmod)
# Creating Empty dataframe to collect final results
df_append <- setNames(data.frame(matrix(ncol = 8, nrow = 0)),
c("Date", "Symbol", "Open","High","Low","Close","Volume","Adjusted"))
fetch_stock_data_fn <- function(stock_name){
# Fetching Stock data for each symbol
df_quant <- quantmod::getSymbols(Symbols = {{stock_name}}, src="yahoo",
from = "2021-05-01",auto.assign = F) %>%
# converting time series to dataframe
data.frame(as.matrix(.), Date=time(.), row.names = NULL) %>%
# Adding Symbol Column
mutate(Symbol = {{stock_name}},
Symbol = str_remove(Symbol, ".NS")) %>%
select(Date,Symbol,everything())
# Removing String from Column Names
for (col in 3: ncol(df_quant)){
colnames(df_quant)[col] <- str_remove(colnames(df_quant)[col],paste0({{stock_name}},"."))
}
# Selecting Required columns only
df_quant <- df_quant %>%
select(Date:Adjusted)
# Append data to final dataframe
df_append <- rbind(df_append,df_quant)
return(df_append)
}
Calling Function:
test_vector <- c("SHREECEM.NS","ADANIPORTS.NS")
for (vec_count in 1: length(test_vector)){
# print(test_vector[vec_count])
fetch_stock_data_fn(test_vector[vec_count])
}