public class PortfolioUtils extends Object
These methods evaluate supplied weights; they do not normalize or optimize them. Asset order and dimensions must agree. Returns and covariance must use the same horizon and units. Variance is in squared-return units; its square root is volatility. Scaling weights also scales exposure and risk, so a sum-to-one check belongs in the calling portfolio workflow.
For two uncorrelated assets, portfolio variance is the sum of squared weights times individual variances.
import dev.nm.algebra.linear.matrix.doubles.matrixtype.dense.DenseMatrix;
import dev.nm.algebra.linear.vector.doubles.dense.DenseVector;
import tech.nmfin.portfoliooptimization.PortfolioUtils;
DenseVector weights = new DenseVector(0.6, 0.4);
DenseVector expectedReturns = new DenseVector(0.05, 0.10);
DenseMatrix covariance = new DenseMatrix(new double[][]{{0.04, 0}, {0, 0.09}});
double expectedReturn = PortfolioUtils.getPortfolioReturns(weights, expectedReturns);
double variance = PortfolioUtils.getPortfolioVariance(weights, covariance);
assert Math.abs(expectedReturn - 0.07) < 1e-12;
assert Math.abs(variance - 0.0288) < 1e-12;
assert Math.abs(Math.sqrt(variance) - 0.1697056274847714) < 1e-12;
| Modifier and Type | Method and Description |
|---|---|
static double |
getPortfolioReturns(Vector weights,
Vector mu)
Computes the expected portfolio return.
|
static double |
getPortfolioVariance(Vector weights,
Matrix sigma)
Computes the portfolio variance.
|
static double |
getSharpeRatio(Vector weights,
Vector mu,
Matrix sigma,
double benchmarkRate)
Computes the portfolio Sharpe ratio.
|
public static double getPortfolioReturns(Vector weights, Vector mu)
weights - the weights of assetsmu - the expected returns of assetspublic static double getPortfolioVariance(Vector weights, Matrix sigma)
weights - the weights of assetssigma - the covariances of assetspublic static double getSharpeRatio(Vector weights, Vector mu, Matrix sigma, double benchmarkRate)
weights - the weights of assetsmu - the expected returns of assetssigma - the covariances of assetsbenchmarkRate - the risk free/benchmark rateCopyright © 2010-2026 NM Group. All Rights Reserved.