Harry Markowitz’s Modern Portfolio Theory (MPT) is a cornerstone in finance. It posits that investors should construct portfolios based on expected returns and risk (measured by variance or standard deviation). The goal is to maximize returns for a given level of risk, or minimize risk for a given level of return.
Let us start from the basic example, we will calculate the Apple and Microsoft portfolio for the years 2018-2023. Recall PT is one period model.
# Load required libraries
library(quantmod)
## Ładowanie wymaganego pakietu: xts
## Ładowanie wymaganego pakietu: zoo
##
## Dołączanie pakietu: 'zoo'
## Następujące obiekty zostały zakryte z 'package:base':
##
## as.Date, as.Date.numeric
## Ładowanie wymaganego pakietu: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(PerformanceAnalytics)
##
## Dołączanie pakietu: 'PerformanceAnalytics'
## Następujący obiekt został zakryty z 'package:graphics':
##
## legend
# Get historical data for two stocks (e.g., Apple and Microsoft)
getSymbols(c("AAPL", "MSFT"), from = "2018-01-01", to = "2023-12-31")
## [1] "AAPL" "MSFT"
# Calculate daily returns
returns <- na.omit(ROC(merge(AAPL[,6], MSFT[,6])))
# Calculate expected returns and covariance matrix
mu <- colMeans(returns)
cov_mat <- cov(returns)
# Set up portfolio weights
weights <- c(0.5, 0.5) # Equal weights for AAPL and MSFT
# Calculate portfolio expected return and variance
portfolio_return <- sum(weights * mu)
portfolio_variance <- t(weights) %*% cov_mat %*% weights
# Print results
print(paste("Portfolio expected return:", round(portfolio_return * 252, 2), "%"))
## [1] "Portfolio expected return: 0.26 %"
print(paste("Portfolio annualized volatility:", round(sqrt(portfolio_variance * 252) * 100, 2), "%"))
## [1] "Portfolio annualized volatility: 28.93 %"
This code demonstrates a basic application of portfolio theory in R:
Data Acquisition: It fetches historical price data for Apple (AAPL) and Microsoft (MSFT) using the quantmod package.
Return Calculation: Daily returns are calculated using the ROC function.
Expected Return and Covariance: The expected returns (mu) and covariance matrix (cov_mat) are calculated from the historical returns.
Portfolio Weights: Equal weights are assigned to both stocks.
Portfolio Metrics: The expected return and variance of the portfolio are calculated based on the weights, expected returns, and covariance matrix.
Output: The annualized expected return and volatility of the portfolio are printed.
Note: This is a simplified example. In practice, you might consider more sophisticated techniques like mean-variance optimization to find optimal portfolio weights based on specific risk tolerance and return objectives. Additionally, you can explore other packages like PortfolioAnalytics for more advanced portfolio analysis.