Hello All,
Below are the steps I took to generate a var model. I used Apple and Microsoft.
Best, Jordan
library(quantmod)
library(vars)
library(forecast)
library(fpp)
# Create Empty Structure
stock.data <- new.env()
# Start and End Dates
s.date <- as.Date("2013-04-25")
e.date <- as.Date("2018-04-25")
# Tickers
tickers <- c("AAPL","MSFT")
# Get Data
getSymbols(tickers, env = stock.data, from = s.date, to = e.date)
## [1] "AAPL" "MSFT"
# Get Monthly Adjusted
stock.data.adj <- do.call(merge, eapply(stock.data, Ad))
stock.data.adj.month <- stock.data.adj[endpoints(stock.data.adj, 'months')]
# Transform Data
stock.data.adj.month$AAPL.Adjusted <- custom.log(stock.data.adj.month$AAPL.Adjusted)
stock.data.adj.month$MSFT.Adjusted <- custom.log(stock.data.adj.month$MSFT.Adjusted)
plot(stock.data.adj.month)
# Select Parameters
param <- VARselect(stock.data.adj.month, lag.max=8, type="const")
param$selection
## AIC(n) HQ(n) SC(n) FPE(n)
## 1 1 1 1
# Make sure matrix is a time series matrix
stock.data.adj.month <- as.ts(stock.data.adj.month)
# Create Models
var.1 <- VAR(stock.data.adj.month, p=1, type="const")
serial.test(var.1, lags.pt=10, type="PT.asymptotic")
##
## Portmanteau Test (asymptotic)
##
## data: Residuals of VAR object var.1
## Chi-squared = 29.354, df = 36, p-value = 0.7756
var.2 <- VAR(stock.data.adj.month, p=2, type="const")
serial.test(var.2, lags.pt=10, type="PT.asymptotic")
##
## Portmanteau Test (asymptotic)
##
## data: Residuals of VAR object var.2
## Chi-squared = 26.532, df = 32, p-value = 0.7396
# Forecast
fcst1 <- forecast(var.1)
fcst2 <- forecast(var.2)
plot(fcst1)
plot(fcst2)