Get startedGet started for free

Auto regressive model

1. Auto regressive model

This is not a modelling or a time series course, so don't be intimidated by the title of this last case study. We're just going to simulate data by writing loops. Something you should be familiar with by now.

2. Auto regressive model, AR

We want to simulate data from an auto regressive model, given the auto correlation parameters in the vector phi, and the characteristics of the distribution of the white noise epsilon. The equation naturally translates to iterative code, and would be somewhat difficult to express with idiomatic vectorized R code. This is one of these cases where using a loop is the right thing to do, but you don't want to do it with R code because you'd get bad performance.

3. AR in C++

The R function from the previous slide can easily be translated to C++ code. You first need to go through the first np values with a simple loop and set them to the result of a rnorm call. Once this is done, you can deal with the main part of the algorithm. You need an outer loop to scan through the result vector, and within each iteration of the outer loop, you need an inner loop to apply the coefficients of the model given by the phi vector. I've highlighted here the structure of the code, and you will fill the gaps in the exercises. As usual when you deal with C++ loops, be careful about indexing, and remember that the first value is at index 0.

4. Moving average simulation

In the same spirit, let's simulate data from a moving average process. This is pretty similar to AR, except that the current value is calculated as a combination of the previous values of the noise, instead of the values themselves.

5. Moving average simulation

The code only needs a few adjustments but is very similar. One important difference is that it needs to remember the previous values of the noise, so you cannot simply simulate them with calls to the scalar "rnorm" function. You will however, simulate all the noise at once into a vector ahead of the loop with the rnorm function from the Rcpp namespace.

6. ARMA(p,q) = AR(p) + MA(q)

Finally, you can combine AR and MA into an ARMA model where the current observation depends on previous values of the simulated process as well as the previous values of the noise.

7. Let's practice!

Go on! Write the C++ code to create an ARMA model.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.