##### Slidedeck e3: Hypothesis Testing Variances in R ##### source("http://rfs.kvasaheim.com/stat200.R") ito1 = "#E1EBEE" ito2 = "#00AAE4" ito = c(ito1,ito2) # Create the Data set.seed(370) ### ### ### ### ### ### ### ### ### # # Variance Theory # # graphic 1 par(bg="transparent") par(yaxs="i", xpd=NA, yaxt="n") par(family="serif",las=1) par(mar=c(3.5,0,0,0.5)) par(font.lab=2,cex.lab=1.1) plot.new() plot.window( xlim=c(-0.5,45), ylim=c(0,0.063)) axis(1, at=seq(0,80,5)) title(xlab="Test Statistic Value", line=2.25) nu=24 xx = seq(0,200, length=1e4) yy = dchisq(xx, df=nu) polygon( x=c( xx,rev(xx)), y=c(yy, rep(0,length(yy))), col=ito[1]) bnd = qchisq(0.025, df=nu) xx = seq(0,bnd, length=1e4) yy = dchisq(xx, df=nu) polygon( x=c( xx,rev(xx)), y=c(yy, rep(0,length(yy))), col=ito[2] ) mtext(side=1, at=bnd, text="lb") bnd = qchisq(0.975, df=nu) xx = seq(bnd,200, length=1e4) yy = dchisq(xx, df=nu) polygon( x=c( xx,rev(xx)), y=c(yy, rep(0,length(yy))), col=ito[2] ) mtext(side=1, at=bnd, text="ub") # graphic par(bg="transparent") par(yaxs="i", xpd=NA, yaxt="n") par(family="serif",las=1) par(mar=c(3.5,0,0,0.5)) par(font.lab=2,cex.lab=1.1) plot.new() plot.window( xlim=c(-0.5,45), ylim=c(0,0.063)) axis(1, at=seq(0,80,5)) title(xlab="Test Statistic Value", line=2.25) nu=24 xx = seq(0,200, length=1e4) yy = dchisq(xx, df=nu) polygon( x=c( xx,rev(xx)), y=c(yy, rep(0,length(yy))), col=ito[1]) bnd = qchisq(0.04, df=nu) xx = seq(0,bnd, length=1e4) yy = dchisq(xx, df=nu) polygon( x=c( xx,rev(xx)), y=c(yy, rep(0,length(yy))), col=ito[2] ) mtext(side=1, at=bnd, text="X2") ### ### ### ### ### ### ### ### ### # # Volatility # #install.packages("quantmod") library(quantmod) ### Example 1 # IBM getSymbols("IBM",src="yahoo") getSymbols("MSFT",src="yahoo") getSymbols("AAPL",src="yahoo") getSymbols("AMZN",src="yahoo") summary(IBM) IBMvals = as.numeric(IBM$IBM.Close) AAPLvals = as.numeric(AAPL$AAPL.Close) MSFTvals = as.numeric(MSFT$MSFT.Close) # graphic par(cex=1.2) chartSeries(IBM) shapiroTest(IBMvals) length(IBMvals) # The Chi-square test onevar.test(IBMvals, s2=750) # The Bootstrap ts = numeric() for(i in 1:1000) { xx = sample(IBMvals, replace=TRUE) ts[i] = var(xx) } quantile(ts, c(0.025,0.975)) hist(ts) ### Example 2 # Apple and Microsoft chartSeries(AAPL) chartSeries(MSFT) # Volatility shapiro.test(MSFTvals) shapiro.test(AAPLvals) # The F-test var.test(MSFTvals, AAPLvals) # The Bootstrap ts = numeric() for(i in 1:1000) { xx = sample(MSFTvals, replace=TRUE) yy = sample(AAPLvals, replace=TRUE) ts[i] = var(xx) / var(yy) } quantile(ts, c(0.025,0.975)) hist(ts) ### End of File