Search code examples
rlistxtsquantmod

Loading in list of xts to be used in Quantmod


So I have large list of xts objects which is OHLC data for 900 plus names. It orginally came in a dataframe coupled with other stuff I didn't need. I now want to use it in quantmod using getsymbols and load it into my environment however it is taking far too long. Anyone know a more efficient way of doing this or what I might be doing wrong? Can getSymbols handle a list of xts?

load(file = "biglistofdataframes.Rdata")

### Convert the list of dataframes to xts
list_of_xts <- lapply(listofdataframes,function(x) xts(x[,2:6],x$date))

####change column names to match quantmod
list_of_xts <- lapply(list_of_xts, setNames,nm = c("Open","High","Low","Close","Volume"))
 ####Save to Rdatafile
save(list_of_xts, file="1.RData")
#First I  clear the environment then I load the data back into the environment
load("1.RData")
##
getSymbols("list_of_xts", src="RData", auto.assign=TRUE)#this craps out on me

The reason I am trying to get it into this format is so that I can replicate Ross Bennett's momentum code. See below

https://rbresearch.wordpress.com/2012/10/20/momentum-in-r-part-2/


Solution

  • I wouldn't expect this code to work:

    getSymbols("list_of_xts", src = "RData", auto.assign = TRUE)
    

    ?getSymbols.RData says that Symbols (the first argument) should be "a character vector specifying the names of each symbol to be loaded". You don't have a symbol and file named "list_of_xts.RData".

    Also, getSymbols.RData() expects each symbol to be in its own file, so you would have to write each xts object in your list to a separate file.

    # Get some data
    env_of_xts <- new.env()
    getSymbols(symbols, env=env_of_xts)
    # Write it to a temporary directory
    tdir <- tempdir()
    for (nm in names(env_of_xts)) {
      save(list = nm, file = file.path(tdir, paste0(nm, ".RData")), envir = env_of_xts)
    }
    
    # Now you can use getSymbols() to load from file
    getSymbols(symbols[1], src = "RData", dir = tdir, extension = "RData")
    # [1] "AAPL"
    head(AAPL)
    #            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
    # 2007-01-03  12.32714  12.36857 11.70000   11.97143   309579900      8.137179
    # 2007-01-04  12.00714  12.27857 11.97429   12.23714   211815100      8.317789
    # 2007-01-05  12.25286  12.31428 12.05714   12.15000   208685400      8.258555
    # 2007-01-08  12.28000  12.36143 12.18286   12.21000   199276700      8.299341
    # 2007-01-09  12.35000  13.28286 12.16429   13.22429   837324600      8.988768
    # 2007-01-10  13.53571  13.97143 13.35000   13.85714   738220000      9.418928