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?