/// <summary>
        /// Constructor for the Cox-Ingersoll-Ross Calibration Problem based on caps matrices,
        /// using an <see cref="InterestRateMarketData"/> to derive the required data.
        /// </summary>
        /// <param name="irmd">
        /// An <see cref="InterestRateMarketData"/> containing the
        /// required information for the optimization problem.
        /// </param>
        public CapCIROptimizationProblem(InterestRateMarketData irmd)
        {
            this.capMaturity = irmd.CapMaturity;
            this.capRate     = irmd.CapRate;
            this.tau         = irmd.CapTenor;

            PFunction zr = new PFunction(null);

            zr.m_Function.iType = DVPLUtils.EInterpolationType.LINEAR;
            double[,] zrval     = (double[, ])ArrayHelper.Concat(irmd.ZRMarketDates.ToArray(),
                                                                 irmd.ZRMarket.ToArray());
            zr.Expr = zrval;

            this.r0 = zr.Evaluate(0.0);

            BlackModel bm = new BlackModel(zr);

            this.blackCaps = new Matrix(this.capMaturity.Length, this.capRate.Length);
            for (int i = 0; i < this.capMaturity.Length; i++)
            {
                for (int j = 0; j < this.capRate.Length; j++)
                {
                    if (irmd.CapVolatility[i, j] == 0)
                    {
                        this.blackCaps[i, j] = 0;
                    }
                    else
                    {
                        this.blackCaps[i, j] = bm.Cap(this.capRate[j], irmd.CapVolatility[i, j],
                                                      this.tau, this.capMaturity[i]);
                    }

                    if (double.IsNaN(this.blackCaps[i, j]))
                    {
                        throw new Exception("Error on cap market price calculation");
                    }
                }
            }
        }
        /// <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.º 3
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);
        }
        /// <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;
        }
        /// <summary>
        /// Constructor for the Cox-Ingersoll-Ross Calibration Problem based on caps matrices,
        /// using an <see cref="InterestRateMarketData"/> to derive the required data.
        /// </summary>
        /// <param name="irmd">
        /// An <see cref="InterestRateMarketData"/> containing the
        /// required information for the optimization problem.
        /// </param>
        public CapCIROptimizationProblem(InterestRateMarketData irmd)
        {
            this.capMaturity = irmd.CapMaturity;
            this.capRate = irmd.CapRate;
            this.tau = irmd.CapTenor;

            PFunction zr = new PFunction(null);
            zr.m_Function.iType = DVPLUtils.EInterpolationType.LINEAR;
            double[,] zrval = (double[,])ArrayHelper.Concat(irmd.ZRMarketDates.ToArray(),
                                                            irmd.ZRMarket.ToArray());
            zr.Expr = zrval;

            this.r0 = zr.Evaluate(0.0);

            BlackModel bm = new BlackModel(zr);
            this.blackCaps = new Matrix(this.capMaturity.Length, this.capRate.Length);
            for (int i = 0; i < this.capMaturity.Length; i++)
            {
                for (int j = 0; j < this.capRate.Length; j++)
                {
                    if (irmd.CapVolatility[i, j] == 0)
                        this.blackCaps[i, j] = 0;
                    else
                        this.blackCaps[i, j] = bm.Cap(this.capRate[j], irmd.CapVolatility[i, j],
                                                      this.tau, this.capMaturity[i]);

                    if (double.IsNaN(this.blackCaps[i, j]))
                        throw new Exception("Error on cap market price calculation");
                }
            }
        }