#===> Example using stockPortfolio <===# # four components # (1) quick intro # (2) detailed intro # (3) we pick stocks and try it out # (4) additional tools ######################### #===> ((((( 1 ))))) <===# #===> quick example <===# ######################### # load package library(stockPortfolio) # select stocks #IBM: International Business Machines Copr. #WFC: Wells Fargo & Compnay #JPM: JPMorgan Chase & Company #LUV: Southwest Airlines Co. #XOM: Exxon Mobil Corporation ticker <- c('IBM', 'WFC', 'JPM', 'LUV', 'XOM') # get stock data gr <- getReturns(ticker, start='2005-03-31', end='2010-03-31') # gr is a "list" object and we find what it contains # by typing the following: names(gr) # We can access each component of gr by typing: gr$R gr$ticker gr$period gr$start gr$end # obtain the variance-covariance matrix of the returns: cov(gr$R) # obtain the correlation matrix of the returns: cor(gr$R) # We can find summary statistics as follows: summary(gr$R) # To find the mean, variance, and standard deviation of a particular stock mean(gr$R[,4]) mean(gr$R[,5]) var(gr$R[,4]) var(gr$R[,5]) sd(gr$R[,4]) sd(gr$R[,5]) # To find the covariance and correlation between two stocks: cov(gr$R[,4], gr$R[,5]) cor(gr$R[,4], gr$R[,5]) # Let's work with two stocks: IBM and LUV. # Find the composition of the minimum risk portfolio: x_IBM <- (var(gr$R[,4]) - cov(gr$R[,1], gr$R[,4])) / (var(gr$R[,1]) + var(gr$R[,4]) - 2*cov(gr$R[,1], gr$R[,4])) x_LUV <- 1-x_IBM # Find the mean and sd of the minimum risk portfolio: mean_min <- x_IBM*mean(gr$R[,1]) + x_LUV*mean(gr$R[,4]) var_min <- x_IBM^2*var(gr$R[,1]) + x_LUV^2*var(gr$R[,4]) + 2*x_IBM*x_LUV*cov(gr$R[,1], gr$R[,4]) sd_min <- var_min^0.5 # Construct the portfolio possibilities curve and identify the efficient frontier: a <- seq(0,1,.01) b <- 1-a mean_p <- a*mean(gr$R[,1]) + b*mean(gr$R[,4]) var_p <- a^2*var(gr$R[,1]) + b^2*var(gr$R[,4]) + 2*a*b*cov(gr$R[,1], gr$R[,4]) sd_p <- var_p^0.5 plot(sd_p,mean_p, type="l", xlab="Portfolio standard deviation (risk)", ylab="Portfolio expected return") points(sd_min, mean_min, pch=19, col="green") # Identify the efficient frontier: xx <- cbind(sd_p,mean_p) xxx <- xx[which(xx[,2]>mean_min),] points(xxx, type="l", col="blue", lwd=3)