How can I make a loop with tickers created in Excel in R?

135 Views Asked by At

I am trying to make a loop in R with tickers I have created in Excel. I am trying to collect stock data from Yahoo finance, and the idea is that R is going to read the name of the stock from the Excel file, and then collect it from Yahoo Finance and create a graph.

In the data frame "Stocks" there are 10 different stocks listed in different columns, and I would like to run a loop so that I can get 10 different graphs. Here is the formula I have used to create a graph out of the first stock in the dataset.

 `Stocks %>%
ggplot(aes(x=Date, y = NOVO.B.CO.Close)) + 
geom_line(col = "darkgreen") + 
geom_point(col = "darkgreen") +
theme_gray() + 
ggtitle("Novo Nordiske B") `
1

There are 1 best solutions below

0
Oliver On

Wrapping my comments into a proper answer. It is not clear whether you want to make this a single plot (using facet_wrap) or multiple plots combined into a single window. When using ggplot2 it is beneficial to have a single data.frame in long format, as one can let ggplot handle all of the colouring and grouping based on a grouping column similar to the example below

library(ggplot2)
data(mtcars)
ggplot(mtcars, aes(x = mpg, y = hp, col = factor(cyl))) + 
  geom_point() + 
  geom_smooth() + 
  labs(col = 'Nmb. Cylinder') 

From here the guide gives names for each colour, and scale_*_(manual/discrete/continuous) can be used to change specific colour palettes (eg scale_colour_discrete can be used to change the palette for factors).

When it comes to combining ggplots the patchwork package provides the simple interface. If we assume you have a vector tickers, titles and colors respectively, we can create a list of plots and combine them using simply addition (+).

library(purrr)
plots <- vector('list', n <- length(tickers))
base <- ggplot(Stocks, aes(x = Date)) + 
  theme_gray() 
for(i in seq_len(n)){
  plots[[i]] <- base + 
    geom_point(aes_string(y = tickers[i]), col = colors[i]) 
    geom_line(aes_string(y = tickers[i]), col = colors[i]) 
    ggtitle(titles[i])
}
reduce(plots, `+`)

However for stocks the first option is likely going to give a better result.