/// <summary>
        /// Attempts a calibration through <see cref="PelsserCappletOptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null)
        {
            InterestRateMarketData dataset   = data[0] as InterestRateMarketData;
            MatrixMarketData       normalVol = null;

            if (data.Count > 1)
            {
                normalVol = (MatrixMarketData)data[1];
            }
            EstimationResult result;

            if ((dataset.ZRMarket == null) || (dataset.CapVolatility == null))
            {
                result = new EstimationResult();
                result.ErrorMessage = "Not enough data to calibrate.\n" +
                                      "The estimator needs a ZRMarket and a CapVolatility " +
                                      "defined inside InterestRateMarketData";
                return(result);
            }

            // Backup the dates
            DateTime effectiveDate = DateTime.Now.Date;
            DateTime valuationDate = DateTime.Now.Date;

            if (Document.ActiveDocument != null)
            {
                effectiveDate = Document.ActiveDocument.ContractDate;
                valuationDate = Document.ActiveDocument.SimulationStartDate;
            }

            // Creates the Context.
            Document   doc = new Document();
            ProjectROV prj = new ProjectROV(doc);

            doc.Part.Add(prj);

            Function zr = new PFunction(null);

            zr.VarName = "zr";
            // Load the zr.
            double[,] zrvalue = (double[, ])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr           = zrvalue;

            prj.Symbols.Add(zr);


            var bm = BlackModelFactory(zr);

            if (bm is BachelierNormalModel)
            {
                (bm as BachelierNormalModel).Tenor = dataset.CapTenor;
            }

            double deltak = dataset.CapTenor;


            Matrix capVol = normalVol != null ? normalVol.Values:dataset.CapVolatility;
            Vector capMat = normalVol != null ? normalVol.RowValues: dataset.CapMaturity;
            Vector capK   = normalVol != null ? normalVol.ColumnValues: dataset.CapRate;

            var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering;

            // Matrix calculated with black.
            var blackCaps = new Matrix(capMat.Length, capK.Length);

            for (int m = 0; m < capMat.Length; m++)
            {
                for (int s = 0; s < capK.Length; s++)
                {
                    bool skip = false;
                    if (preferences != null)
                    {
                        if (capK[s] < preferences.MinCapRate || capK[s] > preferences.MaxCapRate ||
                            capMat[m] < preferences.MinCapMaturity || capMat[m] > preferences.MaxCapMaturity)
                        {
                            skip = true;
                        }
                    }

                    if (capVol[m, s] == 0 || skip)
                    {
                        blackCaps[m, s] = 0;
                    }
                    else
                    {
                        blackCaps[m, s] = bm.Cap(capK[s], capVol[m, s], deltak, capMat[m]);
                    }
                }
            }

            if (blackCaps.IsNaN())
            {
                Console.WriteLine("Black caps matrix has non real values:");
                Console.WriteLine(blackCaps);
                throw new Exception("Cannot calculate Black caps");
            }

            // Maturity goes from 0 to the last item with step deltaK.
            Vector maturity = new Vector((int)(1.0 + capMat[capMat.Length - 1] / deltak));

            for (int l = 0; l < maturity.Length; l++)
            {
                maturity[l] = deltak * l;
            }

            Vector fwd = new Vector(maturity.Length - 1);

            for (int i = 0; i < fwd.Length; i++)
            {
                fwd[i] = bm.Fk(maturity[i + 1], deltak);
            }

            // Creates a default Pelsser model.
            Pelsser.SquaredGaussianModel model = new Pelsser.SquaredGaussianModel();
            model.a1     = (ModelParameter)0.014;
            model.sigma1 = (ModelParameter)0.001;
            model.zr     = (ModelParameter)"@zr";
            StochasticProcessExtendible iex = new StochasticProcessExtendible(prj, model);

            prj.Processes.AddProcess(iex);

            prj.Parse();

            DateTime t0 = DateTime.Now;
            Caplet   cp = new Caplet();

            PelsserCappletOptimizationProblem problem = new PelsserCappletOptimizationProblem(prj, cp, maturity, fwd, capK, deltak, capMat, blackCaps);

            IOptimizationAlgorithm solver  = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();

            o.NP         = 35;
            o.TargetCost = 0.0025;
            o.MaxIter    = 10;
            o.Verbosity  = Math.Max(1, Engine.Verbose);
            o.controller = controller;
            // Parallel evaluation is not supported for this calibration.
            o.Parallel = false;
            o.Debug    = true;
            SolutionInfo solution = null;

            Vector x0 = (Vector) new double[] { 0.1, 0.1 };

            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }

            o.epsilon   = 10e-7;
            o.h         = 10e-7;
            o.MaxIter   = 1000;
            o.Debug     = true;
            o.Verbosity = Math.Max(1, Engine.Verbose);

            if (solution != null)
            {
                solution = solver2.Minimize(problem, o, solution.x);
            }
            else
            {
                solution = solver2.Minimize(problem, o, x0);
            }

            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }

            Console.WriteLine(solution);

            string[] names = new string[] { "alpha1", "sigma1" };
            result = new EstimationResult(names, solution.x);

            result.ZRX        = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY        = (double[])dataset.ZRMarket.ToArray();
            result.Objects    = new object[1];
            result.Objects[0] = solution.obj;
            //result.Fit = solution.obj;//Uncomment in 1.6
            // Restore the dates
            if (Document.ActiveDocument != null)
            {
                Document.ActiveDocument.ContractDate        = effectiveDate;
                Document.ActiveDocument.SimulationStartDate = valuationDate;
            }

            return(result);
        }
Exemplo n.º 2
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SteepestDescent obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            double oneOver2Pi = 1.0 / (1.0 * Math.Sqrt(2 * Math.PI));

            Console.WriteLine(NormalCDFInverse(0.99));
            Console.WriteLine(inv_cdf(0.99));
            Console.WriteLine(InverseCDF.QNorm(0.99, 0, 1, true, false));
            Console.WriteLine(NormalCDFInverse(0.5));
            Console.WriteLine(inv_cdf(0.5));
            Console.WriteLine(InverseCDF.QNorm(0.5, 0, 1, true, false));
            Console.WriteLine(NormalCDFInverse(0.31));
            Console.WriteLine(inv_cdf(0.31));
            Console.WriteLine(InverseCDF.QNorm(0.31, 0, 1, true, false));

            //x4−8x2 + 5
            Func <double[], double> testFunc1 = (x) =>
            {
                return(Math.Pow(x[0], 4) - 8 * Math.Pow(x[0], 2) + 5);
            };

            Func <double[], double>[] dtestFunc1 = new Func <double[], double> [1];

            dtestFunc1[0] = (x) =>
            {
                return(4 * Math.Pow(x[0], 3) - 16 * x[0]);
            };

            Func <double[], double> testConstr = (x) =>
            {
                return(5 - Math.Exp(x[0]) + 2.0 * Math.Pow(x[0] - 1, 2));
            };

            Func <double[], double> testv = (x) =>
            {
                double a = x[0];
                return(0.0);
            };

            //Func<Variables, double> testFunc = (x) => {
            //    return Math.Pow(x.Vars[0], 4) - 3 * Math.Pow(x.Vars[0], 3) + 2;
            //};

            //Func<Variables, double> dTestfunc = (x) =>
            //{
            //    return 4 * Math.Pow(x.Vars[0], 3) - 9 * Math.Pow(x.Vars[0], 2);
            //};

            //x4−3x3 + 2

            //TestFunc();

            Func <double[], double> bananaFunc = (x) =>
            {
                return(Math.Pow(1 - x[0], 2) + 100 * Math.Pow(x[1] - x[0] * x[0], 2));
            };

            Func <double[], double> powell = (x) =>
            {
                return(Math.Pow(x[0] + 10 * x[1], 2) +
                       5 * Math.Pow(x[2] - x[3], 2) +
                       Math.Pow(x[1] + 2 * x[2], 4) +
                       10 * Math.Pow(x[0] - x[3], 4));
            };

            OptVector[] ttt = new OptVector[3];
            ttt[0] = new OptVector(new double[3] {
                1, 2, 3
            });
            ttt[1] = new OptVector(new double[3] {
                4, 5, 6
            });
            ttt[2] = new OptVector(new double[3] {
                7, 8, 9
            });

            var tr = OptVector.Transpose(ttt);

            //TestsSQP.Test0();
            TestsSQP.Test1();
            TestsSQP.Test2();
            TestsSQP.Test3();
            ////TestsSQP.Test4();
            ////TestsSQP.Test5();
            TestsSQP.Test6();
            TestsSQP.Test7();
            TestsSQP.Test8();
            TestsSQP.Test9();
            TestsSQP.Test10();
            TestsSQP.Test11();
            TestsSQP.Test12();
            TestsSQP.Test13();
            TestsSQP.Test14();
            TestsSQP.Test15();
            TestsSQP.Test16();
            TestsSQP.Test17();
            TestsSQP.Test18();
            TestsSQP.Test19();
            TestsSQP.Test20();
            TestsSQP.Test21();
            TestsSQP.Test22();
            TestsSQP.Test23();
            TestsSQP.Test24();
            TestsSQP.Test25();
            TestsSQP.Test26();
            TestsSQP.Test27();
            TestsSQP.Test28();
            //TestCGMethod();

            BFGS bfsg = new BFGS();

            var result0 = bfsg.Solve(powell, new double[] { 3.0, -1.0, 0.0, 1.0 }, 10000);

            Console.WriteLine("Min " + powell(result0));

            NLCG gradient = new NLCG();

            var result = gradient.Solve(powell, new double[] { 3.0, -1.0, 0.0, 1.0 }, 4000);

            Console.WriteLine("Min " + powell(result));

            SteepestDescent gradientSteep = new SteepestDescent();

            var result1 = gradientSteep.Solve(powell, new double[] { 3.0, -1.0, 0.0, 1.0 }, 10000);

            Console.WriteLine("Min " + powell(result1));

            //Variables result = SteepestDescent(testFunc, dTestFunc, 2, 20);

            for (int i = 0; i < result.Length; i++)
            {
                Console.WriteLine("result " + result[i]);
            }

            //Console.WriteLine("ver " + testFunc(result));

            Console.ReadLine();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Attempts a calibration through <see cref="SwaptionHW1OptimizationProblem"/>
        /// using swaption matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null)
        {
            InterestRateMarketData dataset   = data[0] as InterestRateMarketData;
            MatrixMarketData       normalVol = null;

            if (data.Count > 1)
            {
                normalVol = (MatrixMarketData)data[1];
            }

            PFunction zr = new PFunction(null);

            // Loads the zero rate.
            double[,] zrvalue = (double[, ])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr           = zrvalue;

            double deltak = dataset.SwaptionTenor;

            Console.WriteLine("Swaption Tenor\t" + dataset.SwaptionTenor);

            var swaptionsFiltering = settings as SwaptionsFiltering;

            if (swaptionsFiltering == null)
            {
                swaptionsFiltering = new SwaptionsFiltering();//creates a default
            }
            //F stands for Full matrix
            var optionMaturityF      = normalVol != null ? normalVol.RowValues: dataset.OptionMaturity;
            var swapDurationF        = normalVol != null ? normalVol.ColumnValues: dataset.SwapDuration;
            var swaptionsVolatilityF = normalVol != null ? normalVol.Values: dataset.SwaptionsVolatility;

            int maturitiesCount = optionMaturityF.Count(x => x >= swaptionsFiltering.MinSwaptionMaturity && x <= swaptionsFiltering.MaxSwaptionMaturity);
            int durationsCount  = swapDurationF.Count(x => x >= swaptionsFiltering.MinSwapDuration && x <= swaptionsFiltering.MaxSwapDuration);


            Console.WriteLine(string.Format("Calibrating on {0} swaptions prices [#maturiries x #durations]=[{1} x {2}]", maturitiesCount * durationsCount, maturitiesCount, durationsCount));

            if (maturitiesCount * durationsCount == 0)
            {
                return(new EstimationResult("No swaptions satisfying criteria found, please relax filters"));
            }

            //reduced version
            var swaptionsVolatility = new Matrix(maturitiesCount, durationsCount); // dataset.SwaptionsVolatility;
            var optionMaturity      = new Vector(maturitiesCount);                 // dataset.OptionMaturity;
            var swapDuration        = new Vector(durationsCount);                  // dataset.SwapDuration;


            //Build filtered matrix and vectors
            int fm = 0;

            for (int m = 0; m < optionMaturityF.Length; m++)
            {
                int fd = 0;
                if (optionMaturityF[m] >= swaptionsFiltering.MinSwaptionMaturity && optionMaturityF[m] <= swaptionsFiltering.MaxSwaptionMaturity)
                {
                    for (int d = 0; d < swapDurationF.Length; d++)
                    {
                        if (swapDurationF[d] >= swaptionsFiltering.MinSwapDuration && swapDurationF[d] <= swaptionsFiltering.MaxSwapDuration)
                        {
                            swaptionsVolatility[fm, fd] = swaptionsVolatilityF[m, d];
                            swapDuration[fd]            = swapDurationF[d];
                            fd++;
                        }
                    }

                    optionMaturity[fm] = optionMaturityF[m];
                    fm++;
                }
            }

            var swbm = new SwaptionsBlackModel(zr, BlackModelFactory(zr));

            Matrix fsr;
            var    blackSwaptionPrice = 1000.0 * swbm.SwaptionsSurfBM(optionMaturity, swapDuration, swaptionsVolatility, deltak, out fsr);


            Console.WriteLine("Maturities\t" + optionMaturity);
            Console.WriteLine("swapDuration\t" + swapDuration);
            Console.WriteLine("SwaptionHWEstimator: Black model prices");
            Console.WriteLine(blackSwaptionPrice);

            SwaptionHW1 swhw1 = new SwaptionHW1(zr);
            SwaptionHW1OptimizationProblem problem = new SwaptionHW1OptimizationProblem(swhw1, blackSwaptionPrice, optionMaturity, swapDuration, deltak);

            IOptimizationAlgorithm solver  = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();

            o.NP         = 20;
            o.MaxIter    = 5;
            o.Verbosity  = 1;
            o.controller = controller;
            SolutionInfo solution = null;

            Vector x0 = new Vector(new double[] { 0.1, 0.1 });

            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }

            o.epsilon = 10e-8;
            o.h       = 10e-8;
            o.MaxIter = 1000;

            // We can permit this, given it is fast.
            o.accourate_numerical_derivatives = true;

            if (solution != null)
            {
                solution = solver2.Minimize(problem, o, solution.x);
            }
            else
            {
                solution = solver2.Minimize(problem, o, x0);
            }
            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }
            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = new string[] { "Alpha", "Sigma" };

            Console.WriteLine("SwaptionHWEstimator: hw model prices and error");
            problem.Obj(solution.x, true);

            EstimationResult result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();

            double obj = problem.Obj(solution.x);

            return(result);
        }
        /// <summary>
        /// Attempts a calibration through <see cref="CapsHW1OptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            PFunction zr = new PFunction(null);
            zr.VarName = "zr";

            var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering;

            // Loads ZR
            double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr = zrvalue;

            BlackModel bm = new BlackModel(zr);

            double deltak = dataset.CapTenor;

            if (dataset.CapVolatility == null)
                return new EstimationResult("Cap not available at requested date");

            Matrix capVolatility = dataset.CapVolatility;
            Vector capMaturity = dataset.CapMaturity;
            Vector capRate = dataset.CapRate;
            double a = 0.1;
            double sigma = 0.1;

            // Matrix calculated with Black.
            Matrix blackCaps = new Matrix(capMaturity.Length, capRate.Length);
            Matrix logic = new Matrix(capMaturity.Length, capRate.Length);

            for (int m = 0; m < capMaturity.Length; m++)
            {
                for (int s = 0; s < capRate.Length; s++)
                {
                    blackCaps[m, s] = bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]);
                    if (double.IsNaN(blackCaps[m, s]))
                    {
                        bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]);
                        throw new Exception("Malformed black caps");
                    }

                    if (blackCaps[m, s] == 0.0)
                    {
                        logic[m, s] = 0.0;
                    }
                    else
                    {
                        logic[m, s] = 1.0;
                    }

                    //filter
                    if (preferences != null)
                    {
                        if (capRate[s] < preferences.MinCapRate || capRate[s] > preferences.MaxCapRate ||
                            capMaturity[m]<preferences.MinCapMaturity|| capMaturity[m]>preferences.MaxCapMaturity)
                                {logic[m, s] = 0; blackCaps[m, s] = 0;}
                    }

                }
            }

            DateTime t0 = DateTime.Now;
            CapHW1 hw1Caps = new CapHW1(zr);
            Matrix caps = hw1Caps.HWMatrixCaps(capMaturity, capRate, a, sigma, deltak);

            for (int m = 0; m < capMaturity.Length; m++)
            {
                for (int s = 0; s < capRate.Length; s++)
                {
                    caps[m, s] = logic[m, s] * caps[m, s];
                }
            }

            CapsHW1OptimizationProblem problem = new CapsHW1OptimizationProblem(hw1Caps, blackCaps, capMaturity, capRate, deltak);
            Vector provaparam = new Vector(2);

            var solver = new QADE();

            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 20;
            o.MaxIter = 10;
            o.Verbosity = 1;
            o.Parallel = false;
            SolutionInfo solution = null;
            Vector x0 = new Vector(new double[] { 0.05, 0.01 });
            o.controller = controller;
            solution = solver.Minimize(problem, o, x0);

            o.epsilon = 10e-8;
            o.h = 10e-8;

            o.MaxIter = 100;
            solution = solver2.Minimize(problem, o, solution.x);
            if (solution.errors)
                return new EstimationResult(solution.message);
            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = new string[] { "Alpha", "Sigma" };

            //solution.x[0] *= 3;

            EstimationResult result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();

            return result;
        }
    void Visualize()
    {
        idx         = 0;
        vDataPoints = new List <GameObject>(); // vDataPoints is a list of GameOjbects (prefix 'v' is for visualized)

        // mapping each type to a material index assuming number of unique types is less than number of materials
        int materialIndex = 0;
        Dictionary <string, int> typeToColor = new Dictionary <string, int>();

        foreach (DataPoint dataPoint in dataPoints)
        {
            if (!typeToColor.ContainsKey(dataPoint.type))
            {
                typeToColor.Add(dataPoint.type, materialIndex);
                materialIndex++;
            }
        }

        /*
         * order is a list of datapoints in the order of removal by steepest descent
         * it's easier to imagine order as dataPoints but with a different ordering of elements
         * this order of elements matters because it's the order of the traversal of the visualization method.
         *
         * TODO change from list to array because size is known beforehand
         */
        List <DataPoint> order = new List <DataPoint>();

        while (dataPoints.Any()) // FIXME SteepestDescent returns NaN when there are no unique coordinates in dataPoints
        {
            if (dataPoints.Count == 1)
            {
                order.Add(dataPoints.Last());
                break;
            }

            double init_x = dataPoints[0].x, init_y = dataPoints[0].y; // initial point is first point

            Vector2[] steps = SteepestDescent.Run(dataPoints, init_x, init_y, 0.03, 300);

            int nearest = GetNearest(dataPoints, steps.Last());
            order.Add(dataPoints[nearest]);
            dataPoints.RemoveAt(nearest); // TODO optimize using dictionary or boolean visited array
        }

        // instantiate datapoints
        foreach (DataPoint dataPoint in order)
        {
            double     y        = SteepestDescent.CauchyTotalPotential(order, dataPoint.x, dataPoint.y);
            double     x        = dataPoint.x;
            double     z        = dataPoint.y;
            Vector3    position = new Vector3(XZ_Scale * (float)x, Y_Scale * (float)y, XZ_Scale * (float)z);
            GameObject vPoint   = Instantiate(rockPrefab, position, Quaternion.identity);

            int colorIndex = typeToColor[dataPoint.type];
            vPoint.GetComponent <MeshRenderer>().material = colors[colorIndex];

            vDataPoints.Add(vPoint);
        }

        // instaniate trail
        trail = Instantiate(trailPrefab, Vector3.zero, Quaternion.identity);

        StartCoroutine(Animate());
    }
Exemplo n.º 7
0
        /// <summary>
        /// Attempts a calibration through <see cref="CapsHW1OptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            PFunction zr = new PFunction(null);

            zr.VarName = "zr";

            var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering;

            // Loads ZR
            double[,] zrvalue = (double[, ])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr           = zrvalue;

            BlackModel bm = new BlackModel(zr);

            double deltak = dataset.CapTenor;

            if (dataset.CapVolatility == null)
            {
                return(new EstimationResult("Cap not available at requested date"));
            }


            Matrix capVolatility = dataset.CapVolatility;
            Vector capMaturity   = dataset.CapMaturity;
            Vector capRate       = dataset.CapRate;
            double a             = 0.1;
            double sigma         = 0.1;

            // Matrix calculated with Black.
            Matrix blackCaps = new Matrix(capMaturity.Length, capRate.Length);
            Matrix logic     = new Matrix(capMaturity.Length, capRate.Length);

            for (int m = 0; m < capMaturity.Length; m++)
            {
                for (int s = 0; s < capRate.Length; s++)
                {
                    blackCaps[m, s] = bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]);
                    if (double.IsNaN(blackCaps[m, s]))
                    {
                        bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]);
                        throw new Exception("Malformed black caps");
                    }

                    if (blackCaps[m, s] == 0.0)
                    {
                        logic[m, s] = 0.0;
                    }
                    else
                    {
                        logic[m, s] = 1.0;
                    }

                    //filter
                    if (preferences != null)
                    {
                        if (capRate[s] < preferences.MinCapRate || capRate[s] > preferences.MaxCapRate ||
                            capMaturity[m] < preferences.MinCapMaturity || capMaturity[m] > preferences.MaxCapMaturity)
                        {
                            logic[m, s] = 0; blackCaps[m, s] = 0;
                        }
                    }
                }
            }

            DateTime t0      = DateTime.Now;
            CapHW1   hw1Caps = new CapHW1(zr);
            Matrix   caps    = hw1Caps.HWMatrixCaps(capMaturity, capRate, a, sigma, deltak);

            for (int m = 0; m < capMaturity.Length; m++)
            {
                for (int s = 0; s < capRate.Length; s++)
                {
                    caps[m, s] = logic[m, s] * caps[m, s];
                }
            }

            CapsHW1OptimizationProblem problem = new CapsHW1OptimizationProblem(hw1Caps, blackCaps, capMaturity, capRate, deltak);
            Vector provaparam = new Vector(2);

            var solver = new QADE();

            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();

            o.NP        = 20;
            o.MaxIter   = 10;
            o.Verbosity = 1;
            o.Parallel  = false;
            SolutionInfo solution = null;
            Vector       x0       = new Vector(new double[] { 0.05, 0.01 });

            o.controller = controller;
            solution     = solver.Minimize(problem, o, x0);

            o.epsilon = 10e-8;
            o.h       = 10e-8;


            o.MaxIter = 100;
            solution  = solver2.Minimize(problem, o, solution.x);
            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }
            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = new string[] { "Alpha", "Sigma" };


            //solution.x[0] *= 3;

            EstimationResult result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();

            return(result);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Attempts to solve the Heston optimization problem using
        /// <see cref="Heston.HestonOptimizationProblem"/>.
        /// </summary>
        /// <param name="marketData">Data to be used in order to perform the optimization.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">IController.</param>
        /// <returns>The results of the optimization.</returns>
        public EstimationResult Estimate(List <object> marketData, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null)
        {
            DateTime              t0 = DateTime.Now;
            var                   interestDataSet = (CurveMarketData)marketData[0];
            CallPriceMarketData   callDataSet     = (CallPriceMarketData)marketData[1];
            EquityCalibrationData equityCalData   = new EquityCalibrationData(callDataSet, interestDataSet);
            var                   spotPrice       = (DVPLI.MarketDataTypes.Scalar)marketData[2];


            Setup(equityCalData, settings);

            var calSettings = settings as HestonCalibrationSettings;
            // Creates the context.
            Document   doc = new Document();
            ProjectROV prj = new ProjectROV(doc);

            doc.Part.Add(prj);

            // Optimization problem instance.
            Vector matBound    = new Vector(2);
            Vector strikeBound = new Vector(2);

            if (calSettings != null)
            {
                matBound[0]    = calSettings.MinMaturity;
                matBound[1]    = calSettings.MaxMaturity;
                strikeBound[0] = calSettings.MinStrike;
                strikeBound[1] = calSettings.MaxStrike;
            }
            else
            {
                //use defaults
                matBound[0]    = 1.0 / 12; // .25;
                matBound[1]    = 6;        // 10; //Up to 6Y maturities
                strikeBound[0] = 0.4;
                strikeBound[1] = 1.6;
            }
            Console.WriteLine(callDataSet);

            /*
             * //CBA TEST
             * matBound[0] = 1;// .25;
             * matBound[1] = 3.5;// 10; //Up to 6Y maturities
             * strikeBound[0] = 0.5;// 0.5;
             * strikeBound[1] = 2;//1.5;
             */
            HestonCallOptimizationProblem problem = NewOptimizationProblem(equityCalData, matBound, strikeBound);
            int totalOpts = problem.numCall + problem.numPut;

            Console.WriteLine("Calibration based on " + totalOpts + " options. (" + problem.numCall + " call options and " + problem.numPut + " put options).");

            IOptimizationAlgorithm solver = new  QADE();
            //IOptimizationAlgorithm solver = new MultiLevelSingleLinkage();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();

            o.controller = controller;

            // If true the optimization algorithm will operate in parallel.
            o.Parallel = Engine.MultiThread;
            o.h        = 10e-8;
            o.epsilon  = 10e-8;

            SolutionInfo solution = null;

            double minObj = double.MaxValue;
            Vector minX   = null;
            int    Z      = 1;

            //if (problem.GetType() == typeof(Heston.HestonCallSimulationOptimizationProblem))
            //    Z = 2;

            for (int z = 0; z < Z; z++)
            {
                if (solver.GetType() == typeof(MultiLevelSingleLinkage))
                {
                    o.NP       = 50;
                    o.MaxIter  = 25;
                    o.MaxGamma = 6;
                }
                else
                {
                    o.NP      = 60;
                    o.MaxIter = 35;
                }
                o.Verbosity = 1;
                Vector x0 = null;// new Vector(new double[] { 0.5, 0.5, 0.8, -0.5, 0.05 });

                // GA
                solution = solver.Minimize(problem, o, x0);
                if (solution.errors)
                {
                    return(null);
                }

                o.options = "qn";
                o.MaxIter = 500;// 1000;

                if (solution != null)
                {
                    solution = solver2.Minimize(problem, o, solution.x);
                }
                else
                {
                    solution = solver2.Minimize(problem, o, x0);
                }
                if (solution.errors)
                {
                    return(null);
                }

                if (solution.obj < minObj)
                {
                    minObj = solution.obj;
                    minX   = solution.x.Clone();
                }
            }



            solution.obj = minObj;
            solution.x   = minX;

            //Displays pricing error structure
            HestonCallOptimizationProblem.displayObjInfo = true;
            problem.Obj(solution.x);
            HestonCallOptimizationProblem.displayObjInfo = false;
            Console.WriteLine("Calibration Time (s)\t" + (DateTime.Now - t0).TotalSeconds);

            return(BuildEstimate(spotPrice, interestDataSet, callDataSet, equityCalData, solution));
        }
        /// <summary>
        /// Attempts a calibration through <see cref="SwaptionHW1OptimizationProblem"/>
        /// using swaption matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            PFunction zr = new PFunction(null);
            // Loads the zero rate.
            double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr = zrvalue;

            double deltak = dataset.SwaptionTenor;

            var swaptionsFiltering = settings as SwaptionsFiltering;

            if (swaptionsFiltering == null)
                swaptionsFiltering = new SwaptionsFiltering();//creates a default

            int maturitiesCount = dataset.OptionMaturity.Count(x => x >= swaptionsFiltering.MinSwaptionMaturity && x <= swaptionsFiltering.MaxSwaptionMaturity);
            int durationsCount = dataset.SwapDuration.Count(x => x >= swaptionsFiltering.MinSwapDuration && x <= swaptionsFiltering.MaxSwapDuration);

            Console.WriteLine(string.Format("Calibrating on {0} swaptions prices [#maturiries x #durations]=[{1} x {2}]", maturitiesCount * durationsCount, maturitiesCount,durationsCount));

            if (maturitiesCount * durationsCount == 0)
                return new EstimationResult("No swaptions satisfying criteria found, please relax filters");

            Matrix swaptionsVolatility = new Matrix(maturitiesCount, durationsCount);// dataset.SwaptionsVolatility;
            Vector optionMaturity = new Vector(maturitiesCount);// dataset.OptionMaturity;
            Vector swapDuration = new Vector(durationsCount);// dataset.SwapDuration;

            //Build filtered matrix and vectors
            int fm=0;
            for (int m = 0; m < dataset.OptionMaturity.Length; m++)
            {
                int fd=0;
                if (dataset.OptionMaturity[m] >= swaptionsFiltering.MinSwaptionMaturity && dataset.OptionMaturity[m] <= swaptionsFiltering.MaxSwaptionMaturity)
                {
                    for (int d = 0; d < dataset.SwapDuration.Length; d++)
                    {
                        if (dataset.SwapDuration[d] >= swaptionsFiltering.MinSwapDuration && dataset.SwapDuration[d] <= swaptionsFiltering.MaxSwapDuration)
                        {
                            swaptionsVolatility[fm, fd] = dataset.SwaptionsVolatility[m, d];
                            swapDuration[fd] = dataset.SwapDuration[d];
                            fd++; }
                    }

                    optionMaturity[fm] = dataset.OptionMaturity[m];
                    fm++;
                }

            }

            SwaptionsBlackModel swbm = new SwaptionsBlackModel(zr);

            Matrix fsr;
            var blackSwaptionPrice = 1000.0 * swbm.SwaptionsSurfBM(optionMaturity, swapDuration, swaptionsVolatility, deltak, out fsr);

            Console.WriteLine("SwaptionHWEstimator: Black model prices");
            Console.WriteLine(blackSwaptionPrice);

            SwaptionHW1 swhw1 = new SwaptionHW1(zr);
            SwaptionHW1OptimizationProblem problem = new SwaptionHW1OptimizationProblem(swhw1, blackSwaptionPrice, optionMaturity, swapDuration, deltak);

            IOptimizationAlgorithm solver = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 20;
            o.MaxIter = 5;
            o.Verbosity = 1;
            o.controller = controller;
            SolutionInfo solution = null;

            Vector x0 = new Vector(new double[] { 0.1, 0.1 });
            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);

            o.epsilon = 10e-8;
            o.h = 10e-8;
            o.MaxIter = 1000;

            // We can permit this, given it is fast.
            o.accourate_numerical_derivatives = true;

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
                solution = solver2.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);
            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = new string[] { "Alpha", "Sigma" };

            EstimationResult result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();

            double obj = problem.Obj(solution.x);

            return result;
        }
Exemplo n.º 10
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SteepestDescent obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
Exemplo n.º 11
0
        /// <summary>
        /// Attempts to solve the Heston optimization problem using
        /// <see cref="Heston.HestonOptimizationProblem"/>.
        /// </summary>
        /// <param name="marketData">Data to be used in order to perform the optimization.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">IController.</param>
        /// <returns>The results of the optimization.</returns>
        public EstimationResult Estimate(List<object> marketData, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            DateTime t0 = DateTime.Now;
            var interestDataSet = (CurveMarketData)marketData[0];
            CallPriceMarketData callDataSet = (CallPriceMarketData)marketData[1];
            EquityCalibrationData equityCalData = new EquityCalibrationData(callDataSet, interestDataSet);
            var spotPrice = (DVPLI.MarketDataTypes.Scalar)marketData[2];

            Setup(equityCalData, settings);

            var calSettings = settings as HestonCalibrationSettings;
            // Creates the context.
            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);

            // Optimization problem instance.
            Vector matBound = new Vector(2);
            Vector strikeBound = new Vector(2);
            if (calSettings != null)
            {
                matBound[0] = calSettings.MinMaturity;
                matBound[1] = calSettings.MaxMaturity;
                strikeBound[0] = calSettings.MinStrike;
                strikeBound[1] = calSettings.MaxStrike;
            }
            else
            {
                //use defaults
                matBound[0] = 1.0 / 12;// .25;
                matBound[1] = 6;// 10; //Up to 6Y maturities
                strikeBound[0] = 0.4;
                strikeBound[1] = 1.6;
            }
            Console.WriteLine(callDataSet);
            /*
            //CBA TEST
            matBound[0] = 1;// .25;
            matBound[1] = 3.5;// 10; //Up to 6Y maturities
            strikeBound[0] = 0.5;// 0.5;
            strikeBound[1] = 2;//1.5;
            */
            HestonCallOptimizationProblem problem = NewOptimizationProblem(equityCalData, matBound, strikeBound);
            int totalOpts = problem.numCall + problem.numPut;
            Console.WriteLine("Calibration based on "+totalOpts+ " options. (" + problem.numCall + " call options and "+problem.numPut+" put options).");

            IOptimizationAlgorithm solver = new  QADE();
            //IOptimizationAlgorithm solver = new MultiLevelSingleLinkage();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.controller = controller;

            // If true the optimization algorithm will operate in parallel.
            o.Parallel = Engine.MultiThread;
            o.h = 10e-8;
            o.epsilon = 10e-8;

            SolutionInfo solution = null;

            double minObj=double.MaxValue;
            Vector minX= null;
            int Z = 1;
            //if (problem.GetType() == typeof(Heston.HestonCallSimulationOptimizationProblem))
            //    Z = 2;

            for(int z=0;z<Z;z++)
            {
                if (solver.GetType() == typeof(MultiLevelSingleLinkage))
                {
                    o.NP = 50;
                    o.MaxIter = 25;
                    o.MaxGamma = 6;
                }
                else
                {
                    o.NP = 60;
                    o.MaxIter = 35;
                }
                o.Verbosity = 1;
            Vector x0 = null;// new Vector(new double[] { 0.5, 0.5, 0.8, -0.5, 0.05 });

            // GA
            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return null;

            o.options = "qn";
            o.MaxIter = 500;// 1000;

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
            {
                solution = solver2.Minimize(problem, o, x0);
            }
            if (solution.errors)
                return null;

            if (solution.obj < minObj)
            {
                minObj = solution.obj;
                minX = solution.x.Clone();
            }
            }

            solution.obj = minObj;
            solution.x = minX;

            //Displays pricing error structure
            HestonCallOptimizationProblem.displayObjInfo = true;
            problem.Obj(solution.x);
            HestonCallOptimizationProblem.displayObjInfo = false;
            Console.WriteLine("Calibration Time (s)\t" + (DateTime.Now - t0).TotalSeconds);

            return BuildEstimate(spotPrice,interestDataSet, callDataSet, equityCalData, solution);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Attempts a calibration through <see cref="PelsserCappletOptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;
            EstimationResult result;
            if ((dataset.ZRMarket == null) || (dataset.CapVolatility == null))
            {
                result = new EstimationResult();
                result.ErrorMessage = "Not enough data to calibrate.\n" +
                    "The estimator needs a ZRMarket and a CapVolatility " +
                    "defined inside InterestRateMarketData";
                return result;
            }

            // Backup the dates
            DateTime effectiveDate = DateTime.Now.Date;
            DateTime valuationDate = DateTime.Now.Date;
            if (Document.ActiveDocument != null)
            {
                effectiveDate = Document.ActiveDocument.ContractDate;
                valuationDate = Document.ActiveDocument.SimulationStartDate;
            }

            // Creates the Context.
            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);

            Function zr = new PFunction(null);
            zr.VarName = "zr";
            // Load the zr.
            double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr = zrvalue;

            prj.Symbols.Add(zr);

            BlackModel bm = new BlackModel(zr);

            double deltak = dataset.CapTenor;

            Matrix capVol = dataset.CapVolatility;
            Vector capMat = dataset.CapMaturity;
            Vector capK = dataset.CapRate;

            var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering;

            // Matrix calculated with black.
            Matrix blackCaps = new Matrix(capMat.Length, capK.Length);
            for (int m = 0; m < capMat.Length; m++)
            {
                for (int s = 0; s < capK.Length; s++)
                {
                    bool skip = false;
                    if (preferences != null)
                    {
                        if (capK[s] < preferences.MinCapRate || capK[s] > preferences.MaxCapRate ||
                           capMat[m] < preferences.MinCapMaturity || capMat[m] > preferences.MaxCapMaturity)
                                {skip = true; }
                    }

                    if (capVol[m, s] == 0 || skip)
                        blackCaps[m, s] = 0;
                    else
                        blackCaps[m, s] = bm.Cap(capK[s], capVol[m, s], deltak, capMat[m]);
                }
            }

            if (blackCaps.IsNAN())
            {
                Console.WriteLine("Black caps matrix has non real values:");
                Console.WriteLine(blackCaps);
                throw new Exception("Cannot calculate Black caps");
            }

            // Maturity goes from 0 to the last item with step deltaK.
            Vector maturity = new Vector((int)(1.0 + capMat[capMat.Length - 1] / deltak));
            for (int l = 0; l < maturity.Length; l++)
                maturity[l] = deltak * l;

            Vector fwd = new Vector(maturity.Length - 1);
            for (int i = 0; i < fwd.Length; i++)
            {
                fwd[i] = bm.Fk(maturity[i + 1], deltak);
            }

            // Creates a default Pelsser model.
            Pelsser.SquaredGaussianModel model = new Pelsser.SquaredGaussianModel();
            model.a1 = (ModelParameter)0.014;
            model.sigma1 = (ModelParameter)0.001;
            model.zr = (ModelParameter)"@zr";
            StochasticProcessExtendible iex = new StochasticProcessExtendible(prj, model);
            prj.Processes.AddProcess(iex);

            prj.Parse();

            DateTime t0 = DateTime.Now;
            Caplet cp = new Caplet();

            PelsserCappletOptimizationProblem problem = new PelsserCappletOptimizationProblem(prj, cp, maturity, fwd, capK, deltak, capMat, blackCaps);

            IOptimizationAlgorithm solver = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 35;
            o.TargetCost = 0.0025;
            o.MaxIter = 10;
            o.Verbosity = Math.Max(1, Engine.Verbose);
            o.controller = controller;
            // Parallel evaluation is not supported for this calibration.
            o.Parallel = false;
            o.Debug = true;
            SolutionInfo solution = null;

            Vector x0 = (Vector)new double[] { 0.1, 0.1 };

            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);

            o.epsilon = 10e-7;
            o.h = 10e-7;
            o.MaxIter = 1000;
            o.Debug = true;
            o.Verbosity = Math.Max(1, Engine.Verbose);

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
                solution = solver2.Minimize(problem, o, x0);

            if (solution.errors)
                return new EstimationResult(solution.message);

            Console.WriteLine(solution);

            string[] names = new string[] { "alpha1", "sigma1" };
            result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();
            result.Objects = new object[1];
            result.Objects[0] = solution.obj;
            //result.Fit = solution.obj;//Uncomment in 1.6
            // Restore the dates
            if (Document.ActiveDocument != null)
            {
                Document.ActiveDocument.ContractDate = effectiveDate;
                Document.ActiveDocument.SimulationStartDate = valuationDate;
            }

            return result;
        }
Exemplo n.º 13
0
        /// <summary>
        /// Attempts a calibration through <see cref="CapsCIROptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">A controller used for the optimization process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            // Creates the context.
            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);

            CapCIROptimizationProblem problem = new CapCIROptimizationProblem(dataset);
            IOptimizationAlgorithm solver = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 50;
            o.MaxIter = 50;
            o.Verbosity = 1;
            o.Parallel = false;
            o.controller = controller;
            SolutionInfo solution = null;

            Vector x0 = new Vector(new double[] { 1, 0.01, 0.05 });
            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);

            o.epsilon = 10e-10;
            o.h = 10e-10;
            o.MaxIter = 1000;

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
                solution = solver2.Minimize(problem, o, x0);

            if (solution.errors)
                return new EstimationResult(solution.message);

            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = CIR.parameterNames;
            Vector values = new Vector(4);
            values[Range.New(0, 2)] = solution.x;
            values[3] = problem.r0;

            EstimationResult result = new EstimationResult(names, values);

            return result;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Attempts a calibration through <see cref="CapsCIROptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">A controller used for the optimization process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            // Creates the context.
            Document   doc = new Document();
            ProjectROV prj = new ProjectROV(doc);

            doc.Part.Add(prj);

            CapCIROptimizationProblem problem = new CapCIROptimizationProblem(dataset);
            IOptimizationAlgorithm    solver  = new QADE();
            IOptimizationAlgorithm    solver2 = new SteepestDescent();

            DESettings o = new DESettings();

            o.NP         = 50;
            o.MaxIter    = 50;
            o.Verbosity  = 1;
            o.Parallel   = false;
            o.controller = controller;
            SolutionInfo solution = null;

            Vector x0 = new Vector(new double[] { 1, 0.01, 0.05 });

            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }

            o.epsilon = 10e-10;
            o.h       = 10e-10;
            o.MaxIter = 1000;

            if (solution != null)
            {
                solution = solver2.Minimize(problem, o, solution.x);
            }
            else
            {
                solution = solver2.Minimize(problem, o, x0);
            }

            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }

            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names  = CIR.parameterNames;
            Vector   values = new Vector(4);

            values[Range.New(0, 2)] = solution.x;
            values[3] = problem.r0;

            EstimationResult result = new EstimationResult(names, values);

            return(result);
        }
        private static void Main()
        {
            Parameters.Verbosity = VerbosityLevels.AboveNormal;
            // this next line is to set the Debug statements from OOOT to the Console.
            Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));

            /* In this example, we first present how the details of an optimzation
             * problem can be saved to an XML-file so that it can be read in
             * and solved as opposed to defining all the details in an imperative
             * (code line by code line) way. In the first function, the xml file
             * name "test1.xml" is created. */
            makeAndSaveProblemDefinition();

            /* now we create a series of different optimization methods and test
             * them on the problem. The problem is now opened from the file and
             * the details are stored in an object of class "Problem Definition".*/
            var stream = new FileStream(filename, FileMode.Open);


            ProblemDefinition probTest1 = ProblemDefinition.OpenprobFromXml(stream);
            abstractOptMethod opty;


            /***********Gradient Based Optimization with Steepest Descent****************/
            SearchIO.output("***********Gradient Based Optimization with Steepest Descent****************");
            opty = new GradientBasedOptimization();
            opty.Add(probTest1);
            abstractSearchDirection searchDirMethod = new SteepestDescent();

            opty.Add(searchDirMethod);
            //abstractLineSearch lineSearchMethod = new ArithmeticMean(0.0001, 1, 100);
            //abstractLineSearch lineSearchMethod = new DSCPowell(0.0001, 1, 100);
            abstractLineSearch lineSearchMethod = new GoldenSection(0.0001, 1);

            opty.Add(lineSearchMethod);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            /* since this is not a population-based optimization method, we need to remove the MaxSpan criteria. */
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            double[] xStar;
            var      timer = Stopwatch.StartNew();
            var      fStar = opty.Run(out xStar);

            printResults(opty, xStar, fStar, timer);

            /***********Gradient Based Optimization with Fletcher-Reeves****************/
            SearchIO.output("***********Gradient Based Optimization with Fletcher-Reeves****************");

            /* we don't need to reset (invoke the constructor) for GradientBasedOptimization since we are only
             * change the seaach direction method. */
            searchDirMethod = new FletcherReevesDirection();
            /* you could also try the remaining 3 search direction methods. */
            //searchDirMethod = new CyclicCoordinates();
            //searchDirMethod = new BFGSDirection();
            //searchDirMethod = new PowellMethod(0.001, 6);
            opty.Add(searchDirMethod);

            timer = Stopwatch.StartNew();
            opty.ResetFunctionEvaluationDatabase();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);
            /******************Generalized Reduced Gradient***********************/
            SearchIO.output("******************Generalized Reduced Gradient***********************");
            opty = new GeneralizedReducedGradientActiveSet();
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);

            /* GRG is the ONLY one here that handles constraints explicity. It find the
             * optimal very quickly and accurately. However, many of the other show a
             * better value of f*, this is because they are using an imperfect penalty
             * function (new squaredExteriorPenalty(opty, 10)). While it seems that GRG
             * includes it as well, it is only used in the the line search method. */


            /******************Random Hill Climbing ***********************/
            SearchIO.output("******************Random Hill Climbing ***********************");
            opty = new HillClimbing();
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 8));
            opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor));
            opty.Add(new KeepSingleBest(optimize.minimize));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            /* the deltaX convergence needs to be removed as well, since RHC will end many iterations
             * at the same point it started. */
            opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence);

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);



            /******************Exhaustive Hill Climbing ***********************/
            SearchIO.output("******************Exhaustive Hill Climbing ***********************");
            /* Everything else about the Random Hill Climbing stays the same. */
            opty.Add(new ExhaustiveNeighborGenerator(probTest1.SpaceDescriptor));

            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);



            /******************Simulated Annealing***********************/
            SearchIO.output("******************Simulated Annealing***********************");
            opty = new SimulatedAnnealing(optimize.minimize);
            opty.Add(probTest1);
            opty.Add(new squaredExteriorPenalty(opty, 10));
            opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor, 100));
            opty.Add(new SACoolingSangiovanniVincentelli(100));
            opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence);

            /* the deltaX convergence needs to be removed as well, since RHC will end many iterations
             * at the same point it started. */
            opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence);


            timer = Stopwatch.StartNew();
            fStar = opty.Run(out xStar);
            printResults(opty, xStar, fStar, timer);


            /******************Exhaustive Search ***********************/
            // SearchIO.output("******************Exhaustive Search ***********************");
            //opty = new ExhaustiveSearch(probTest1.SpaceDescriptor, optimize.minimize);
            //opty.Add(probTest1);

            /* No convergence criteria is needed as the process concludes when all
             * states have been visited but for this problem that is 4 trillion states.*/
            //opty.ConvergenceMethods.Clear();
            /* if you DID KNOW the best, you can include a criteria like...*/
            //opty.ConvergenceMethods.Add(new ToKnownBestXConvergence(new[] { 3.0, 3.0 }, 0.0000001));
            //timer = Stopwatch.StartNew();
            //fStar = opty.Run(out xStar);

            /* you probably will never see this process complete. Even with the added
             * convergence criteria (which is not factored into the estimated time of
             * completion), you are probably looking at 1 to 2 years. */
            //printResults(opty, xStar, fStar, timer);
        }