Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split xts object by index (date)

I have an xts object that has intraday data:

head(stocks[,1])
                    SMH.close
2009-01-02 09:31:00     17.66
2009-01-02 09:32:00     17.66
2009-01-02 09:33:00     17.64
2009-01-02 09:34:00     17.60
2009-01-02 09:35:00     17.58
2009-01-02 09:36:00     17.63

I want to perform various analytics on intraday data but operations should not cross day boundaries. So what I want to do is split the data by date (ignoring the time). As such I extracted the index and saved unique date values by:

y <- index(stocks)
x <- strptime(y, format="%Y-%m-%d")
uniquedates <- unique(x)

Now I would like to do something similar to the example in ?split

> g <- airquality$Month
> l <- split(airquality, g)

Here the airquality data is split into a list object by the value of the Month column. I'm not sure how to do something similar as the date is the index in my case and not a data column. I tried but get an error.

> split(stocks, uniquedates)
Error in args[[i]] : subscript out of bounds

Perhaps there is a cleaner way of achieving what I want to do. I would greatly appreciate your help.

like image 825
codingknob Avatar asked Apr 16 '26 19:04

codingknob


1 Answers

You should skip the unique() step. Just use split.xts with an f="days" argument.

data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
split.xts(sample.xts, f="days")
[[1]]
               Open     High      Low    Close
2007-01-02 50.03978 50.11778 49.95041 50.11778

[[2]]
              Open     High     Low    Close
2007-01-03 50.2305 50.42188 50.2305 50.39767

[[3]]
               Open     High      Low    Close
2007-01-04 50.42096 50.42096 50.26414 50.33236

[[4]]
snipped
like image 173
IRTFM Avatar answered Apr 18 '26 07:04

IRTFM



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!