0

I tried to run this code and it seems to produce no errors but at the end I don't get the plot for some reason. I had some issues with the variables for the plot but i think that should be fixed now. I can't get the plot in my viewer. Is there an issue with the code or should I reinstall plotly?

library(PortfolioAnalytics)
library(quantmod)
library(PerformanceAnalytics)
library(zoo)
library(plotly)
library(foreach)
library(DEoptim)
library(iterators)
library(fGarch)
library(Rglpk)
library(quadprog)
library(ROI)
library(ROI.plugin.glpk)
library(ROI.plugin.quadprog)
library(ROI.plugin.symphony)
library(pso)
library(GenSA)
library(corpcor)
library(testthat)
library(nloptr)
library(MASS)
library(robustbase)

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

# Assign to dataframe
# Get adjusted prices
prices.data <- merge.zoo(MSFT[,6], SBUX[,6], IBM[,6], AAPL[,6], GSPC[,6], AMZN[,6])

# Calculate returns
returns.data <- CalculateReturns(prices.data)
returns.data <- na.omit(returns.data)

# Set names
colnames(returns.data) <- c("MSFT", "SBUX", "IBM", "AAPL", "^GSPC", "AMZN")

# Save mean return vector and sample covariance matrix
meanReturns <- colMeans(returns.data)
covMat <- cov(returns.data)

# Start with the names of the assets
port <- portfolio.spec(assets = c("MSFT", "SBUX", "IBM", "AAPL", "^GSPC", "AMZN"))

# Box
port <- add.constraint(port, type = "box", min = 0.05, max = 0.8)

# Leverage
port <- add.constraint(portfolio = port, type = "full_investment")

# Generate random portfolios
rportfolios <- random_portfolios(port, permutations = 5000, rp_method = "sample")

# Get minimum variance portfolio
minvar.port <- add.objective(port, type = "Risk", name = "var")

# Optimize
minvar.opt <- optimize.portfolio(returns.data, minvar.port, optimize_method = "random", 
                                 rp = rportfolios)

# Generate maximum return portfolio
maxret.port <- add.objective(port, type = "Return", name = "mean")

# Optimize
maxret.opt <- optimize.portfolio(returns.data, maxret.port, optimize_method = "random", 
                                 rp = rportfolios)

# Generate vector of returns
minret <- 0.06/100
maxret <- maxret.opt$weights %*% meanReturns

vec <- seq(minret, maxret, length.out = 100)

eff.frontier <- data.frame(Risk = rep(NA, length(vec)),
                           Return = rep(NA, length(vec)), 
                           SharpeRatio = rep(NA, length(vec)))

frontier.weights <- mat.or.vec(nr = length(vec), nc = ncol(returns.data))
colnames(frontier.weights) <- colnames(returns.data)

for(i in 1:length(vec)){
  eff.port <- add.constraint(port, type = "Return", name = "mean", return_target = vec[i])
  eff.port <- add.objective(eff.port, type = "Risk", name = "var")
  # eff.port <- add.objective(eff.port, type = "weight_concentration", name = "HHI",
  #                            conc_aversion = 0.001)

  eff.port <- optimize.portfolio(returns.data, eff.port, optimize_method = "ROI")

  eff.frontier$Risk[i] <- sqrt(t(eff.port$weights) %*% covMat %*% eff.port$weights)

  eff.frontier$Return[i] <- eff.port$weights %*% meanReturns

  eff.frontier$Sharperatio[i] <- eff.port$Return[i] / eff.port$Risk[i]

  frontier.weights[i,] = eff.port$weights

  print(paste(round(i/length(vec) * 100, 0), "% done..."))
}

feasible.sd <- apply(rportfolios, 1, function(x){
  return(sqrt(matrix(x, nrow = 1) %*% covMat %*% matrix(x, ncol = 1)))
})

feasible.means <- apply(rportfolios, 1, function(x){
  return(x %*% meanReturns)
})

feasible.sr <- feasible.means / feasible.sd

p <- plot_ly(x = feasible.sd, y = feasible.means, color = feasible.sr, 
             mode = "markers", type = "scattergl", showlegend = F,

             marker = list(size = 3, opacity = 0.5, 
                           colorbar = list(title = "Sharpe Ratio"))) %>% 

  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",
         yaxis = list(title = "Mean Returns", tickformat = ".2%"),
         xaxis = list(title = "Standard Deviation", tickformat = ".2%"),
         plot_bgcolor = "#434343",
         paper_bgcolor = "#F8F8F8",
         annotations = list(
           list(x = 0.4, y = 0.75, 
                ax = -30, ay = -30, 
                text = "Efficient frontier", 
                font = list(color = "#F6E7C1", size = 15),
                arrowcolor = "white")
         ))

2 Answers 2

1

You have a problem with add_trace() function syntax. If you want markers on the plot you will need to make dimensions of eff.frontier table corresponding to your feasible.sd and feasible.means dimensions, which you set as the first layer of your plot.

Simply, eff.frontier columns length should be the same as for the feasible.sd and feasible.means vectors.

So, if we create an example eff.frontier table with right dimensions we could construct plotly object without any problem:

# create eff.frontier example object
eff.frontier_example <- data.frame(Risk = seq(0.01373, 0.01557, length.out = length(feasible.sd)), 
                                   Return = seq(0.0006444, 0.0008915, length.out = length(feasible.sd)))

# create plotly object
p <- plot_ly(x = feasible.sd, y = feasible.means, color = feasible.sr, 
             mode = "markers", type = "scattergl", showlegend = F,

             marker = list(size = 3, opacity = 0.5, 
                           colorbar = list(title = "Sharpe Ratio"))) %>% 

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

  layout(title = "Random Portfolios with Plotly",
         yaxis = list(title = "Mean Returns", tickformat = ".2%"),
         xaxis = list(title = "Standard Deviation", tickformat = ".2%"),
         plot_bgcolor = "#434343",
         paper_bgcolor = "#F8F8F8",
         annotations = list(
           list(x = 0.4, y = 0.75, 
                ax = -30, ay = -30, 
                text = "Efficient frontier", 
                font = list(color = "#F6E7C1", size = 15),
                arrowcolor = "white")
         ))

# show plotly object
p

plot with eff.frontier_example

Sign up to request clarification or add additional context in comments.

5 Comments

when i copy paste your solution i get the Error: Column color must be length 1 or 435, not 434. And also how can i use my data instead of the example frontier?
Joan, I made my answer a bit more clear. Please, check the result of the code. Now, the plot should appear. The main problem of the plotly object is inconsistency of the plot layers (in your original code). The first layer visualizes objects feasible.sd and feasible.means with length 435 or more (the length is changing day to day according to your code) and the second layer tries to visualize columns of eff.frontier table which have different length. It is impossible on the one graph. You should set coordinates for lines consistent with dimensions of your first layer.
My code introduces example eff.frontier data with consistent dimensions and shows that plotly object appears. So, you just need to correctly set your eff.frontier object under your research purposes.
Thank you so much Irina, im still pretty lost but i think im going in the right direction. I kindo of getting a graph now but its empty and in the console it says : GLError: gl-shader: Error compiling vertex shader of unknown name (see npm glsl-shader-name): ERROR: 0:1: 'highp' : precision is not supported in fragment shader Error compiling vertex shader of unknown name (see npm glsl-shader-name): 1: precision highp float; ^^^ 'highp' : precision is not supported in fragment shader
Could you reproduce a plot with eff.frontier_example data frame as in my code?
0

I'll assume you ran the code exactly as posted. Your last code block assigns the plotly plot to p. Just add the line p to call the plot.

p <- plotly_ly(...) p

2 Comments

when i just add the q i get Warning messages: 1: Can't display both discrete & non-discrete data on same axis
and a blank plot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.