/// <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) { LambdaCalibrationSettings lsettings = (LambdaCalibrationSettings)settings; if (lsettings.Years > lsettings.BondMaturity) { throw new Exception("Bond maturity has to be greater of the historical series time span."); } InterestRateMarketData irmd = data[0] as InterestRateMarketData; List <object> IrmdData = new List <object>(); IrmdData.Add(irmd); CapletEstimator CapEst = new CapletEstimator(); EstimationResult er1 = CapEst.Estimate(IrmdData); DiscountingCurveMarketData[] dcmd = Array.ConvertAll <IMarketData, DiscountingCurveMarketData> ((IMarketData[])data[1], el => (DiscountingCurveMarketData)el); MarketPriceOfRiskCalculator mporc = new MarketPriceOfRiskCalculator(); double lambda = mporc.Calculate(dcmd, lsettings); string[] names = new string[er1.Names.Length + 1]; for (int i = 0; i < er1.Names.Length; i++) { names[i] = er1.Names[i]; } names[er1.Names.Length] = "lambda0"; Vector values = new Vector(er1.Values.Length + 1); values[new Range(0, values.Length - 2)] = (Vector)er1.Values; values[Range.End] = lambda; EstimationResult result = new EstimationResult(names, values); 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"); } } } }
public void TestCalibration() { InterestRateMarketData IData = InterestRateMarketData.FromFile("../../TestData/IRMD-sample.xml"); CallPriceMarketData HData = CallPriceMarketData.FromFile("../../TestData/CallData-sample.xml"); //InterestRateMarketData IData = InterestRateMarketData.FromFile("../../../EquityModels.Tests/TestData/IRMD-EU-30102012-close.xml"); //CallPriceMarketData HData = CallPriceMarketData.FromFile("../../../EquityModels.Tests/TestData/30102012-SX5E_Index-HestonData.xml"); //CallPriceMarketData HData = ObjectSerialization.ReadFromXMLFile("../../../EquityModels.Tests/TestData/FTSE.xml") as CallPriceMarketData; List <object> l = new List <object>(); l.Add(IData.DiscountingCurve); l.Add(HData); DupireEstimator DE = new DupireEstimator(); DupireCalibrationSettings settings = new DupireCalibrationSettings(); settings.LocalVolatilityCalculation = LocalVolatilityCalculation.Method1; //settings.LocalVolatilityCalculation = LocalVolatilityCalculation.QuantLib; EstimationResult res = DE.Estimate(l, settings); //int nmat = HData.Maturity.Length; //int nstrike = HData.Strike.Length; int i = 5; // Maturity. int j = 4; // Strike. Engine.MultiThread = true; Document doc = new Document(); ProjectROV rov = new ProjectROV(doc); doc.Part.Add(rov); doc.DefaultProject.NMethods.m_UseAntiteticPaths = true; int n_sim = 10000; int n_steps = 500; double strike = HData.Strike[j]; //double volatility = HData.Volatility[i, j]; /* * PFunction2D.PFunction2D impvolfunc = new PFunction2D.PFunction2D(rov); * impvolfunc = res.Objects[3] as PFunction2D.PFunction2D; * impvolfunc.VarName = "impvol"; * rov.Symbols.Add(impvolfunc); * double volatility = impvolfunc.Evaluate(HData.Maturity[i], HData.Strike[j]); */ double volatility = 0.2; double maturity = HData.Maturity[i]; ModelParameter Pstrike = new ModelParameter(strike, string.Empty, "strike"); rov.Symbols.Add(Pstrike); AFunction payoff = new AFunction(rov); payoff.VarName = "payoff"; payoff.m_IndependentVariables = 1; payoff.m_Value = (RightValue)("max(x1 - strike ; 0)"); rov.Symbols.Add(payoff); bool found; double S0 = PopulateHelper.GetValue("S0", res.Names, res.Values, out found); ModelParameter PS0 = new ModelParameter(S0, string.Empty, "S0"); rov.Symbols.Add(PS0); PFunction rfunc = new PFunction(rov); rfunc = res.Objects[0] as PFunction; rfunc.VarName = "r"; rov.Symbols.Add(rfunc); PFunction qfunc = new PFunction(rov); qfunc = res.Objects[1] as PFunction; qfunc.VarName = "q"; rov.Symbols.Add(qfunc); PFunction2D.PFunction2D volfunc = new PFunction2D.PFunction2D(rov); volfunc = res.Objects[2] as PFunction2D.PFunction2D; volfunc.VarName = "localvol"; rov.Symbols.Add(volfunc); DupireProcess process = new DupireProcess(); process.s0 = (ModelParameter)"S0"; process.r = (ModelParameter)"@r"; process.q = (ModelParameter)"@q"; process.localVol = (ModelParameter)"@localvol"; double rate = rfunc.Evaluate(maturity); double dy = qfunc.Evaluate(maturity); StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process); rov.Processes.AddProcess(s); // Set the discounting. RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo; rfi.ActualizationType = EActualizationType.RiskFree; rfi.m_deterministicRF = rate; OptionTree op = new OptionTree(rov); op.PayoffInfo.PayoffExpression = "payoff(v1)"; op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturity; op.PayoffInfo.European = true; rov.Map.Root = op; rov.NMethods.Technology = ETechType.T_SIMULATION; rov.NMethods.PathsNumber = n_sim; rov.NMethods.SimulationSteps = n_steps; ROVSolver solver = new ROVSolver(); solver.BindToProject(rov); solver.DoValuation(-1); if (rov.HasErrors) { rov.DisplayErrors(); } Assert.IsFalse(rov.HasErrors); ResultItem price = rov.m_ResultList[0] as ResultItem; double samplePrice = price.value; double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim); Console.WriteLine("Surf = " + volfunc.Expr); // Calculation of the theoretical value of the call. double theoreticalPrice = BlackScholes.Call(rate, S0, strike, volatility, maturity, dy); Console.WriteLine("Theoretical Price = " + theoreticalPrice.ToString()); Console.WriteLine("Monte Carlo Price = " + samplePrice); Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString()); double tol = 4.0 * sampleDevSt; doc.WriteToXMLFile("Dupire.fair"); Assert.LessOrEqual(Math.Abs(theoreticalPrice - samplePrice), tol); }
/// <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); }
public static void Main(string[] args) { int Caso = 1; if (Caso == 0) { InterestRateMarketData MData = InterestRateMarketData.FromFile("../../../TestData/InterestRatesModels/05052009-EU.xml"); CallPriceMarketData test = CallPriceMarketData.FromFile("../../../TestData/Heston/05052009-SX5E-HestonData.xml"); EquityCalibrationData CalData = new EquityCalibrationData(test, MData); Matrix CallMarketPrice = (Matrix)test.CallPrice; Vector Maturity = (Vector)test.Maturity; Vector Strike = (Vector)test.Strike; Vector DividendYield = (Vector)test.DividendYield; Vector Drift = CalData.Rate - CalData.DividendYield; Vector Rate = CalData.Rate; double u, kappa, theta, sigma, rho, v0, s0, r, q, T, K, val; u = 1.0; kappa = 19.4; theta = 0.235; sigma = 0.00500999; rho = -0.96; v0 = 0.664; s0 = 3872.15; r = -0.0867303549580581; q = 0; T = 0.50; K = 6000; Vector MatBound = new Vector(2); Vector StrikeBound = new Vector(2); MatBound[0] = 0.0; MatBound[1] = 2.0; StrikeBound[0] = 0.7; StrikeBound[1] = 1.3; Matrix Volatility = new Matrix(test.CallPrice.R, test.CallPrice.C); HestonCallOptimizationProblem HP = new HestonCallOptimizationProblem(CallMarketPrice, Maturity, Strike, Rate, DividendYield, test.S0, MatBound, StrikeBound, Volatility); Complex Cval, Cu; Cu = u - Complex.I; HestonCall hc = new HestonCall(HP); Cval = hc.phi(u, kappa, theta, sigma, rho, s0, v0, r, T); Console.WriteLine("phi1 = {0}", Cval); Cval = hc.phi(Cu, kappa, theta, sigma, rho, s0, v0, r, T); Console.WriteLine("phi2 = {0}", Cval); val = hc.IntegrandFunc(u, kappa, theta, sigma, rho, s0, v0, r, q, T, K); Console.WriteLine("IntFunc = {0}", val); Vector x = new Vector(5); x[0] = kappa; x[1] = theta; x[2] = sigma; x[3] = rho; x[4] = v0; DateTime T1, T2; TimeSpan ElapsedTime; double Time, Time2, Time3; T1 = DateTime.Now; val = hc.HestonCallPrice(x, s0, T, K, r, q); T2 = DateTime.Now; ElapsedTime = T2 - T1; Time = (double)ElapsedTime.Milliseconds; Time2 = (double)ElapsedTime.Seconds; Console.WriteLine("Price = {0}", val); Console.WriteLine("Elapsed Time = {0}", Time2 + Time / 1000); int NProve = 10; int NPassi = 1000; double val2; Random CasNum = new Random(); for (int i = 0; i < NProve; i++) { for (int j = 0; j < 5; j++) { val2 = ((double)CasNum.Next(0, NPassi)) / ((double)NPassi); x[j] = HP.Bounds.Lb[j] + (HP.Bounds.Ub[j] - HP.Bounds.Lb[j]) * val2; } Console.Write("Trial {0} x = " + x.ToString(), i + 1); T1 = DateTime.Now; val = HP.Obj(x); T2 = DateTime.Now; ElapsedTime = T2 - T1; Time = (double)ElapsedTime.Milliseconds; Time2 = (double)ElapsedTime.Seconds; Time3 = (double)ElapsedTime.Minutes; Console.WriteLine(" Time = {0}' {1}'' Val = {2}", Time3, Time2 + Time / 1000, val); } } if (Caso == 1) { TestHestonCallEstimation NewTest = new TestHestonCallEstimation(); bool Result = NewTest.Run(); } }
/// <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> /// 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"); } } }