public void TeardownCompilerEngine() { engine = null; sctx = null; target = null; root = null; }
public void Populate(IStochasticProcess container, EstimationResult estimate) { bool found; this.s0 = new ModelParameter(PopulateHelper.GetValue("S0", estimate.Names, estimate.Values, out found), this.s0.Description); bool errors = RetrieveCurve(container.Context, false); if (!errors) { PFunction rFunc = estimate.Objects[0] as PFunction; PFunction rFuncDest = this.r.fVRef() as PFunction; rFuncDest.Expr = rFunc.Expr; PFunction qFunc = estimate.Objects[1] as PFunction; PFunction qFuncDest = this.q.fVRef() as PFunction; qFuncDest.Expr = qFunc.Expr; //Calibrator assumes dividend yield is a step constant function, the simulation model must be coherent with that assumption. qFuncDest.m_Function.iType = DVPLUtils.EInterpolationType.ZERO_ORDER_LEFT; PFunction2D.PFunction2D localVolSrc = estimate.Objects[2] as PFunction2D.PFunction2D; PFunction2D.PFunction2D localVolDest = this.localVol.fVRef() as PFunction2D.PFunction2D; localVolDest.Expr = localVolSrc.Expr; localVolDest.Interpolation = localVolSrc.Interpolation; } }
public CompilerState (PFunction source, Engine targetEngine, ILGenerator il, CompilerPass pass, FunctionLinking linking) { if (source == null) throw new ArgumentNullException("source"); if (targetEngine == null) throw new ArgumentNullException("targetEngine"); if (il == null) throw new ArgumentNullException("il"); _source = source; _linking = linking; _pass = pass; _targetEngine = targetEngine; _il = il; _indexMap = new Dictionary<int, string>(); _instructionLabels = new Label[Source.Code.Count + 1]; for (var i = 0; i < InstructionLabels.Length; i++) InstructionLabels[i] = il.DefineLabel(); _returnLabel = il.DefineLabel(); _symbols = new SymbolTable<CilSymbol>(); _tryBlocks = new Stack<CompiledTryCatchFinallyBlock>(); MetaEntry cilHints; _foreachHints = new List<ForeachHint>(); _cilExtensionOffsets = new Queue<int>(); if (source.Meta.TryGetValue(Loader.CilHintsKey, out cilHints)) { SortedSet<int> cilExtensionOffsets = null; foreach (var entry in cilHints.List) { var hint = entry.List; if (hint.Length < 1) continue; switch (hint[0].Text) { case CilExtensionHint.Key: if (cilExtensionOffsets == null) cilExtensionOffsets = new SortedSet<int>(); var cilExt = CilExtensionHint.FromMetaEntry(hint); foreach (var offset in cilExt.Offsets) cilExtensionOffsets.Add(offset); break; case ForeachHint.Key: _ForeachHints.Add(ForeachHint.FromMetaEntry(hint)); break; } } if (cilExtensionOffsets != null) { foreach (var offset in cilExtensionOffsets) _cilExtensionOffsets.Enqueue(offset); } } _seh = new StructuredExceptionHandling(this); _stackSize = new int[source.Code.Count]; }
internal FunctionContext ( Engine parentEngine, PFunction implementation, PValue[] args, PVariable[] sharedVariables, bool suppressInitialization) { if (parentEngine == null) throw new ArgumentNullException("parentEngine"); if (implementation == null) throw new ArgumentNullException("implementation"); if (sharedVariables == null) sharedVariables = new PVariable[] {}; if (args == null) args = new PValue[] {}; if ( !(suppressInitialization || implementation.ParentApplication._SuppressInitialization)) implementation.ParentApplication.EnsureInitialization(parentEngine); _parentEngine = parentEngine; _implementation = implementation; _bindArguments(args); _createLocalVariables(); ReturnMode = ReturnMode.Exit; if (_implementation.Meta.ContainsKey(PFunction.SharedNamesKey)) { var sharedNames = _implementation.Meta[PFunction.SharedNamesKey].List; //Ensure enough shared variables have been passed if (sharedNames.Length > sharedVariables.Length) throw new ArgumentException ( "The function " + _implementation.Id + " requires " + sharedNames.Length + " variables to be shared."); for (var i = 0; i < sharedNames.Length; i++) { if (sharedVariables[i] == null) throw new ArgumentNullException ( "sharedVariables", String.Format( "The element at index {0} passed in sharedVariables is null for function {1}.", i, implementation)); if (_localVariables.ContainsKey(sharedNames[i])) continue; //Arguments are redeclarations, that is not shared _localVariables.Add(sharedNames[i], sharedVariables[i]); } } //Populate fast variable access array (call by index) _localVariableArray = new PVariable[_localVariables.Count]; foreach (var mapping in _implementation.LocalVariableMapping) _localVariableArray[mapping.Value] = _localVariables[mapping.Key]; }
public FunctionContext ( Engine parentEngine, PFunction implementation, PValue[] args, PVariable[] sharedVariables) : this(parentEngine, implementation, args, sharedVariables, false) { }
public TestStackContext(Engine engine, Application app) { if (engine == null) throw new ArgumentNullException("engine"); if (app == null) throw new ArgumentNullException("app"); _engine = engine; _implementation = app.CreateFunction(); }
public string GetFunctionLine(PFunction pFunc, params string[] parameters) { ParameterInfo[] infos = pFunc.FunctionInfo.GetParameters(); var sb = new StringBuilder(); bool isAsync = false; if (pFunc.FunctionInfo.ReturnType.CanCastingTo <System.Threading.Tasks.Task>()) { isAsync = true; sb.Append("(await "); } sb.Append(pFunc.FunctionInfo.DeclaringType.Name); sb.Append("."); sb.Append(pFunc.FunctionInfo.Name); sb.Append("("); for (int i = 0; i < parameters.Length; i++) { sb.Append($"{parameters[i]}.AutoCast<{infos[i].ParameterType.Name}>()"); if (i < parameters.Length - 1) { sb.Append(", "); } } int scopeCount = 1; for (int i = parameters.Length; i < infos.Length; i++) { if (infos[i].ParameterType == typeof(Action)) { if (parameters.Length > 0) { sb.Append(", "); } sb.Append($"{infos[i].Name}: () => {{Scope:{scopeCount++}}}"); } if (i < infos.Length - 1) { sb.Append(", "); } } sb.Append(")"); if (isAsync) { sb.Append(")"); } return(sb.ToString()); }
public ZeroRateFunction(DateTime refDate, DVPLI.Vector x, DVPLI.Vector y) : base(new ActualActual()) { this.date = new Date(refDate); DVPLDOM.PFunction pf = new PFunction(null); double[,] zrvalue = (double[, ])ArrayHelper.Concat(x.ToArray(), y.ToArray()); pf.Expr = zrvalue; this.function = pf; this.maxT = x.Max() + 130;// add years in order to handle date approximations }
/// <summary> /// Creates a new closure. /// </summary> /// <param name = "func">A (nested) function, that has shared variables.</param> /// <param name = "sharedVariables">A list of variables to share with the function.</param> /// <exception cref = "ArgumentNullException">Either <paramref name = "func" /> or <paramref name = "sharedVariables" /> is null.</exception> public Closure(PFunction func, PVariable[] sharedVariables) { if (func == null) throw new ArgumentNullException("func"); if (sharedVariables == null) throw new ArgumentNullException("sharedVariables"); _function = func; _sharedVariables = sharedVariables; }
public void PFunctionTest() { var function = new PFunction(x, n, 1, k); Assert.AreEqual(new Fraction(1, 2), function.Calculate()); var function1 = new PFunction(x, n, 2, k); Assert.AreEqual(new Fraction(2, 3), function1.Calculate()); }
/// <summary> /// Creates a new closure. /// </summary> /// <param name = "func">A (nested) function, that has shared variables.</param> /// <param name = "sharedVariables">A list of variables to share with the function.</param> /// <exception cref = "ArgumentNullException">Either <paramref name = "func" /> or <paramref name = "sharedVariables" /> is null.</exception> public CilClosure(PFunction func, PVariable[] sharedVariables) { if (func == null) throw new ArgumentNullException("func"); if (sharedVariables == null) throw new ArgumentNullException("sharedVariables"); if (!func.HasCilImplementation) throw new ArgumentException(func + " does not have a cil implemenetation"); _function = func; _sharedVariables = sharedVariables; }
private EstimationResult FairmatEstimate(CurveMarketData discountingCurve, CallPriceMarketData Hdataset) { EquityCalibrationData HCalData = new EquityCalibrationData(Hdataset, discountingCurve); //HCalData.Setup(Hdataset, discountingCurve); bool hasArbitrage = HCalData.HasArbitrageOpportunity(10e-2); if (hasArbitrage) { Console.WriteLine("Market data contains arbitrage opportunity"); } this.r = new DVPLDOM.PFunction(discountingCurve.Durations, discountingCurve.Values); this.q = HCalData.dyFunc as PFunction; //this.q.Expr = (double[,])ArrayHelper.Concat(HCalData.MaturityDY.ToArray(), HCalData.DividendYield.ToArray()); this.r.Parse(null); this.q.Parse(null); Vector locVolMat, locVolStr; //IFunction fittedSurface = FitImplVolModel(Hdataset); //Matrix locVolMatrix = LocVolMatrixFromImpliedVol(Hdataset, fittedSurface, out locVolMat, out locVolStr); CallPriceSurface fittedSurface = CallPriceSurface.NoArbitrageSurface(HCalData); Matrix locVolMatrix = LocVolMatrixFromCallPrices(Hdataset, fittedSurface, out locVolMat, out locVolStr); Console.WriteLine(locVolMatrix); // Create dupire outputs. PFunction2D.PFunction2D localVol = new PFunction2D.PFunction2D(locVolMat, locVolStr, locVolMatrix); localVol.Parse(null); string[] names = new string[] { "S0" }; Vector param = new Vector(1); param[0] = Hdataset.S0; EstimationResult result = new EstimationResult(names, param); //result.Objects = new object[3]; result.Objects = new object[4]; result.Objects[0] = this.r; result.Objects[1] = this.q; result.Objects[2] = localVol; result.Objects[3] = fittedSurface; //Console.WriteLine("r = " + HCalData.Rate.ToString()); //Console.WriteLine("q = " + HCalData.DividendYield.ToString()); return(result); }
public void Test() { double[,] values = { { .5, .015 }, { 1, .0165 }, { 2, .0168 }, { 3, .0172 }, { 5, .0182 }, { 8, .0210 }, { 10, .025 }, { 15, .031 }, { 20, .035 }, { 30, .037 }, { 40, .038 }, }; Function zeroratecurve = new PFunction(null); zeroratecurve.Expr = values; (zeroratecurve as PFunction).m_Function.iType = EInterpolationType.LINEAR; // Execute the test. CapHW1 hwc = new CapHW1(zeroratecurve); // CAP and FLOOR Tests. double[] results = new double[2]; results[0] = hwc.HWCap(0.14, 0.02, 0.02, 0.5, 1); results[1] = hwc.HWCap(0.14, 0.02, 0.02, 0.5, 2); Console.WriteLine("CAP 2 col 1 row:" + results[0]); Console.WriteLine("CAP 2 col 2 row:" + results[1]); // Check the results with previously manually calculated values. double[] targets = { 0.00214717607719883, 0.0084939015243779 }; double eps = 10e-6; for (int r = 0; r < results.Length; r++) { Assert.LessOrEqual(Math.Abs(targets[r] - results[r]), eps); } }
public void Test() { double[,] values = { { .5, .015 }, { 1, .0165 }, { 2, .0168 }, { 3, .0172 }, { 5, .0182 }, { 8, .0210 }, { 10, .025 }, { 15, .031 }, { 20, .035 }, { 30, .037 }, { 40, .038 }, }; Function zeroratecurve = new PFunction(null); zeroratecurve.Expr = values; (zeroratecurve as PFunction).m_Function.iType = EInterpolationType.LINEAR; // Execute the test. CapHW1 hwc = new CapHW1(zeroratecurve); // CAP and FLOOR Tests. double[] results = new double[2]; results[0] = hwc.HWCap(0.14, 0.02, 0.02, 0.5, 1); results[1] = hwc.HWCap(0.14, 0.02, 0.02, 0.5, 2); Console.WriteLine("CAP 2 col 1 row:" + results[0]); Console.WriteLine("CAP 2 col 2 row:" + results[1]); // Check the results with previously manually calculated values. double[] targets = { 0.00214717607719883, 0.0084939015243779 }; double eps = 10e-6; for (int r = 0; r < results.Length; r++) { Assert.LessOrEqual(Math.Abs(targets[r] - results[r]), eps); } }
/// <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"); } } } }
internal BenchmarkEntry(Benchmark parent, PFunction function) { if (function == null) throw new ArgumentNullException("function"); if (parent == null) throw new ArgumentNullException("parent"); Parent = parent; Function = function; var m = function.Meta; if (m.ContainsKey(Benchmark.TitleKey)) Title = m[Benchmark.TitleKey]; else Title = function.Id; if (m.ContainsKey(Benchmark.DescriptionKey)) Description = m[Benchmark.DescriptionKey]; else Description = String.Format("The benchmarked function {0}", Title); UsesIteration = m[Benchmark.UsesIterationKey]; if (m.ContainsKey(Benchmark.OverheadKey)) Overhead = m[Benchmark.OverheadKey]; }
/// <summary> /// Method that calculates the color of all pixels of the <see cref="HdrImage"/> /// datamember according to the rendering equation, /// specified by a <see cref="PFunction"/> object. It also implements /// antialiasing to avoid Moirè fringes effects. /// </summary> /// <param name="fun"> The delegate function that transforms a <see cref="Ray"/> into a <see cref="Color"/>.</param> public void fireAllRays(PFunction fun) { //Parallel.For(0, image.height, i => for (int i = 0; i < image.height; i++) { for (int j = 0; j < image.width; j++) { Color appo = Constant.Black; if (this.samplesPerSide > 0) { //Stratified sampling! Automatically casts samplesPerSide into a perfect-square number // samplesPerSide = (int)Math.Pow(Math.Sqrt(samplesPerSide) - (int)Math.Sqrt(samplesPerSide), 2); for (int iPixRow = 0; iPixRow < samplesPerSide; iPixRow++) { for (int iPixCol = 0; iPixCol < samplesPerSide; iPixCol++) { float uPix = (iPixCol + pcg.randomFloat()) / (float)samplesPerSide; float vPix = (iPixRow + pcg.randomFloat()) / (float)samplesPerSide; Ray rr = this.fireRay(col: j, row: i, uPixel: uPix, vPixel: vPix); appo += fun(rr); } } this.image.setPixel(j, i, appo * (1.0f / (float)Math.Pow(samplesPerSide, 2))); } else { Ray raggio = this.fireRay(j, i); Color colore = fun(raggio); this.image.setPixel(j, i, colore); } } // if (i % 50 == 0 && i != 0) // Console.Write(((float)i / image.height).ToString("0.00") + " of rendering completed\r"); } }
public string GetFunctionLine(PFunction pFunc, params string[] parameters) { ParameterInfo[] infos = pFunc.FunctionInfo.GetParameters(); var sb = new StringBuilder(); sb.Append(pFunc.FunctionInfo.DeclaringType.Name); sb.Append("."); sb.Append(pFunc.FunctionInfo.Name); sb.Append("("); for (int i = 0; i < parameters.Length; i++) { sb.Append($"({infos[i].ParameterType.Name}){parameters[i]}"); if (i < parameters.Length - 1) { sb.Append(", "); } } sb.Append(")"); return(sb.ToString()); }
/// <summary> /// Sets several variables used to solve the optimization problem. /// </summary> /// <param name="callMarketPrice">A matrix containing call option market prices.</param> /// <param name="maturity"> /// Vector of call option maturities relative to callMarketPrice matrix. /// </param> /// <param name="strike"> /// Vector of call option strikes relative to callMarketPrice matrix. /// </param> /// <param name="rate"> /// Vector of zero coupon bond rates calculated relative to maturity vector maturities. /// </param> /// <param name="dividendYield"> /// Vector of dividend yield rates calculated relative to maturity vector maturities. /// </param> /// <param name="s0">Index/Equity value at the time of calibration.</param> /// <param name="matBound"> /// A vector containing the minimum and maximum values /// for maturities to be used in calibration. /// </param> /// <param name="strikeBound"> /// A vector containing the minimum and maximum values /// for strikes to be used in calibration.</param> private void SetVariables(Matrix callMarketPrice, Vector maturity, Vector strike, Vector rate, Vector dividendYield, double s0) { this.s0 = s0; //var rf = new PFunction(maturity, rate); var dy = new PFunction(maturity, dividendYield); //var rfF = new Fairmat.Math.Integrate(x => rf.Evaluate(x)); var dyF = new Fairmat.Math.Integrate(x => dy.Evaluate(x)); this.rate = new Vector(maturity.Length); this.dividendYield = new Vector(maturity.Length); for (int z = 0; z < maturity.Length; z++) { //this.rate[z] = rfF.AdaptLobatto(0, maturity[z]) / maturity[z]; this.dividendYield[z] = dyF.AdaptLobatto(0, maturity[z]) / maturity[z]; } this.rate = rate; this.maturity = maturity; //this.drift = this.rate - this.dividendYield; this.strike = strike; this.callMarketPrice = callMarketPrice; this.numCall = 0; callWeight = new Matrix(this.callMarketPrice.R, this.callMarketPrice.C); putWeight = new Matrix(this.callMarketPrice.R, this.callMarketPrice.C); for (int r = 0; r < this.callMarketPrice.R; r++) { if (this.maturity[r] >= matBound[0] && this.maturity[r]<= matBound[1]) { for (int c = 0; c < this.callMarketPrice.C; c++) { if (this.strike[c] >= s0 * strikeBound[0] && this.strike[c] <= s0 * strikeBound[1]) { if (calibrateOnCallOptions) if (this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0) { this.callWeight[r, c] = CalculateWeight(this.cpmd.CallVolume[r, c]); this.numCall++; this.totalVolume += CalculateWeight(this.cpmd.CallVolume[r, c]) ; } if (calibrateOnPutOptions) if (this.cpmd.PutPrice != null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0) { this.putWeight[r, c] = CalculateWeight(this.cpmd.PutVolume[r, c]); this.numPut++; this.totalVolume += CalculateWeight(this.cpmd.PutVolume[r, c]); } } } } } //calibrate minVolatility: actually in this.cpmd.Volatility there is sigma not sigma^2 if (this.cpmd.Volatility != null) { //Rows maturities, columns strikes vLastMin = 0.5 * Math.Pow(this.cpmd.Volatility.Min().Min(), 2); v0Min = 0.99 * Math.Pow(this.cpmd.Volatility[0, Range.All].Min().Min(), 2); v0Max = 1.01 * Math.Pow(this.cpmd.Volatility[0, Range.All].Max().Max(), 2); } Console.WriteLine("Options weighting:\t" + weighting); Console.WriteLine("OptionThreshold:\t" + optionThreshold); Console.WriteLine("Strike Bounds:\t" + strikeBound); Console.WriteLine("Maturity Bounds:\t" + matBound); Console.WriteLine("Lb:\t" + Bounds.Lb); Console.WriteLine("Ub:\t" + Bounds.Ub); if(Engine.Verbose>=2) PutCallTest(); }
/// <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); }
// case if s = 0; private Fraction StartValueCalculate() { var pFunction = new PFunction(_x, _n, _t, _k); return(pFunction.Calculate()); }
public override bool Remove(PFunction item) { PFunction f; if(_table.TryGetValue(item.Id,out f) && ReferenceEquals(f,item)) { f.Declaration.IdChanging -= _idChangingHandler; _table.Remove(item.Id); return true; } else return false; }
public override bool Contains(PFunction item) { return _table.ContainsKey(item.Id); }
public override void Add(PFunction item) { if (_table.ContainsKey(item.Id)) throw new ArgumentException( "The function table already contains a function named " + item.Id); item.Declaration.IdChanging += _idChangingHandler; _table.Add(item.Id, item); }
/// <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"); } } }
private EstimationResult FairmatEstimate(CurveMarketData discountingCurve, CallPriceMarketData Hdataset) { EquityCalibrationData HCalData = new EquityCalibrationData(Hdataset, discountingCurve); //HCalData.Setup(Hdataset, discountingCurve); bool hasArbitrage = HCalData.HasArbitrageOpportunity(10e-2); if (hasArbitrage) Console.WriteLine("Market data contains arbitrage opportunity"); this.r = new DVPLDOM.PFunction(discountingCurve.Durations,discountingCurve.Values); this.q = HCalData.dyFunc as PFunction; //this.q.Expr = (double[,])ArrayHelper.Concat(HCalData.MaturityDY.ToArray(), HCalData.DividendYield.ToArray()); this.r.Parse(null); this.q.Parse(null); Vector locVolMat, locVolStr; //IFunction fittedSurface = FitImplVolModel(Hdataset); //Matrix locVolMatrix = LocVolMatrixFromImpliedVol(Hdataset, fittedSurface, out locVolMat, out locVolStr); CallPriceSurface fittedSurface = CallPriceSurface.NoArbitrageSurface(HCalData); Matrix locVolMatrix = LocVolMatrixFromCallPrices(Hdataset, fittedSurface, out locVolMat, out locVolStr); Console.WriteLine(locVolMatrix); // Create dupire outputs. PFunction2D.PFunction2D localVol = new PFunction2D.PFunction2D(locVolMat, locVolStr, locVolMatrix); localVol.Parse(null); string[] names = new string[] { "S0" }; Vector param = new Vector(1); param[0] = Hdataset.S0; EstimationResult result = new EstimationResult(names, param); //result.Objects = new object[3]; result.Objects = new object[4]; result.Objects[0] = this.r; result.Objects[1] = this.q; result.Objects[2] = localVol; result.Objects[3] = fittedSurface; //Console.WriteLine("r = " + HCalData.Rate.ToString()); //Console.WriteLine("q = " + HCalData.DividendYield.ToString()); 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> /// Calculates call put prices for several strikes using controlled interpolation. /// </summary> /// <param name="context"></param> private void CalculateSingleRowWithInterpolation(object context) { HestonCall hc = context as HestonCall; int r = hc.row; hc.sum = 0; // Finds upper extreme for call and put int max_c = 0; for (int c = this.callMarketPrice.C - 1; c > 0; c--) { bool callCondition = this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0; bool putCondition = this.cpmd.PutPrice != null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0; if (callCondition || putCondition) { max_c = c; break; } } var strikes = new List <double>(); var calls = new List <double>(); var puts = new List <double>(); //Evaluates in strategic points for (int c = 0; c < this.callMarketPrice.C; c++) { bool callCondition = this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0; bool putCondition = this.cpmd.PutPrice != null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0; if (callCondition || putCondition) { hc.K = this.strike[c]; var callPut = hc.HestonCallPutPrice(); strikes.Add(hc.K); calls.Add(callPut[0]); puts.Add(callPut[1]); if (c == max_c) { break; } c += 1;//skip the subsequent strikes if (c > max_c) { c = max_c; } } } // Builds interpolated call and put values. var callFun = new PFunction((Vector)strikes.ToArray(), (Vector)calls.ToArray()); callFun.m_Function.iType = DVPLUtils.EInterpolationType.SPLINE; var putFun = new PFunction((Vector)strikes.ToArray(), (Vector)puts.ToArray()); putFun.m_Function.iType = DVPLUtils.EInterpolationType.SPLINE; // Evaluates at the requested strikes for (int c = 0; c < this.callMarketPrice.C; c++) { bool callCondition = this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0; bool putCondition = this.cpmd.PutPrice != null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0; if (callCondition) { hc.hestonCallPrice[r, c] = callFun.Evaluate(this.strike[c]); if (HestonCallOptimizationProblem.optimizeRelativeError) { double mkt = pricingMin + this.callMarketPrice[r, c]; double model = pricingMin + hc.hestonCallPrice[r, c]; hc.sum += callWeight[r, c] * Math.Pow((model - mkt) / mkt, 2); } else { hc.sum += callWeight[r, c] * Math.Pow(hc.hestonCallPrice[r, c] - this.callMarketPrice[r, c], 2); } } if (putCondition) { hc.hestonPutPrice[r, c] = putFun.Evaluate(this.strike[c]); if (HestonCallOptimizationProblem.optimizeRelativeError) { double mkt = pricingMin + this.cpmd.PutPrice[r, c]; double model = pricingMin + hc.hestonPutPrice[r, c]; hc.sum += putWeight[r, c] * Math.Pow((model - mkt) / mkt, 2); } else { hc.sum += putWeight[r, c] * Math.Pow(hc.hestonPutPrice[r, c] - this.cpmd.PutPrice[r, c], 2); } } } return; }
/// <summary> /// Sets several variables used to solve the optimization problem. /// </summary> /// <param name="callMarketPrice">A matrix containing call option market prices.</param> /// <param name="maturity"> /// Vector of call option maturities relative to callMarketPrice matrix. /// </param> /// <param name="strike"> /// Vector of call option strikes relative to callMarketPrice matrix. /// </param> /// <param name="rate"> /// Vector of zero coupon bond rates calculated relative to maturity vector maturities. /// </param> /// <param name="dividendYield"> /// Vector of dividend yield rates calculated relative to maturity vector maturities. /// </param> /// <param name="s0">Index/Equity value at the time of calibration.</param> /// <param name="matBound"> /// A vector containing the minimum and maximum values /// for maturities to be used in calibration. /// </param> /// <param name="strikeBound"> /// A vector containing the minimum and maximum values /// for strikes to be used in calibration.</param> private void SetVariables(Matrix callMarketPrice, Vector maturity, Vector strike, Vector rate, Vector dividendYield, double s0) { this.s0 = s0; //var rf = new PFunction(maturity, rate); var dy = new PFunction(maturity, dividendYield); //var rfF = new Fairmat.Math.Integrate(x => rf.Evaluate(x)); var dyF = new Fairmat.Math.Integrate(x => dy.Evaluate(x)); this.rate = new Vector(maturity.Length); this.dividendYield = new Vector(maturity.Length); for (int z = 0; z < maturity.Length; z++) { //this.rate[z] = rfF.AdaptLobatto(0, maturity[z]) / maturity[z]; this.dividendYield[z] = dyF.AdaptLobatto(0, maturity[z]) / maturity[z]; } this.rate = rate; this.maturity = maturity; //this.drift = this.rate - this.dividendYield; this.strike = strike; this.callMarketPrice = callMarketPrice; this.numCall = 0; callWeight = new Matrix(this.callMarketPrice.R, this.callMarketPrice.C); putWeight = new Matrix(this.callMarketPrice.R, this.callMarketPrice.C); for (int r = 0; r < this.callMarketPrice.R; r++) { if (this.maturity[r] >= matBound[0] && this.maturity[r] <= matBound[1]) { for (int c = 0; c < this.callMarketPrice.C; c++) { if (this.strike[c] >= s0 * strikeBound[0] && this.strike[c] <= s0 * strikeBound[1]) { if (calibrateOnCallOptions) { if (this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0) { this.callWeight[r, c] = CalculateWeight(this.cpmd.CallVolume[r, c]); this.numCall++; this.totalVolume += CalculateWeight(this.cpmd.CallVolume[r, c]); } } if (calibrateOnPutOptions) { if (this.cpmd.PutPrice != null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0) { this.putWeight[r, c] = CalculateWeight(this.cpmd.PutVolume[r, c]); this.numPut++; this.totalVolume += CalculateWeight(this.cpmd.PutVolume[r, c]); } } } } } } //calibrate minVolatility: actually in this.cpmd.Volatility there is sigma not sigma^2 if (this.cpmd.Volatility != null) { //Rows maturities, columns strikes vLastMin = 0.5 * Math.Pow(this.cpmd.Volatility.Min().Min(), 2); v0Min = 0.99 * Math.Pow(this.cpmd.Volatility[0, Range.All].Min().Min(), 2); v0Max = 1.01 * Math.Pow(this.cpmd.Volatility[0, Range.All].Max().Max(), 2); } Console.WriteLine("Options weighting:\t" + weighting); Console.WriteLine("OptionThreshold:\t" + optionThreshold); Console.WriteLine("Strike Bounds:\t" + strikeBound); Console.WriteLine("Maturity Bounds:\t" + matBound); Console.WriteLine("Lb:\t" + Bounds.Lb); Console.WriteLine("Ub:\t" + Bounds.Ub); if (Engine.Verbose >= 2) { PutCallTest(); } }
public void Include(PFunction function) { if (function == null) throw new ArgumentNullException("function"); _entries.Add(new BenchmarkEntry(this, function)); }
public void LinkMetadata(PFunction func) { if (!MakeAvailableForLinking) return; var T = _getRuntimeType(); T.GetField(_mkFieldName(func.Id)).SetValue(null, func); }
public Environment() { Output = new Output(); EmptyArgs = new SArgs(this); True = new LBoolean(this, true); False = new LBoolean(this, false); Undefined = new LUndefined(this); Null = new LNull(this); GlobalObject = new BGlobal(this); GlobalEnvironment = new SLexicalEnvironment(this, new SObjectEnvironmentRecord(this, GlobalObject, false), null); MathObject = new BMath(this); JsonObject = new BJson(this); ObjectConstructor = new CObject(this); FunctionConstructor = new CFunction(this); ArrayConstructor = new CArray(this); StringConstructor = new CString(this); BooleanConstructor = new CBoolean(this); NumberConstructor = new CNumber(this); DateConstructor = new CDate(this); RegExpConstructor = new CRegExp(this); ErrorConstructor = new CError(this); EvalErrorConstructor = new CEvalError(this); RangeErrorConstructor = new CRangeError(this); ReferenceErrorConstructor = new CReferenceError(this); SyntaxErrorConstructor = new CSyntaxError(this); TypeErrorConstructor = new CTypeError(this); UriErrorConstructor = new CUriError(this); ObjectPrototype = new PObject(this); FunctionPrototype = new PFunction(this); ArrayPrototype = new PArray(this); StringPrototype = new PString(this); BooleanPrototype = new PBoolean(this); NumberPrototype = new PNumber(this); DatePrototype = new PDate(this); RegExpPrototype = new PRegExp(this); ErrorPrototype = new PError(this); EvalErrorPrototype = new PEvalError(this); RangeErrorPrototype = new PRangeError(this); ReferenceErrorPrototype = new PReferenceError(this); SyntaxErrorPrototype = new PSyntaxError(this); TypeErrorPrototype = new PTypeError(this); UriErrorPrototype = new PUriError(this); GlobalObject.Initialize(); MathObject.Initialize(); JsonObject.Initialize(); ObjectConstructor.Initialize(); FunctionConstructor.Initialize(); ArrayConstructor.Initialize(); StringConstructor.Initialize(); BooleanConstructor.Initialize(); NumberConstructor.Initialize(); DateConstructor.Initialize(); RegExpConstructor.Initialize(); ErrorConstructor.Initialize(); EvalErrorConstructor.Initialize(); RangeErrorConstructor.Initialize(); ReferenceErrorConstructor.Initialize(); SyntaxErrorConstructor.Initialize(); TypeErrorConstructor.Initialize(); UriErrorConstructor.Initialize(); ObjectPrototype.Initialize(); FunctionPrototype.Initialize(); ArrayPrototype.Initialize(); StringPrototype.Initialize(); BooleanPrototype.Initialize(); NumberPrototype.Initialize(); DatePrototype.Initialize(); RegExpPrototype.Initialize(); ErrorPrototype.Initialize(); EvalErrorPrototype.Initialize(); RangeErrorPrototype.Initialize(); ReferenceErrorPrototype.Initialize(); SyntaxErrorPrototype.Initialize(); TypeErrorPrototype.Initialize(); UriErrorPrototype.Initialize(); }
/// <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 override void AddOverride(PFunction item) { PFunction oldFunc; if (_table.TryGetValue(item.Id,out oldFunc)) { oldFunc.Declaration.IdChanging -= _idChangingHandler; _table.Remove(oldFunc.Id); } item.Declaration.IdChanging += _idChangingHandler; _table.Add(item.Id, item); }
/// <summary> /// Provides macro environment to its implementing function. The resulting closure /// implements the expansion of the macro. /// </summary> /// <param name = "sctx">The stack context to use for wrapping the context.</param> /// <param name = "func">The implementation of the macro.</param> /// <param name = "context">The macro context for this expansion.</param> /// <returns>A closure that implements the expansion of this macro.</returns> public static Closure PrepareMacroImplementation(StackContext sctx, PFunction func, MacroContext context) { var contextVar = CompilerTarget.CreateReadonlyVariable(sctx.CreateNativePValue(context)); var env = new SymbolTable<PVariable>(1) {{MacroAliases.ContextAlias, contextVar}}; var sharedVariables = func.Meta[PFunction.SharedNamesKey].List.Select(entry => env[entry.Text]). ToArray(); return new Closure(func, sharedVariables); }
public override void CopyTo(PFunction[] array, int arrayIndex) { if (_table.Count + arrayIndex > array.Length) throw new ArgumentException("Array to copy functions into is not long enough."); var i = arrayIndex; foreach (var kvp in _table) { if (i >= array.Length) break; array[i++] = kvp.Value; } }
public bool TryGetFunction(string id, ModuleName moduleName, out PFunction func) { var app = this; if (moduleName != null && moduleName != Module.Name) { if (!Compound.TryGetApplication(moduleName, out app)) { func = null; return false; } } return app.Functions.TryGetValue(id, out func); }
public override bool TryGetValue(string id, out PFunction func) { return _table.TryGetValue(id, out func); }
public PFunction CreateFunction(string id) { var decl = Module.CreateFunction(id); var func = new PFunction(this, decl); _functionTable.Add(func); return func; }
/// <summary> /// Determines whether a function allows debugging or not. /// </summary> /// <param name = "function">The function to be checked for debugging settings.</param> /// <returns>True if the function allows debugging, false otherwise.</returns> public static bool IsDebuggingEnabled(PFunction function) { if (function.Meta.ContainsKey(DebuggingMetaKey)) return function.Meta[DebuggingMetaKey].Switch; else return function.ParentApplication.Meta[DebuggingMetaKey].Switch; }
protected internal static void _expectSharedVariables_(PFunction func, string[] shared) { MetaEntry entry; var hasShared = func.Meta.TryGetValue(PFunction.SharedNamesKey, out entry); if (shared.Length == 0 && hasShared) Assert.Fail("The function {0} is not expected to share variables.", func.Id); else if ((!hasShared) && shared.Length != 0) Assert.Fail("The function {0} is expected to share variables.", func.Id); else if ((!hasShared) && shared.Length == 0) return; var entries = entry.List; Assert.AreEqual( shared.Length, entries.Length, "The function {0} is expected to have a different number of shared variables.", func.Id); for (var i = 0; i < entries.Length; i++) Assert.IsTrue( Engine.StringsAreEqual(shared[i], entries[i] == null ? "" : entries[i].Text), "The function {0} is expected to require sharing of variable {1}.", func.Id, shared[i]); }
private static void _expectSehDeficiency(PFunction function) { Assert.IsNotNull(function, "function not found"); Assert.IsTrue(function.Meta[PFunction.VolatileKey].Switch, "Function is expected to be volatile."); Assert.IsTrue(function.Meta[PFunction.DeficiencyKey].Text.Contains("SEH"), "CIL deficiency is expected to be related to SEH."); }
public string GetFunctionLine(PFunction pFunc, params string[] parameters) { throw new NotImplementedException(); }
/// <summary> /// Calculates call put prices for several strikes using controlled interpolation. /// </summary> /// <param name="context"></param> private void CalculateSingleRowWithInterpolation(object context) { HestonCall hc = context as HestonCall; int r = hc.row; hc.sum = 0; // Finds upper extreme for call and put int max_c =0; for (int c = this.callMarketPrice.C-1; c > 0; c--) { bool callCondition = this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0; bool putCondition = this.cpmd.PutPrice!=null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0; if (callCondition || putCondition) { max_c = c; break; } } var strikes = new List<double>(); var calls = new List<double>(); var puts = new List<double>(); //Evaluates in strategic points for (int c = 0; c < this.callMarketPrice.C; c++) { bool callCondition = this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0; bool putCondition = this.cpmd.PutPrice!=null&& this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0; if (callCondition || putCondition) { hc.K = this.strike[c]; var callPut = hc.HestonCallPutPrice(); strikes.Add(hc.K); calls.Add(callPut[0]); puts.Add(callPut[1]); if (c == max_c) break; c += 1;//skip the subsequent strikes if (c > max_c) c = max_c; } } // Builds interpolated call and put values. var callFun = new PFunction((Vector)strikes.ToArray(), (Vector)calls.ToArray()); callFun.m_Function.iType = DVPLUtils.EInterpolationType.SPLINE; var putFun = new PFunction((Vector)strikes.ToArray(), (Vector)puts.ToArray()); putFun.m_Function.iType = DVPLUtils.EInterpolationType.SPLINE; // Evaluates at the requested strikes for (int c = 0; c < this.callMarketPrice.C; c++) { bool callCondition = this.callMarketPrice[r, c] > s0 * optionThreshold && this.cpmd.CallVolume[r, c] > 0; bool putCondition = this.cpmd.PutPrice!=null && this.cpmd.PutPrice[r, c] > s0 * optionThreshold && this.cpmd.PutVolume[r, c] > 0; if (callCondition) { hc.hestonCallPrice[r, c] = callFun.Evaluate(this.strike[c]); if (HestonCallOptimizationProblem.optimizeRelativeError) { double mkt = pricingMin + this.callMarketPrice[r, c]; double model = pricingMin + hc.hestonCallPrice[r, c]; hc.sum += callWeight[r,c] * Math.Pow((model - mkt) / mkt, 2); } else { hc.sum += callWeight[r, c] * Math.Pow(hc.hestonCallPrice[r, c] - this.callMarketPrice[r, c], 2); } } if (putCondition) { hc.hestonPutPrice[r, c] = putFun.Evaluate(this.strike[c]); if (HestonCallOptimizationProblem.optimizeRelativeError) { double mkt = pricingMin + this.cpmd.PutPrice[r, c]; double model = pricingMin + hc.hestonPutPrice[r, c]; hc.sum += putWeight[r, c] * Math.Pow((model - mkt) / mkt, 2); } else { hc.sum += putWeight[r, c] * Math.Pow(hc.hestonPutPrice[r, c] - this.cpmd.PutPrice[r, c], 2); } } } return; }
/// <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 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; 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; }