sp500 <- GetSP500Stocks()

sp500tickers <- sp500[,c(1,2,4)]


#We select 5 Leading Tech Hardware Stocks and download the price data for those

stocks1 <- c("amc.ax","cba.ax","col.ax","csl.ax","gmg.ax","ltr.ax","wbc.ax","wes.ax")
prices1 <- getSymbols(stocks1[1], source="yahoo", auto.assign=FALSE,
                      return.class="xts")[,6]
for (i in 2:length(stocks1)){
  prices.tmp <- getSymbols(stocks1[i], source="yahoo", auto.assign=FALSE,
                           return.class="xts")[,6]
  prices1 <- cbind(prices1, prices.tmp)
}
## Warning: ltr.ax contains missing values. Some functions will not work if objects
## contain missing values in the middle of the series. Consider using na.omit(),
## na.approx(), na.fill(), etc to remove or replace them.
colnames(prices1) <- c("amc.ax","cba.ax","col.ax","csl.ax","gmg.ax","ltr.ax","wbc.ax","wes.ax")

plot(prices1$amc.ax)

plot(prices1$cba.ax)

plot(prices1$col.ax)

plot(prices1$csl.ax)

plot(prices1$gmg.ax)

plot(prices1$ltr.ax)

plot(prices1$wbc.ax)

plot(prices1$wes.ax)

#Since we will be working with returns, let us convert the price data to returns 

Portfolio1 <- na.omit(diff(log(prices1)))

#Trimming the Data to get recent data post 12-31-2014
Portfolio1 <- Portfolio1["2015/"]

mean(Portfolio1$amc.ax)
## [1] 0.0005013187
var(Portfolio1$amc.ax)
##             amc.ax
## amc.ax 0.000187823
mean(Portfolio1$cba.ax)|
  var(Portfolio1$cba.ax)
##        cba.ax
## cba.ax   TRUE
mean(Portfolio1$col.ax)|
  var(Portfolio1$col.ax)
##        col.ax
## col.ax   TRUE
mean(Portfolio1$csl.ax)|
  var(Portfolio1$csl.ax)
##        csl.ax
## csl.ax   TRUE
mean(Portfolio1$gmg.ax)|
  var(Portfolio1$gmg.ax)
##        gmg.ax
## gmg.ax   TRUE
mean(Portfolio1$ltr.ax)|
  var(Portfolio1$ltr.ax)
##        ltr.ax
## ltr.ax   TRUE
mean(Portfolio1$cba.ax)|
  var(Portfolio1$cba.ax)
##        cba.ax
## cba.ax   TRUE
mean(Portfolio1$wbc.ax)|
  var(Portfolio1$wbc.ax)
##        wbc.ax
## wbc.ax   TRUE
mean(Portfolio1$wes.ax)|
  var(Portfolio1$wes.ax)
##        wes.ax
## wes.ax   TRUE
means <- c(mean(Portfolio1$amc.ax),mean(Portfolio1$cba.ax),mean(Portfolio1$col.ax),mean(Portfolio1$csl.ax),mean(Portfolio1$gmg.ax),mean(Portfolio1$ltr.ax),mean(Portfolio1$cba.ax),mean(Portfolio1$wbc.ax),mean(Portfolio1$wes.ax))
vars <- c(var(Portfolio1$amc.ax),var(Portfolio1$cba.ax),var(Portfolio1$col.ax),var(Portfolio1$csl.ax),var(Portfolio1$gmg.ax),var(Portfolio1$ltr.ax),var(Portfolio1$cba.ax),var(Portfolio1$wbc.ax),var(Portfolio1$wes.ax))

Stockplot <- as.data.frame(t(cbind(vars, means)))
colnames(Stockplot)<- c("amc.ax", "cba.ax", "col.ax", "csl.ax", "gmg.ax", "ltr.ax", "cba.ax", "wbc.ax", "wes.ax")
Stockplot <- t(Stockplot)

plot(Stockplot, col = rainbow(5), pch= 15, xlab = "Variance", ylab = "Mean Returns", main = "Risk vs Return")
legend("bottomright", legend=c("amc.ax", "cba.ax", "col.ax", "csl.ax", "gmg.ax", "ltr.ax", "cba.ax", "wbc.ax", "wes.ax"),
       col=rainbow(5), lty=1:2, cex=0.8, pch = 15)

#Convert the numeric vectors to timeseries vectors

Portfolio1 <- as.timeSeries(Portfolio1)

#Let us build portfolio using each of the stock combinations to obtain the minimum variance portfolio in each of the cases


#Set Specs

Spec = portfolioSpec()
setNFrontierPoints(Spec)<-100
#Portfolio 1 - Tech Stocks

##Determine the efficient frontier and plot the same
effFrontier1 <- portfolioFrontier(Portfolio1, Spec ,constraints = "LongOnly")
effFrontier1
## 
## Title:
##  MV Portfolio Frontier 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       LongOnly 
##  Portfolio Points:  5 of 99 
## 
## Portfolio Weights:
##    amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax
## 1  0.0000 0.0000 0.0712 0.0000 0.0000 0.0000 0.9288 0.0000
## 25 0.3929 0.0000 0.3080 0.0708 0.0702 0.1238 0.0000 0.0343
## 50 0.2360 0.0000 0.2225 0.0566 0.0662 0.4188 0.0000 0.0000
## 74 0.0784 0.0000 0.1287 0.0333 0.0575 0.7021 0.0000 0.0000
## 99 0.0000 0.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000
## 
## Covariance Risk Budgets:
##    amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax
## 1  0.0000 0.0000 0.0193 0.0000 0.0000 0.0000 0.9807 0.0000
## 25 0.2785 0.0000 0.2182 0.0528 0.0581 0.3677 0.0000 0.0247
## 50 0.0322 0.0000 0.0302 0.0096 0.0161 0.9119 0.0000 0.0000
## 74 0.0031 0.0000 0.0051 0.0021 0.0064 0.9832 0.0000 0.0000
## 99 0.0000 0.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000
## 
## Target Returns and Risks:
##       mean     Cov    CVaR     VaR
## 1  -0.0001  0.0174  0.0433  0.0230
## 25  0.0010  0.0123  0.0287  0.0190
## 50  0.0021  0.0250  0.0494  0.0359
## 74  0.0031  0.0400  0.0767  0.0560
## 99  0.0042  0.0562  0.1071  0.0774
## 
## Description:
##  Mon Jul 11 15:31:11 2022 by user:
plot(effFrontier1, c(1))

##Plot the weights for all the portfolio in the efficient frontier
frontierWeights1 <- getWeights(effFrontier1)
barplot(t(frontierWeights1), main="Frontier Weights", col=cm.colors(ncol(frontierWeights1)+2), legend=colnames(frontierWeights1))

##Obtain the weights for each stock for the portfolio with the least variance
mvp1 <- minvariancePortfolio(Portfolio1, spec=portfolioSpec(),constraints="LongOnly")
mvp1
## 
## Title:
##  MV Minimum Variance Portfolio 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       LongOnly 
## 
## Portfolio Weights:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.4113 0.0000 0.3154 0.0586 0.0479 0.0135 0.0805 0.0727 
## 
## Covariance Risk Budgets:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.4113 0.0000 0.3154 0.0586 0.0479 0.0135 0.0805 0.0727 
## 
## Target Returns and Risks:
##   mean    Cov   CVaR    VaR 
## 0.0005 0.0106 0.0261 0.0156 
## 
## Description:
##  Mon Jul 11 15:31:11 2022 by user:
##Obtain the weights for each stock for the tangency portfolio
tanPort1 <- tangencyPortfolio(Portfolio1, spec=portfolioSpec(), constraints="LongOnly")
tanPort1
## 
## Title:
##  MV Tangency Portfolio 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       LongOnly 
## 
## Portfolio Weights:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.3335 0.0000 0.2806 0.0710 0.0716 0.2433 0.0000 0.0000 
## 
## Covariance Risk Budgets:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.1185 0.0000 0.0996 0.0282 0.0353 0.7185 0.0000 0.0000 
## 
## Target Returns and Risks:
##   mean    Cov   CVaR    VaR 
## 0.0014 0.0166 0.0359 0.0252 
## 
## Description:
##  Mon Jul 11 15:31:11 2022 by user:
#Let us tabulate the weights for the two portfolios for comparison
minvarweights1 <- getWeights(mvp1) 
tanportweights1 <- getWeights(tanPort1)
weights1 <- (cbind(minvarweights1, tanportweights1))
colnames(weights1) <- c("Minimum Variance Portfolio", "Tangency Portfolio")

Portfolio1 <- as.timeSeries(Portfolio1)
plot(Portfolio1)

mvp1 <- minvariancePortfolio(Portfolio1, spec=portfolioSpec(),constraints="LongOnly")
mvp1
## 
## Title:
##  MV Minimum Variance Portfolio 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       LongOnly 
## 
## Portfolio Weights:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.4113 0.0000 0.3154 0.0586 0.0479 0.0135 0.0805 0.0727 
## 
## Covariance Risk Budgets:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.4113 0.0000 0.3154 0.0586 0.0479 0.0135 0.0805 0.0727 
## 
## Target Returns and Risks:
##   mean    Cov   CVaR    VaR 
## 0.0005 0.0106 0.0261 0.0156 
## 
## Description:
##  Mon Jul 11 15:31:12 2022 by user:
tanPort1 <- tangencyPortfolio(Portfolio1, spec=portfolioSpec(), constraints="LongOnly")
tanPort1
## 
## Title:
##  MV Tangency Portfolio 
##  Estimator:         covEstimator 
##  Solver:            solveRquadprog 
##  Optimize:          minRisk 
##  Constraints:       LongOnly 
## 
## Portfolio Weights:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.3335 0.0000 0.2806 0.0710 0.0716 0.2433 0.0000 0.0000 
## 
## Covariance Risk Budgets:
## amc.ax cba.ax col.ax csl.ax gmg.ax ltr.ax wbc.ax wes.ax 
## 0.1185 0.0000 0.0996 0.0282 0.0353 0.7185 0.0000 0.0000 
## 
## Target Returns and Risks:
##   mean    Cov   CVaR    VaR 
## 0.0014 0.0166 0.0359 0.0252 
## 
## Description:
##  Mon Jul 11 15:31:12 2022 by user:
minvarweights1 <- getWeights(mvp1) 
tanportweights1 <- getWeights(tanPort1)
weights1 <- (cbind(minvarweights1, tanportweights1))
colnames(weights1) <- c("Minimum Variance Portfolio", "Tangency Portfolio")
weights1
##        Minimum Variance Portfolio Tangency Portfolio
## amc.ax                 0.41134109         0.33351819
## cba.ax                 0.00000000         0.00000000
## col.ax                 0.31539298         0.28059092
## csl.ax                 0.05863499         0.07098561
## gmg.ax                 0.04794209         0.07162252
## ltr.ax                 0.01348886         0.24328276
## wbc.ax                 0.08047864         0.00000000
## wes.ax                 0.07272135         0.00000000
weights1 <- data.frame(minvarweights1)
assets <- colnames(frontierWeights1)
ggplot(data=weights1, aes(x=assets, y=minvarweights1, fill=assets)) +
  geom_bar(stat="identity", position=position_dodge(),colour="black") +
  geom_text(aes(label=sprintf("%.02f %%",minvarweights1*100)),
            position=position_dodge(width=0.9), vjust=-0.25, check_overlap = TRUE) +
  ggtitle("Minimum Variance Portfolio Optimal Weights")+ theme(plot.title = element_text(hjust = 0.5)) +
  labs(x= "Assets", y = "Weight (%)")

tanwt1 <- data.frame(tanportweights1)
assets <- colnames(frontierWeights1)
ggplot(data=tanwt1, aes(x=assets, y=tanportweights1, fill=assets)) +
  geom_bar(stat="identity", position=position_dodge(),colour="black") +
  geom_text(aes(label=sprintf("%.02f %%",tanportweights1*100)),
            position=position_dodge(width=0.9), vjust=-0.25, check_overlap = TRUE) +
  ggtitle("Tangency Portfolio Optimal Weights")+ theme(plot.title = element_text(hjust = 0.5)) +
  labs(x= "Assets", y = "Weight (%)")