/// <summary> /// Evaluates the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The function arguments.</param> /// <returns>The result value of the function evaluation.</returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } IFunction function = DataType.SubsetFunction; if ((function.Evaluate( context, new EvaluationValue(args[0], args[0].GetType(context)), new EvaluationValue(args[1], args[1].GetType(context))) == EvaluationValue.True) && (function.Evaluate( context, new EvaluationValue(args[1], args[1].GetType(context)), new EvaluationValue(args[0], args[0].GetType(context))) == EvaluationValue.True)) { return(EvaluationValue.True); } else { return(EvaluationValue.False); } }
public static IFunction Integrate(IFunction func, double xMin, double xMax, int granularity) { var points = new List <Point>(); double xDiff = xMax - xMin; double delta = xDiff / granularity; double x = xMin; double yPrev = 0; for (int i = 0; i < granularity; ++i) { double xa = x; double xb = x + delta; double ya = func.Evaluate(xa); double yb = func.Evaluate(xb); double area = delta * (ya + yb) / 2; double y = yPrev + area; points.Add(new Point(x, y)); x += delta; yPrev = y; } return(new LinearInterpolation(points)); }
/// <summary> /// Evaluates the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The function arguments.</param> /// <returns>The result value of the function evaluation.</returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } var retBag = new BagValue(DataType); IFunction functionDup = DataType.IsInFunction; foreach (object par1 in args[0].Elements) { EvaluationValue retVal = functionDup.Evaluate(context, new EvaluationValue(par1, args[0].GetType(context)), retBag); if (!retVal.BoolValue) { retBag.Add(new EvaluationValue(par1, args[0].GetType(context))); } } foreach (object par2 in args[1].Elements) { EvaluationValue retVal = functionDup.Evaluate(context, new EvaluationValue(par2, args[1].GetType(context)), retBag); if (!retVal.BoolValue) { retBag.Add(new EvaluationValue(par2, args[1].GetType(context))); } } return(new EvaluationValue(retBag, DataType)); }
private double Integrate(int index, double a, double b) { IFunction function = functions[index]; if (!IsInvalid(function.Evaluate(a)) && !IsInvalid(function.Evaluate(b))) { return(integrator.Integrate(function, a, b).value); } return(0); }
public double Integrate(IFunction <double> fx, Range <double> range) { var x0 = range.Start; var sum = 0d; foreach (var x1 in range.All.Skip(1)) { sum += TrapezoidalRule(x1, x0, fx.Evaluate(x1), fx.Evaluate(x0)); x0 = x1; } return(sum); }
protected override double EstimateIntegralOver(IFunction <double> fx, double x0, double x2) { // Simpson's method var H = x2 - x0; var h = 0.5 * H; var x1 = x0 + h; var fx0 = fx.Evaluate(x0); var fx1 = fx.Evaluate(x1); var fx2 = fx.Evaluate(x2); return((h / 3) * (fx0 + 4 * fx1 + fx2)); }
/// <summary> /// Method called by the EvaluationEngine to evaluate the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The IFuctionParameters that will be used as arguments to the function.</param> /// <returns></returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } IFunction function = args[0].GetFunction(0); if (!args[1].IsBag) { return(EvaluationValue.False); } var retVal = new BagValue(args[1].GetType(context)); foreach (var par in args[1].Elements) { retVal.Add( function.Evaluate( context, new EvaluationValue(par, args[1].GetType(context)))); } return(new EvaluationValue(retVal, args[1].GetType(context))); }
public HestonCallSimulationOptimizationProblem(EquityCalibrationData equityCalData, Vector matBound, Vector strikeBound) : base(equityCalData, matBound, strikeBound) { //this.dyFunc = equityCalData.dyFunc; this.dyFunc = CallEstimator.IstantaneousDividendYield(equityCalData); this.zrFunc = equityCalData.zrFunc; // Generates common random numbers I = (int)Math.Ceiling(cpmd.Maturity[Range.End] / dt); epsilon = new Matrix(I, 2 * N); NewRandomNumbers(); // Precalculates istantaneous growth rates growth = new Vector(I); for (int i = 0; i < I; i++) { double t = i * dt; double zr_t = zrFunc.Evaluate(t); growth[i] = zr_t + FunctionHelper.Partial(zr_t, zrFunc, new Vector() { t }, 0, dt) * t - dyFunc.Evaluate(t); } Console.WriteLine("Heston Simulation Calibration: Paths=" + N); }
/// <summary> /// Method called by the EvaluationEngine to evaluate the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The IFuctionParameters that will be used as arguments to the function.</param> /// <returns></returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } IFunction function = args[0].GetFunction(0); if (!Equals(function.Returns, DataTypeDescriptor.Boolean)) { return(EvaluationValue.Indeterminate); } foreach (var par1 in args[1].Elements) { foreach (var par2 in args[2].Elements) { EvaluationValue retVal = function.Evaluate( context, new EvaluationValue(par1, args[1].GetType(context)), new EvaluationValue(par2, args[2].GetType(context))); if (!retVal.BoolValue) { return(EvaluationValue.False); } } } return(EvaluationValue.True); }
/// <summary> /// Evaluates the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The function arguments.</param> /// <returns>The result value of the function evaluation.</returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } IFunction function = DataType.EqualFunction; foreach (object par1 in args[0].Elements) { foreach (object par2 in args[1].Elements) { EvaluationValue retVal = function.Evaluate( context, new EvaluationValue(par1, args[0].GetType(context)), new EvaluationValue(par2, args[1].GetType(context))); if (retVal.BoolValue) { return(EvaluationValue.True); } } } return(EvaluationValue.False); }
/// <summary> /// Evaluates the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The function arguments.</param> /// <returns>The result value of the function evaluation.</returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } if (args[1].IsBag) { IFunction function = DataType.EqualFunction; foreach (object value in args[1].Elements) { if (function.Evaluate( context, new EvaluationValue(args[0], args[0].GetType(context)), new EvaluationValue(value, args[1].GetType(context))) == EvaluationValue.True) { return(EvaluationValue.True); } } } return(EvaluationValue.False); }
/// <summary> /// Method called by the EvaluationEngine to evaluate the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The IFuctionParameters that will be used as arguments to the function.</param> /// <returns></returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } IFunction function = args[0].GetFunction(0); foreach (var par1 in args[1].Elements) { bool hasFound = false; foreach (var par2 in args[2].Elements) { EvaluationValue retVal = function.Evaluate( context, new EvaluationValue(par1, args[1].GetType(context)), new EvaluationValue(par2, args[2].GetType(context))); if (retVal.BoolValue) { hasFound = true; break; } } if (!hasFound) { return(EvaluationValue.False); } } return(EvaluationValue.True); }
/// <summary> /// Method called by the EvaluationEngine to evaluate the function. /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="args">The IFuctionParameters that will be used as arguments to the function.</param> /// <returns></returns> public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args) { if (context == null) { throw new ArgumentNullException("context"); } if (args == null) { throw new ArgumentNullException("args"); } IFunction function = args[0].GetFunction(0); var value = new EvaluationValue(args[1], args[1].GetType(context)); foreach (var par in args[2].Elements) { EvaluationValue retVal = function.Evaluate( context, value, new EvaluationValue(par, args[2].GetType(context))); if (retVal.BoolValue) { return(retVal); } } return(EvaluationValue.False); }
private bool UnsatisfiedRoot(IFunction function, double i1, double d1, double i2, double d2) { if (Math.Sign(d1) != Math.Sign(d2)) { double root = EMath.Geometry.Line.Root(i1, d1, i2, d2); if (!((decimal)root >= (decimal)i1 && (decimal)root <= (decimal)i2 && Math.Abs(function.Evaluate(root)) < rootTolerance)) { Debug.Log(Math.Abs(function.Evaluate(root))); Debug.Log("Unsatisfied Root!!!"); return(true); } } return(false); }
public double Integrate(IFunction <double> fx, Range <double> range) { var x0 = range.Start; var sum = 0d; foreach (var x2 in range.All.Skip(1)) { var h = x2 - x0; var x1 = x0 + 0.5 * h; var fx0 = fx.Evaluate(x0); var fx1 = fx.Evaluate(x1); var fx2 = fx.Evaluate(x2); sum += (h / 6) * (fx0 + 4 * fx1 + fx2); x0 = x2; } return(sum); }
private Matrix LocVolMatrixFromImpliedVol(CallPriceMarketData Hdataset, IFunction impVol, out Vector locVolMat, out Vector locVolStr) { int nmat = calibrationSettings.LocalVolatilityMaturities; int nstrike = calibrationSettings.LocalVolatilityStrikes; double lastMat = Hdataset.Maturity[Range.End]; double lastStr = Hdataset.Strike[Range.End]; locVolMat = Vector.Linspace(Hdataset.Maturity[0], lastMat, nmat); locVolStr = Vector.Linspace(Hdataset.Strike[0], lastStr, nstrike); Matrix locVolMatrix = new Matrix(nmat, nstrike); Integrate integrate = new Integrate(this); double sigma, dSigmadk, num, y, den, avgGrowthRate; Vector x = new Vector(2); for (int i = 0; i < nmat; i++) { avgGrowthRate = integrate.AdaptLobatto(0.0, locVolMat[i]); int j = 0; x[0] = locVolMat[i]; x[1] = locVolStr[j]; sigma = impVol.Evaluate(x); dSigmadk = impVol.Partial(x, 1); num = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] * impVol.Partial(x, 0); den = 1.0; locVolMatrix[i, j] = Math.Sqrt(num / den); // The rest of the cycle. for (j = 1; j < nstrike; j++) { x[1] = locVolStr[j]; sigma = impVol.Evaluate(x); dSigmadk = impVol.Partial(x, 1); num = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] * (impVol.Partial(x, 0) + avgGrowthRate * x[1] * dSigmadk); y = Math.Log(locVolStr[j] / Hdataset.S0) + avgGrowthRate; den = System.Math.Pow(1.0 - x[1] * y * dSigmadk / sigma, 2) + x[1] * sigma * x[0] * (dSigmadk - 0.25 * x[1] * sigma * x[0] * dSigmadk * dSigmadk + x[1] * impVol.Partial2(x, 1)); locVolMatrix[i, j] = Math.Sqrt(num / den); } } return(locVolMatrix); }
internal void RegisterFunction(IFunction function) { this.CheckForExistingFunctionName(function.Name); this.registeredFunctions.Add(function.Name, (p, a) => { function.Variables = a; return(function.Evaluate(p, this.options)); }); }
private void AddFunctionLine(IFunction function, double i, double ih, double b, Material material, List <Point> points, int index) { double d = function.Evaluate(i); if (IsInvalid(d)) { SetInvalidContinuity(points, index); return; } Point start = GetPoint(i, d); points.Add(start); double dh = function.Evaluate(ih); if (IsInvalid(dh)) { SetInvalidContinuity(ih, b, points, index); return; } Point end = GetPoint(ih, dh); if ((decimal)ih >= (decimal)b) { points.Add(end); } if (UnsatisfiedRoot(function, i, d, ih, dh)) { SetInvalidContinuity(ih, b, points, index); return; } PlotLine(start, end, material); }
public double Evaluate(double x) { if (_validateDomain) { if (!_domain.IsValid(x)) { throw new ArgumentOutOfRangeException($"{x} does not fall within domain {_domain}."); } } return(_function.Evaluate(x)); }
/// <summary> /// Linear Differential Equation of the form y` = P(t)y + G(t) /// </summary> /// <param name="Pt">function of t to multiply with y</param> /// <param name="Gt">function of t to add to result</param> /// <returns>differential equation</returns> public static FirstOrderDE <T> Linear(IFunction <T> Pt, IFunction <T> Gt) { var calc = Pt.Calculator ?? Gt.Calculator; return(new FirstOrderDE <T>( new NativeFunction2 <T>(calc, ((T, T)args) => { var x = args.Item1; var y = args.Item2; return calc.Subtract( calc.Multiply(Pt.Evaluate(x), y), Gt.Evaluate(x) ); })
static double Mean(IFunction f, double a, double b) { double sum = 0; int N = 20; double h = b - a; double dt = h / N; for (int z = 0; z < N; z++) { sum += f.Evaluate(a + (dt * z)) * dt; } return(sum / h); }
/* not tochable */ //---------------------------------------------------------------------------------- private void Button1_Click(object sender, EventArgs e) /*plot derivative*/ { if (coordinates != null) { foreach (var item in coordinates) { coordinates.Remove(item); } } /*plot on the pictureBox*/ zoomValue = trackBar1.Value; orgX = pictureBox1.Width / 2; orgY = pictureBox1.Height / 2; derivativePen = new Pen(Brushes.Red, 2.0F); /* plot Newton's derivative with pen purple */ derivativePen = new Pen(Brushes.Purple, 2.0F); for (float i = -orgX; i <= pictureBox1.Height / 2; i += 0.01f) { double h = 0.01; double Y1 = ((root.Evaluate(i + h) - root.Evaluate(i)) / h); //f(x+h) - f(x) / h double Y2 = ((root.Evaluate(i + (0.01) + h) - root.Evaluate(i + (0.01))) / h); Y1 = ((-1) * Y1 * zoomValue) + orgY; Y2 = ((-1) * Y2 * zoomValue) + orgY; double X = (zoomValue * i) + orgX; double X2 = (zoomValue * i) + orgX + 0.01f; if (Y1 <= pictureBox1.Height && Y2 <= pictureBox1.Height && Y1 >= 0 && Y2 >= 0) { g.DrawLine(derivativePen, (float)X, (float)Y1, (float)X2, (float)Y2); } } /* plot the Analytical derivative and plotting the tree*/ IFunction p; p = root.derivative(); DrawBinaryTree(p); derivativePen = new Pen(Brushes.Green, 2.0F); for (float i = -orgX; i <= pictureBox1.Height; i += 0.01f) { double X = (double)i; float Y = (float)p.Evaluate(X) * zoomValue; float Y2 = ((float)p.Evaluate(i + 0.1) * zoomValue); if (Y <= pictureBox1.Height / 2 && Y2 <= pictureBox1.Height / 2 && Y >= -200 && Y2 >= -200) { g.DrawLine(derivativePen, (float)(X * zoomValue) + orgX, orgY - Y, (float)(orgX + (X * zoomValue) + 0.1), orgY - Y2); } } }
public DefiniteIntegral Integrate(IFunction function, double a, double b) { double c1 = (b + a) / 2.0; double c2 = (b - a) / 2.0; double sum = 0; for (int i = 0; i < polynomials.n; i++) { sum += polynomials.weights[i] * function.Evaluate(c1 + c2 * polynomials.roots[i]); } return(new DefiniteIntegral(c2 * sum)); }
public static IFunction Differentiate(IFunction func, double xMin, double xMax, int granularity) { var points = new List <Point>(); double xDiff = xMax - xMin; double delta = xDiff / granularity; double x = xMin; for (int i = 0; i < granularity; ++i) { double xa = x - delta / 2; double xb = x + delta / 2; double ya = func.Evaluate(xa); double yb = func.Evaluate(xb); double slope = (yb - ya) / (xb - xa); points.Add(new Point(x, slope)); x += delta; } return(new LinearInterpolation(points)); }
protected static void SaveCsv(string name, IFunction <double> approx, IFunction <double> real, Range <double> range) { if (!Directory.Exists(".data")) { Directory.CreateDirectory(".data"); } using (var writer = new StreamWriter(Path.Combine(".data", $"{name}.xy.csv"))) { writer.WriteLine("x, y, ~y"); foreach (var x in range.All) { writer.WriteLine($"{x},{real.Evaluate(x)},{approx.Evaluate(x)}"); } } }
protected static void SaveCsv(string name, IFunction <double> approx, Func <double, double> real) { if (!Directory.Exists(".data")) { Directory.CreateDirectory(".data"); } using (var writer = new StreamWriter(Path.Combine(".data", $"{name}.xy.csv"))) { writer.WriteLine("x, y, y`"); for (var x = -10d; x <= 10d; x += 0.1d) { writer.WriteLine($"{x},{real(x)},{approx.Evaluate(x)}"); } } }
/// <summary> /// Returns the Strike vector embedded in the volatility matrix. /// The method manage the convention that if rates/strikes [defined in .ColumnValues fields] are equal to -1, /// the strike vector is ATM and must be derived from the term structure. /// </summary> /// <param name="normalVol">The matrix</param> /// <param name="zr">The term structure.</param> /// <returns>The strike vector.</returns> static Vector GetStrikes(MatrixMarketData normalVol, IFunction zr) { if (IsAtmMatrix(normalVol)) { // builds the vector of ATM strikes var s = new Vector(normalVol.RowValues.Length); for (int j = 0; j < s.Length; j++) { s[j] = zr.Evaluate(normalVol.RowValues[j]); } return(s); } else { return(normalVol.ColumnValues); } }
/// <summary> /// Registers the supplied <paramref name="function"/> for use within compiling and evaluating an <see cref="Expression"/>. /// </summary> /// <param name="function">The <see cref="IFunction"/> to perform the function evaluation.</param> /// <param name="force">Whether to forcefully override any existing function.</param> public void RegisterFunction(IFunction function, bool force = false) { if (function is null) { throw new ArgumentNullException(nameof(function)); } this.RegisterFunction( function.Name, (p, a) => { function.Variables = a; return(function.Evaluate(p, this)); }, force); }
internal static Matrix ToMatrix(IFunction func) { int n = 20; double ub = 5; var sup = func as ISupport1D; if (sup != null) { ub = sup.Support[1]; } var mat = new Matrix(n, 2); for (int i = 0; i < n; i++) { double x = i * ub / n; mat[i, 0] = x; mat[i, 1] = func.Evaluate(x); } return(mat); }
public void RegisterFunction(IFunction function, bool force = false) { ExecFunction exec = new ExecFunction((p, a, c) => { return(function.Evaluate(p, a, c)); }); if (force) { this[function.Name] = exec; } else if (!this.ContainsKey(function.Name)) { this.Add(function.Name, exec); } else { throw new FunctionNameAlreadyRegisteredException(function.Name); } }
static double Mean(IFunction f, double a, double b) { double sum = 0; int N = 20; double h = b - a; double dt = h / N; for (int z = 0; z < N; z++) sum += f.Evaluate(a + (dt * z)) * dt; return sum / h; }
/// <summary> /// Evaluates a function and also validates it's return value and parameter data types /// </summary> /// <param name="context">The evaluation context instance.</param> /// <param name="functionInstance">The function to call</param> /// <param name="arguments">The function arguments</param> /// <returns>The return value of the function</returns> public static EvaluationValue EvaluateFunction(EvaluationContext context, IFunction functionInstance, params IFunctionParameter[] arguments) { if (context == null) throw new ArgumentNullException("context"); // If the caller is in a missing attribute state the function should not be called if (context.IsMissingAttribute) { context.Trace("There's a missing attribute in the parameters"); return EvaluationValue.Indeterminate; } else { // Validate function defined arguments int functionArgumentIdx; for (functionArgumentIdx = 0; functionArgumentIdx < functionInstance.Arguments.Length; functionArgumentIdx++) { // Validate the value is not an Indeterminate value if (arguments[functionArgumentIdx] is EvaluationValue && ((EvaluationValue)arguments[functionArgumentIdx]).IsIndeterminate) { if (!context.IsMissingAttribute) { context.ProcessingError = true; } context.Trace("There's a parameter with Indeterminate value"); return EvaluationValue.Indeterminate; } // Compare the function and the value data type if (((functionInstance.Arguments[functionArgumentIdx] != arguments[functionArgumentIdx].GetType(context)) && ((functionInstance.Arguments[functionArgumentIdx] != DataTypeDescriptor.Bag) && (arguments[functionArgumentIdx] is BagValue)))) { context.ProcessingError = true; context.Trace("There's a parameter with an invalid datatype"); return EvaluationValue.Indeterminate; } } //If the function supports variable arguments, the last datatype is used to validate the //rest of the parameters if (functionInstance.VarArgs) { functionArgumentIdx--; for (int argumentValueIdx = functionArgumentIdx; argumentValueIdx < arguments.Length; argumentValueIdx++) { // Validate the value is not an Indeterminate value if (arguments[argumentValueIdx] is EvaluationValue && ((EvaluationValue)arguments[argumentValueIdx]).IsIndeterminate) { if (!context.IsMissingAttribute) { context.ProcessingError = true; } context.Trace("There's a parameter with Indeterminate value"); return EvaluationValue.Indeterminate; } // Compare the function and the value data type if ((functionInstance.Arguments[functionArgumentIdx] != arguments[argumentValueIdx].GetType(context)) && ((arguments[argumentValueIdx] is BagValue) && (functionInstance.Arguments[functionArgumentIdx] != DataTypeDescriptor.Bag))) { context.ProcessingError = true; context.Trace("There's a parameter with an invalid datatype"); return EvaluationValue.Indeterminate; } } } var sb = new StringBuilder(); // Call the function in a controlled evironment to capture any exception try { sb.Append(functionInstance.Id); sb.Append("( "); bool isFirst = true; foreach (IFunctionParameter param in arguments) { if (isFirst) { isFirst = false; } else { sb.Append(", "); } sb.Append(param.ToString()); } sb.Append(" )"); sb.Append(" = "); EvaluationValue returnValue = functionInstance.Evaluate(context, arguments); sb.Append(returnValue.ToString()); context.Trace(sb.ToString()); return returnValue; } catch (EvaluationException e) { context.Trace(sb.ToString()); context.ProcessingError = true; context.Trace("Error: {0}", e.Message); return EvaluationValue.Indeterminate; } } }
internal static Matrix ToMatrix(IFunction func) { int n = 20; double ub=5; var sup = func as ISupport1D; if (sup != null) ub = sup.Support[1]; var mat = new Matrix(n,2); for (int i = 0; i < n; i++) { double x = i*ub / n; mat[i, 0] = x; mat[i, 1] = func.Evaluate(x); } return mat; }
public HestonCallSimulationOptimizationProblem(EquityCalibrationData equityCalData, Vector matBound, Vector strikeBound) : base(equityCalData,matBound,strikeBound) { //this.dyFunc = equityCalData.dyFunc; this.dyFunc = CallEstimator.IstantaneousDividendYield(equityCalData); this.zrFunc = equityCalData.zrFunc; // Generates common random numbers I = (int)Math.Ceiling(cpmd.Maturity[Range.End] / dt); epsilon = new Matrix(I, 2*N); NewRandomNumbers(); // Precalculates istantaneous growth rates growth = new Vector(I); for (int i = 0; i < I; i++) { double t = i * dt; double zr_t = zrFunc.Evaluate(t); growth[i] = zr_t + FunctionHelper.Partial(zr_t,zrFunc, new Vector() { t }, 0, dt) * t - dyFunc.Evaluate(t); } Console.WriteLine("Heston Simulation Calibration: Paths=" + N); }
public static double LogAverageFactor(double y, IFunction func, Vector x) { return (y == func.Evaluate(x)) ? 0.0 : Double.NegativeInfinity; }
private Matrix LocVolMatrixFromImpliedVol(CallPriceMarketData Hdataset, IFunction impVol, out Vector locVolMat, out Vector locVolStr) { int nmat = calibrationSettings.LocalVolatilityMaturities; int nstrike = calibrationSettings.LocalVolatilityStrikes; double lastMat = Hdataset.Maturity[Range.End]; double lastStr = Hdataset.Strike[Range.End]; locVolMat = Vector.Linspace(Hdataset.Maturity[0], lastMat, nmat); locVolStr = Vector.Linspace(Hdataset.Strike[0], lastStr, nstrike); Matrix locVolMatrix = new Matrix(nmat, nstrike); Integrate integrate = new Integrate(this); double sigma, dSigmadk, num, y, den, avgGrowthRate; Vector x = new Vector(2); for (int i = 0; i < nmat; i++) { avgGrowthRate = integrate.AdaptLobatto(0.0, locVolMat[i]); int j = 0; x[0] = locVolMat[i]; x[1] = locVolStr[j]; sigma = impVol.Evaluate(x); dSigmadk = impVol.Partial(x, 1); num = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] * impVol.Partial(x, 0); den = 1.0; locVolMatrix[i, j] = Math.Sqrt(num / den); // The rest of the cycle. for (j = 1; j < nstrike; j++) { x[1] = locVolStr[j]; sigma = impVol.Evaluate(x); dSigmadk = impVol.Partial(x, 1); num = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] * (impVol.Partial(x, 0) + avgGrowthRate * x[1] * dSigmadk); y = Math.Log(locVolStr[j] / Hdataset.S0) + avgGrowthRate; den = System.Math.Pow(1.0 - x[1] * y * dSigmadk / sigma, 2) + x[1] * sigma * x[0] * (dSigmadk - 0.25 * x[1] * sigma * x[0] * dSigmadk * dSigmadk + x[1] * impVol.Partial2(x, 1)); locVolMatrix[i, j] = Math.Sqrt(num / den); } } return locVolMatrix; }