# How to generate simulated stock price from historical data using R?

I have created a strategy specifically for a particular stock which I backtested with its historical data. Now I want to forward test it with simulated stock price generated using Monte Carlo. I have used this websites formula for generating simulated return.

$$\operatorname{Return} = \mu\Delta t + \sigma r\sqrt{Δt}$$

This is my code

library(quantmod)
set.seed(100)
aapl=getSymbols("AAPL",from="2014-01-01",auto.assign=F)
N=1000 #number of iterations
ret=ROC(Cl(aapl))
plot(ret)
t=1
mu=mean(na.omit(ret))
sigma=sd(na.omit(ret))
new_ret=NULL

for( i in 1:N){
phi=runif(1, min=0, max=1)
new_ret[i]=mu*t+sigma*phi*sqrt(t)
}
plot(new_ret)


The simulated return(new_ret) looks some what odd and not proper? How to generate simulated data using historical data of a stock price?

Return is calculated using ROC() function which in turn uses diff(log()) function. How can I generate price from simulated return vales?

## 1 Answer

This approach is rather crude. It only takes the mean and volatility of the historical returns and assumes a very simple model. I'm not sure if you have much experience with Time Series, but your returns series is a Time series.

You can now perform tests on these log returns to ensure you can continue with Time series models. One very simple model is ARMA. You can extend it to ARCH-GARCH. R has these function built in and it also has features which will simulate future values using the model it builds.

Check out he arima() function, or uGARCH. Sorry if you have not come across this yet. It is a fairly simple model but very good in my experience for returns. Id expect it to be better than your model above. It is a common approach in modelling financial time series.

Hope this is useful.

For your final question. Your code looks fine, although inefficient if you are simulating a lot of data. To forecast prices, you have some return $r$. IF you take today's stock price $S_0$, then tomorrows price will be $S_0(1+r)$ if you use normal returns. Similar formulae hold if you use log prices as I mentioned before. IF your using standard returns, then predicting $n$ days ahead requires $$S_0(1+r_1)(1+r_2)\cdots(1+r_n).$$ This can be applied in a crude for loop or more elegant methods in R.