Sunday, 28 April 2013

How to simulate a Random Walk in R

I've put together this R script to demonstrate how to simulate a random walk in R. Actually, the script shows how to do a lot more than simulate a random walk. To give an overview of the content of the R script, I wrote code to simulate the following processes:
  • Gaussian white noise
  • Random walk
  • AR(1) with positive phi
  • AR(1) with negative phi
  • AR(2) with two positive phi's
  • MA(1) with positive theta
  • MA(1) with negative theta
  • MA(2) with two positive theta's
  • ARMA(1,1) with positive phi and positive theta
I suggest that you edit the script and play around with the values and signs on the coefficients. For example, try to find out what happens when some of the models do not satisfy the stationarity conditions. What would the autocorrelation function look like in that case?

Keep in mind that the pure MA processes are always stationary even if the coefficients on theta are greater than one in absolute value. Despite the fact that pure MA processes are always stationary because they contain no AR terms, they may, however, not be invertible.

In case you need some quick revision... the conditions for stationarity and invertibility are...

As I already said, tinker around with the coefficients and don't forget to inspect the autocorrelation functions and partial autocorrelation functions to see how each process behaves.

Note that there is a function from the stats package for simulating ARIMA models. The function is called arima.sim(). I did not use this function in the script that I compiled for this blog post. The reason being I wanted to write code that would make sense to those who have not used R previously and to those who understand the theory behind the models, but who are perhaps new to programming languages.

No comments:

Post a Comment