Skip to content
All library documents

Finding Risk-Parity Weights with Nelder–Mead Optimization

Article Quant Q&A · Author: Eduardo Sahione

Summary

The document describes a two-asset risk-parity objective: compute each asset’s share of portfolio variance from its weight and the covariance matrix, then minimize the distance between those shares and equal contributions. The initial attempt uses a constrained nonlinear optimizer and reports a null error when solving. The author’s accepted workaround switches to the Nelder–Mead method, initializes the weights equally, and minimizes the same distance function.

The example provides C# code and reports optimizer diagnostics such as estimated error, iterations, and function evaluations, but it does not report the resulting weights or compare runtimes. The example also changes the covariance matrix between the initial and final versions, so it does not isolate the optimizer change. Nelder–Mead is presented as a practical workaround rather than a demonstrated faster or generally superior method; the objective as shown also does not enforce portfolio weight constraints such as nonnegativity or weights summing to one.

Key ideas

  • Risk parity seeks weights that give portfolio components equal contributions to total variance.
  • The example calculates variance contributions using the covariance matrix and asset weights.
  • The author replaces a constrained nonlinear solver with Nelder–Mead to minimize the contribution-distance objective.
  • The example does not establish that Nelder–Mead is faster or that the resulting weights satisfy portfolio constraints.

Tags

Full text
# Risk-Parity Portfolio Optimization using Extreme Optimization in C#


# Risk-Parity Portfolio Optimization using Extreme Optimization in C#












I'm trying to create a risk-parity portfolio in C# using the Extreme Optimization routines.

I'm mostly trying them out to see if I like them or not before I buy them (I'm a student so money is tight).

My idea was to implement this new kind of portfolio optimization called risk-parity. It basically says that in order to diversify your portfolio you should give equal risk to each of its components.

I'm getting a null error when running `np1.Solve()` and I don't understand why. I thought that everything else was calculated by Extreme Optimization.

- What am I doing wrong?

- Is there a faster way to do this optimization that I'm not aware of?

- If you don't know the EO Libraries, but could implement this with something else, could you please drop a comment on how you would go about solving this?

By the way, the details on the portfolio construction are in the comments of the distance function, in case you're interested.

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Extreme.Statistics;
using Extreme.Mathematics;
using Extreme.Mathematics.Optimization;

namespace TestingRiskParityOptimization
{
    class Program
    {

        static void Main(string[] args)
        {

            NonlinearProgram np1 = new NonlinearProgram(2);
            Func<Vector, double> distance = DistanceFunction;
            np1.ObjectiveFunction = distance;
            np1.InitialGuess = Vector.CreateConstant(2, 1.0 / ((double)2));

            np1.AddNonlinearConstraint(x => x[0] + x[1], ConstraintType.GreaterThanOrEqual, 0);
            Vector solution = np1.Solve();

            Console.WriteLine("Solution: {0:F6}", solution);
            Console.WriteLine("Optimal value:   {0:F6}", np1.OptimalValue);
            Console.WriteLine("# iterations: {0}", np1.SolutionReport.IterationsNeeded);

            Console.Write("Press Enter key to exit...");
            Console.ReadLine();

        }

        private static double DistanceFunction(Vector Weights)
        {
            Matrix Sigma = Matrix.Create(new double[,] {
                  {0.1, 0.2},
                  {0.2, 0.4}
                });
            // if VarP = Weights' * CovarMatrix * Weights and VolP = sqrt(VarP)
            // Then the marginal contribution to risk of an asset is the i-th number of
            // Sigma*Weights*VolP
            // And thus the contribution to risk of an asset is simply Weights . (Sigma*Weights/VarP)
            // we need to find weights such that Weights (i) * Row(i) of (Sigma*Weights/VarP) = 1/N

            // that is we want to minimize the distance of row vector (Weights (i) * Row(i) of (Sigma*Weights/VarP)) and vector 1/N

            double Variance = Vector.DotProduct(Weights, Sigma * Weights);

            Vector Beta = Sigma * Weights / Variance;

            for (int i = 0; i < Beta.Length; i++)
            {
                // multiplies row of beta by weight to find the percent contribution to risk
                Beta[i] = Weights[i] * Beta[i];
            }

            Vector ObjectiveVector = Vector.CreateConstant(Weights.Length, 1.0 / ((double)Weights.Length));
            Vector Distance = Vector.Subtract(Beta, ObjectiveVector);

            return Math.Sqrt(Vector.DotProduct(Distance, Distance));

        }
    }
}
```

## Answer by Eduardo Sahione (score 2, accepted)

https://quant.stackexchange.com/a/3820

In case anyone is interested, I solved it using Nelder-Mead's algorithm instead. The performance could be better, but I didn't want to waste any more time in it.

Here's the final solution:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Extreme.Statistics;
using Extreme.Mathematics;
using Extreme.Mathematics.Optimization;

namespace TestingRiskParityOptimization
{
    class Program
    {

        static void Main(string[] args)
        {
            Func<Vector, double> distance = DistanceFunction;

            NelderMeadOptimizer nm1 = new NelderMeadOptimizer();
            nm1.ObjectiveFunction = DistanceFunction;
            nm1.ContractionFactor = 0.5;
            nm1.ExpansionFactor = 2;
            nm1.ReflectionFactor = -2;
            nm1.SolutionTest.AbsoluteTolerance = 1e-15;
            nm1.InitialGuess = Vector.CreateConstant(2, 1.0 / ((double)2));
            nm1.ExtremumType = ExtremumType.Minimum;
            Vector solution = nm1.FindExtremum();

            Console.WriteLine("Solution: {0:F6}", solution);
            Console.WriteLine("  Estimated error: {0}", nm1.EstimatedError);
            Console.WriteLine("  # iterations: {0}", nm1.IterationsNeeded);
            Console.WriteLine("  # function evaluations: {0}", nm1.EvaluationsNeeded);
            Console.Write("Press Enter key to exit...");
            Console.ReadLine();

        }

        private static double DistanceFunction(Vector Weights)
        {
            Matrix Sigma = Matrix.Create(new double[,] {
                  {0.1, 0.23},
                  {0.23, 0.7}
                });
            // if VarP = Weights' * CovarMatrix * Weights and VolP = sqrt(VarP)
            // Then the marginal contribution to risk of an asset is the i-th number of
            // Sigma*Weights*VolP
            // And thus the contribution to risk of an asset is simply Weights . (Sigma*Weights/VarP)
            // we need to find weights such that Weights (i) * Row(i) of (Sigma*Weights/VarP) = 1/N

            // that is we want to minimize the distance of row vector (Weights (i) * Row(i) of (Sigma*Weights/VarP)) and vector 1/N

            double Variance = Vector.DotProduct(Weights, Sigma * Weights);

            Vector Beta = Sigma * Weights / Variance;

            for (int i = 0; i < Beta.Length; i++)
            {
                // multiplies row of beta by weight to find the percent contribution to risk
                Beta[i] = Weights[i] * Beta[i];
            }

            Vector ObjectiveVector = Vector.CreateConstant(Weights.Length, 1.0 / ((double)Weights.Length));
            Vector Distance = Vector.Subtract(Beta, ObjectiveVector);

            return Math.Sqrt(Vector.DotProduct(Distance, Distance));

        }
    }
}
```

Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.