3

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.

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

+1 but split is a generic, so you don't need to explicitly call split.xts. split(sample.xts, "days") works.
Yes. I knew that but the arguments to split.xts are different than for split.default, so I decided to emphasize that difference.
Also, note that split() returns zoo objects, while split.xts returns xts/zoo objects.
0

Perhaps you're looking for apply.daily (or period.apply in general)?

2 Comments

The period.apply functions will definitely come in use but I also want to compute various statistics - some rolling and others probability based - at every time increment X intraday. For example I want to know how many stocks are up / down at time = X * n (where n is an integer). As a result I think I need to split the data by day but perhaps there is a cleaner way preparing the data.
We could suggest the best alternatives if you gave a more complete example of what you're trying to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.