rggplot2quantmod

Plotting multiple graphs from a list in Rstudio


I am writing a code to track the performance of financial assets.

This is what I've done so far:

library(ggplot2)
library(quantmod)
library(magrittr)

start_date <- as.Date("2020-01-02")
end_date <- as.Date("2023-04-12")

ETF_list <- list("WTEE.DE", "VGWD.DE")

for (i in ETF_list){
  getSymbols(i, 
              from = start_date, to = end_date,
              src = "yahoo")}

# Plot the data

chartSeries(VGWD.DE,
            theme = chartTheme("white"), # Theme
            name = str(VGWD.DE), # Name
            bar.type = "hlc", # High low close 
            up.col = "green", # Up candle color
            dn.col = "red",  # Down candle color
            TA = list("addVo()", #Volume
                      "addEMA(n = 200, on = 1, col = 'blue')", 
                      "addEMA(n = 50, on =1, col = 'red')"))

This works fine for a single element of the list. But when I try to plot all the elements at once with this modified version of the code:

for (i in ETF_list){
  chartSeries(i,
              theme = chartTheme("white"), # Theme
              name = str(i), # Name
              bar.type = "hlc", # High low close 
              up.col = "green", # Up candle color
              dn.col = "red",  # Down candle color
              TA = list("addVo()", #Volume
                        "addEMA(n = 200, on = 1, col = 'blue')", 
                        "addEMA(n = 50, on =1, col = 'red')"))}

I get this: Error in try.xts(x, error = "chartSeries requires an xtsible object") : chartSeries requires an xtsible object

Any ideas?

Thanks in advance.


Solution

  • Looking at your current code, it seems that you do not save the output of the loop that includes getSymbols().

    If you are new to R, remember that for loops don't produce objects alone. you have to create a placeholder object before the loop and use the loop to populate it.

    Example:

    a= 1:10
    for(i in a){ i^2}
    print(max(a)) # ==10, the loop did not change anything.
    
    a= 1:10
    b= numeric() # placeholder object)
    for(i in a){ b=c(b,i^2)} #adding i^2 to the bottom of b
    print(max(b)) # ==100, the loop changed the result.
    

    Your code is behaving as the first case, so when you call chartSeries, you are calling it in the object list("WTEE.DE", "VGWD.DE") which is not a time series.