static double CumulativeNormDistFunction(double x) { try { double b0 = 0.2316419; double b1 = 0.319381530; double b2 = -0.356563782; double b3 = 1.781477937; double b4 = -1.821255978; double b5 = 1.330274429; double pi = Math.PI; double phi = Math.Exp(-x * x / 2.0) / Math.Sqrt(2.0 * pi); double t, c; double CDF = 0.5; if (x > 0.0) { t = 1.0 / (1.0 + b0 * x); CDF = 1.0 - phi * (b1 * t + b2 * Math.Pow(t, 2) + b3 * Math.Pow(t, 3) + b4 * Math.Pow(t, 4) + b5 * Math.Pow(t, 5)); } else if (x < 0.0) { x = -x; t = 1.0 / (1.0 + b0 * x); c = 1.0 - phi * (b1 * t + b2 * Math.Pow(t, 2) + b3 * Math.Pow(t, 3) + b4 * Math.Pow(t, 4) + b5 * Math.Pow(t, 5)); CDF = 1.0 - c; } return(CDF); } catch (Exception ex) { throw; } }
// For performance improvements Color and Spatial functions are recalculated prior to filter execution and put into 2 dimensional arrays private void InitSpatialFunc( ) { if ((spatialFunc == null) || (spatialFunc.Length != kernelSize * kernelSize) || (spatialPropertiesChanged)) { if ((spatialFunc == null) || (spatialFunc.Length != kernelSize * kernelSize)) { spatialFunc = new double[kernelSize, kernelSize]; } int kernelRadius = kernelSize / 2; for (int i = 0; i < kernelSize; i++) { int ti = i - kernelRadius; int ti2 = ti * ti; for (int k = 0; k < kernelSize; k++) { int tk = k - kernelRadius; int tk2 = tk * tk; spatialFunc[i, k] = M.Exp(-0.5 * M.Pow(M.Sqrt((ti2 + tk2) / spatialFactor), spatialPower)); } } spatialPropertiesChanged = false; } }
public Task <QuotationResult> CalculatePremiums(QuotationInput quoteparams) { try { return(Task.Run(() => { double d1 = 0.0; double d2 = 0.0; QuotationResult quotes = new QuotationResult(); double S = double.Parse(quoteparams.StockPrice.Replace(".", ",")); double K = double.Parse(quoteparams.StrikePrice.Replace(".", ",")); double T = double.Parse(quoteparams.TimeToMaturity.Replace(".", ",")); double r = double.Parse(quoteparams.InterestRate.Replace(".", ",")); double v = double.Parse(quoteparams.Volatility.Replace(".", ",")); d1 = Math.Round((Math.Log(S / K) + (r + v * v / 2.0) * T) / v / Math.Sqrt(T), 4); d2 = Math.Round(d1 - v * Math.Sqrt(T), 4); quotes.D1 = d1; quotes.D2 = d2; quotes.CallPremium = Math.Round(S * CumulativeNormDistFunction(d1) - K * Math.Exp(-r * T) * CumulativeNormDistFunction(d2), 4); quotes.PutPremium = Math.Round(K * Math.Exp(-r * T) * CumulativeNormDistFunction(-d2) - S * CumulativeNormDistFunction(-d1), 4); return quotes; })); } catch (Exception ex) { throw; } }
// For performance improvements Color and Spatial functions are recalculated prior to filter execution and put into 2 dimensional arrays private void InitSpatialFunc( ) { if ((this.spatialFunc == null) || (this.spatialFunc.Length != this.kernelSize * this.kernelSize) || (this.spatialPropertiesChanged)) { if ((this.spatialFunc == null) || (this.spatialFunc.Length != this.kernelSize * this.kernelSize)) { this.spatialFunc = new double[this.kernelSize, this.kernelSize]; } var kernelRadius = this.kernelSize / 2; for (var i = 0; i < this.kernelSize; i++) { var ti = i - kernelRadius; var ti2 = ti * ti; for (var k = 0; k < this.kernelSize; k++) { var tk = k - kernelRadius; var tk2 = tk * tk; this.spatialFunc[i, k] = M.Exp(-0.5 * M.Pow(M.Sqrt((ti2 + tk2) / this.spatialFactor), this.spatialPower)); } } this.spatialPropertiesChanged = false; } }
/// <summary> /// /// </summary> /// <param name="point"></param> /// <returns></returns> public override double Value(IPoint point) { var time = (double)point.Coords[0]; var value = base.Value(point); return(Math.Exp(-time * value)); }
/// <summary> /// Computes the error function for x. Adopted from http://www.johndcook.com/cpp_erf.html /// </summary> /// <param name="x"></param> /// <returns></returns> public static double Erf(double x) { // constants double a1 = 0.254829592; double a2 = -0.284496736; double a3 = 1.421413741; double a4 = -1.453152027; double a5 = 1.061405429; double p = 0.3275911; // Save the sign of x int sign = 1; if (x < 0) { sign = -1; } x = M.Abs(x); // A&S formula 7.1.26 double t = 1.0 / (1.0 + p * x); double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * M.Exp(-x * x); return(sign * y); }
/// <summary> /// Converts from the zero rate to a terminal wealth. /// </summary> /// <param name="rate"></param> /// <param name="yearFraction"></param> /// <param name="compoundingFrequency"></param> /// <returns></returns> public static decimal TerminalWealthFromZeroRate(decimal rate, decimal yearFraction, CompoundingFrequencyEnum compoundingFrequency) { double compoundingPeriod = GetCompoundingPeriod(compoundingFrequency); decimal result; if (compoundingPeriod == 0) { result = (decimal)Math.Exp(Convert.ToDouble(-rate * yearFraction)); } else { decimal df; if ((double)yearFraction > compoundingPeriod) { df = (decimal)Math.Pow(1 + compoundingPeriod * (double)rate, (double)yearFraction); } else { df = 1 + yearFraction * rate; } result = 1 / df; } return(result); }
public static float[,] CalculateGaussianKernel(int W, double sigma) { float[,] kernel = new float[W, W]; double mean = W / 2.0; float sum = 0.0f; for (int x = 0; x < W; ++x) { for (int y = 0; y < W; ++y) { kernel[x, y] = (float)(Math.Exp(-0.5 * (Math.Pow((x - mean) / sigma, 2.0) + Math.Pow((y - mean) / sigma, 2.0))) / (2 * Math.PI * sigma * sigma)); sum += kernel[x, y]; } } for (int x = 0; x < W; ++x) { for (int y = 0; y < W; ++y) { kernel[x, y] *= (1.0f) / sum; } } return(kernel); }
private float[] Softmax(float[] values) { var maxVal = values.Max(); var exp = values.Select(v => Math.Exp(v - maxVal)); var sumExp = exp.Sum(); return(exp.Select(v => (float)(v / sumExp)).ToArray()); }
/// <summary> /// Bootstraps the specified priceable assets. /// </summary> /// <param name="priceableAssets">The priceable assets.</param> /// <param name="baseDate">The base date.</param> /// <param name="extrapolationPermitted">The extrapolationPermitted flag.</param> /// <param name="interpolationMethod">The interpolationMethod.</param> /// <param name="tolerance">Solver tolerance to use.</param> /// <returns></returns> public static TermPoint[] Bootstrap(List <IPriceableFxAssetController> priceableAssets, DateTime baseDate, Boolean extrapolationPermitted, InterpolationMethod interpolationMethod, Double tolerance) { const Double solveRateGap = 0.015d;//should we need more precising perhaps??? const Decimal dfamMinThreshold = 0.0m; const Decimal defaultGuess = 0.9m; const Double accuracy = 0.000001d; InterpolationMethod interp = InterpolationMethodHelper.Parse("LinearInterpolation"); //only works for linear on zero. priceableAssets = priceableAssets.OrderBy(a => a.GetRiskMaturityDate()).ToList(); var dates = new List <DateTime>(); var discountFactors = new List <double>(); var items = new Dictionary <DateTime, Pair <string, decimal> >(); bool firstTime = true; foreach (var asset in priceableAssets) { DateTime assetMaturityDate = asset.GetRiskMaturityDate(); //check if the maturity date is already in the list. If not contimue. if (items.ContainsKey(assetMaturityDate)) { continue; } decimal guess = asset.ForwardAtMaturity > dfamMinThreshold ? asset.ForwardAtMaturity : defaultGuess; decimal dfam; if (firstTime) { firstTime = false; dates.Add(assetMaturityDate); discountFactors.Add(Convert.ToDouble(guess)); dfam = asset.CalculateImpliedQuote(new SimpleFxCurve(baseDate, interp, extrapolationPermitted, dates, discountFactors)); discountFactors[0] = (double)dfam; } else { //The first guess, which should be correct for all priceable assets with analytical solutions that have been implemented. //So far this is only wrt Depos and Futures...This now should automatically extrapolate the required discount factor on a flat rate basis. dfam = asset.CalculateImpliedQuote(new SimpleFxCurve(baseDate, interp, extrapolationPermitted, dates, discountFactors)); discountFactors.Add((double)dfam); dates.Add(assetMaturityDate); } //Add a check on the dfam so that the solver is only called if outside the tolerance. var objectiveFunction = new FxAssetQuote(asset, baseDate, interpolationMethod, extrapolationPermitted, dates, discountFactors, tolerance); if (!objectiveFunction.InitialValue()) { var timeInterval = Actual365.Instance.YearFraction(baseDate, assetMaturityDate); var solveInterval = Math.Exp(-solveRateGap * timeInterval); var min = Math.Max(0, (double)dfam * solveInterval); var max = (double)dfam / solveInterval; var solver = new Brent(); dfam = (decimal)solver.Solve(objectiveFunction, accuracy, (double)dfam, min, max); } items.Add(assetMaturityDate, new Pair <string, decimal>(asset.Id, dfam)); } return(TermPointsFactory.Create(items)); }
/// <summary> /// /// </summary> /// <param name="amplitude"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="centerX"></param> /// <param name="Y"></param> /// <param name="sigmaX"></param> /// <param name="sigmaY"></param> /// <returns></returns> public static double Gaussian(double amplitude, double x, double y, double centerX, double centerY, double sigmaX, double sigmaY) { double cx = x - centerX; double cy = y - centerY; double componentX = (cx * cx) / (2.0f * sigmaX * sigmaX); double componentY = (cy * cy) / (2.0f * sigmaY * sigmaY); return(amplitude * SysMath.Exp(-(componentX + componentY))); }
private CellDimensions MapBoundingBoxToCell(int x, int y, int box, BoundingBoxDimensions boxDimensions) { return(new CellDimensions { X = ((float)y + Sigmoid(boxDimensions.X)) * CELL_WIDTH, Y = ((float)x + Sigmoid(boxDimensions.Y)) * CELL_HEIGHT, Width = (float)Math.Exp(boxDimensions.Width) * CELL_WIDTH * anchors[box * 2], Height = (float)Math.Exp(boxDimensions.Height) * CELL_HEIGHT * anchors[box * 2 + 1], }); }
static List <double> GetResolutions() { List <double> ret = new List <double>(); for (float i = 0.01f; i < 7f; i += 0.1f) { ret.Add(Math.Exp(i)); } return(ret); }
/// <summary> /// *** /// *** Term to Maturity is No_of_Periods /// *** Tenor is now known from the input data (in years) /// *** IR Vol is driven by the remaining Term to Maturity /// *** Rate is driven by the remaining Term to Maturity. /// *** /// </summary> /// <param name="term"></param> /// <param name="tenor"></param> /// <param name="rate">Rate = Get_Rate(Term, Rate_Col_no)</param> /// <param name="irVol">IR_Vol = Get_IRVol(Term, IRVol_Col_no)</param> /// <param name="meanRev"></param> /// <param name="ci"></param> /// <param name="time"></param> /// <returns></returns> public static double FraPCE(double term, double tenor, double rate, double irVol, double meanRev, double ci, double time) { //**** diffusion component double temp1 = Math.Sqrt((1.0D - Math.Exp(-2.0D * meanRev * time)) / (2.0D * meanRev)); return(rate * ci * irVol * tenor * temp1); }
/// <summary> /// calculates the PCE at a point in time /// </summary> /// <param name="term"></param> /// <param name="rate">Rate = Get_Rate(Term, Rate_Col_no)</param> /// <param name="fxVol"></param> /// <param name="meanRev"></param> /// <param name="ci"></param> /// <param name="time"></param> /// <returns></returns> public static double FxForwardPCE(double term, double rate, double fxVol, double meanRev, double ci, double time) { //**** diffusion component double temp1 = fxVol * ci * Math.Sqrt((1.0D - Math.Exp(-2.0D * meanRev * time)) / (2.0D * meanRev)); double temp2 = Math.Exp(-rate * (term - time)); //**** discounting return(temp1 * temp2); }
/// <summary> /// Calculates closed form PCE for fx forward /// </summary> /// <param name="maturity">Time (in days) to maturity of contract</param> /// <param name="time">Time horizon (in days)</param> /// <param name="ci">Confidence level</param> /// <param name="volatility">Currency pair volatility</param> /// <param name="reversion">Reversion rate</param> /// <param name="faceValue">Amount of currency - Size of trade </param> /// <returns></returns> public static double FxFwdPCE(double maturity, double time, double ci, double volatility, double reversion, double faceValue) { if ((time < 0) || (time > maturity)) { return(0.0); } return(faceValue * ci * volatility * Math.Sqrt((1 - Math.Exp(-2 * reversion * time / 365)) / (2 * reversion))); }
private static double AltInterestRateSwapPCE(double rateRenamed, double tenor, double time, double ci, double volatility, double reversion) { //calculates the PCE at a point in time if ((time < 0) || (time > tenor)) // Evaluate argument. { //Invalid form return(0D); //Exit to calling procedure. } double srs = volatility * Math.Sqrt((1 - Math.Exp(-2.0 * reversion * time / 365.0)) / (2.0 * reversion)); return((1.0 - Math.Pow((1.0 + rateRenamed), ((time - tenor) / 365.0))) * (1.0 - Math.Exp(-ci * srs))); }
/// <summary> /// **** /// **** Repurchase Agreements - Cash Settled /// **** /// **** Term to Expiry - seen on input as No_of_Periods /// **** Tenor - seen on input /// **** IR vol is driven by Term to Expiry /// **** Rate is driven by the Tenor /// **** /// </summary> /// <param name="term"></param> /// <param name="tenor"></param> /// <param name="rate">Rate = Get_Rate(Tenor, Rate_Col_no)</param> /// <param name="irVol">IR_Vol = Get_IRVol(Term, IRVol_Col_no)</param> /// <param name="meanRev"></param> /// <param name="ci"></param> /// <param name="time"></param> /// <returns></returns> public static double RepoPCE(double term, double tenor, double rate, double irVol, double meanRev, double ci, double time) { //**** diffusion component double temp1 = irVol * ci * Math.Sqrt((1.0D - Math.Exp(-2.0D * meanRev * time)) / (2.0D * meanRev)); double temp2 = 1.0D - Math.Exp(-temp1); double temp3 = 1.0D - Math.Pow((1.0D + rate), (-1.0D * (tenor - term))); //*** PV of future cash flows return(temp3 * temp2); }
/// <summary> /// calculates the PCE at a point in time /// /// *** Term to Maturity is No_of_Periods /// *** IR Vol is driven by this period /// *** Rate is driven by this period. /// </summary> /// <param name="term"></param> /// <param name="rate">Rate = Get_Rate(Term, Rate_Col_no)</param> /// <param name="irVol">IR_Vol = Get_IRVol(Term, IRVol_Col_no)</param> /// <param name="meanRev"></param> /// <param name="ci"></param> /// <param name="time"></param> /// <returns></returns> public static double IRSwapPCE(double term, double rate, //Rate based on Term and group double irVol, //IR vol double meanRev, double ci, double time) { //**** diffusion component double diffusion = Math.Sqrt((1.0D - Math.Exp(-2.0D * meanRev * time)) / (2.0D * meanRev)); diffusion = 1.0D - Math.Exp(-1.0 * irVol * ci * diffusion); //*** PV of future cash flows double cashflow = 1.0D - Math.Pow((1.0D + rate / 2.0D), (-2.0D * (term - time))); return(cashflow * diffusion); }
/// <summary> /// /// **** Bought swaption - Cash Settled /// **** /// **** Term to Expiry - seen on input as No_of_Periods /// **** Tenor - now known /// **** IR vol is driven by Term to Expiry /// **** Rate is driven by Tenor - should be fwd rate but will proxy this by spot rate. /// </summary> /// <param name="term"></param> /// <param name="tenor"></param> /// <param name="rate">Get_Rate(Tenor, Rate_Col_no)</param> /// <param name="irVol">Get_IRVol(Term, IRVol_Col_no)</param> /// <param name="meanRev"></param> /// <param name="ci"></param> /// <param name="time"></param> /// <returns></returns> public static double SwaptionPCE(double term, double tenor, double rate, double irVol, double meanRev, double ci, double time) { //**** diffusion component double temp1 = irVol * ci * Math.Sqrt((1.0D - Math.Exp(-2.0D * meanRev * time)) / (2.0D * meanRev)); double temp2 = 1.0D - Math.Exp(-temp1); double temp3 = 1.0D - Math.Pow((1.0D + rate / 2.0D), (-2.0D * tenor)); //*** PV of future cash flows double temp4 = Math.Pow((1.0D + rate / 2.0D), (-2.0D * (term - time))); //*** discounting return(temp4 * temp3 * temp2); }
public double[] t_i() { double[] result = new double[K + 1]; double C = 1; double m = m_params.M; double t_1 = C / m * Math.Exp(-m / Flux); result[1] = t_1; for (int i = 2; i <= K; i++) { result[i] = Phi(s_i[i]) / Phi(s_i[1]) * t_1; } return(result); }
///<summary> ///</summary> ///<param name="zeroRate"></param> ///<param name="yearFraction"></param> ///<param name="compoundingPeriod"></param> ///<returns></returns> public static double ZeroRateToDiscountFactor(double zeroRate, double yearFraction, double compoundingPeriod) { double result; if (compoundingPeriod == 0) { result = Math.Exp(zeroRate * -yearFraction); } else { double baseNumber = 1 + zeroRate * compoundingPeriod; double power = -yearFraction / compoundingPeriod; result = Math.Pow(baseNumber, power); } return(result); }
private void MapControlMouseWheel(object sender, MouseWheelEventArgs e) { if (MapControl.Map.ZoomLock) { return; } if (!MapControl.Viewport.HasSize) { return; } var _currentMousePosition = e.GetPosition(this).ToMapsui(); resolution = Math.Exp((e.Delta / 120) * -0.1f) * resolution; // Limit target resolution before animation to avoid an animation that is stuck on the max resolution, which would cause a needless delay resolution = MapControl.Map.Limiter.LimitResolution(resolution, MapControl.Viewport.Width, MapControl.Viewport.Height, MapControl.Map.Resolutions, MapControl.Map.Envelope); MapControl.Navigator.ZoomTo(resolution, _currentMousePosition, MapControl.MouseWheelAnimation.Duration, MapControl.MouseWheelAnimation.Easing); }
/// <summary> /// Evaluates the implied quote. /// </summary> /// <returns></returns> private static Double EvaluateAdjustmentRate(double rate, double volatility, double timeToExpiry) { try { double x = Math.Pow(volatility, 2); double t = timeToExpiry; double y = Math.Exp(x * t) - 1; double factor1 = 2 * y; double factor2 = t * rate - 1; double factor3 = Math.Pow(factor2, 2); double factor4 = 4 * rate / x * y; return(x / factor1 * (factor2 + Math.Sqrt(factor3 + factor4))); } catch { throw new Exception("Real solution does not exist"); } }
/// <summary> /// Evaluates the implied quote. /// </summary> /// <returns></returns> private static Double EvaluateImpliedVolatility(double rate, double volatility, double timeToExpiry) { try { var x = Math.Pow(volatility, 2); var t = timeToExpiry; var y = Math.Exp(x * t) - 1; var factor1 = 2 * y; var factor2 = t * rate - 1; var factor3 = Math.Pow(factor2, 2); var factor4 = 4 * rate / x * y; return(x / factor1 * (factor2 + Math.Sqrt(factor3 + factor4))); } catch { throw new Exception("Real solution does not exist"); } }
///<summary> ///</summary> ///<param name="rateRenamed"></param> ///<param name="bondTenor"></param> ///<param name="repoMaturity"></param> ///<param name="time"></param> ///<param name="ci"></param> ///<param name="volatility"></param> ///<param name="reversion"></param> ///<returns></returns> public static double AltRepoPCE(double rateRenamed, double bondTenor, double repoMaturity, double time, double ci, double volatility, double reversion) { //calculates the PCE at a point in time if ((time < 0) || (time > repoMaturity)) { return(0.0D); //Invalid form } //estimate PCE at time t double srs = volatility * Math.Sqrt((1.0 - Math.Exp(-2 * reversion * time / 365)) / (2 * reversion)); return((1.0 - Math.Pow((1.0 + rateRenamed), ((time - bondTenor) / 365))) * (1.0 - Math.Exp(-ci * srs))); }
// For performance improvements Color and Spatial functions are recalculated prior to filter execution and put into 2 dimensional arrays private void InitColorFunc( ) { if ((this.colorFunc == null) || (this.colorPropertiesChanged)) { if (this.colorFunc == null) { this.colorFunc = new double[colorsCount, colorsCount]; } for (var i = 0; i < colorsCount; i++) { for (var k = 0; k < colorsCount; k++) { this.colorFunc[i, k] = M.Exp(-0.5 * (M.Pow(M.Abs(i - k) / this.colorFactor, this.colorPower))); } } this.colorPropertiesChanged = false; } }
// For performance improvements Color and Spatial functions are recalculated prior to filter execution and put into 2 dimensional arrays private void InitColorFunc( ) { if ((colorFunc == null) || (colorPropertiesChanged)) { if (colorFunc == null) { colorFunc = new double[colorsCount, colorsCount]; } for (int i = 0; i < colorsCount; i++) { for (int k = 0; k < colorsCount; k++) { colorFunc[i, k] = M.Exp(-0.5 * (M.Pow(M.Abs(i - k) / colorFactor, colorPower))); } } colorPropertiesChanged = false; } }
/// <summary> /// Calculates PCE for fx forward /// </summary> /// <param name="maturity">Time (in days) to maturity of contract</param> /// <param name="time">Time horizon (in days) for PCE calculation</param> /// <param name="ci">Confidence level</param> /// <param name="volatility">Currency pair volatility - Measure of the riskiness of the currency pair’s exchange rate</param> /// <param name="reversion">Reversion rate</param> /// <param name="interest">Interest rate</param> /// <returns></returns> private static double AltFwdFxpce(double maturity, double time, double ci, double volatility, double reversion, double interest) { //calculates the PCE at a point in time // Evaluate argument. if ((time < 0) || (time > maturity)) { return(0.0); //Invalid form } //estimate PCE at time t double functionReturnValue = Math.Exp(-interest * (maturity - time) / 365) * ci * volatility * Math.Sqrt((1 - Math.Exp(-2 * reversion * time / 365)) / (2 * reversion)); return(functionReturnValue); }
public static double Exp(double power) => Math.Exp(power);