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
The following function should do it:
getReturn <- function(data, n=20) {
#Assumes 'data' is a two-column data frame with date in the first column, price in the second
num.rows <- nrow(data)
output.range <- 1:(num.rows-20)
buy.price <- data[output.range,2]
sell.price <- data[output.range+20,2]
returns <- data.frame(log(sell.price) - log(buy.price))
returns <- cbind(data[output.range,],returns)
names(returns) <- c("Date","Price","Return")
return(returns)
}
Sample input and output:
> head(data)
Date Price
1 2001-01-01 20
2 2001-01-02 19
3 2001-01-03 19
4 2001-01-04 18
5 2001-01-05 18
6 2001-01-06 18
> return<-getReturn(data)
> head(return)
Date Price Return
1 2001-01-01 20 0.09531018
2 2001-01-02 19 0.14660347
3 2001-01-03 19 0.14660347
4 2001-01-04 18 0.20067070
5 2001-01-05 18 0.24512246
6 2001-01-06 18 0.20067070