Pat
Pat

Reputation: 1339

Aggregating returns in xts object from mondays to fridays

I have a vector of discrete returns.

require(xts)

set.seed(1)
x <- xts(rep(0.01,20), Sys.Date()-20:1)
colnames(x) = c("return")

> x
           return
2015-01-30   0.01
2015-01-31   0.01
2015-02-01   0.01
2015-02-02   0.01
2015-02-03   0.01
2015-02-04   0.01
2015-02-05   0.01
2015-02-06   0.01
2015-02-07   0.01
2015-02-08   0.01
2015-02-09   0.01
2015-02-10   0.01
2015-02-11   0.01
2015-02-12   0.01
2015-02-13   0.01

I need to aggegate the daily returns to weekly returns (monday to friday). The calculation should start on monday with cumprod(1+x)-1 to friday. Each week the calculation starts from zero. I know how to to this with the endpoints function when I have a vector of prices. Unfortunately I only have returns. My new vector should look like this

> x
               return
2015-02-01 0.03030100
2015-02-08 0.07213535
2015-02-13 0.05101005

Thanks for your help.

Upvotes: 2

Views: 323

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176648

You don't want cumprod if you want to aggregate. cumprod will return an observation for every observation in the object passed to it. You want prod instead.

Since you're defining weeks as Monday-Friday, you can do this easily with apply.weekly:

x <- xts(rep(0.01,15), as.Date("2015-02-14")-15:1)
colnames(x) <- "return"
apply.weekly(1+x, prod)-1
#                return
# 2015-02-01 0.03030100
# 2015-02-08 0.07213535
# 2015-02-13 0.05101005

If you're using some other week definition (e.g. Wednesday-Wednesday), then you would need to use period.apply with endpoints.

Upvotes: 3

Related Questions