16 using System.Collections.Generic;
18 using Accord.Math.Optimization;
19 using Accord.Statistics;
30 private double _lower;
31 private double _upper;
32 private double _riskFreeRate;
44 _riskFreeRate = riskFreeRate;
54 return new LinearConstraint(size)
56 CombinedAs = Vector.Create(size, 1.0),
57 ShouldBe = ConstraintType.EqualTo,
69 for (
int i = 0; i < size; i++)
71 yield
return new LinearConstraint(1)
73 VariablesAtIndices =
new int[] { i },
74 ShouldBe = ConstraintType.GreaterThanOrEqualTo,
77 yield
return new LinearConstraint(1)
79 VariablesAtIndices =
new int[] { i },
80 ShouldBe = ConstraintType.LesserThanOrEqualTo,
93 public double[]
Optimize(
double[,] historicalReturns,
double[] expectedReturns =
null,
double[,] covariance =
null)
95 covariance = covariance ?? historicalReturns.Covariance();
96 var returns = (expectedReturns ?? historicalReturns.Mean(0)).Subtract(_riskFreeRate);
98 var size = covariance.GetLength(0);
99 var x0 = Vector.Create(size, 1.0 / size);
100 var k = returns.Dot(x0);
102 var constraints =
new List<LinearConstraint>
107 new LinearConstraint(size)
109 CombinedAs = returns,
110 ShouldBe = ConstraintType.EqualTo,
122 var optfunc =
new QuadraticObjectiveFunction(covariance, Vector.Create(size, 0.0));
123 var solver =
new GoldfarbIdnani(optfunc, constraints);
126 var success = solver.Minimize(Vector.Copy(x0));
127 var sharpeRatio = returns.Dot(solver.Solution) / solver.Value;
128 return success ? solver.Solution : x0;