# R - Moving average; MA(2), Maximum-Likelihood estimation through optim routine

I am trying to complete my assignment for time-series where I have to use Nile data to fit MA(2) model and estimate theta coefficients through creation of new function and optimizing it to get appropriate values which I later compare to build-in arima function. I have written a code to create log-likelihood function which returns me a sum of arguments, however I am not sure how to recognize error terms in the model. I have tried to use error term as random white noise coming from rnorm function but I am certain it is not the way it should be done.

I am almost completely new to R and don't know the optim function too much.

data(Nile)
y <- Nile/1000
T <- length(Nile)

#MA(2) Model

loglik.normal <- function(theta) {
alpha1 <- theta
alpha2 <- theta
alpha3 <- theta
sigma <- theta

for(t in 3:T) {
ma <- (0.5*T*log(2*pi*sigma)+0.5*(y[t]-alpha1-alpha2*e[t-1]-alpha3*e[t-2])^2/sigma)
}
return(sum(ma))
}

theta0 <- c(0.0, 0.0, 0.0, 0.0)

ma22 <- optim(theta0, fn=loglik.normal, hessian=TRUE)\$par


As I know optim calculates the minimum, thus I multiplied the log-likelihood function by -1. If there is anyone who knows how to fit such models to data I would be very grateful for any comments which will help me understand it better.

• after you get your parameters, you can fit the model, and your error terms will be original-predicted and then you can test the data for normality, 0 mean, 1 variance etc – V. Aslanyan Apr 8 at 17:09