代写 R 


MAT 4376F/5313F

R – Time series. Backtesting

GARCH models
• Load a package: library(tseries);
• 

• GARCH analysis of EU stock exchange. plot(EuStockMarkets) ;
• MyTS<-EuStockMarkets[,"DAX"]; • Data <- diff(log(EuStockMarkets))[,"DAX"]; • • 
par(mfrow=c(2,3)) • plot.ts(Data); • hist(Data); qqnorm(Data); # Data are not normal; • acf(Data); acf(Data^2); pacf(Data^2) • 
 • Fit ARCH(1) model: fit.ARCH1<-garch(Data,order=c(0,1)); • attributes(fit.ARCH1); • Coefficients<-fit.ARCH1$coef; • Coefficients; • alpha0=Coefficients[1]; • alpha1=Coefficients[2]; • 
 • Fitted values = "Past prediction of \sigma_t" past.prediction=fit.ARCH1$fitted.values; • past.prediction[1:10]; • # Compare with • sqrt(alpha0+alpha1*Data[1:9]^2); • n=length(Data); • sigmat=past.prediction[2:n]; • par(mfrow=c(1,1)); • plot.ts(sigmat^2); • 
 • Residuals residuals<-fit.ARCH1$residuals; • residuals[1:10]; • n=length(residuals); • residuals=residuals[2:n]; • #Compare with • Data[2:10]/past.prediction[2:10] • 
 Backtesting • We simulate data from exponential distribution. We apply parametric method to estimate value at risk. n=1000; • lambda=1; • p=0.05; • X=rexp(n,lambda); • hatlambda=1/mean(X); • parametric.VAR=-log(p)/hatlambda; • plot.ts(X); • VAR.estim=c(rep(parametric.VAR,n)); • lines(VAR.estim,type="l",col="blue"); • Violations=X[X>VAR.estim];
• Violation.rate=length(Violations)/n;
• 

• Backtesting for ARCH(1). p=0.05;
• predicted.VAR=abs(sigmat)*qnorm(1-p);
• par(mfrow=c(1,1))
• plot.ts(Data);
• lines(predicted.VAR,col=”blue”,type=”l”)
• n=length(Data);
• Data.new=Data[2:n];
• Violations=Data.new[Data.new>predicted.VAR];
• Violation.rate=length(Violations)/(n-1);
• 

• Let’s pretend that our data do not come from a time series. And let’s pretend that our data are normal. Wrong.estim=sd(Data)*qnorm(1-p);
• Wrong.estim.vec=c(rep(Wrong.estim,length(predicted.VAR)));
• lines(Wrong.estim.vec,type=”l”,col=”red”);
• Violations=Data.new[Data.new>Wrong.estim];
• Violation.rate=length(Violations)/(n-1);