【问题标题】:Passing optimization function arguments in R DEoptim在 R DEoptim 中传递优化函数参数
【发布时间】:2019-01-24 16:16:31
【问题描述】:

我正在尝试学习 R 中的 DEoptim 库,但我认为我误解了来自

的库文档

https://www.rdocumentation.org/packages/DEoptim/versions/2.2-4/topics/DEoptim

当我尝试下面的代码时,我收到了错误 argument "returns_covar" is missing, with no default

我要优化(最小化)的功能是:

calculate_portfolio_variance <- function(allocations, returns_covar)
{
  # Name: calculate_portfolio_variance
  # Purpose: Computes expected portfolio variance, to be used as the minimization objective function
  # Input: allocations = vector of allocations to be adjusted for optimality; returns_covar = covariance matrix of stock returns
  # Output: Expected portfolio variance

  portfolio_variance <- allocations%*%returns_covar%*%t(allocations)
  return(portfolio_variance)
}

filter_and_sort_symbols <- function(symbols)
{
  # Name: filter_and_sort_symbols
  # Purpose: Convert to uppercase if not
  # and remove any non valid symbols
  # Input: symbols = vector of stock tickers
  # Output: filtered_symbols = filtered symbols

  # convert symbols to uppercase
  symbols <- toupper(symbols)

  # Validate the symbol names
  valid <- regexpr("^[A-Z]{2,4}$", symbols)

  # Return only the valid ones
  return(sort(symbols[valid == 1]))
}

# Create the list of stock tickers and check that they are valid symbols
tickers <- filter_and_sort_symbols(c("XLE", "XLB", "XLI", "XLY", "XLP", "XLV", "XLK", "XLU", "SHY", "TLT"))
# Set the start and end dates
start_date <- "2013-01-01"
end_date <- "2014-01-01"

# Gather the stock data using quantmod library
getSymbols(Symbols=tickers, from=start_date, to=end_date, auto.assign = TRUE)

# Create a matrix of only the adj. prices
price_matrix <- NULL
for(ticker in tickers){price_matrix <- cbind(price_matrix, get(ticker)[,6])}
# Set the column names for the price matrix
colnames(price_matrix) <- tickers

# Compute log returns
returns_matrix <- apply(price_matrix, 2, function(x) diff(log(x)))
returns_covar <- cov(returns_matrix)

# Specify lower and upper bounds for the allocation percentages
lower <- rep(0, ncol(returns_matrix))
upper <- rep(1, ncol(returns_matrix))

# Calculate the optimum allocation; THIS CAUSES AN ERROR
set.seed(1234)
optim_result <- DEoptim(calculate_portfolio_variance, lower, upper, control = list(NP=100, itermax=300, F=0.8, CR=0.9, allocations, returns_covar))

最后一行的错误是缺少returns_covar 参数,但我尝试将其传递给DEoptim() 函数。

我认为上面有括号错误,所以我尝试了以下

optim_result <- DEoptim(calculate_portfolio_variance, lower, upper, control = list(NP=100, itermax=300, F=0.8, CR=0.9), returns_covar)

这会导致以下错误:

Error in allocations %*% returns_covar %*% t(allocations) : non-conformable arguments

当我检查矩阵的维度时,一切似乎都正常

> dim(allocations)
[1]  1 10
> dim(returns_covar)
[1] 10 10

calculate_portfolio_variance() 函数中添加维度检查

  print(dim(allocations))
  print(dim(returns_covar))

显示分配向量在第二次迭代时变为NULL。我不知道为什么或如何解决它。

[1]  1 10
[1] 10 10
NULL
[1] 10 10
Error in allocations %*% returns_covar %*% t(allocations) : non-conformable arguments

【问题讨论】:

    标签: r matrix optimization differential-evolution deoptimization


    【解决方案1】:

    不清楚这是否是您想要的,但如果您将calculate_portfolio_variance 更改为

      portfolio_variance <- t(allocations)%*%returns_covar%*%allocations
    

    它对我有用。我认为这是您的矩阵数学的问题。

    编辑完整的工作可重现示例:

    library(quantmod)
    library(DEoptim)
    
    
    calculate_portfolio_variance <- function(allocations, returns_covar)
    {
      # Name: calculate_portfolio_variance
      # Purpose: Computes expected portfolio variance, to be used as the minimization objective function
      # Input: allocations = vector of allocations to be adjusted for optimality; returns_covar = covariance matrix of stock returns
      # Output: Expected portfolio variance
    
      ### I CHANGED THIS LINE
      #portfolio_variance <- allocations%*%returns_covar%*%t(allocations)
      portfolio_variance <- t(allocations)%*%returns_covar%*%allocations
      return(portfolio_variance)
    }
    
    filter_and_sort_symbols <- function(symbols)
    {
      # Name: filter_and_sort_symbols
      # Purpose: Convert to uppercase if not
      # and remove any non valid symbols
      # Input: symbols = vector of stock tickers
      # Output: filtered_symbols = filtered symbols
    
      # convert symbols to uppercase
      symbols <- toupper(symbols)
    
      # Validate the symbol names
      valid <- regexpr("^[A-Z]{2,4}$", symbols)
    
      # Return only the valid ones
      return(sort(symbols[valid == 1]))
    }
    
    # Create the list of stock tickers and check that they are valid symbols
    tickers <- filter_and_sort_symbols(c("XLE", "XLB", "XLI", "XLY", "XLP", "XLV", "XLK", "XLU", "SHY", "TLT"))
    # Set the start and end dates
    start_date <- "2013-01-01"
    end_date <- "2014-01-01"
    
    # Gather the stock data using quantmod library
    getSymbols(Symbols=tickers, from=start_date, to=end_date, auto.assign = TRUE)
    
    # Create a matrix of only the adj. prices
    price_matrix <- NULL
    for(ticker in tickers){price_matrix <- cbind(price_matrix, get(ticker)[,6])}
    # Set the column names for the price matrix
    colnames(price_matrix) <- tickers
    
    # Compute log returns
    returns_matrix <- apply(price_matrix, 2, function(x) diff(log(x)))
    returns_covar <- cov(returns_matrix)
    
    # Specify lower and upper bounds for the allocation percentages
    lower <- rep(0, ncol(returns_matrix))
    upper <- rep(1, ncol(returns_matrix))
    
    # Calculate the optimum allocation
    set.seed(1234)
    ### USING YOUR CORRECTED CALL
    optim_result <- DEoptim(calculate_portfolio_variance, lower, upper, control = list(NP=100, itermax=300, F=0.8, CR=0.9), returns_covar)
    

    【讨论】:

    • 您的意思是只修改calculate_portfolio_variance() 内的行吗?我用你的建议替换了它,但仍然得到相同的non-conformable arguments 错误。我同意,矩阵数学似乎存在问题,但我还没有确定它在哪里。当我使用str(lower) 时,它会显示一个正确长度的向量,使用dim(lower) 会显示NULL
    • 对于它的价值,当我在控制台中执行 portfolio_variance &lt;- allocations%*%returns_covar%*%t(allocations) 时,它计算正确。但是当我在控制台中执行portfolio_variance &lt;- t(allocations)%*%returns_covar%*%allocations 时,我得到一个non-conformable arguments 错误
    • @coolhand 我更新了我的答案以包含一个可重复的工作示例。
    • 它对我有用,谢谢!你知道这个问题是否是操作顺序问题吗?
    • @coolhand 有点像,因为allocations 是一个向量,您需要注意转置的位置。请参阅?matmult 了解更多信息。 %*% 似乎会自动尝试转置向量以使乘法工作,但您在右侧显式转置了 allocations。有趣的是,省略转置而只做allocations%*%returns_covar%*%allocations 也可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多