Search This Blog

Monday, 22 June 2020

How to recreate the matrix of prices from the matrix of returns in R

It is very easy, in R, to obtain a matrix of returns starting from a matrix of prices. The opposite procedure, however, is slightly more complicated. Let's say you have a matrix of returns that starts at time t, and a vector of the prices at time t-1. How can you obtain the full matrix of prices that has been used to generate the matrix of returns? I'm going to illustrate you how to do it.

Let us start by generating some prices (5 periods for 3 assets), in order to put together a working example. We also store in a separate object the prices in the first period.

prices <- abs(matrix(rnorm(15,mean=0,sd=1),5,3))
prices_1 <- prices[1,]

We then compute the simple and log returns. 

simple_returns <- diff(as.matrix(prices))/prices[-nrow(prices),]
log_returns <- diff(log(prices))

Now, imagine you were only given the vector of prices at the first period and the matrix of simple or log returns, and you want the matrix of prices. If you were given simple returns, you can do it with this code:

prices_new1 <- rbind(prices_1,simple_returns)
for(i in 2:(nrow(simple_returns)+1)){
  prices_new1[i,] <- prices_new1[i-1,]+prices_new1[i-1,]*prices_new1[i,]
}
row.names(prices_new1) <- 1:nrow(prices_new1)


With log returns, the code is as follows:

prices_new2 <- rbind(prices_1,exp(log_returns))
for(i in 2:(nrow(log_returns)+1)){
  prices_new2[i,] <- prices_new2[i-1,]*prices_new2[i,]
}
row.names(prices_new2) <- 1:nrow(prices_new2)


As you can easily check, the objects prices, prices_new1 and prices_new2 contain exactly the same values.

No comments:

Post a Comment