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

Joshua Ulrich josh.m.ulrich at gmail.com
Sat Jul 23 12:31:30 CEST 2011


On Fri, Jul 22, 2011 at 2: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?
>
Here are two ways to do this using xts.  The first approach creates a
list of xts objects where each list element contains one month of
data.  Then it uses first() and last() to extract the 4th trading day
prior to the end of the month.

require(quantmod)
getSymbols(SPY)
x1 <- do.call(rbind, lapply(split(SPY, "months"), function(x) first(last(x,4))))

The second approach uses apply.monthly(), but that function always
returns an object with index values that correspond to the last
observation in the month.  So we have to manually update the index to
be 3 days prior.

x2 <- apply.monthly(SPY, function(x) first(last(x,4)))
index(x2) <- index(SPY)[endpoints(SPY, "months")[-1]-3]

> Thanks in advance,
>
> John B. Nicholas, Ph.D
> 650-315-9895
>

HTH,
--
Joshua Ulrich  |  FOSS Trading: www.fosstrading.com



More information about the R-help mailing list