I'm playing with R and xts to create a theoretical scenario where 10k was invested into a stock, and see how it would have grown. I can do everything up to calculating stock returns, but I don't know how to add a new column to an xts that would take the 10k and estimate growth over time.
Put simply, how do I have xts make a new column where x (10K) is the starting value, and every point after is the previous month's x*returns?
My code so far:
quantmod::getSymbols("^GSPC", src="yahoo")
GSPC.Returns <- quantmod::periodReturn(GSPC)
GSPC.Returns <- GSPC.Returns*100+100
y <- GSPC.Returns["2019/"]
x <- 10000
y$blargh <- x*y[,"monthly.returns"] # This is the problematic line
It appears you are looking for the cumulative product up to a point. I think you might find the cumprod
function helpful. Does this return the intended result?
GSPC.Returns <- quantmod::periodReturn(GSPC)
GSPC.Returns <- GSPC.Returns*100+100
y <- GSPC.Returns["2019/"]
x <- 10000
y$blargh <- ave(y / 100, FUN = cumprod) * x
> y
monthly.returns blargh
2019-01-31 107.86844 10786.84
2019-02-28 102.97289 11107.52
2019-03-29 101.79243 11306.62
2019-04-30 103.93135 11751.12
...