# Load required libraries
library(tidyquant)
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
## ── Attaching core tidyquant packages ─────────────────────── tidyquant 1.0.11 ──
## ✔ PerformanceAnalytics 2.0.8 ✔ TTR 0.24.4
## ✔ quantmod 0.4.27 ✔ xts 0.14.1
## ── Conflicts ────────────────────────────────────────── tidyquant_conflicts() ──
## ✖ zoo::as.Date() masks base::as.Date()
## ✖ zoo::as.Date.numeric() masks base::as.Date.numeric()
## ✖ PerformanceAnalytics::legend() masks graphics::legend()
## ✖ quantmod::summary() masks base::summary()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(quadprog)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.5.2 ✔ tibble 3.2.1
## ✔ lubridate 1.9.4 ✔ tidyr 1.3.1
## ✔ purrr 1.0.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::first() masks xts::first()
## ✖ dplyr::lag() masks stats::lag()
## ✖ dplyr::last() masks xts::last()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# Sample asset returns (you can replace this with your own return data)
# Simulate monthly returns for 3 assets over 12 months
set.seed(123)
returns <- matrix(rnorm(36, mean = 0.01, sd = 0.05), ncol = 3)
colnames(returns) <- c("Asset1", "Asset2", "Asset3")
# Calculate the covariance matrix
cov_mat <- cov(returns)
# Number of assets
n_assets <- ncol(returns)
# Set up the quadratic programming problem
Dmat <- 2 * cov_mat # Quadratic term (multiplied by 2 because quadprog minimizes (1/2)x'Dx - d'x)
dvec <- rep(0, n_assets) # Linear term
Amat <- cbind(rep(1, n_assets)) # Constraint: sum of weights = 1
bvec <- 1 # Total weight = 1
meq <- 1 # First constraint is equality (sum of weights = 1)
# Solve the quadratic programming problem
result <- solve.QP(Dmat, dvec, Amat, bvec, meq)
# Get the weights
weights <- result$solution
names(weights) <- colnames(returns)
# Display the minimum variance portfolio weights
print("Minimum Variance Portfolio Weights:")
## [1] "Minimum Variance Portfolio Weights:"
print(round(weights, 4))
## Asset1 Asset2 Asset3
## 0.2105 0.4327 0.3568