I am running a portfolio optimization on a series of stocks and I am trying to extract the weights of the rebalanced portfolio.
The problem I am having: instead of getting the weights of the rebalanced portfolio, I am getting 3 dates. The code for the project is down below.
library(ROI)
install.packages("DEoptim")
library(ggplot2)
install.packages("quantmod")
library(quantmod)
library(quantmod)
install.packages("PerfomanceAnalytics")
library(PerformanceAnalytics)
library(PortfolioAnalytics)
library(random)
install.packages("random")
library(random)
library(DEoptim)
install.packages("fPortfolio")
library(fPortfolio)
install.packages("foreach")
install.packages("doParallel")
library(PortfolioAnalytics)
#vector of stocks in my portfolio of
tickers <- c("FB", "AAPL", "AMZN", "GM", "GOOGL", "SQ", "NVDA","RYAM", "AMAT", "IMMR","SOI","PETS")
#bind porfolio prices
portfolioPrices <- NULL
for(ticker in tickers) {
portfolioPrices <- cbind(portfolioPrices,
getSymbols.yahoo(ticker, from='2003-01-03', periodicity = 'daily', auto.assign=FALSE)[,4])
}
#portfolio returns
portfolioReturns <- na.omit(ROC(portfolioPrices))
print(portfolioReturns)
portf <- portfolio.spec(colnames(portfolioReturns))
portf <- add.constraint(portf, type="weight_sum", min_sum=.99, max_sum=1,01)
portf <- add.constraint(portf, type="box", min=.02, max=.60)
portf<-add.constraint(portf,type="transation_cost", ptc=.001)
portf <- add.objective(portf, type="return", name="mean")
portf <- add.objective(portf, type="risk", name="StdDev",target=.005)
rp<-random_portfolios(portf, 10000, "sample")
#optimize portfolio using the "DEoptim solver"
optPort <- optimize.portfolio(portfolioReturns, portf, optimize_method = "DEoptim", trace=TRUE)
#chart weights of optimized portfolio
chart.Weights(optPort)
summary(optPort)
chart.RiskReward(optPort, risk.col = "StDev", return.col = "mean", chart.assets = TRUE)
rp<-random_portfolios(portf, 10000, "sample")
#rebalance portfolo
opt_rebal <- optimize.portfolio.rebalancing(portfolioReturns,
portf,
optimize_method="ROI",
rp=rp,
rebalance_on="years",
training_period=60,
rolling_window=60)
extractWeights(optPort)
chart.Weights(optPort)
#extract weights of rebalanced portfolio
extractWeights(opt_rebal))
How can I fix this?
Your help will be greatly appreciated.
Thank you.
First of all, your code is very messy!
Therefore, while giving you the solution, I also cleaned it.
Here are bullet points that cover all aspects of your question:
Since you are using not only DEoptim
solver but also ROI
, you need to download the recommended support plugins for ROI
:
install.packages(c("fGarch",
"Rglpk",
"ROI.plugin.glpk",
"ROI.plugin.quadprog",
"ROI.plugin.symphony",
"pso",
"GenSA",
"corpcor",
"testthat",
"nloptr",
"MASS",
"robustbase")
)
You should load libraries once and in the correct order since some libraries can mask some functions from each other. Here is the recommended order:
library(ROI)
library(ggplot2)
library(quantmod)
library(PerformanceAnalytics)
library(random)
library(DEoptim)
library(fPortfolio)
library(PortfolioAnalytics)
library(dplyr)
Notice that there is an additional dplyr
library loaded which is needed for piping ( %>%
), ie making your code more efficient and readable::
#vector of stocks in my portfolio of
tickers <- c("FB", "AAPL", "AMZN", "GM", "GOOGL", "SQ", "NVDA","RYAM", "AMAT", "IMMR","SOI","PETS")
#bind porfolio prices
portfolioPrices <- NULL
for(ticker in tickers) {
portfolioPrices <- cbind(portfolioPrices,
getSymbols.yahoo(ticker, from='2003-01-03', periodicity = 'daily', auto.assign=FALSE)[,4])
}
#portfolio returns
portfolioReturns <- na.omit(ROC(portfolioPrices))
print(portfolioReturns)
portf <- portfolio.spec(colnames(portfolioReturns)) %>%
add.constraint(type="weight_sum", min_sum=1, max_sum=1) %>%
add.constraint(type="box", min=.02, max=.60) %>%
add.constraint(type="transation_cost", ptc=.001) %>%
add.objective(type="return", name="mean") %>%
add.objective(type="risk", name="StdDev",target=.005)
Not sure why you cannot use the previous random portfolio rp
which was input to optPort
as an input to opt_rebal
.
rp<-random_portfolios(portf, 10000, "sample")
#optimize portfolio using the "DEoptim solver"
optPort <- optimize.portfolio(portfolioReturns, portf, optimize_method = "DEoptim", trace=TRUE,
rp=rp)
#chart weights of optimized portfolio
chart.Weights(optPort)
summary(optPort)
# chart.RiskReward(optPort, risk.col = "StDev", return.col = "mean", chart.assets = TRUE)
#not sure why you cannot use the previous random portfolio!!
rp<-random_portfolios(portf, 10000, "sample")
There is an error in this function call which I assume is due to the dual objective in your portf
as it might prevent you from getting the efficient frontier. Not sure about that; this is not essential but a task for you to explore:-)
# chart.RiskReward(optPort, risk.col = "StDev", return.col = "mean", chart.assets = TRUE)
ROI
differs from other back-ends and therefore needs a separate portfolio specification portfolio.spec
and portfolio optimisation optimize.portfolio
or optimize.portfolio.rebalancing
.
Here is one way of implementing it (pay attention to portfolio specification which has no add.objective
inside):
portf2 <- portfolio.spec(colnames(portfolioReturns)) %>%
add.constraint(type="weight_sum", min_sum=1, max_sum=1) %>%
add.constraint(type="box", min=.02, max=.60) %>%
add.constraint(type="transation_cost", ptc=.001)
#this optimises based on Sharpe Ratio
optPort2 <- optimize.portfolio(portfolioReturns, portf2, optimize_method = "ROI", trace=TRUE,
maxSR=TRUE)
#rebalance portfolo
opt_rebal <- optimize.portfolio.rebalancing(portfolioReturns,
portf2,
optimize_method="ROI",
rp=rp,
rebalance_on="years",
training_period=60,
rolling_window=60)
extractWeights(optPort)
chart.Weights(optPort)
#extract weights of rebalanced portfolio
extractWeights(opt_rebal)
Output:
> extractWeights(opt_rebal)
FB.Close AAPL.Close AMZN.Close GM.Close GOOGL.Close SQ.Close NVDA.Close RYAM.Close AMAT.Close
2017-12-29 0.6 0.2 0.02 0.02 0.02 0.02 0.02 0.02 0.02
2018-12-31 0.6 0.2 0.02 0.02 0.02 0.02 0.02 0.02 0.02
2019-09-20 0.6 0.2 0.02 0.02 0.02 0.02 0.02 0.02 0.02
IMMR.Close SOI.Close PETS.Close
2017-12-29 0.02 0.02 0.02
2018-12-31 0.02 0.02 0.02
2019-09-20 0.02 0.02 0.02
You can read the documentation about optimize.portfolio
to see what limited type of convex optimization problems it can solve.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.