1

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.

Community
  • 1
  • 1
Aaron Soderstrom
  • 599
  • 1
  • 6
  • 12

2 Answers2

2

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
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Matt Brigida
  • 191
  • 7
1

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))
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418