Quantcast
Channel: r software hub
Viewing all articles
Browse latest Browse all 1015

Portfolio Optimization using R and Plotly

$
0
0

By Riddhiman

In this post we’ll focus on showcasing Plotly’s WebGL capabilities by charting financial portfolios using an R package called PortfolioAnalytics. The package is a generic portfolo optimization framework developed by folks at the University of Washington and Brian Peterson (of the PerformanceAnalytics fame).

You can see the vignette here

Let’s pull in some data first.

library(PortfolioAnalytics)
library(quantmod)
library(PerformanceAnalytics)
library(zoo)
library(plotly)

# Get data
getSymbols(c("MSFT", "SBUX", "IBM", "AAPL", "^GSPC", "AMZN"))

# Assign to dataframe
# Get adjusted prices
prices.data 

Now that we have some data, let's get started by creating a portfolio specification. This can be done by using portfolio.spec()

# Start with the names of the assets
port 

Now for some constraints. Let's use the following:

  • Box constraints
  • Leverage (weight sum)
# Box
port 

Let's use the built-in random solver. This essentially creates a set of feasible portfolios that satisfy all the constraints we have specified. For a full list of supported constraints see here

# Generate random portfolios
rportfolios 

Now let's add some objectives and optimize. For simplicity's sake let's do some mean-variance optimization.

# Get minimum variance portfolio
minvar.port 

Now that we have the minimum variance as well as the maximum return portfolios, we can build out the efficient frontier. Let's add a weight concentration objective as well to ensure we don't get highly concentrated portfolios.

Note:

  • random_portfolios() ignores any diversification constraints. Hence, we didn’t add it previously.
  • Using the random solver for each portfolio in the loop below would be very compute intensive. We’ll use the ROI (R Optmization Infrastructure) solver instead.
eff.frontier 

Now lets plot !

feasible.sd % 

add_trace(data = eff.frontier, x = Risk, y = Return, mode = "markers",
type = "scattergl", showlegend = F,
marker = list(color = "#F7C873", size = 5)) %>%

layout(title = "Random Portfolios with Plotly",
...read more

Source:: r-bloggers.com


Viewing all articles
Browse latest Browse all 1015

Latest Images

Trending Articles



Latest Images