Merge getSymbols result into one xts object

一世执手 提交于 2019-11-27 15:46:18

Load all the data into an environment, then call Ad on each, and merge them. Also note that getSymbols returns an xts object by default, therefore your MainDF is an xts object, not a data.frame.

library(quantmod)
# create new environment
myEnv <- new.env()
# pull all data and load into myEnv
getSymbols("TLT;LQD;HYG;SPY;DBC", env=myEnv)
# eapply calls Ad on each symbol in myEnv and returns a list
# do.call calls merge with each element returned from eapply as an argument
MainXTS <- do.call(merge, c(eapply(myEnv, Ad),all=FALSE))

This is one line of code with my qmao package

library(qmao)
p <- makePriceFrame(tckrs, prefer='Adjusted', silent=TRUE)

For convenience, PF is an alias for makePriceFrame. Also, since by default, the function will find and use the "Adjusted" column if it exists, you can leave out the prefer argument.

p <- PF(tckrs)

You can also combine a bunch of these types of functions

library(FinancialInstrument)
p <- PF(getSymbols(stock(tckrs, currency("USD"))))

Also, note that if you hadn't assigned your Symbol names to tckrs, you'd be able to get them from the PriceFrame.

names(p)
[1] "TLT" "LQD" "HYG" "SPY" "DBC"

If you do not specify a prefer argument, it looks for a column that contains "Adjusted", then "Close", then "Mid", then Price". To see which column was used to make the PriceFrame, look at the "prefer" attribute

attr(p, "prefer")
[1] "Adjusted"

If you keep data in separate environments, PF can handle that as well.

getSymbols(tckrs, env=myEnv)
p <- PF(ls(myEnv), env=myEnv)
42-

Joshua's is probably more elegant than mine:

res <- do.call( merge,  lapply(  lapply(tckrs, get) , Ad) )
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!