13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

140

> amzn = diff(log(Cl(AMZN)))

As in the previous chapter we are now going to loop through the combinations of p, d and

q, to find the optimal ARIMA(p,d,q) model. By "optimal" we mean the order combination that

minimises the Akaike Information Criterion (AIC):

> azfinal.aic <- Inf

> azfinal.order <- c(0,0,0)

> for (p in 1:4) for (d in 0:1) for (q in 1:4) {

> azcurrent.aic <- AIC(arima(amzn, order=c(p, d, q)))

> if (azcurrent.aic < azfinal.aic) {

> azfinal.aic <- azcurrent.aic

> azfinal.order <- c(p, d, q)

> azfinal.arima <- arima(amzn, order=azfinal.order)

> }

> }

We can see that an order of p = 4, d = 0, q = 4 was selected. Notably d = 0, as we have

already taken first order differences above:

> azfinal.order

[1] 4 0 4

If we plot the correlogram of the residuals we can see if we have evidence for a discrete white

noise series, see Figure 11.3.

> acf(resid(azfinal.arima), na.action=na.omit)

There are two significant peaks, namely at k = 15 and k = 21, although we should expect

to see statistically significant peaks simply due to sampling variation 5% of the time. Let us

perform a Ljung-Box test and see if we have evidence for a good fit:

> Box.test(resid(azfinal.arima), lag=20, type="Ljung-Box")

Box-Ljung test

data: resid(azfinal.arima)

X-squared = 12.6337, df = 20, p-value = 0.8925

As we can see the p-value is greater than 0.05 and so we have evidence for a good fit at the

95% level.

We can now use the forecast command from the forecast library in order to predict 25 days

ahead for the returns series of Amazon, which is provided in Figure 11.4.

> plot(forecast(azfinal.arima, h=25))

We can see the point forecasts for the next 25 days with 95% (dark blue) and 99% (light

blue) error bands. We will be using these forecasts in our first time series trading strategy when

we come to combine ARIMA and GARCH later in the book.

Let us carry out the same procedure for the S&P500. Firstly we obtain the data from

quantmod and convert it to a daily log returns stream:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!