Aaron Soderstrom
Aaron Soderstrom

Reputation: 629

R xts Time series, subset by last workday of the week

I have daily closing price in a xts object. What I am trying to do is get the last closing price of the week. Most of the time this will be Friday but sometimes this might be Thursday or even more rare Wednesday.

I been trying to subset this with the solution found here but with no luck. Has anyone seen or found a solution for something around this.

Thanks in advance.

Upvotes: 1

Views: 266

Answers (2)

Matt Brigida
Matt Brigida

Reputation: 291

Convert the time series to weekly OHLC with to.weekly. The weekly closing price should be from the last trading day in the week -- be it Thursday or Wednesday.

For example, 7/4/2014 (a US holiday) was on a Friday, so there was no trading that day. The following code returns observations for 6/27 (a Friday), 7/3 (the Thursday close), and 7/11 (a Friday).

getSymbols("SPY")
Cl(to.weekly(SPY))['2014-06-27/2014-07-11']
#            SPY.Close
# 2014-06-27    195.82
# 2014-07-03    198.20
# 2014-07-11    196.61

Upvotes: 2

Joshua Ulrich
Joshua Ulrich

Reputation: 176688

If your data only contains weekdays (no weekends), then you can use this:

require(quantmod)
getSymbols("SPY")
spy <- do.call(rbind, lapply(split(SPY, "weeks"), last))
table(weekdays(index(spy)))
#   Friday Thursday 
#      436       17 

If your data contains weekends, then you need to remove them before doing the split, lapply, rbind.

data(sample_matrix)
x <- as.xts(sample_matrix)
x <- x[.indexwday(x) %in% 1:5]
y <- do.call(rbind, lapply(split(x, "weeks"), last))

Upvotes: 1

Related Questions