private void CalculatePrices() { if (S <= 0 || K <= 0 || r <= 0 || t <= 0 || sigma <= 0) { ErrorMsg = "Please, fill all fields with values >0"; return; } else { ErrorMsg = ""; try { var bc = new BlacksCholes { S = S, K = K, r = r, sigma = sigma, t = t }; BlacksCholesCalculator.CalculatePremium(ref bc); CallPrice = bc.Call; PutPrice = bc.Put; } catch (DivideByZeroException ex) { ErrorMsg = "if you use / make sure to add .0 to the end of the number for example 180/365.0"; return; } catch (Exception ex) { ErrorMsg = ex.Message; return; } } }
public static void CalculatePremium(ref BlacksCholes b) { b.d1 = Calculate_d1(b); b.d2 = Calculate_d2(b); b.Call = CalculateCallPrice(b); b.Put = CalculatePutPrice(b); }
public void Calculate_d2(double S, double K, double t, double sigma, double r, double d2) { //Arrange var blacksCholes = new BlacksCholes { S = S, K = K, t = t, sigma = sigma, r = r }; //Act BlacksCholesCalculator.CalculatePremium(ref blacksCholes); //Assert Assert.AreEqual(d2, Math.Round(blacksCholes.d2, 4)); }
//Calculate the value of d1 static double Calculate_d1(BlacksCholes b) { try { double d1 = ((Math.Log(b.S / b.K) + (b.r + Math.Pow(b.sigma, 2) / 2.0) * b.t)) / (b.sigma * Math.Sqrt(b.t)); if (double.IsInfinity(d1)) { throw new DivideByZeroException(); } return(d1); } catch (Exception ex) { throw ex; } }
//Calculate the value of Put price static double CalculatePutPrice(BlacksCholes b) { return(b.K * Math.Exp(-b.r * b.t) * NormalDistributionHelper.ND(-b.d2) - b.S * NormalDistributionHelper.ND(-b.d1)); }
//Calculate the value of d2 static double Calculate_d2(BlacksCholes b) { return(b.d1 - b.sigma * Math.Sqrt(b.t)); }