Skip to content

Iterating through subset of XTS object

3 messages · Noah Silverman, Jeff Ryan, Joshua Ulrich

#
Hi,

I have an xts object with 1 minute bars of trading data.

I want to select a subset, then iterate through each bar.  The "obvious" solution doesn't work:

For each bar in the loop, I want to access all the fields (open, close, volume, etc.)


I tried the following, but it doesn't work:

----------------------------------------------
for( one in bars['T10:00/T10"30', ]){
	print(one$open)
	print(one$close)
}
---------------------------------------------

Note: I DO need the loop for the code I'm writing.  

Can someone suggest the proper way to do this?

Thanks!

--
Noah Silverman
UCLA Department of Statistics
8117 Math Sciences Building
Los Angeles, CA 90095
#
Jeffrey Ryan    |    Founder    |    jeffrey.ryan at lemnica.com

www.lemnica.com
On Jul 5, 2011, at 12:53 AM, Noah Silverman <noahsilverman at ucla.edu> wrote:

            
Your solution isn't really obvious enough to R :-)

Try a very basic loop like

for(i in 1:nrow(xts_obj)) {
  xts_obj[i]
}

And make sure you subset by time first to avoid repeating that. 

You could also use apply

In general this is more an R-help question, as it has nothing to do with finance.
You might be surprised that this is likely not true ... But you probably expected someone to point that out.
Best,
Jeff
#
On Tue, Jul 5, 2011 at 12:53 AM, Noah Silverman <noahsilverman at ucla.edu> wrote:
A reproducible example would have been nice (a "bars" object and code
without syntax errors).

You're going to have this issue with a lot of objects and for loops
because ?"for" says that seq (the part of a for loop after in) is
"[A]n expression evaluating to a vector (including a list and an
expression) or to a pairlist or 'NULL'".  xts objects are not strictly
vectors.
[1] FALSE

So it gets coerced to numeric.
[1] 3 4 5 6 8 7 6 5
The proper way is to loop over the indices of the object.

for(i in 1:NROW(bars['T10:00/T10:30',])) {
  bar <- bars[i,]
  # do stuff
}
Best,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com