Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty xts objects via for loop

I am attempting to create a series of empty xts objects via a for loop, but I am failing.

I have created a character vector named SYMBOL_vector which contains the names of the empty XTS objects I wish to create. I also have also downloaded some stock market data using getSymbols, including data for the symbol SPY. As a result, an XTS object named SPY exists.

My for loop code is:

for (i in 1 : length(SYMBOL_vector)) {
  SYMBOL_vector[i] <- as.xts(order.by = index(SPY))
}

When I run the code I receive the following error:

Error in xts(x = NULL, order.by = x, ...) : formal argument "order.by" matched by multiple actual arguments

If it matters to the feedback, once the empty xts objects are created, I am going to write another for loop to fill each with daily return data.

I'm not opposed to taking a totally different approach to the loop...this one just seemed to be quick and easy. Thanks in advance for any help!

like image 452
PHXtrader Avatar asked Jul 12 '26 01:07

PHXtrader


1 Answers

Your code should work if you just use xts instead of as.xts, however, it's not really the "R way" (or "quantmod way") to attack the problem.

Consider this:

library(quantmod)
s <- c("SPY", "DIA", "QQQ")
e <- new.env() # an empty environment to hold yahoo price data
getSymbols(s, env=e)
L <- eapply(e, dailyReturn) # a list of returns
L$SPY

You can probably stop here, but if you want, you can convert the list to an environment.

ret <- as.environment(L) # an environment with xts objects of daily returns
ls(ret)
get("DIA", pos=ret)

Or if you really want you could attach that ret environment (NOT recommended)

attach(ret)  # not recommended
head(QQQ)
#           daily.returns
#2007-01-03 -0.0050621261
#2007-01-04  0.0189639223
#2007-01-05 -0.0047662279
#2007-01-08  0.0006841505
#2007-01-09  0.0050136737
#2007-01-10  0.0117913832
like image 171
GSee Avatar answered Jul 13 '26 16:07

GSee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!