Learn R Programming

README

This V2.1 version of PortfolioAnalytics is an update to the substantial V2.0 version that was released on 2024-07-03. We first describe the V2.0 features, then discuss the R demo capability, and finally we describe the additional V2.1 features.

2.0 Features

A major feature of 2.0 was the integration of the CVXR solver R package for convex optimization. CVXR supports eleven solver packages, each of which supports solvers for one or more of the following optimization problems: LP, QP, SOCP, SDP, EXP, MIP. See the Table near the beginning of the document “Convex Optimization in R” at https://cvxr.rbind.io/. Thus, with PortfolioAnalytics 2.0, users are able to use any one of a large variety of solvers available in CVXR for their portfolio optimization problems.

A particular use of CVXR in PortfolioAnalytics 2.0 is for computing Minimum Coherent Second Moment (MCSM) portfolios, which are second-order cone programming (SOCP) optimization problems. This is a quite new capability that is not available in other portfolio optimization software products. Details are provided in the Vignette “cvxrPortfolioAnalytics”.

Another important feature of PortfolioAnalytics 2.0, is that it contains functionality for computing outliers-robust minimum variance (MV) optimal portfolios based on any one of several robust covariance matrix estimators that are not much influenced by outliers Details are provided in the Vignette “robustCovMatForPA”.

New PortfolioAnalytics Functions:

  1. meancsm.efficient.frontier (create Mean-CSM efficient frontier) utility function
  2. meanrisk.efficient.frontier (generate multiple efficient frontiers for portfolios with the same constraint object.
  3. extract_risk (extract the risk value, e.g., StdDev or ES or CSM, based on the weights of a portfolio)
  4. chart.EfficientFrontierCompare (Overlay the efficient frontiers of different minRisk portfolio objects on a single plot)
  5. backtest.plot (based on Peter Carl’s code, generate plots of the cumulative returns and/or drawdown for back-testing)
  6. opt.outputMvo (converts output of optimize.portfolio to a list of the portfolio weights, mean, volatility and Sharpe Ratio)
  7. plotFrontiers (plot frontiers based on the result of meanvar.efficient.frontier, meanetl.efficient.frontier or meancsm.efficient.frontier)

Enhanced PortfolioAnalytics Functions:

  1. optimize.portfolio (enhanced with CVXR solvers, CSM objective, customizable arg momentFUN= and output ~$moment_values)
  2. optimize.portfolio.rebalancing (enhanced with CVXR solvers, CSM objective and customizable arg momentFUN=)
  3. create.EfficientFrontier (enhanced with type mean-CSM and mean-risk, and customizable arg momentFUN=)

Support of S3 Methods for CVXR:

  1. print.optimize.portfolio.CVXR
  2. extractStats.optimize.portfolio.CVXR

Custom Moment Functions for Robust Covariance Matrices:

  1. custom.covRob.MM
  2. custom.covRob.Rocke
  3. custom.covRob.Mcd
  4. custom.covRob.TSGS
  5. MycovRobMcd
  6. MycovRobTSGS

Two New Vignettes, the pdf files of which are downloadable from PortfolioAnalytics at https://CRAN.R-project.org/package=PortfolioAnalytics:

  1. cvxrPortfolioAnalytics, with CRAN title “CVXR for PortfolioAnalytics”.
  2. robustCovMatForPA, with CRAN title “Robust Covariance Matrices for PortfolioAnalytics”

PortfolioAnalytics Demo Scripts

PortfolioAnalytics has contained a substantial number of demo R scripts in the demo folder for a long time. Assuming that an R package is installed, but not necessarily loaded, you can view a list of the names of al the demo folder R scripts with the following R command

demo(package = “packageName”)

Use the above for the PortfolioAnalytics package, and you will see a list of over 30 demo scripts, among which you will see the the following two demo scripts

  1. demo_cvxrPortfolioAnalytics.R
  2. demo_robustCovMatForPA.R

which runs the code for the corresponding two Vignettes listed above.

You can view the code for any demo R script with the command “??” (but not with “help” command). For example, in RStudio, use of the command

?? demo_cvxrPortfolioAnalytics

results in a Help tab display with the followng two links:

  • PortfolioAnalytics::demo_cvxrPortfolioAnalytics
  • (Run demo).

Use the first link, which results in a display of the entire R script in the Help tab. Then copy/paste the script into your own new R file, and run it in chunks that are of interest to you. Many of the chunks will run quite quickly, e.g., a few seconds, but a few of them may take 2-4 minutes. Doing so for the demo_cvxrPortfolioAnalytics.R will help you learn some PortfolioAnalytics basics, as well as learn how to use new capabilities in Versions 2.0 and 2.1. Running the demo_robustCovMatForPA.R scripts will show you how to compute robust minimum variance portfolios based on returns robust covariance matrix estimators that are not much influenced by returns outliers.

NOTE: We do not recommend general use of (Run demo). This is because it runs the entire demo script, which will often take much too long. Furthermore, some scripts may fail to execute properly when run this way. That said, the (Run demo) link can be handy for running R demo scripts that execute quickly.

New 2.1 Features

The 2.1 version of PortfolioAnalytics contains the following new demo scripts:

  1. demo_JPM2024MinDownsideRisk.R
  2. demo_JPM2024MinDownsideRiskCVXR.R

The first script replicates all the Exhibits (Figures and Tables) in the Journal of Portfolio Management paper “Minimum Downside Risk Portfolios", published in October 2024. This first script uses CVXR package solvers “under the hood”, i.e., not directly visible, in PortfolioAnalytics. The second script replicates just the back-test results in Exhibits 6, 8, 10, 12, 14, 16, 18, in the above paper, but it uses the CVXR code directly in the script, where on can easily see the CVXR code details.

The 2.1 release also contains:

  1. Extended functionalities for graphical displays of multiple efficient frontiers, and robust covariance estimator settings
  2. The term EQS for expected quadratic shortfall was replaced with CSM for coherent second moment risk.
  3. Updates to the vignettes cvxrPortfolioAnalytics and robustCovMatForPA, and their demo scripts.

Bug Reporting

Please contribute with bug fixes, comments, and testing scripts!

Please take your data and disguise it when submitting, or use data sets like “edhec” like we do in the demos or or like “stocksCRSP” and “factorsSPGMI” in the PCRA package or with your constraints and other objectives modified to demonstrate your problem on public data.

Please report any bugs or issues on the PortfolioAnalytics GitHub page at https://github.com/braverock/PortfolioAnalytics/issues

Acknowledgements

The bulk of the work in creating PortfolioAnalytics 2.0 was done by Xinran Zhao, along with contributions from Yifu Kang, under the support of a 2022 Google Summer of Code (GSOC 2022). Xinran and Yifu were mentored in GSOC 2022 by Professor Doug Martin and Professor Steve Murray in the Applied Mathematics Department at the University of Washington.

Copy Link

Version

Install

install.packages('PortfolioAnalytics')

Monthly Downloads

3,820

Version

2.1.0

License

GPL-3

Issues

Pull Requests

Stars

Forks

Last Published

December 4th, 2024

Functions in PortfolioAnalytics (2.1.0)

centroid.buckets

Buckets Centroid
centroid.complete.mc

Complete Cases Centroid
add.sub.portfolio

Add sub-portfolio
box_constraint

constructor for box_constraint.
applyFUN

Apply a risk or return function to a set of weights
black.litterman

Black Litterman Estimates
centroid.sectors

Multiple Sectors Centroid
center

Center
backtest.plot

generate plots of the cumulative returns and drawdown for back-testing
barplotGroupWeights

barplot of group weights by group or category
chart.GroupWeights

Chart weights by group or category
chart.RiskBudget

Generic method to chart risk contribution
chart.EfficientFrontierCompare

Overlay the efficient frontiers of different minRisk portfolio objects on a single plot.
chart.EfficientFrontierOverlay

Plot multiple efficient frontiers
chart.EfficientFrontier

Chart the efficient frontier and risk-return scatter
chart.EF.Weights

Chart weights along an efficient frontier
centroid.sign

Positive and Negative View Centroid
chart.RiskReward

classic risk reward scatter
chart.Weights

boxplot of the weights of the optimal portfolios
chart.Concentration

Classic risk reward scatter and concentration
check_constraints

check if a set of weights satisfies the constraints
cokurtosisSF

Cokurtosis Matrix Estimate
coskewnessMF

Coskewness Matrix Estimate
combine.optimizations

Combine objects created by optimize.portfolio
combine.portfolios

Combine a list of portfolio objects
cokurtosisMF

Cokurtosis Matrix Estimate
coskewnessSF

Coskewness Matrix Estimate
constraint_v1

constructors for class constraint
constraint_ROI

constructor for class constraint_ROI
constrained_objective

calculate a numeric return value for a portfolio based on a set of constraints and objectives
custom.covRob.Mcd

Compute returns mean vector and covariance matrix with custom.covRob.Mcd
create.EfficientFrontier

create an efficient frontier
diversification_constraint

constructor for diversification_constraint
equal.weight

Create an equal weight portfolio
custom.covRob.Rocke

Compute returns mean vector and covariance matrix with custom.covRob.Rocke
custom.covRob.MM

Compute returns mean vector and covariance matrix with custom.covRob.MM
extractObjectiveMeasures

Extract the objective measures
extractCoskewness

Coskewness Estimate
extractCokurtosis

Cokurtosis Estimate
extractGroups

Extract the group and/or category weights
extract_risk

extract the risk value when knowing the weights
extractCovariance

Covariance Estimate
covarianceMF

Covariance Matrix Estimate
extractEfficientFrontier

Extract the efficient frontier data points
covarianceSF

Covariance Matrix Estimate
etl_opt

Minimum ETL LP Optimization
custom.covRob.TSGS

Compute returns mean vector and covariance matrix with custom.covRob.TSGS
get_constraints

Helper function to get the enabled constraints out of the portfolio object When the v1_constraint object is instantiated via constraint, the arguments min_sum, max_sum, min, and max are either specified by the user or default values are assigned. These are required by other functions such as optimize.portfolio and constrained_objective . This function will check that these variables are in the portfolio object in the constraints list. We will default to min_sum=1 and max_sum=1 if leverage constraints are not specified. We will default to min=-Inf and max=Inf if box constraints are not specified. This function is used at the beginning of optimize.portfolio and other functions to extract the constraints from the portfolio object. We Use the same naming as the v1_constraint object.
gmv_opt

GMV/QU QP Optimization
etl_milp_opt

Minimum ETL MILP Optimization
diversification

Function to compute diversification as a constraint
extractStats

extract some stats and weights from a portfolio run via optimize.portfolio
gmv_opt_toc

GMV/QU QP Optimization with Turnover Constraint
group_constraint

constructor for group_constraint
is.constraint

check function for constraints
extractWeights

Extract weights from a portfolio run via optimize.portfolio or optimize.portfolio.rebalancing
insert_constraints

Insert a list of constraints into the constraints slot of a portfolio object
inverse.volatility.weight

Create an inverse volatility weighted portfolio
insert_objectives

Insert a list of objectives into the objectives slot of a portfolio object
meanvar.efficient.frontier

Generate the efficient frontier for a mean-variance portfolio
meucci.moments

Compute moments
fn_map

mapping function to transform or penalize weights that violate constraints
indexes

Six Major Economic Indexes
factor_exposure_constraint

Constructor for factor exposure constraint
group_fail

Test if group constraints have been violated
meucci.ranking

Asset Ranking
meanrisk.efficient.frontier

Generate multiple efficient frontiers for the same portfolio
optimize.portfolio

Constrained optimization of portfolios
leverage_exposure_constraint

constructor for leverage_exposure_constraint
optimize.portfolio.parallel

Execute multiple optimize.portfolio calls, presumably in parallel
maxret_milp_opt

Maximum Return MILP Optimization
meanetl.efficient.frontier

Generate the efficient frontier for a mean-etl portfolio
minmax_objective

constructor for class tmp_minmax_objective
portfolio.spec

constructor for class portfolio
optimize.portfolio.rebalancing

Portfolio Optimization with Rebalancing Periods
mult.portfolio.spec

Multple Layer Portfolio Specification
pHist

Generates histogram
print.efficient.frontier

Print an efficient frontier object
print.constraint

print method for constraint objects
return_constraint

constructor for return_constraint
name.replace

utility function to replace awkward named from unlist
portfolio_risk_objective

constructor for class portfolio_risk_objective
random_portfolios_v1

generate an arbitary number of constrained random portfolios
gmv_opt_leverage

GMV/QU QP Optimization with Turnover Constraint
random_portfolios

version 2 generate an arbitary number of constrained random portfolios
randomize_portfolio_v1

Random portfolio sample method
meancsm.efficient.frontier

Generate the efficient frontier for a mean-CSM portfolio
set.portfolio.moments

Portfolio Moments
maxret_opt

Maximum Return LP Optimization
plotFrontiers

Generate efficient frontiers plot by providing frontiers.
position_limit_constraint

constructor for filter_constraint
generatesequence

create a sequence of possible weights for random or brute force portfolios
plot.optimize.portfolio.DEoptim

plot method for objects of class optimize.portfolio
opt.outputMvo

Optimal Portfolio Weights and Performance Values
objective

constructor for class 'objective'
pos_limit_fail

function to check for violation of position limits constraints
rp_sample

Generate random portfolios using the sample method
return_objective

constructor for class return_objective
trailingFUN

apply a function over a configurable trailing period
regime.portfolios

Regime Portfolios
summary.portfolio

Summarize Portfolio Specification Objects
rp_simplex

Generate random portfolios using the simplex method
statistical.factor.model

Statistical Factor Model
gmv_opt_ptc

GMV/QU QP Optimization with Proportional Transaction Cost Constraint
print.optimize.portfolio.ROI

Printing output of optimize.portfolio
set.portfolio.moments_v1

set portfolio moments for use by lower level optimization functions
turnover

Calculates turnover given two vectors of weights. This is used as an objective function and is called when the user adds an objective of type turnover with add.objective
transaction_cost_constraint

constructor for transaction_cost_constraint
portfolio.moments.boudt

Portfolio Moments
summary.optimize.portfolio.rebalancing

summary method for optimize.portfolio.rebalancing
portfolio.moments.bl

Portfolio Moments
random_walk_portfolios

deprecated random portfolios wrapper until we write a random trades function
rp_grid

Generate random portfolios based on grid search method
randomize_portfolio

version 2 generate random permutations of a portfolio seed meeting your constraints on the weights of each asset
update_constraint_v1tov2

Helper function to update v1_constraint objects to v2 specification in the portfolio object
risk_budget_objective

constructor for class risk_budget_objective
weight_sum_constraint

constructor for weight_sum_constraint
update.constraint

function for updating constrints, not well tested, may be broken
is.portfolio

check function for portfolio
print.portfolio

Printing Portfolio Specification Objects
is.objective

check class of an objective object
summary.optimize.portfolio

Summarizing output of optimize.portfolio
rp_transform

Transform a weights vector to satisfy constraints
print.summary.optimize.portfolio

Printing summary output of optimize.portfolio
summary.efficient.frontier

Summarize an efficient frontier object
var.portfolio

Calculate portfolio variance
print.optimize.portfolio.rebalancing

Printing output of optimize.portfolio.rebalancing
weight_concentration_objective

Constructor for weight concentration objective
quadratic_utility_objective

constructor for quadratic utility objective
print.summary.optimize.portfolio.rebalancing

Printing summary output of optimize.portfolio.rebalancing
scatterFUN

Apply a risk or return function to asset returns
turnover_constraint

constructor for turnover_constraint
turnover_objective

constructor for class turnover_objective
BlackLittermanFormula

Computes the Black-Litterman formula for the moments of the posterior normal.
EntropyProg

Entropy pooling program for blending views on scenarios with a prior scenario-probability distribution
CCCgarch.MM

compute comoments for use by lower level optimization functions when the conditional covariance matrix is a CCC GARCH model
PortfolioAnalytics-package

Numeric methods for optimization of portfolios
add.objective

General interface for adding optimization objectives, including risk, return, and risk budget
add.constraint

General interface for adding and/or updating optimization constraints.
HHI

Concentration of weights
ac.ranking

Asset Ranking
MycovRobMcd

Control settings for custom.covRob.Mcd
MycovRobTSGS

Control settings for custom.covRob.TSGS