Portfolio Optimization With R

R offers so many benefits to those interested in Quantitative Finance. It makes life super easy in terms of getting data, and in this particular case analyzing the data and constructing an optimal portfolio. Doing this in Excel is arduous. Getting bulk data via an API is slow. And automating calculations for the efficient frontier takes forever. Python is not on R’s level yet in terms of packages for finance either.

In general, in order to construct a minimum variance portfolio you need three things:

• Historical Returns
• Historical Volatility
• Some sort of covariance matrix or correlation matrix

In order to run this script, we will need a few packages. I would like to highlight one in particular, fPortfolio. This package is specifically geared towards portfolio optimization.

We need to prepare a time series object in order to plot the Efficient Frontier for a given portfolio. First, we will construct a vector of tickers and gather prices for them using the getSymbols function within quantmod. We will next calculate returns and convert the data to a time series object.

We can now calculate and plot the Efficient Frontier. We will do this by using the portfolioFrontier() function within R. This is what makes this package so great. We can overlay many different series’ on top of the frontier. The options are displayed below. We can also output the covariance matrix and correlation matrix for our portfolio of assets. On top of all of this, we can extract certain portfolios such as the Minimum Variance Portfolio or Max Return Portfolio as well as their individual characteristics. These characteristics include the expected return for each asset, the expected volatility for each asset, as well as different Value at Risk calculations. We can isolate any of these characteristics as well to graph and compare. Let’s examine some.

We can output the weights generated by the frontier and save them to a CSV file. We can also output the mean and volatility for each point also.

Let’s examine the weights of each point on the frontier graphically:

We can annualize this data and plot the risk returns on a scatter plot also. Note we can also annualize the returns data with the performance analytics library also as mentioned before. We can also plot the Sharpe Ratio of each point on the frontier on a scatter graph also.

Let’s examine the correlation matrix and covariance matrix associated with our assets also.

Next, we can examine specific classes of portfolios that could lie on the frontier. These can include the Tangency Portfolio, Minimum Variance Portfolio. In the documentation for fPortfolio, the following options are available as portfolio classes:

• feasiblePortfolio
• cmlPortfolio (deprecated)
• tangencyPortfolio
• efficientPortfolio
• minvariancePortfolio

Let’s output some basic stats for the Minimum Variance Portfolio and Tangency Portfolio. The Tangency Portfolio is one where the Sharpe Ratio is maximized. We can also use the ggplot2 library to output some awesome graphs.

We can also examine the Efficient Frontier under different constraints and specifications. I provided a list of the available constraints and specifications below.

Constraints List (Truncated)

 minW minimum weight in asset maxW maximum weight in asset eqsumW sum of weights (assets) minsumW minimum sum of weights (assets) maxsumW maximum sum of weights (assets)

Specs List

 setType Sets type of portfolio optimization setOptimize Sets what to optimize, min risk or max return setEstimator Sets names of mean and covariance estimators setParams Sets optional model parameters setWeights Sets weights vector setTargetReturn Sets target return value setTargetRisk Sets target risk value setTargetAlpha Sets CVaR target alpha value setRiskFreeRate Sets risk-free rate value setNFrontierPoints Sets number of frontier points setStatus Sets status value setSolver Sets the type of solver to be used setObjective Sets objective function name to be used setTrace Sets the logical trace flag.

Let’s implement some constraints and specifications in our portfolio. We will allow short selling in this portfolio and set the minimum and maximum weight in one given asset throughout the entire list of tickers.

Let’s examine the output on a minimal level.

In short, fPortfolio is extremely useful when analyzing a given portfolio of assets. We could prepare good looking automated reports with this package. fPortfolio also allows for backtesting strategies also and examining portfolios under rolling time frames as well. Theoretically, we could iterate over thousands of portfolio optimization models under different constraints and compare them. The backtesting features of this module are outside the scope of this post and will be discussed in later posts.