Assignment 4
Background
Here is a function that generates data from an AR(1) model starting with the first value set to 0
< function(n = 100, c = 0, phi, sigma = 1) {
generate_ar1 # Generate errors
< rnorm(n, mean = 0, sd = sigma)
error # Set up vector for the response with initial values set to 0
< rep(0, n)
y # Generate remaining observations
for(i in seq(2, length.out = n1)) {
< c + phi * y[i1] + error[i]
y[i]
}return(y)
}
Here n
is the number of observations to simulate, c
is the constant, phi
is the AR coefficient, and sigma
is the standard deviation of the noise. The following example shows the function being used to generate 50 observations
library(fpp3)
tsibble(time = 1:50, y = generate_ar1(n=50, c=1, phi=0.8), index = time) >
autoplot(y)
Instructions

Modify the
generate_ar1
function to generate data from an ARIMA(p,0,q) model with parameters to be specified by the user. The first line of your function definition should be< function(n = 100, c = 0, phi = NULL, theta = NULL, sigma = 1) generate_arma
Here
phi
andtheta
are vectors of AR and MA coefficients. Your function should return a numeric vector of lengthn
.For example
generate_arma(n = 50, c = 2, phi = 0.4, theta = c(0.3, 0.6))
should return 50 observations generated from the ARIMA(1,0,2) model y_t = 2 + 0.4 y_{t1} + 0.3\varepsilon_{t1}  0.6\varepsilon_{t2} + \varepsilon_t where \varepsilon \sim N(0,1). 
The noise should be generated using the
rnorm()
function. 
Your function should check stationarity and invertibility conditions and return an error if either condition is not satisfied. You can use the
stop()
function to generate an error. The model will be stationary if the following expression returnsTRUE
:!any(abs(polyroot(c(1,phi))) <= 1)
The MA parameters will be invertible if the following expression returns
TRUE
:!any(abs(polyroot(c(1,theta))) <= 1)

The above function sets the first value of every series to 0. Your function should fix this problem by generating more observations than required and then discarding the first few observations. You will need to consider how many observations to discard, to prevent the returned series from being affected by the initial values.
Please submit your solution as a .R file.
Due: 5 May 2024
Submit