1
votes

I'm trying to do a variant of the following: Calculate the percent change per time period of a time series and then apply those percent changes to a separate time series.

It's like applying AAPL's daily price changes to the current price of some given stock and showing what that would look like.

I have a time series with the appropriate percent changes:

            index        change price
2007-07-01 136.47            NA 136.3
2007-08-01 136.44 -0.0002198285   0.0
2007-09-01 135.55 -0.0065230138   0.0
2007-10-01 133.86 -0.0124677241   0.0
2007-11-01 131.34 -0.0188256387   0.0
2007-12-01 129.61 -0.0131719202   0.0

And I can calculate each future price value using mapply and lag:

ts$price[-1,] <- mapply(function(x, y) x + (x*y), lag(ts$price, 1)[-1,], ts$change[-1,])

However it only calculates one row at a time, it won't work recursively. I've looked into rollapply and I get the same problem: Only one record at a time gets updated:

ts[-1,]$price <- rollapply(as.zoo(ts), 2,
   function(x) x[1, "price"] + (x[2, "change"] * x[1, "price"]), by.column = F)

The calculations are correct and I could get it to work with a loop but I'd like to understand what I'm doing wrong. There's gotta be a way to get this to work recursively.

Or maybe I've made this far more difficult than it needs to be?

1

1 Answers

1
votes

Here is a solution I hope it helps.

The following few lines are just the data

data<-matrix(data=c(2007-07-01, 136.47,NA, 136.3,2007-08-01, 136.44, -0.0002198285,0.0,2007-09-01, 135.55,-0.0065230138,0.0,2007-10-01, 133.86,-0.0124677241,0.0,2007-11-01,131.34,-0.0188256387,0.0,2007-12-01,129.61, -0.0131719202,0.0), nrow=6, ncol=4,byrow=TRUE)
data<-data[,-1]
ts<-ts(ts,frequency=12,start=c(2007,7))
colnames(ts)<-c("index", "change", "price")

You can apply this to get the desired output:

for(i in 2:nrow(ts)){
  ts[i,3]<-ts[1,3]*(1+ts[i,2])
}

The output looks like:

> ts
          index        change    price
Jul 2007 136.47            NA 136.3000
Aug 2007 136.44 -0.0002198285 136.2700
Sep 2007 135.55 -0.0065230138 135.4109
Oct 2007 133.86 -0.0124677241 134.6006
Nov 2007 131.34 -0.0188256387 133.7341
Dec 2007 129.61 -0.0131719202 134.5047