4

我有以下代码:

library(quantmod)
tckrs <- c("TLT", "LQD", "HYG", "SPY", "DBC")
NumTckrs  <-  length(tckrs)
getSymbols(tckrs, from="1900-01-01", to=Sys.Date())

# merge to allign the start dates
MainDF <- merge(Ad(TLT), Ad(LQD), Ad(HYG), Ad(SPY), Ad(DBC), all=FALSE)

我不想在最后一行重复股票代码。有谁知道如何做到这一点?

4

3 回答 3

5

将所有数据加载到环境中,然后调用Ad每个数据并合并它们。另请注意,getSymbols默认情况下返回 xts 对象,因此您MainDF是 xts 对象,而不是 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))
于 2012-06-24T16:55:26.997 回答
3

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)
于 2012-06-24T19:59:39.477 回答
2

Joshua's is probably more elegant than mine:

res <- do.call( merge,  lapply(  lapply(tckrs, get) , Ad) )
于 2012-06-24T17:06:15.233 回答