/// <summary> /// Attempts to solve the Variance Gamma Optimization problem using /// <see cref="Heston.VarianceGammaOptimizationProblem"/>. /// </summary> /// <param name="data"> /// The data to be used in order to perform the optimization. /// </param> /// <param name="settings">The parameter is not used.</param> /// <returns>The results of the optimization.</returns> public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null) { EquitySpotMarketData espmd = data[0] as EquitySpotMarketData; CallPriceMarketData cpmd = data[1] as CallPriceMarketData; DiscountingCurveMarketData dcmd = data[2] as DiscountingCurveMarketData; EquityCalibrationData ecd = new EquityCalibrationData(cpmd, dcmd); this.s0 = espmd.Price; this.r = espmd.RiskFreeRate; this.q = espmd.DividendYield; this.k = ecd.Hdata.Strike; this.m = ecd.Hdata.Maturity; this.cp = ecd.Hdata.CallPrice; Vector x0 = (Vector) new double[] { -0.1, 0.2, 0.1 }; IOptimizationAlgorithm algorithm = new QADE(); OptimizationSettings optimizationSettings = new DESettings(); // Maximum number of iteration allowed. // Positive integer values print debug info. optimizationSettings.Verbosity = 1; // Tolerance. optimizationSettings.epsilon = 10e-5; var solution = algorithm.Minimize(new VarianceGammaOptimizationProblem(this.q, this.s0, this.k, this.r, this.cp, this.m), optimizationSettings, x0); if (solution.errors) { return(new EstimationResult(solution.message)); } var er = new EstimationResult(); er.Names = new string[] { "S0", "theta", "sigma", "nu", "rate", "dividend" }; er.Values = new double[] { this.s0, solution.x[0], solution.x[1], solution.x[2], this.r, this.q }; return(er); }
/// <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); }
/// <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; }
/// <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 to solve the Variance Gamma Optimization problem using /// <see cref="Heston.VarianceGammaOptimizationProblem"/>. /// </summary> /// <param name="data"> /// The data to be used in order to perform the optimization. /// </param> /// <param name="settings">The parameter is not used.</param> /// <returns>The results of the optimization.</returns> public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null) { EquitySpotMarketData espmd = data[0] as EquitySpotMarketData; CallPriceMarketData cpmd = data[1] as CallPriceMarketData; DiscountingCurveMarketData dcmd = data[2] as DiscountingCurveMarketData; EquityCalibrationData ecd = new EquityCalibrationData(cpmd, dcmd); this.s0 = espmd.Price; this.r = espmd.RiskFreeRate; this.q = espmd.DividendYield; this.k = ecd.Hdata.Strike; this.m = ecd.Hdata.Maturity; this.cp = ecd.Hdata.CallPrice; Vector x0 = (Vector)new double[] { -0.1, 0.2, 0.1 }; IOptimizationAlgorithm algorithm = new QADE(); OptimizationSettings optimizationSettings = new DESettings(); // Maximum number of iteration allowed. // Positive integer values print debug info. optimizationSettings.Verbosity = 1; // Tolerance. optimizationSettings.epsilon = 10e-5; var solution = algorithm.Minimize(new VarianceGammaOptimizationProblem(this.q, this.s0, this.k, this.r, this.cp, this.m), optimizationSettings, x0); if (solution.errors) return new EstimationResult(solution.message); var er = new EstimationResult(); er.Names= new string[]{"S0","theta","sigma","nu","rate","dividend"}; er.Values = new double[] {this.s0,solution.x[0],solution.x[1],solution.x[2],this.r,this.q}; return er; }
/// <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="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; }
/// <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="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> /// 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; }
/// <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); }