Exemplo n.º 1
0
        public double GetEuroPrice(double volatility /*sigma*/)
        {
            // Return reasonable values for expired options
            if (_maturity <= 0)
            {
                return(_callOrPut == LegType.Call
                                                        ? _spotPrice - _strikePrice
                                                        : _strikePrice - _spotPrice);
            }

            double result;

            if (_callOrPut == LegType.Call)
            {
                result = (_spotPrice * Math.Exp(-_divYield * _maturity) * NormDistribution.CumulativeDistribution(D1(volatility))) -
                         (_strikePrice * Math.Exp(-_interestRate * _maturity) * NormDistribution.CumulativeDistribution(D2(volatility)));
            }
            else
            {
                result = (_strikePrice * Math.Exp(-_interestRate * _maturity) *
                          NormDistribution.CumulativeDistribution(-D2(volatility))) -
                         (_spotPrice * Math.Exp(-_divYield * _maturity) * NormDistribution.CumulativeDistribution(-D1(volatility)));
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Theta = first derivative of price with respect to time to expiration.
        /// </summary>
        /// <returns>theta of the option</returns>
        public static double BlackScholesTheta(this EuropeanOption option, Date valueDate, double spot, double vol, double rate, double div)
        {
            var    dist = new Normal();
            var    T    = (double)(option._exerciseDate - valueDate) / 365;
            double d1   = D1(spot, option._strike, vol, rate, div, T);
            double d2   = D2(spot, option._strike, vol, rate, div, T);
            double theta;

            var flag = (double)option._putOrCall;

            double t1 = (Math.Exp(-div * T) * spot * dist.Density(d1) * vol * 0.5) / Math.Sqrt(T);
            double t2 = div * Math.Exp(-div * T) * spot * dist.CumulativeDistribution(flag * d1);
            double t3 = rate * option._strike * Math.Exp(-rate * T) * dist.CumulativeDistribution(flag * d2);

            if (option._putOrCall == PutOrCall.Call)
            {
                theta = -t1 + t2 - t3;
            }
            else
            {
                theta = -t1 - t2 + t3;
            }

            return(theta);
        }
Exemplo n.º 3
0
        public static stats GenStats(List <List <round> > input)
        {
            List <double> faction_damage = new List <double> ();
            List <double> asset_damage   = new List <double> ();

            foreach (var i in input)
            {
                faction_damage.Add(i.Select(e => Convert.ToDouble(e.direct_faction_damage)).Sum());

                asset_damage.Add(i.Select(e => Convert.ToDouble(e.damage)).Sum());
            }

            var statistics = new DescriptiveStatistics(faction_damage);
            var stats      = new stats();

            stats.faction_stats.Maximum = statistics.Maximum;
            stats.faction_stats.Minimum = statistics.Minimum;
            // stats.values.Median = statistics.Median;

            stats.faction_stats.Mean              = statistics.Mean;
            stats.faction_stats.Variance          = statistics.Variance;
            stats.faction_stats.StandardDeviation = statistics.StandardDeviation;

            stats.faction_stats.Kurtosis = statistics.Kurtosis;
            stats.faction_stats.Skewness = statistics.Skewness;

            statistics = new DescriptiveStatistics(asset_damage);

            stats.asset_stats.Maximum = statistics.Maximum;
            stats.asset_stats.Minimum = statistics.Minimum;
            // stats.values.Median = statistics.Median;

            stats.asset_stats.Mean              = statistics.Mean;
            stats.asset_stats.Variance          = statistics.Variance;
            stats.asset_stats.StandardDeviation = statistics.StandardDeviation;

            stats.asset_stats.Kurtosis = statistics.Kurtosis;
            stats.asset_stats.Skewness = statistics.Skewness;

            Normal fac_normal = new Normal(stats.faction_stats.Mean, stats.faction_stats.StandardDeviation, Program.rand);

            Normal asset_normal = new Normal(stats.asset_stats.Mean, stats.asset_stats.StandardDeviation, Program.rand);

            for (int i = Convert.ToInt32(Math.Floor(stats.faction_stats.Minimum)); i < stats.faction_stats.Maximum; i++)
            {
                double item1 = fac_normal.CumulativeDistribution(i);

                stats.faction_stats.normalized_dist.Add((i, item1));
            }

            for (int i = Convert.ToInt32(Math.Floor(stats.asset_stats.Minimum)); i < stats.asset_stats.Maximum; i++)
            {
                double item1 = fac_normal.CumulativeDistribution(i);

                stats.asset_stats.normalized_dist.Add((i, item1));
            }

            return(stats);
        }
Exemplo n.º 4
0
        /// <summary>
        /// The Black the scholes formula
        /// </summary>
        /// <param name="putOrCall">put or call.</param>
        /// <param name="K">The strike.</param>
        /// <param name="T">The time to maturity in years.</param>
        /// <param name="S">The underlying spot price.</param>
        /// <param name="vol">The lognormal volatility of the underlying price.</param>
        /// <param name="rate">The continuous rate used for drifting the underlying and discounting the payoff.</param>
        /// <param name="div">The contiuous dividend yield that decreased the drift on the underlying.</param>
        /// <returns></returns>
        public static double BlackScholes(PutOrCall putOrCall, double K, double T, double S, double vol, double rate, double div)
        {
            Normal dist       = new Normal();
            double sigmaSqrtT = vol * Math.Sqrt(T);
            double d1         = (1 / sigmaSqrtT) * (Math.Log(S / K) + rate - div + 0.5 * vol * vol);
            double d2         = d1 - sigmaSqrtT;
            double F          = S * Math.Exp((rate - div) * T);

            return(Math.Exp(-rate * T) * (F * dist.CumulativeDistribution(d1) - K * dist.CumulativeDistribution(d2)));
        }
        //public int CompareTo(NeuralPredictionModel other)
        //{
        //    double otherAcc = other._accuracy;
        //    double thisAcc = _accuracy;
        //    double thisWeight = _score;
        //    double otherWeight = other._score;

        //    if (thisAcc != otherAcc)
        //        return otherAcc.CompareTo(thisAcc);
        //    else
        //        return otherWeight.CompareTo(thisWeight);
        //}

        //public override bool Equals(object obj)
        //{
        //    var other = (NeuralPredictionModel)obj;

        //    if (other._accuracy == _accuracy)
        //    {
        //        if (other._score == _score)
        //            return true;
        //        else
        //            return false;
        //    }

        //    return false;
        //}

        //public override int GetHashCode()
        //{
        //    return base.GetHashCode();
        //}

        //public static bool operator ==(NeuralPredictionModel x, NeuralPredictionModel y)
        //{
        //    if (x._accuracy == y._accuracy)
        //    {
        //        if (x._score == y._score)
        //            return true;
        //        else
        //            return false;
        //    }

        //    return false;
        //}

        //public static bool operator !=(NeuralPredictionModel x, NeuralPredictionModel y)
        //{
        //    if (x._accuracy == y._accuracy)
        //    {
        //        if (x._score == y._score)
        //            return false;
        //        else
        //            return true;
        //    }

        //    return true;
        //}

        //public static bool operator >(NeuralPredictionModel x, NeuralPredictionModel y)
        //{
        //    if (x._accuracy > y._accuracy)
        //        return true;
        //    else
        //    {
        //        if (x._accuracy == y._accuracy)
        //        {
        //            if (x._score > y._score)
        //                return true;
        //            else
        //                return false;
        //        }
        //        else
        //            return false;
        //    }
        //}

        //public static bool operator <(NeuralPredictionModel x, NeuralPredictionModel y)
        //{
        //    if (x._accuracy < y._accuracy)
        //        return true;
        //    else
        //    {
        //        if (x._accuracy == y._accuracy)
        //        {
        //            if (x._score < y._score)
        //                return true;
        //            else
        //                return false;
        //        }
        //        else
        //            return false;
        //    }
        //}

        /// <summary>
        /// Finds the percentage of potential ratings that are above the potential renewal thresholds. Use Log values.
        /// </summary>
        /// <param name="Mean1">Projected Rating</param>
        /// <param name="SD1">Standard Deviation for Projected Rating</param>
        /// <param name="Mean2">Renewal Threshold Rating</param>
        /// <param name="SD2">Standard Deviation for Renewal Thresholds</param>
        /// <returns></returns>
        double AreaOfOverlap(double Mean1, double SD1, double Mean2, double SD2)
        {
            //Find intersection points
            double point1, point2;

            var Distribution1 = new Normal(Mean1, SD1);
            var Distribution2 = new Normal(Mean2, SD2);

            if (SD1 * SD2 == 0)
            {
                return(0);
            }

            if (SD1 == SD2)
            {
                point1 = (Mean1 + Mean2) / 2;
                point2 = point1;
            }
            else
            {
                //Find Square of each SD
                double
                    Squared1 = Math.Pow(SD1, 2),
                    Squared2 = Math.Pow(SD2, 2);

                //Then find part that will be positive and negative radical

                var radical = Math.Sqrt(Math.Pow(Mean1 - Mean2, 2) + 2 * (Squared1 - Squared2) * Math.Log(SD1 / SD2));

                point1 = (Mean2 * Squared1 - SD2 * (Mean1 * SD2 + SD1 * radical)) / (Squared1 - Squared2);
                point2 = (Mean2 * Squared1 - SD2 * (Mean1 * SD2 + SD1 * -radical)) / (Squared1 - Squared2);
            }

            if (point1 == point2)
            {
                return((1 - Distribution1.CumulativeDistribution(point1)) * 2);
            }
            else
            {
                var min = Math.Min(point1, point2);
                var max = Math.Max(point1, point2);

                var beginning1 = Distribution1.CumulativeDistribution(min);
                var beginning2 = Distribution2.CumulativeDistribution(min);


                var middle1 = Distribution1.CumulativeDistribution(max) - Distribution1.CumulativeDistribution(min);
                var middle2 = Distribution2.CumulativeDistribution(max) - Distribution2.CumulativeDistribution(min);

                var end1 = 1 - Distribution1.CumulativeDistribution(max);
                var end2 = 1 - Distribution2.CumulativeDistribution(max);

                return(Math.Min(beginning1, beginning2) + Math.Min(middle1, middle2) + Math.Min(end1, end2));
            }
        }
Exemplo n.º 6
0
        // Helper function that calculates the probability of no tag read for a given
        // amount of time T.
        // Calculates 1 - (integral from 0 to T of gaussian+),
        // where gaussian+ is when we consider only the positive values in the Gaussian
        // distribution and then renormalize.
        private double probNoTagRead(double T, bool visible)
        {
            Normal dist = this.coveredDist;

            if (visible)
            {
                dist = this.visibleDist;
            }

            return(1.0 - (dist.CumulativeDistribution(T) - dist.CumulativeDistribution(0)) / (1.0 - dist.CumulativeDistribution(0)));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Updates the Kelly Criterion values
        /// </summary>
        public void UpdateScores()
        {
            try
            {
                // need at least 2 samples
                if (_requiresRecalculation && _insightValues.Count > 1)
                {
                    _requiresRecalculation = false;

                    var averagePowered = Math.Pow(_average, 2);

                    var variance               = _insightValues.Variance();
                    var denominator            = averagePowered + variance;
                    var kellyCriterionEstimate = denominator.IsNaNOrZero() ? 0 : _average / denominator;

                    KellyCriterionEstimate = kellyCriterionEstimate.SafeDecimalCast();

                    var variancePowered = Math.Pow(variance, 2);
                    var kellyCriterionStandardDeviation = Math.Sqrt(
                        (1 / variance + 2 * averagePowered / variancePowered)
                        / _insightValues.Count - 1);

                    KellyCriterionProbabilityValue = kellyCriterionStandardDeviation.IsNaNOrZero() ? 1 :
                                                     1 - _normalDistribution.CumulativeDistribution(kellyCriterionEstimate / kellyCriterionStandardDeviation)
                                                     .SafeDecimalCast();
                }
            }
            catch (Exception exception)
            {
                // just in case...
                Log.Error(exception);
            }
        }
Exemplo n.º 8
0
        public static double CF_Modified_Kirk(double S1_0, double S2_0,
                                              double K, double rho, double T, double r,
                                              double sigma1, double sigma2)
        {
            //Here we calculate our volatility
            double a_kirk  = Math.Sqrt(Math.Pow(sigma1, 2) - 2 * rho * sigma1 * sigma2 * (S2_0 / (S2_0 + K)) + Math.Pow(sigma2 * (S2_0 / (S2_0 + K)), 2));
            double X_t     = Math.Log(S1_0);
            double x_aster = Math.Log(S2_0 + K);
            double I_t     = Math.Sqrt(Math.Pow(a_kirk, 2)) + 0.5 * (Math.Pow((sigma2 * S2_0 / (S2_0 + K)) - rho * sigma1, 2)) * (1 / (Math.Pow(Math.Sqrt(Math.Pow(a_kirk, 2)), 3))) * Math.Pow(sigma2, 2) * ((S2_0 * K) / (Math.Pow(S2_0 + K, 2))) * (X_t - x_aster);

            //Here we calculate our d1 and d2
            double S  = S1_0 / (S2_0 + K);
            double d1 = (Math.Log(S) + 0.5 * Math.Pow(I_t, 2) * T) / (I_t * Math.Sqrt(T));
            double d2 = d1 - I_t * Math.Sqrt(T);

            //Fit a normal distribution
            var normal = new Normal(0, 1);

            //#Here we use the above calculations to approximate the call spread using Kirk's formula
            double C_modified_kirk = S1_0 * normal.CumulativeDistribution(d1) - (S2_0 + K) * normal.CumulativeDistribution(d2);

            C_modified_kirk *= Math.Exp(-r * T);

            return(C_modified_kirk);
        }
        protected override double Transform(double value)
        {
            var result = normal.CumulativeDistribution(value);

            result = result * difference + lower;
            return(result);
        }
        /// <summary> Takes two normal distributions and returns the probability that a point sample from of the first will be greater than one from the second. That is, the probability of discarding A because of B. </summary>
        /// <param name="A">A normal distribution</param>
        /// <param name="B">Another normal distribution</param>
        /// <returns>P(A>B)</returns>
        public static double PairwiseExact(Normal A, Normal B)
        {
            Normal BMinusA = new Normal(mean: B.Mean - A.Mean,
                                        stddev: Math.Sqrt(A.Variance + B.Variance));

            return(BMinusA.CumulativeDistribution(0));
        }
Exemplo n.º 11
0
        protected override double Transform(double value)
        {
            var result = normal.CumulativeDistribution(value);

            result = distribution.InverseCumulativeDistribution(result);
            return(result);
        }
Exemplo n.º 12
0
        public static double BSPricing(double s, double k, double t, double r, double sigma, OptionTypeEnum optionType)
        {
            double[] dValueArray = GetDValues(s, k, t, r, sigma, optionType);
            double   d1          = dValueArray[0];
            double   d2          = dValueArray[1];

            Normal normal = new Normal();

            if (optionType == OptionTypeEnum.Call)
            {
                return(s * normal.CumulativeDistribution(d1) - k * Math.Exp(-r * t) * normal.CumulativeDistribution(d2));
            }
            else
            {
                return(k * Math.Exp(-r * t) * normal.CumulativeDistribution(-d2) - s * normal.CumulativeDistribution(-d1));
            }
        }
Exemplo n.º 13
0
    public double pWartosc(double value)
    {
        Normal norm = new Normal();
        double next = norm.CumulativeDistribution(value);

        //    Console.WriteLine("dystriusa:  " + next);
        return(next);
    }
Exemplo n.º 14
0
        // Implied Volatility
        private static double GetVega(double s, double k, double t, double r, double sigma)
        {
            Normal normal = new Normal();
            double d1     = (Math.Log(s / k) + r * t) / (sigma * t) + 0.5 * sigma * t;
            double vega   = s * Math.Sqrt(t) * normal.CumulativeDistribution(d1);

            return(vega);
        }
Exemplo n.º 15
0
        /// <summary>
        /// The Black formula
        /// </summary>
        /// <param name="putOrCall">put or call.</param>
        /// <param name="strike">The strike.</param>
        /// <param name="T">The time to maturity in years from the value date to the exercise date.</param>
        /// <param name="forward">The forward at the option exercise date.</param>
        /// <param name="vol">The lognormal volatility of the underlying price.</param>
        /// <param name="discountFactor">The discount factor from the value date to the settlement date of the option.</param>
        /// <returns></returns>
        public static double Black(PutOrCall putOrCall, double strike, double T, double forward, double vol, double discountFactor)
        {
            var dist       = new Normal();
            var sigmaSqrtT = vol * Math.Sqrt(T);
            var d1         = 1 / sigmaSqrtT * (Math.Log(forward / strike) + 0.5 * vol * vol);
            var d2         = d1 - sigmaSqrtT;

            return(discountFactor * (forward * dist.CumulativeDistribution(d1) - strike * dist.CumulativeDistribution(d2)));
        }
Exemplo n.º 16
0
        public static double ApplyAdjustment(double baseWinrate, double adjustment)
        {
            if (adjustment == 0)
            {
                return(baseWinrate);
            }

            return(_standardNormal.CumulativeDistribution(_standardNormal.InverseCumulativeDistribution(baseWinrate) + adjustment));
        }
Exemplo n.º 17
0
        public void hipothesisTesting()
        {
            Console.WriteLine("*****************Testowanie Hipotez*****************");
            double z;
            double alpha;
            double p;
            int    FirstClass;
            int    SecondClass;

            Console.WriteLine("Podaj poziom istotności alpha: ");
            alpha = Convert.ToDouble(Console.ReadLine(), CultureInfo.InvariantCulture);
anotherHipothesis:
            if (DataForHipothesisTesting.Count == 2)
            {
                Console.WriteLine("Sprawdzany czy da się przypisać daną wartość do właściwej etykiety z prawdopodobieństwem większym niż alpha. \n" +
                                  "Będziemy prowadzić obliczenia dla Etykiety: " + DataForHipothesisTesting[0].Label + " i kolumny: " + DataForHipothesisTesting[0].Collumn + "\n" +
                                  " oraz dla Etykiety: " + DataForHipothesisTesting[1].Label + " i kolumny: " + DataForHipothesisTesting[1].Collumn + ".");
                FirstClass  = 0;
                SecondClass = 1;
            }
            else
            {
                Console.WriteLine("Poniżej wybierz numery etykiet, dla których chcesz sprawdzić czy da się przypisać daną wartość do właściwej etykiety z prawdopodobieństwem większym niż alpha.");
                for (int i = 0; i < DataForHipothesisTesting.Count; ++i)
                {
                    Console.WriteLine(i + " etykieta: " + DataForHipothesisTesting[i].Label + " kolumna: " + (DataForHipothesisTesting[i].Collumn + 1));
                }
                Console.WriteLine("Podaj numer pierwszej z etykiet: ");
                FirstClass = Int32.Parse(Console.ReadLine());
                Console.WriteLine("Podaj numer drugiej z etykiet: ");
                SecondClass = Int32.Parse(Console.ReadLine());
            }

            z = (DataForHipothesisTesting[FirstClass].AritmeticMean - DataForHipothesisTesting[SecondClass].AritmeticMean) / (Math.Pow((Math.Pow(DataForHipothesisTesting[FirstClass].StandardDeviation, 2) / DataForHipothesisTesting[FirstClass].ProbeStrenght) + (Math.Pow(DataForHipothesisTesting[SecondClass].StandardDeviation, 2) / DataForHipothesisTesting[SecondClass].ProbeStrenght), 0.5));
            Normal Norm = new Normal();

            p = Math.Round(2 * Norm.CumulativeDistribution(-Math.Abs(z)), 6);
            Console.WriteLine("alpha: " + alpha);
            Console.WriteLine("z: " + z);
            Console.WriteLine("p: " + p);

            if (p < alpha)
            {
                Console.WriteLine("Da się przypisać daną do etykiety po wartości tej danej z prawdopodobieństwem " + p);
            }
            else
            {
                Console.WriteLine("Nie da się przypisać danej do etykiety po wartości tej danej z prawdopodobieństwem " + p + " mniejszym od alpha.");
            }
            Console.WriteLine("Czy chcesz przetestować inny zbiór danych? T/N");
            string Check = Console.ReadLine();

            if (Check == "T" || Check == "t")
            {
                goto anotherHipothesis;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Delta = first derivative of price with respect to underlying price.
        /// </summary>
        /// <returns>delta of the option</returns>
        public static double BlackScholesDelta(this EuropeanOption option, Date valueDate, double spot, double vol, double rate, double div)
        {
            var    T  = (double)(option._exerciseDate - valueDate) / 365;
            double d1 = D1(spot, option._strike, vol, rate, div, T);
            double delta;
            double dtq = Math.Exp(-div * T);

            var dist = new Normal();

            if (option._putOrCall == PutOrCall.Call)
            {
                delta = dtq * dist.CumulativeDistribution(d1);
            }
            else
            {
                delta = dtq * (dist.CumulativeDistribution(d1) - 1);
            }
            return(delta);
        }
Exemplo n.º 19
0
        private static double Nu(double x, double tol)
        {
            double nu;
            double lnu0, lnu1, dk, xk;
            int    i, k;

            // fpnorm(x): pnorm(x, 0, 1, lower.tail=TRUE, log.p=FALSE)
            // calculates P(X <= x)
            var norm = new Normal(); // N(0, 1)

            if (x > 0.01)
            {
                lnu1 = Math.Log(2.0) - 2 * Math.Log(x);
                lnu0 = lnu1;
                k    = 2;
                dk   = 0;
                for (i = 0; i < k; i++)
                {
                    dk = dk + 1;
                    xk = -x *Math.Sqrt(dk) / 2.0;

                    lnu1 = lnu1 - 2.0 * norm.CumulativeDistribution(xk) / dk;
                }
                while (Math.Abs((lnu1 - lnu0) / lnu1) > tol)
                {
                    lnu0 = lnu1;
                    for (i = 0; i < k; i++)
                    {
                        dk = dk + 1;
                        xk = -x *Math.Sqrt(dk) / 2.0;

                        lnu1 = lnu1 - 2.0 * norm.CumulativeDistribution(xk) / dk;
                    }
                    k *= 2;
                }
            }
            else
            {
                lnu1 = -0.583 * x;
            }
            nu = Math.Exp(lnu1);
            return(nu);
        }
Exemplo n.º 20
0
        // Geometric Asian Options
        private static double getGeoAsianOptionPrice(double s, double k, double r, double t, double sigma, int n, OptionTypeEnum optionType)
        {
            double sigsqT = Math.Pow(sigma, 2) * t * (n + 1) * (2 * n + 1) / (6 * n * n);
            double muT    = 0.5 * sigsqT + (r - 0.5 * sigma * sigma) * t * (n + 1) / (2 * n);

            double d1 = (Math.Log(s / k) + (muT + 0.5 * sigsqT)) / (Math.Sqrt(sigsqT));
            double d2 = d1 - Math.Sqrt(sigsqT);

            Normal normal = new Normal();

            if (optionType == OptionTypeEnum.Call)
            {
                return(Math.Exp(-r * t) * (s * Math.Exp(muT) * normal.CumulativeDistribution(d1) - k * normal.CumulativeDistribution(d2)));
            }
            else
            {
                return(Math.Exp(-r * t) * (k * normal.CumulativeDistribution(-d2) - s * Math.Exp(muT) * normal.CumulativeDistribution(-d1)));
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Samples from a truncated normal distribution.
        /// </summary>
        /// <param name="mean">The distribution's mean.</param>
        /// <param name="standardDeviation">The distribution's standard deviation.</param>
        /// <param name="minimum">Minimum value.</param>
        /// <param name="maximum">Maximum value.</param>
        /// <returns>The generated sample.</returns>
        public double SampleFromTruncatedNormal(
            double mean,
            double standardDeviation,
            double minimum,
            double maximum)
        {
            // Create the underlying normal distribution to make use of inversion technique.
            var originalDistribution = new Normal(mean, standardDeviation);

            // Select a random value of the distribution function whose inverse is part of the interval.
            var randomFactor           = this.SampleFromUniformDistribution(0, 1);
            var distributionValueWidth = originalDistribution.CumulativeDistribution(maximum)
                                         - originalDistribution.CumulativeDistribution(minimum);
            var randomDistributionValueInInterval = originalDistribution.CumulativeDistribution(minimum)
                                                    + (randomFactor * distributionValueWidth);

            // Return that inverse.
            return(originalDistribution.InverseCumulativeDistribution(randomDistributionValueInInterval));
        }
Exemplo n.º 22
0
        /// <summary>
        /// The Black the scholes formula
        /// </summary>
        /// <param name="putOrCall">put or call.</param>
        /// <param name="strike">The strike.</param>
        /// <param name="T">The time to maturity in years.</param>
        /// <param name="spot">The underlying spot price.</param>
        /// <param name="vol">The lognormal volatility of the underlying price.</param>
        /// <param name="rate">The continuous rate used for drifting the underlying and discounting the payoff.</param>
        /// <param name="div">The continuous dividend yield that decreased the drift on the underlying.</param>
        /// <returns></returns>
        public static double BlackScholes(PutOrCall putOrCall, double strike, double T, double spot, double vol, double rate,
                                          double div)
        {
            var dist       = new Normal();
            var sigmaSqrtT = vol * Math.Sqrt(T);
            var d1         = 1 / sigmaSqrtT * (Math.Log(spot / strike) + rate - div + 0.5 * vol * vol);
            var d2         = d1 - sigmaSqrtT;
            var forward    = spot * Math.Exp((rate - div) * T);

            return(Math.Exp(-rate * T) * (forward * dist.CumulativeDistribution(d1) - strike * dist.CumulativeDistribution(d2)));
        }
Exemplo n.º 23
0
        private double Transform(double value)
        {
            var result = transformationCache.Get(value);

            if (result == 0)
            {
                result = standardNormal.CumulativeDistribution(value);
                result = distribution.InverseCumulativeDistribution(result);
                transformationCache.Add(value, result);
            }
            return(result);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Rho = first derivative of price with respect to the risk-free rate.
        /// </summary>
        /// <returns>rho of the option</returns>
        public static double BlackScholesRho(this EuropeanOption option, Date valueDate, double spot, double vol, double rate, double div)
        {
            var    dist = new Normal();
            var    T    = (double)(option._exerciseDate - valueDate) / 365;
            double d2   = D2(spot, option._strike, vol, rate, div, T);
            double rho;

            var flag = (double)option._putOrCall;

            rho = flag * T * option._strike * Math.Exp(-rate * T) * dist.CumulativeDistribution(flag * d2);

            return(rho);
        }
Exemplo n.º 25
0
        public static double CF_Kirk(double S1_0, double S2_0,
                                     double K, double rho, double T, double r,
                                     double sigma1, double sigma2)
        {
            //Here we calculate our volatility
            double a_kirk = Math.Sqrt(Math.Pow(sigma1, 2) - 2 * rho * sigma1 * sigma2 * (S2_0 / (S2_0 + K)) + Math.Pow(sigma2 * (S2_0 / (S2_0 + K)), 2));

            //Here we calculate our d1 and d2
            double S  = (S1_0 / (S2_0 + K));
            double d1 = (Math.Log(S) + 0.5 * Math.Pow(a_kirk, 2) * T) / (a_kirk * Math.Sqrt(T));
            double d2 = d1 - a_kirk * Math.Sqrt(T);

            //Fit a normal distribution
            var normal = new Normal(0, 1);

            //#Here we use the above calculations to approximate the call spread using Kirk's formula
            double C_kirk = S1_0 * normal.CumulativeDistribution(d1) - (S2_0 + K) * normal.CumulativeDistribution(d2);

            C_kirk *= Math.Exp(-r * T);

            return(C_kirk);
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            IRIS iris = new IRIS(@"~\..\..\..\data\input\iris.data.csv");

            iris.start(iris.Dane);


            Normal norm = new Normal();
            double next = norm.CumulativeDistribution(1 - 1.96);

            //       Console.WriteLine("dystriusa:  " + next);


            Console.ReadKey();
        }
Exemplo n.º 27
0
        public void ValidateSkewedNormalDistribution(double location, double scale, double skew, double x)
        {
            var sn = new SkewedGeneralizedT(location, scale, skew, 2, double.PositiveInfinity);
            var n  = new Normal(location, scale);

            var sp = sn.CumulativeDistribution(x);
            var p  = n.CumulativeDistribution(x);

            if (skew > 0)
            {
                Assert.IsTrue(sp > p);
            }
            else
            {
                Assert.IsTrue(sp < p);
            }
        }
        public static void CalculatePValue(List <LSPADItem> items)
        {
            items.Sort((m1, m2) => m1.Intensity.CompareTo(m2.Intensity));
            var oneSix = items.Count / 6;

            List <double> ratios = new List <double>();

            for (int i = 0; i < oneSix; i++)
            {
                ratios.Add(items[i].LogRatio);
            }
            int lastOne  = 0;
            int firstOne = oneSix - 1;

            for (int i = 0; i < items.Count; i++)
            {
                int first = Math.Min(i + oneSix, items.Count);
                int last  = Math.Max(i - oneSix, 1);

                for (int a = lastOne; a < last; a++)
                {
                    ratios.RemoveAt(0);
                }

                for (int a = firstOne; a < first; a++)
                {
                    ratios.Add(items[a].LogRatio);
                }

                var acc = new MeanStandardDeviation(ratios);
                items[i].Mean = acc.Mean;
                items[i].SD   = acc.StdDev;

                Normal nd = new Normal(acc.Mean, acc.StdDev);
                items[i].PValue = nd.CumulativeDistribution(items[i].LogRatio);
                items[i].PValue = Math.Min(items[i].PValue, 1 - items[i].PValue);
            }
        }
        /// <summary>
        /// Run example
        /// </summary>
        /// <a href="http://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a>
        public void Run()
        {
            // 1. Initialize the new instance of the Normal distribution class with parameters Mean = 0, StdDev = 1
            var normal = new Normal(0, 1);

            Console.WriteLine(@"1. Initialize the new instance of the Normal distribution class with parameters Mean = {0}, StdDev = {1}", normal.Mean, normal.StdDev);
            Console.WriteLine();

            // 2. Distributuion properties:
            Console.WriteLine(@"2. {0} distributuion properties:", normal);

            // Cumulative distribution function
            Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", normal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000"));

            // Probability density
            Console.WriteLine(@"{0} - Probability density at location '0.3'", normal.Density(0.3).ToString(" #0.00000;-#0.00000"));

            // Log probability density
            Console.WriteLine(@"{0} - Log probability density at location '0.3'", normal.DensityLn(0.3).ToString(" #0.00000;-#0.00000"));

            // Entropy
            Console.WriteLine(@"{0} - Entropy", normal.Entropy.ToString(" #0.00000;-#0.00000"));

            // Largest element in the domain
            Console.WriteLine(@"{0} - Largest element in the domain", normal.Maximum.ToString(" #0.00000;-#0.00000"));

            // Smallest element in the domain
            Console.WriteLine(@"{0} - Smallest element in the domain", normal.Minimum.ToString(" #0.00000;-#0.00000"));

            // Mean
            Console.WriteLine(@"{0} - Mean", normal.Mean.ToString(" #0.00000;-#0.00000"));

            // Median
            Console.WriteLine(@"{0} - Median", normal.Median.ToString(" #0.00000;-#0.00000"));

            // Mode
            Console.WriteLine(@"{0} - Mode", normal.Mode.ToString(" #0.00000;-#0.00000"));

            // Variance
            Console.WriteLine(@"{0} - Variance", normal.Variance.ToString(" #0.00000;-#0.00000"));

            // Standard deviation
            Console.WriteLine(@"{0} - Standard deviation", normal.StdDev.ToString(" #0.00000;-#0.00000"));

            // Skewness
            Console.WriteLine(@"{0} - Skewness", normal.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();

            // 3. Generate 10 samples
            Console.WriteLine(@"3. Generate 10 samples");
            for (var i = 0; i < 10; i++)
            {
                Console.Write(normal.Sample().ToString("N05") + @" ");
            }

            Console.WriteLine();
            Console.WriteLine();

            // 4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram
            Console.WriteLine(@"4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram");
            var data = new double[100000];

            for (var i = 0; i < data.Length; i++)
            {
                data[i] = normal.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 5. Generate 100000 samples of the Normal(-10, 0.2) distribution and display histogram
            Console.WriteLine(@"5. Generate 100000 samples of the Normal(-10, 0.01) distribution and display histogram");
            normal.Mean   = -10;
            normal.StdDev = 0.01;
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = normal.Sample();
            }

            ConsoleHelper.DisplayHistogram(data);
        }
Exemplo n.º 30
0
 private static double NormalDistr(double x)
 {
     return(_normalDistribution.CumulativeDistribution(x));
 }