You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言DEoptim包返回结果不一致问题求助

问题

使用DEoptim工具做投资组合优化,通过最小化夏普比率的倒数等价实现最大化夏普比率,但多次运行后,sol$optim$bestmem返回的最优权重向量不一致,希望每次运行得到相同结果。相关代码如下:

# Computing the covariance matrix and returns to be used in the optimization
covMat <- cov(dft[idx_window_begin:idx_window_end,returns])
Returns <- colMeans(dft[idx_window_begin:idx_window_end,returns])

# Sharpe ratio function to be used in the DEoptim function
port_sharpe <- function(W) {
  W <- W/sum(W)
  return(as.numeric((W%*%covMat%*%W)^0.5/(W%*%Returns)))
}

# Calling DEoptim
sol <- DEoptim(port_sharpe, lower=rep(-100,nrow(covMat)), upper=rep(100,nrow(covMat)))
解决方法
  • 固定随机种子:DEoptim是基于随机进化的优化算法,每次运行的初始种群由随机数生成,这是结果不一致的核心原因。在调用DEoptim前设置固定随机种子,就能让每次运行的随机序列完全相同,从而得到一致的结果。
    示例代码中添加种子设置:
    set.seed(123) # 可替换为任意整数,只要固定即可
    
  • 验证最优解唯一性:如果存在多个权重组合能达到相同的最大夏普比率,即使固定种子,结果也可能有差异(但这种场景不多)。可以计算不同权重对应的夏普比率,若数值一致,说明是多解情况,可添加额外约束(比如最小化权重绝对值之和)来唯一化解。
  • 优化算法参数:适当增加迭代次数(iter参数)或种群规模(NP参数),能提升算法收敛到全局最优的稳定性,但前提还是要固定随机种子保证可复现。

修改后的完整代码示例:

# 设置固定随机种子
set.seed(456)

# Computing the covariance matrix and returns to be used in the optimization
covMat <- cov(dft[idx_window_begin:idx_window_end,returns])
Returns <- colMeans(dft[idx_window_begin:idx_window_end,returns])

# Sharpe ratio function to be used in the DEoptim function
port_sharpe <- function(W) {
  W <- W/sum(W)
  return(as.numeric((W%*%covMat%*%W)^0.5/(W%*%Returns)))
}

# Calling DEoptim
sol <- DEoptim(port_sharpe, lower=rep(-100,nrow(covMat)), upper=rep(100,nrow(covMat)))

内容的提问来源于stack exchange,提问作者KaiSqDist

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:47:14