简体   繁体   English

提取相关投资组合的权重

[英]extracting weighs of relalanced portfolio

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.我遇到的问题:我没有得到重新平衡的投资组合的权重,而是得到 3 个日期。 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:以下是涵盖您问题所有方面的要点:

  1. Support plugins支持插件

Since you are using not only DEoptim solver but also ROI , you need to download the recommended support plugins for ROI :由于您不仅使用DEoptim求解器,还使用ROI ,因此您需要下载推荐ROI支持插件:

 install.packages(c("fGarch", 
                        "Rglpk", 
                        "ROI.plugin.glpk", 
                        "ROI.plugin.quadprog", 
                        "ROI.plugin.symphony",
                        "pso",
                        "GenSA",
                        "corpcor",
                        "testthat",
                        "nloptr", 
                        "MASS", 
                        "robustbase")
                      )

  1. Use of libraries图书馆的使用

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) 
  1. Use of pipe operator pipe算子的使用

Notice that there is an additional dplyr library loaded which is needed for piping ( %>% ), ie making your code more efficient and readable::请注意,还加载了一个额外的dplyr库,这是管道%>% )所需的,即使您的代码更高效和可读:

#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)
  1. Removing redundancies消除冗余

Not sure why you cannot use the previous random portfolio rp which was input to optPort as an input to opt_rebal .不知道为什么你不能使用之前输入到optPort的随机投资组合rp作为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")
  1. Understanding the use of Risk-Reward plot了解风险回报 plot 的使用

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.这个 function 调用中有一个错误,我认为这是由于您的portf中的双重目标,因为它可能会阻止您获得有效的边界。 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)
  1. Understanding ROI了解投资回报率

ROI differs from other back-ends and therefore needs a separate portfolio specification portfolio.spec and portfolio optimisation optimize.portfolio or optimize.portfolio.rebalancing . ROI与其他后端不同,因此需要单独的投资组合规范portfolio.spec和投资组合优化optimize.portfoliooptimize.portfolio.rebalancing

Here is one way of implementing it (pay attention to portfolio specification which has no add.objective inside):这是实现它的一种方法(注意内部没有add.objective的投资组合规范):

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: 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.您可以阅读有关optimize.portfolio的文档,了解它可以解决哪些有限类型的凸优化问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM