程序代写 # get data for 4 stocks and the s&p 500

# get data for 4 stocks and the s&p 500
library(quantmod)
getSymbols(c(‘AAPL’, ‘XOM’, ‘MSFT’, ‘TGT’, ‘^GSPC’), from = ‘2017-01-01’, to = ‘2021-12-31’)
# keep only adjusted closing prices

Copyright By PowCoder代写 加微信 powcoder

AAPL <- Ad(AAPL); XOM <- Ad(XOM); MSFT <- Ad(MSFT); TGT <- Ad(TGT); GSPC <- Ad(GSPC) # calculate returns: ret <- merge(monthlyReturn(AAPL), monthlyReturn(XOM), monthlyReturn(MSFT), monthlyReturn(TGT), monthlyReturn(GSPC)) names(ret) <- c('AAPL', 'XOM', 'MSFT', 'TGT', 'Market') plot(ret[, c(1,5)], legend.loc = 'topleft') plot(ret[, c(2,5)], legend.loc = 'topleft') plot(ret[, c(3,5)], legend.loc = 'topleft') plot(ret[, c(4,5)], legend.loc = 'topleft') # covariance matrix # correlation matrix # using corrplot library(corrplot) corrplot.mixed(cor(ret), upper = 'ellipse') # Estimating beta and alpha betaHat.aapl <- cov(ret$AAPL, ret$Market) / var(ret$Market) alphaHat.aapl <- mean(ret$AAPL) - betaHat.aapl * mean(ret$Market) betaHat.xom <- cov(ret$XOM, ret$Market) / var(ret$Market) alphaHat.xom <- mean(ret$XOM) - betaHat.xom * mean(ret$Market) betaHat.msft <- cov(ret$MSFT, ret$Market) / var(ret$Market) alphaHat.msft <- mean(ret$MSFT) - betaHat.msft * mean(ret$Market) betaHat.tgt <- cov(ret$TGT, ret$Market) / var(ret$Market) alphaHat.tgt <- mean(ret$TGT) - betaHat.tgt * mean(ret$Market) # Portfolio analysis using AAPL & XOM mu.A <- 0.035; mu.X <- 0.0013; sigma.A <- 0.085; sigma.X <- 0.085; rho.AX <- -0.9999 # Portfolio with 50-50 investment in each x.A <- seq(from = -0.5, to = 1.5, by = 0.001) x.X <- 1 - x.A mu.p <- x.A * mu.A + x.X * mu.X sigma.p <- sqrt(x.A^2*sigma.A^2 + x.X^2*sigma.X^2 + 2*x.A*x.X*sigma.A*sigma.X*rho.AX) # cbind(mu.p, sigma.p) plot(sigma.p, mu.p, type = 'l') # using formula for min variance portfolio x.A.min <- (sigma.X^2-sigma.A*sigma.X*rho.AX) / (sigma.A^2 + sigma.X^2 - 2*sigma.A*sigma.X*rho.AX) x.X.min <- 1 - x.A.min # c(x.A.min, x.X.min) # min standard deviation of potfolio sigma.p.min <- sqrt(x.A.min^2*sigma.A^2 + x.X.min^2*sigma.X^2 + 2*x.A.min*x.X.min*sigma.A*sigma.X*rho.AX) sigma.p.min 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com