Portfolio optimization is basically composed of four main steps:
In this recipe, we will employ PortfolioAnaltycs
and some other packages by joining together functionalities from different packages in order to provide a convenient and straightforward way to compose a financial portfolio.
The recipe workflow will be as follows:
In this recipe, we will join together powerful functions from different packages.
First of all, we will download stock quotations from Yahoo Finance by leveraging the quantmod
package.
The downloaded information will then be grouped within a portfolio
object and an optimal portfolio composition will be computed, employing functions from the PortfolioAnalytics
, ROI
, and Deoptim
packages. The ROI
package will be employed in its extended version, thanks to the glpk
and quadrprog
plugins.
In order to add those plugins, we will first have to install the Rcmdr
package.
Summing it all, you will have to run the following code to install and load the required packages:
library(DEoptim) library(ROI) library(ROI.plugin.glpk) library(ROI.plugin.quadprog) library(plugin) library(quantmod) library(PortfolioAnalytics)
stocks <- getSymbols(c("FCA","AAPL","GOOG"), env = sp500, from = as.Date("2015-01-01"), to = as.Date("2015-10-31")) FCA <- sp500$FCA FCA <- get("FCA",envir = sp500) FCA <- with(sp500, FCA) AAPL <- sp500$AAPL AAPL <- get("AAPL",envir = sp500) AAPL <- with(sp500,AAPL) GOOG <- sp500$GOOG GOOG <- get("GOOG",envir = sp500) GOOG <- with(sp500,GOOG) FCA <- as.data.frame(FCA) FCA <- FCA$FCA.Adjusted GOOG <- as.data.frame(GOOG) GOOG <- GOOG$GOOG.Adjusted AAPL <- as.data.frame(AAPL) AAPL <- AAPL$AAPL.Adjusted portfolio <- data.frame(FCA,GOOG,AAPL)
row.names(portfolio) <- seq.Date(from = as.Date("2015-01-01"), to = as.Date("2015-01-01") + nrow(portfolio)-1,by ="days")
portfolio
object by passing to it stock names:portfolio_obj <- portfolio.spec(assets = colnames(portfolio))
portfolio_obj <- add.constraint(portfolio = portfolio_obj, type = "box", min = c(0.01, 0.28, 0.1), max = c(0.4, 0.5, 0.25))
portfolio_obj <- add.constraint(portfolio = portfolio_obj, type = "diversification", div_target = 0.7)
portfolio_obj <- add.objective(portfolio = portfolio_obj, type = 'return', name = 'mean')
optimal_portfolio_obj <- optimize.portfolio( R = portfolio, portfolio = portfolio_obj, optimize_method = "ROI", trace = TRUE) print(optimal_portfolio_obj) > print(optimal_portfolio_obj) *********************************** PortfolioAnalytics Optimization *********************************** Call: optimize.portfolio(R = portfolio, portfolio = portfolio_obj, optimize_method = "ROI", trace = TRUE) Optimal Weights: FCA GOOG AAPL 0.25 0.50 0.25 Objective Measure: mean 322.5