[R] Picking returns from particular days of the month from a zoo object

Gabor Grothendieck ggrothendieck at gmail.com
Sat Jul 23 14:46:38 CEST 2011

On Fri, Jul 22, 2011 at 3:37 PM, john nicholas <jbnichola at sbcglobal.net> wrote:
>  Hello,
> I would like to implement a "turn-of-the-month' trading strategy in R.
> Given a daily series of stock market return data as a zoo object, the strategy
> would go long (buy) four trading days before the end of the month, and sell the
> third trading day of the following month.
> How can I select these days, particularly the fourth day before and the third
> day after the turn of the month, from a zoo object?

library(quantmod) # also brings in zoo

# set up some test data
getSymbols("IBM", return.class = "zoo")

# get index in ibm to 3rd trading day in month
# and 4th last trading day in month
ym <- as.yearmon(time(IBM))
ithird <- c(tapply(seq_along(tt), ym, "[", 3))
ilast4 <- c(tapply(seq_along(tt), ym, function(x) x[length(x)-3]))

Now IBM[ithird, ] and IBM[ilast4, ] give the subseries at the third and
fourth last days of each month, respectively.

time(IBM)[ithird] and time(IBM)[ilast4] are just the dates.

Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

More information about the R-help mailing list