I\'m trying to get a time series of returns for holding a certain asset for a specific time.
My dataframe looks like this:
Date Price
1998-01-01
I suggest switching to a time series class, like xts
or zoo
. But if you just want to get it done, and learn more later, you can do it pretty easily as a data frame. Note that I have to pad the return vectors with NA
s to make it line up correctly and that a hold
of 20 really buy on 1 and sells on 1 + 20:
> library(xts)
> set.seed(2001)
> n <- 50
> hold <- 20
> price <- rep(55, n)
> walk <- rnorm(n)
> for (i in 2:n) price[i] <- price[i-1] + walk[i]
> data <- data.frame(date=as.Date("2001-05-25") + seq(n), price=price)
> data <- transform(data, return=c(diff(log(price), lag=hold), rep(NA, hold)))
If you're ready for xts
or zoo
(this should work in either), then I suggest using rollapply
to get the forward look (assuming you want the forward looking return, which makes it a lot easier to form portfolios today and see how it works into the future):
> data.xts <- xts(data[, -1], data[, 1])
> f <- function(x) log(tail(x, 1)) - log(head(x, 1))
> data.xts$returns.xts <- rollapply(data.xts$price, FUN=f, width=hold+1, align="left", na.pad=T)
The two approaches are the same:
> head(data.xts, hold+2)
price return returns.xts
[1,] 55.00000 0.026746496 0.026746496
[2,] 54.22219 0.029114744 0.029114744
[3,] 53.19811 0.047663206 0.047663206
[4,] 53.50088 0.046470723 0.046470723
[5,] 53.85202 0.041843116 0.041843116
[6,] 54.75061 0.018464467 0.018464467
[7,] 55.52704 -0.001105607 -0.001105607
[8,] 56.15930 -0.024183803 -0.024183803
[9,] 56.61779 -0.010757559 -0.010757559
[10,] 55.51042 0.005494771 0.005494771
[11,] 55.17217 0.044864991 0.044864991
[12,] 56.07005 0.025411005 0.025411005
[13,] 55.47287 0.052408720 0.052408720
[14,] 56.10754 0.034089602 0.034089602
[15,] 56.35584 0.075726190 0.075726190
[16,] 56.40290 0.072824657 0.072824657
[17,] 56.05761 0.070589032 0.070589032
[18,] 55.93916 0.069936575 0.069936575
[19,] 56.50367 0.081570964 0.081570964
[20,] 56.12105 0.116041931 0.116041931
[21,] 56.49091 0.095520517 0.095520517
[22,] 55.82406 0.137245367 0.137245367