Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ihabo01/409afd938767768a3be6 to your computer and use it in GitHub Desktop.
Save ihabo01/409afd938767768a3be6 to your computer and use it in GitHub Desktop.
#Required libraries
library("stockPortfolio")
library("rugarch")
#clean memory
rm(list = ls())
#get the MSFT datafrom Yahoo!Finance
ticker = c("MSFT")
fullstocks = getReturns(ticker, "day", start="2008-01-01")
stocks = fullstocks[[6]][[1]][[7]]
returns = diff(stocks)/stocks[-length(stocks)]
#calculate the number of ticks
n = length(returns)
#fit to ARMA(1,1) + GARCH(2,2)
gspec.ru = ugarchspec(mean.model=list(armaOrder=c(1,1)), variance.model=list(garchOrder=(c(2,2))), distribution="std")
gfit.ru = ugarchfit(gspec.ru, returns)
#calculate Sigma2 of the returns using GARCH
set.seed(2)
epsilon = rep(0,n)
eta = rnorm(n)
garchSigma2 = rep(0, n)
c = coef(gfit.ru)
for (t in 3:n){
garchSigma2[t] = c[4] + c[5] * epsilon[t-1]^2 + c[6] * epsilon[t-2]^2 + c[7] * garchSigma2[t-1] + c[8] * garchSigma2[t-2]
epsilon[t] = eta[t] * sqrt(garchSigma2[t])
}
#calculate the return using ARMA
garchReturn = rep(0, n)
for (t in 3:n){
garchReturn[t]= c[1] + c[2] * garchReturn[t-1] + epsilon[t-1] + c[3] * epsilon[t-2]
}
# calculate the stock price from the return generated using a random Shock
garchPrice = rep(0, n+1)
X0 = stocks[1] #X0 is the value on the first day
garchPrice[1] = X0;
for(t in 2:(n+1)){
garchPrice[t] = garchPrice[t-1] * exp(garchReturn[t - 1])
}
# calculate the stock price from the return generated from the fitted model
garchFittedPrice = rep(0, n+1)
garchFittedPrice[1] = X0;
for(t in 2:(n+1)){
garchFittedPrice[t] = garchFittedPrice[t-1] * exp(fitted(gfit.ru)[t-1])
}
#plot all diagrams
matrix = matrix(nrow=n+1,ncol=3);
matrix[,1] = garchFittedPrice
matrix[,2] = garchPrice
matrix[,3] = stocks
colnames(matrix)= c("Garch Fitted", "Garch Random Shock", "Real Price")
ts.plot(matrix,gpars= list(col=rainbow(3)))
legend(20,10,colnames(matrix),col=rainbow(3), lty=c(1,1,1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment