## Stock PC analysis ## AHW3 ## Decmeber 4, 2007 rm(list = ls()) ## read in data stock <- read.table("stock.txt", header=T) n <- nrow(stock) p <- ncol(stock) ## plot the data par(mfrow=c(5,1)) for(i in 1:p){ plot(stock[,i], type="l", lwd=2, ylab=names(stock)[i], xlab="return", col=i, cex.lab=1.5) } par(mfrow=c(1,1)) plot(stock[,1], type="l", lwd=2, ylab="Stocks", col=1, cex.lab=1.5) for(i in 2:p){ lines(stock[,i], type="l", lwd=2, col=i) } par(mfrow=c(1,1)) pairs(stock) ## get sample mean, cov, cor stock.m <- round(apply(stock, 2, mean),4) stock.m stock.S <- round(cov(stock),5) stock.S stock.R <- round(cor(stock),3) stock.R ## get the principle components using the correlation matrix pc <- eigen(stock.S) pc ## proportion of variance explained by each component pc$values/sum(pc$values) ## added proportion of variance explained by each component cumsum(pc$values)/sum(pc$values) ## look at the scree plot plot(1:5, pc$values, type="l", main="Scree Plot") points(1:5, pc$values, col="blue", pch=16) ## from the plot 3 components seem sufficient ## get the principle components using the correlation matrix pc <- eigen(stock.R) pc ## proportion of variance explained by each component pc$values/sum(pc$values) ## added proportion of variance explained by each component cumsum(pc$values)/sum(pc$values) ## look at the scree plot plot(1:5, pc$values, type="l", main="Scree Plot") points(1:5, pc$values, col="blue", pch=16) ## from the plot 3 components seem sufficient