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

[This article was first published on Investing Blueprints, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

To leave a comment for the author, please follow the link and comment on their blog: Investing Blueprints. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)