PortfolioAnalytics - Error in factor_exposure_constraint : number of rows of B must be equal to number of assets

时间:2015-05-24 20:44:40

标签: r

I am trying to reproduce the Examples in Ross Bennetts Presentation which can be found here http://www.rinfinance.com/agenda/2014/workshop/RossBennett.pdf

However in Example 1 I face the issue that the function factor_exposure_constraint always evaluates the betas matrix as having less rows than assets in the portfolio. The function seems to evaluate the number of assets in line 4:

nassets <- length(assets)

From my point of view does this evaluate the length of the whole object and not number of columns (= number of assets). As the betas are input as a matrix with 35 rows which can never equal the full length of the assets object (app. 25550).

What am I missing here?

My code below (data taken from Ross's github page for the presentation @ https://github.com/rossb34/PortfolioAnalyticsPresentation):

require(PortfolioAnalytics)
require(PerformanceAnalytics)
require(Ecdat)

#try(data(package = "PerformanceAnalytics"))
#try(data(package = "PortfolioAnalytics"))

source(paste(getwd(), "/_IncludeAlways.R", sep=""))

load(paste(dirData, "crsp_weekly.rda" , sep=""))

equity.data <- cbind(largecap_weekly[,1:15], 
                     midcap_weekly[,1:15], 
                     smallcap_weekly[,1:5])

market <- largecap_weekly[,21]
Rf <- largecap_weekly[,22]

chart.Boxplot(equity.data, sort.by="variance", colorset = "black", sort.ascending=TRUE)

portf.dn <- portfolio.spec(equity.data)

# Add constraint such that the portfolio weights sum to 0*
portf.dn <- add.constraint(portf.dn, type="weight_sum", 
                           min_sum=-0.01, max_sum=0.01)

# Add box constraint such that no asset can have a weight of greater than
# 20% or less than -20%
portf.dn <- add.constraint(portf.dn, type="box", min=-0.2, max=0.2)

# Add constraint such that we have at most 20 positions
portf.dn <- add.constraint(portf.dn, type="position_limit", max_pos=20)

# Add constraint such that the portfolio beta is between -0.25 and 0.25
betas <- t(CAPM.beta(equity.data, market, Rf))
portf.dn <- add.constraint(portf.dn, type="factor_exposure", B=betas, 
                           lower=-0.25, upper=0.25)

Error comes up in the last command and as mentioned in the function factor_exposure_constraint.

Must be something obvious I am missing, so thanks in advance for your help.

1 个答案:

答案 0 :(得分:0)

似乎在第一次看到它已经为时已晚,但投资组合分析的头文件在vingette @

中陈述

http://cran.r-project.org/web/packages/PortfolioAnalytics/vignettes/portfolio_vignette.pdf

第2节中的

明确:

  

使用portfolio.spec函数实例化组合对象。   portfolio.spec的主要论据是资产,这是必需的   论点。 assets参数可以是数字的标量值   资产,基金名称的字符向量,或初始的命名向量   权重。

基于此是我的代码问题,应该如下:

equity.data.names <- colnames(equity.data)
portf.dn <- portfolio.spec(equity.data.names)

换句话说:

  1. 使用资产名称
  2. 创建一个向量
  3. 仅向portfolio.spec
  4. 提供名称向量

    ......一切正常。