gpt4 book ai didi

java - 如何构建迭代器来获取列表中所有可能的组合

转载 作者:行者123 更新时间:2023-12-02 06:13:52 25 4
gpt4 key购买 nike

我正在尝试计算股票投资组合的方差。为了实现这一目标,我需要计算 Assets 之间的加权协方差。我有一个类,其中包括一个用于存储投资组合中每种 Assets 权重的字段和一个用于存储计算的股票 yield 列表的字段。到目前为止,我已经构建了一个辅助函数来遍历 Assets 列表并使用 apache.commons.math3 库执行一部分计算(请参阅下面的代码)。然而,这显然是错误的,因为他没有包括所有可能的 Assets 组合。我已经研究过 apache.commons CombinationsIterator,但我不确定如何实现它。任何帮助将不胜感激。

private double getPortfolioVariance(double portfolioVariance, List<AssetDto> assets, int historyLength) {
for (int i = 0; i < assets.size() - 1; i++) {
double weight = assets.get(i).getWeight() / 100;
double weightOther = assets.get(i + 1).getWeight() / 100;
if (assets.get(i).getStockReturns() != null && assets.get(i + 1) != null) {
List<Double> returns = assets.get(i).getStockReturns().stream().limit(historyLength).collect(Collectors.toList());
List<Double> returnsOther = assets.get(i).getStockReturns().stream().limit(historyLength).collect(Collectors.toList());
Covariance covariance = new Covariance();
double assetsCovariance = covariance.
covariance(returns.stream().mapToDouble(Double::doubleValue).toArray(),
returnsOther.stream().mapToDouble(Double::doubleValue).toArray());
portfolioVariance += 2 * weight * weightOther * assetsCovariance;
}
}
return portfolioVariance;
}

最佳答案

您可以使用 commons-math3 中的 CombinatoricsUtils 类项目。实用方法combinationsIterator创建一个迭代器,它产生n到k的所有组合而不重复。下面的例子:

private double getPortfolioVariance(double portfolioVariance, List<AssetDto> assets, int historyLength) {
Iterator<int[]> iterator = CombinatoricsUtils.combinationsIterator(assets.size(), 2);
while (iterator.hasNext()) {
final int[] combination = iterator.next();
AssetDto firstAsset = assets.get(combination[0]);
AssetDto otherAsset = assets.get(combination[1]);

double weight = firstAsset.getWeight() / 100;
double weightOther = otherAsset.getWeight() / 100;

if (firstAsset.getStockReturns() != null && otherAsset != null) {
List<Double> returns = firstAsset.getStockReturns().stream().limit(historyLength).collect(Collectors.toList());
List<Double> returnsOther = otherAsset.getStockReturns().stream().limit(historyLength).collect(Collectors.toList());
Covariance covariance = new Covariance();
double assetsCovariance = covariance.
covariance(returns.stream().mapToDouble(Double::doubleValue).toArray(),
returnsOther.stream().mapToDouble(Double::doubleValue).toArray());
portfolioVariance += 2 * weight * weightOther * assetsCovariance;
}
}
return portfolioVariance;
}

关于java - 如何构建迭代器来获取列表中所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com