install.packages(c("quantmod", "PerformanceAnalytics", "quadprog"))
## Installing packages into '/cloud/lib/x86_64-pc-linux-gnu-library/4.4'
## (as 'lib' is unspecified)
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(PerformanceAnalytics)
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
library(quadprog)
symbols <- c("AAPL", "MSFT", "GOOG")
getSymbols(symbols, from = "2022-01-01", to = "2023-12-31")
## [1] "AAPL" "MSFT" "GOOG"
prices <- na.omit(merge(Cl(AAPL), Cl(MSFT), Cl(GOOG)))
colnames(prices) <- symbols
returns <- na.omit(Return.calculate(prices))
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)) # Constraints: sum(weights) = 1 and weights >= 0
bvec <- c(1, rep(0, n_assets))
result <- solve.QP(Dmat, dvec, Amat, bvec, meq = 1)
weights <- result$solution
names(weights) <- colnames(returns)
print(weights)
## AAPL MSFT GOOG
## 0.57897831 0.35859050 0.06243118