library(quantmod)
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(quadprog)
library(PerformanceAnalytics)
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
symbols <- c("AAPL", "MSFT", "GOOG", "AMZN")
getSymbols(symbols, from = "2023-01-01", to = "2024-01-01")
## [1] "AAPL" "MSFT" "GOOG" "AMZN"
prices <- do.call(merge, lapply(symbols, function(sym) Ad(get(sym))))
returns <- na.omit(ROC(prices, type = "discrete"))
colnames(returns) <- symbols
cov_matrix <- cov(returns)
n_assets <- ncol(returns)
Dmat <- 2 * cov_matrix
dvec <- rep(0, n_assets)
Amat <- cbind(rep(1, n_assets), diag(n_assets))
bvec <- c(1, rep(0, n_assets))
meq <- 1
sol <- solve.QP(Dmat, dvec, Amat, bvec, meq)
weights <- sol$solution
names(weights) <- symbols
print("Minimum Variance Portfolio Weights (No Short-Selling):")
## [1] "Minimum Variance Portfolio Weights (No Short-Selling):"
print(round(weights, 4))
## AAPL MSFT GOOG AMZN
## 0.7197 0.2292 0.0203 0.0308
portfolio_variance <- t(weights) %*% cov_matrix %*% weights
print(paste("Portfolio Variance:", round(portfolio_variance, 6)))
## [1] "Portfolio Variance: 0.000145"