Esempio n. 1
0
        public bool SimpleImpliedVolatilityTest()
        {
            OptionType type         = OptionType.Call;
            double     strike       = 31.21;
            double     spot         = 31.525;
            double     volatility   = 0.25116165;
            double     riskFreeRate = 0.085209;
            double     ttm          = (double)35 / 365;

            EquityOptionStaticData staticData = new EquityOptionStaticData(type, strike, spot, volatility, riskFreeRate, ttm);
            IPriceable             priceable  = staticData.BuildPriceable();
            double price = priceable.Price();

            BlackScholes bs           = new BlackScholes();
            double       volGuess     = 0.25;
            double       relTolerance = 0.00001;
            int          maxAttempts  = 10;

            price = 1.28;
            double impliedVol = bs.GetImpliedVolatility(type, price, spot, strike, riskFreeRate, ttm, volGuess, relTolerance, maxAttempts);

            double relDiff = Math.Abs(impliedVol - volatility) / volatility;

            if (relDiff <= relTolerance)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public static ModelConfig BlackScholes1()
        {
            var stepsX = 1000;
            var stepsT = 750;
            var xMin   = .001;
            var xMax   = +6.0;
            var tMax   = 4.0;

            var grid = new Grid(stepsX, stepsT, xMin, xMax, tMax);

            var sigma        = .35;
            var mu           = .2;
            var blackScholes = new BlackScholes(mu, sigma);

            var x0  = .9;
            var p_0 = Helpers.GetDiracDelta(x0, grid, .99);

            var integral0 = .0;
            var dx        = (xMax - xMin) / (double)stepsX;

            for (int iStepX = 0; iStepX < stepsX; iStepX++)
            {
                integral0 += p_0(xMin + iStepX * dx) * dx;
            }

            return(new ModelConfig(blackScholes, grid, p_0));
        }
        private decimal CalcPosDelta()
        {
            decimal delta = 0M;

            delta += _futuresPosition;

            delta += DeltaBuffer;

            _optionsPositions.ForEach(pair =>
            {
                decimal?futPrice = null;

                if (pair.Value > 0)
                {
                    futPrice = Security.BestBid?.Price;
                }
                if (pair.Value < 0)
                {
                    futPrice = Security.BestAsk?.Price;
                }

                var bs = new BlackScholes(pair.Key, Security, Connector);

                delta += bs.Delta(DateTimeOffset.Now, null, futPrice).CheckIfValueNullThenZero() * pair.Value;
            });

            return(delta);
        }
        private decimal[] GetSecurityGreeks(Security sec, decimal pos)
        {
            decimal delta = 0M;
            decimal gamma = 0M;
            decimal vega  = 0M;
            decimal theta = 0M;

            if (sec.Type == SecurityTypes.Future)
            {
                delta += pos;
            }

            if (sec.Type == SecurityTypes.Option)
            {
                var bs        = new BlackScholes(sec, _dataManager.UnderlyingAsset, _connector);
                var lastPrice = pos > 0
                    ? _dataManager.UnderlyingAsset.BestBid.Price
                    : _dataManager.UnderlyingAsset.BestAsk.Price;

                delta = MessageManager.MsgGreeksRounding(bs.Delta(DateTimeOffset.Now, null, lastPrice) ?? 0);
                gamma = MessageManager.MsgGreeksRounding(bs.Gamma(DateTimeOffset.Now, null, lastPrice) ?? 0, 1);
                vega  = MessageManager.MsgGreeksRounding(bs.Vega(DateTimeOffset.Now, null, lastPrice) ?? 0);
                theta = MessageManager.MsgGreeksRounding(bs.Theta(DateTimeOffset.Now, null, lastPrice) ?? 0, -2);
            }

            return(new decimal[] { delta, gamma, vega, theta });
        }
        private decimal[] GetSummaryGreeks(Dictionary <Security, decimal> securityPositionMapping)
        {
            decimal delta = 0M;
            decimal gamma = 0M;
            decimal vega  = 0M;
            decimal theta = 0M;

            securityPositionMapping.OrderBy(kvp => kvp.Key.Code).ForEach(kvp =>
            {
                if (kvp.Value == 0)
                {
                    return;
                }

                if (kvp.Key.Type == SecurityTypes.Future)
                {
                    delta += kvp.Value;
                }

                if (kvp.Key.Type == SecurityTypes.Option)
                {
                    var bs        = new BlackScholes(kvp.Key, _dataManager.UnderlyingAsset, _connector);
                    var lastPrice = kvp.Value > 0
                        ? _dataManager.UnderlyingAsset.BestBid.Price
                        : _dataManager.UnderlyingAsset.BestAsk.Price;

                    delta += MessageManager.MsgGreeksRounding((bs.Delta(DateTimeOffset.Now, null, lastPrice) ?? 0)) * kvp.Value;
                    gamma += MessageManager.MsgGreeksRounding((bs.Gamma(DateTimeOffset.Now, null, lastPrice) ?? 0), 1) * kvp.Value;
                    vega  += MessageManager.MsgGreeksRounding((bs.Vega(DateTimeOffset.Now, null, lastPrice) ?? 0)) * kvp.Value;
                    theta += MessageManager.MsgGreeksRounding((bs.Theta(DateTimeOffset.Now, null, lastPrice) ?? 0), -2) * kvp.Value;
                }
            });

            return(new decimal[] { delta, gamma, vega, theta });
        }
Esempio n. 6
0
        /// <summary>
        /// We can roughly proxy the alpha-th percentile of the simulation
        /// by calculating the upper alpha percentile confidence point for a given time slice
        /// of the ln-OU process and pricing the collar with this asset value for a given profile point
        /// This should roughly compare to the calculated (1-alpha)-worst PCE point.
        /// </summary>
        /// <param name="spot"></param>
        /// <param name="kappa"></param>
        /// <param name="theta"></param>
        /// <param name="histvol"></param>
        /// <param name="time0"></param>
        /// <param name="maturity"></param>
        /// <param name="callstrike"></param>
        /// <param name="putstrike"></param>
        /// <param name="zerodays"></param>
        /// <param name="zerorates"></param>
        /// <param name="divdays"></param>
        /// <param name="divamts"></param>
        /// <param name="volSurface"></param>
        /// <returns></returns>
        public static double PCEProxyCalc(double spot,
                                          double kappa,
                                          double theta,
                                          double histvol,
                                          double time0,
                                          double maturity,
                                          double callstrike,
                                          double putstrike,
                                          int[] zerodays,
                                          double[] zerorates,
                                          int[] divdays,
                                          double[] divamts,
                                          List <OrcWingParameters> volSurface)
        {
            double       tau        = maturity - time0;
            double       upperBound = EquityPCEAnalytics.LNOUUpperBound(spot, 0.95, kappa, theta, histvol, time0);
            double       fStar      = EquityAnalytics.GetForwardCCLin365(upperBound, time0, maturity, divdays, divamts, zerodays, zerorates);
            double       callvol    = EquityAnalytics.GetWingValue(volSurface, new LinearInterpolation(), tau, callstrike);
            double       putvol     = EquityAnalytics.GetWingValue(volSurface, new LinearInterpolation(), tau, putstrike);
            double       r0         = EquityAnalytics.GetRateCCLin365(time0, maturity, zerodays, zerorates);
            BlackScholes bs         = new BlackScholes();
            double       lhs        = Math.Max(bs.BSprice(fStar, tau, callstrike, r0, callvol, true) - bs.BSprice(fStar, tau, putstrike, r0, putvol, false), 0);

            return(lhs);
        }
Esempio n. 7
0
        private static void SingleConvergeTest()
        {
            int numberOfSteps = 2000;
            var tree          = new CapmBinTree(numberOfSteps);

            tree.InitialStockPrice = 100;
            tree.Volatility        = 0.2;
            tree.StrikePrice       = 105;
            tree.TotalTimeYears    = 0.5;
            tree.RiskFree          = 0.03;
            tree.MarketRiskPremium = 0.06;
            tree.StockBeta         = 1;
            // B&S = call: 4.17 (con strike =105)

            double callPriceBS = BlackScholes.CallPrice((double)tree.InitialStockPrice,
                                                        (double)tree.StrikePrice,
                                                        (double)tree.TotalTimeYears,
                                                        (double)tree.RiskFree,
                                                        (double)tree.Volatility);

            Console.WriteLine("call B&S: " + callPriceBS.ToString("##0.######"));


            tree.CalculateStockPrices();
            tree.CalculateOptionPrices();

            Console.WriteLine();
            //OutputTree(tree, delegate(BinTree.Node node) { return node.StockPrice.ToString("##0.##"); });
            Console.WriteLine("call: " + tree.GetRootNode().OptionPrice.ToString("##0.######"));
        }
Esempio n. 8
0
        public static void SmallTreeBetaGraph()
        {
            int numberOfSteps = 10;
            var tree          = new CapmBinTree(numberOfSteps);

            tree.InitialStockPrice = 100;
            tree.Volatility        = 0.2;
            tree.StrikePrice       = 105;
            tree.TotalTimeYears    = 0.5;
            tree.RiskFree          = 0.03;
            tree.MarketRiskPremium = 0.06;
            tree.StockBeta         = 1;
            // B&S = call: 4.17 (con strike =105)

            double callPriceBS = BlackScholes.CallPrice((double)tree.InitialStockPrice,
                                                        (double)tree.StrikePrice,
                                                        (double)tree.TotalTimeYears,
                                                        (double)tree.RiskFree,
                                                        (double)tree.Volatility);

            Console.WriteLine("call B&S: " + callPriceBS.ToString("##0.######"));


            tree.CalculateStockPrices();
            tree.CalculateOptionPrices();

            Console.WriteLine();
            OutputTree(tree, delegate(BinTree.Node node) {
                return((-node.ReplPortBond / (node.StockPrice * node.ReplPortDelta + node.ReplPortBond)).ToString("##0.##"));
            });
        }
Esempio n. 9
0
        private double CalcDeltaOne(BlackScholes blackScholes)
        {
            double stockDividedByStrike = Math.Log(blackScholes.StockPrice / blackScholes.StrikePrice);
            double riskPerVolatility    = blackScholes.RiskFreeRate + blackScholes.Volatility * blackScholes.Volatility / 2.0;
            double stockPerRisksAndDays = stockDividedByStrike + riskPerVolatility * blackScholes.PeriodInDays;

            return(stockPerRisksAndDays / (blackScholes.Volatility * Math.Sqrt(blackScholes.PeriodInDays)));
        }
Esempio n. 10
0
        private double CalculateForCallOption(BlackScholes blackScholes, double deltaOne, double deltaTwo)
        {
            double riskPerPeriod    = Math.Exp(-blackScholes.RiskFreeRate * blackScholes.PeriodInDays);
            double stockVersusDelta = blackScholes.StockPrice * deltaOne.CumulativeNormalDistribution();
            double strikeVersusRisk = blackScholes.StrikePrice * riskPerPeriod * deltaTwo.CumulativeNormalDistribution();

            return(stockVersusDelta - strikeVersusRisk);
        }
Esempio n. 11
0
        public void CalculateTest()
        {
            var algorithm = new BlackScholes();

            var data = algorithm.CalculateBlackScholes(Domain.Enums.CallPutFlag.C, 30, 20, 1, 5, 40);

            Assert.AreEqual(30, data);
        }
Esempio n. 12
0
        public static object BSDelta(double Spot, double DivYield, double Vol, double T, double DF, double Strike, int PutCall)
        {
            CallPut cp = (CallPut)PutCall;

            CommonTypes.Maths.BlackScholes bb = new BlackScholes(cp, T, DF, Vol, DivYield, Spot, Strike);

            double delta = bb.Delta();

            return(delta);
        }
Esempio n. 13
0
        public static object BSPremium(double Spot, double DivYield, double Vol, double T, double DF, double Strike, int PutCall)
        {
            CallPut cp = (CallPut)PutCall;

            CommonTypes.Maths.BlackScholes bb = new BlackScholes(cp, T, DF, Vol, DivYield, Spot, Strike);

            double premium = bb.Premium();

            return(premium);
        }
Esempio n. 14
0
    private static void asset_path_test()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    ASSET_PATH_TEST tests ASSET_PATH.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    08 June 2016
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        const int n = 100;

        Console.WriteLine("");
        Console.WriteLine("ASSET_PATH_TEST:");
        Console.WriteLine("  Demonstrate the simulated of an asset price path.");

        const double s0    = 2.0;
        const double mu    = 0.1;
        const double sigma = 0.3;
        const double t1    = 1.0;
        int          seed  = 123456789;

        typeMethods.r8vecNormalData data = new();

        Console.WriteLine("");
        Console.WriteLine("  The asset price at time 0      S0    = " + s0 + "");
        Console.WriteLine("  The asset expected growth rate MU    = " + mu + "");
        Console.WriteLine("  The asset volatility           SIGMA = " + sigma + "");
        Console.WriteLine("  The expiry date                T1    = " + t1 + "");
        Console.WriteLine("  The number of time steps       N     = " + n + "");
        Console.WriteLine("  The random number seed was     SEED  = " + seed + "");

        double[] s = BlackScholes.asset_path(s0, mu, sigma, t1, n, ref data, ref seed);

        typeMethods.r8vec_print_part(n + 1, s, 10, "  Partial results:");

        string output_filename = "asset_path.txt";

        typeMethods.r8vec_write(output_filename, n + 1, s);

        Console.WriteLine("");
        Console.WriteLine("  Full results written to \"" + output_filename + "\".");
    }
Esempio n. 15
0
        private static void IterateByAmountOfSteps()
        {
            double InitialStockPrice = 100;
            double Volatility        = 0.2;
            double StrikePrice       = 105;
            double TotalTimeYears    = 0.5;
            double RiskFree          = 0.03;
            double MarketRiskPremium = 0.06;
            double StockBeta         = 1;
            double callPriceBS       = BlackScholes.CallPrice((double)InitialStockPrice,
                                                              (double)StrikePrice,
                                                              (double)TotalTimeYears,
                                                              (double)RiskFree,
                                                              (double)Volatility);

            int minNumberOfSteps = 7000;
            int maxNumberOfSteps = 9000;

            bool createHeaders = !File.Exists("output.csv");


            using (var writer = new StreamWriter("output.csv", true))
            {
                if (createHeaders)
                {
                    writer.WriteLine("Steps,CallValueBS,CallValueCAPM");
                }

                var tree = new CapmBinTree(maxNumberOfSteps);

                tree.InitialStockPrice = InitialStockPrice;
                tree.Volatility        = Volatility;
                tree.StrikePrice       = StrikePrice;
                tree.TotalTimeYears    = TotalTimeYears;
                tree.RiskFree          = RiskFree;
                tree.MarketRiskPremium = MarketRiskPremium;
                tree.StockBeta         = StockBeta;

                for (int steps = minNumberOfSteps; steps < maxNumberOfSteps; steps += (int)Math.Pow(Math.Log10(steps), 3))
                {
                    tree.NumberOfSteps = steps;
                    tree.ResetTreeParameterCalcs();
                    tree.CalculateStockPrices();
                    tree.CalculateOptionPrices();

                    writer.WriteLine(steps + "," + callPriceBS.ToString("##0.#############################") +
                                     ", " + tree.GetRootNode().OptionPrice.ToString("##0.#############################"));

                    writer.Flush();

                    Console.WriteLine("Step Number: " + steps);
                }
            }
        }
Esempio n. 16
0
        public void CalculateImpliedVolatility(string ammOptionsFile, string underlyingsMarketDataFile, string optionsMarketDataFile, double daysToMaturity, double riskFreeRate, ref VolSurface volSurface)
        {
            double workingDaysInTheYear = 252;
            double timeToMaturity       = daysToMaturity / workingDaysInTheYear;

            Dictionary <string, OptionInfo> allAvailableOptions   = this.ListAllAvailableOptions(ammOptionsFile);
            Dictionary <string, OrderBook>  underlyingsMarketData = this.GetMarketData(underlyingsMarketDataFile);
            Dictionary <string, OrderBook>  optionsMarketData     = this.GetMarketData(optionsMarketDataFile);

            foreach (var pair in optionsMarketData)
            {
                OrderBook optionOrderBook = pair.Value;

                OptionInfo option = null;
                if (allAvailableOptions.TryGetValue(optionOrderBook.Name, out option))
                {
                    OrderBook underlyingOrderBook = null;
                    if (underlyingsMarketData.TryGetValue(option.Underlying, out underlyingOrderBook))
                    {
                        double spot    = underlyingOrderBook.GetPriceMid();
                        double bid     = (optionOrderBook.Bid != null) ? optionOrderBook.Bid.Value : 0.00;
                        double bidSize = (optionOrderBook.BidSize != null) ? optionOrderBook.BidSize.Value : 0.00;;
                        double ask     = (optionOrderBook.Ask != null) ? optionOrderBook.Ask.Value : 0.00;;
                        double askSize = (optionOrderBook.AskSize != null) ? optionOrderBook.AskSize.Value : 0.00;;

                        BlackScholes bs = new BlackScholes();
                        double       bidImpliedVolatility = 0.00;
                        double       askImpliedVolatility = 0.00;

                        if (bid > 0.00 && bidSize > 0.00)
                        {
                            bidImpliedVolatility = bs.GetImpliedVolatility(option.Type, bid, spot, option.Strike, riskFreeRate, timeToMaturity);
                        }
                        if (ask > 0.00 && askSize > 0.00)
                        {
                            askImpliedVolatility = bs.GetImpliedVolatility(option.Type, ask, spot, option.Strike, riskFreeRate, timeToMaturity);
                        }

                        if (!(bidImpliedVolatility > 0.0000))
                        {
                            bidImpliedVolatility = 0.00;
                        }
                        if (!(askImpliedVolatility > 0.0000))
                        {
                            askImpliedVolatility = 0.00;
                        }

                        VolQuote volQuote = new VolQuote(bidSize, askSize, bidImpliedVolatility, askImpliedVolatility);
                        volSurface.Update(option.ExpiryDate, option.Strike, option.Type, volQuote);
                    }
                }
            }
        }
Esempio n. 17
0
        public static object BSRho(double Spot, double DivYield, double Vol, double T, double DF, double Strike, int PutCall, object DaysOpt)
        {
            double days = Utils.GetOptionalParameter(DaysOpt, 1);

            CallPut cp = (CallPut)PutCall;

            CommonTypes.Maths.BlackScholes bb = new BlackScholes(cp, T, DF, Vol, DivYield, Spot, Strike);

            double rho = bb.Rho(days);

            return(rho);
        }
Esempio n. 18
0
        public static object TestBS(double Spot, double DivYield, double Vol, double T, double DF, double Strike)
        {
            CommonTypes.Maths.BlackScholes bb = new BlackScholes(CallPut.Call, T, DF, Vol, DivYield, Spot, Strike);

            object[,] ret = new object[2, 2];

            double premium = bb.Premium();
            double delta   = bb.Delta();

            ret[0, 0] = "Premium"; ret[0, 1] = premium;
            ret[1, 0] = "Delta"; ret[1, 1] = delta;

            return(ret);
        }
Esempio n. 19
0
    private static void mc_test()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    MC_TEST tests MC.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    08 June 2016
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        Console.WriteLine("");
        Console.WriteLine("MC_TEST:");
        Console.WriteLine("  A demonstration of the Monte Carlo method");
        Console.WriteLine("  for option valuation.");

        const double s0    = 2.0;
        const double e     = 1.0;
        const double r     = 0.05;
        const double sigma = 0.25;
        const double t1    = 3.0;
        const int    m     = 1000000;
        int          seed  = 123456789;

        typeMethods.r8vecNormalData data = new();

        Console.WriteLine("");
        Console.WriteLine("  The asset price at time 0, S0    = " + s0 + "");
        Console.WriteLine("  The exercise price         E     = " + e + "");
        Console.WriteLine("  The interest rate          R     = " + r + "");
        Console.WriteLine("  The asset volatility       SIGMA = " + sigma + "");
        Console.WriteLine("  The expiry date            T1    = " + t1 + "");
        Console.WriteLine("  The number of simulations  M     = " + m + "");
        Console.WriteLine("  The random number seed was SEED  = " + seed + "");

        double[] conf = BlackScholes.mc(s0, e, r, sigma, t1, m, ref data, ref seed);

        Console.WriteLine("");
        Console.WriteLine("  The confidence interval is [" + conf[0] + ", " + conf[1] + "].");
    }
Esempio n. 20
0
        public static object BSVega(double Spot, double DivYield, double Vol, double T, double DF, double Strike, int PutCall)
        {
            CallPut cp = (CallPut)PutCall;

            CommonTypes.Maths.BlackScholes bb = new BlackScholes(cp, T, DF, Vol, DivYield, Spot, Strike);

            if (PutCall == 0)
            {
                return(0);
            }

            double vega = bb.Vega();

            return(vega);
        }
Esempio n. 21
0
        public static double IterativeBS(double price, double underlying, double strike, double expiry, double rate, string cp)
        {
            //Newton-Ralpson iterative method

            BlackScholes option = new BlackScholes(price, underlying,  strike, expiry, rate, cp);

            do
            {
                option.CalculateRiskProbabilities();

                option.vol = option.vol - (option.CalculateOptionValue() - price) / option.CalculateVega();

            } while ((option.CalculateOptionValue() - price) > 0.01);
            return option.vol;
        }
Esempio n. 22
0
        //public void GenerateOptionsSample()
        //{
        //    OptionType type = OptionType.Call;
        //    double spot = 100;
        //    double riskFreeRate = 0.10;

        //    // Time to maturity = 1 month
        //    List<OptionInfo> optionInfos1M = new List<OptionInfo>();
        //    double ttm = 1 / 12;

        //    StrikeVol[] strikeVol1M =
        //    {
        //        new StrikeVol(50, 60),
        //        new StrikeVol(60, 45),
        //        new StrikeVol(70, 35),
        //        new StrikeVol(80, 25),
        //        new StrikeVol(90, 20),
        //        new StrikeVol(100, 15),
        //        new StrikeVol(110, 12),
        //        new StrikeVol(120, 15),
        //        new StrikeVol(130, 20),
        //        new StrikeVol(140, 30),
        //        new StrikeVol(150, 40)
        //    };

        //    for (int i = 0; i < strikeVol1M.Length; i++)
        //    {
        //        OptionInfo info = this.PopulateOptionInfo(type, strikeVol1M[i].Strike, spot, strikeVol1M[i].Volatility, riskFreeRate, ttm);
        //        optionInfos1M.Add(info);
        //    }

        //    // Time to maturity = 2 months
        //    List<OptionInfo> optionInfos2M = new List<OptionInfo>();
        //    ttm = 2 / 12;

        //    StrikeVol[] strikeVol2M =
        //    {
        //        new StrikeVol(50, 60),
        //        new StrikeVol(60, 58),
        //        new StrikeVol(70, 56),
        //        new StrikeVol(80, 54),
        //        new StrikeVol(90, 52),
        //        new StrikeVol(100, 50),
        //        new StrikeVol(110, 50),
        //        new StrikeVol(120, 52),
        //        new StrikeVol(130, 54),
        //        new StrikeVol(140, 56),
        //        new StrikeVol(150, 58)
        //    };

        //    for (int i = 0; i < strikeVol2M.Length; i++)
        //    {
        //        OptionInfo info = this.PopulateOptionInfo(type, strikeVol2M[i].Strike, spot, strikeVol2M[i].Volatility, riskFreeRate, ttm);
        //        optionInfos2M.Add(info);
        //    }

        //    // Time to maturity = 3 months
        //    List<OptionInfo> optionInfos3M = new List<OptionInfo>();
        //    ttm = 3 / 12;

        //    StrikeVol[] strikeVol3M =
        //    {
        //        new StrikeVol(100, 45),
        //        new StrikeVol(110, 44),
        //        new StrikeVol(120, 43),
        //        new StrikeVol(130, 42),
        //        new StrikeVol(140, 41),
        //        new StrikeVol(150, 40),
        //        new StrikeVol(160, 39),
        //        new StrikeVol(170, 38),
        //        new StrikeVol(180, 37),
        //        new StrikeVol(190, 36),
        //        new StrikeVol(200, 35)
        //    };

        //    for (int i = 0; i < strikeVol3M.Length; i++)
        //    {
        //        OptionInfo info = this.PopulateOptionInfo(type, strikeVol3M[i].Strike, spot, strikeVol3M[i].Volatility, riskFreeRate, ttm);
        //        optionInfos3M.Add(info);
        //    }
        //}

        public void CalculateImpliedVolatilityToFile(string ammOptionsFile, string underlyingsMarketDataFile, string optionsMarketDataFile, string outputFile, double daysToMaturity, double riskFreeRate, double volGuess)
        {
            double workingDaysInTheYear = 252;
            double relTolerance         = 0.0001;
            int    maxAttempts          = 10;
            double timeToMaturity       = daysToMaturity / workingDaysInTheYear;

            Dictionary <string, OptionInfo> allAvailableOptions   = this.ListAllAvailableOptions(ammOptionsFile);
            Dictionary <string, OrderBook>  underlyingsMarketData = this.GetMarketData(underlyingsMarketDataFile);
            Dictionary <string, OrderBook>  optionsMarketData     = this.GetMarketData(optionsMarketDataFile);

            StreamWriter streamWriter = new StreamWriter(outputFile);

            foreach (var pair in optionsMarketData)
            {
                OrderBook optionOrderBook = pair.Value;

                OptionInfo option = null;
                if (allAvailableOptions.TryGetValue(optionOrderBook.Name, out option))
                {
                    OrderBook underlyingOrderBook = null;
                    if (underlyingsMarketData.TryGetValue(option.Underlying, out underlyingOrderBook))
                    {
                        double spot = underlyingOrderBook.GetPriceMid();
                        double optionObservedPrice = optionOrderBook.GetPriceAverage();

                        BlackScholes bs         = new BlackScholes();
                        double       impliedVol = bs.GetImpliedVolatility(option.Type, optionObservedPrice, spot, option.Strike, riskFreeRate, timeToMaturity, volGuess, relTolerance, maxAttempts);

                        if (impliedVol > 0.00000 && impliedVol < 1000)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append(option.Name);
                            sb.Append(";");
                            string optionType = (option.Type == OptionType.Call) ? "Call" : "Put";
                            sb.Append(optionType);
                            sb.Append(";");
                            sb.Append(option.Strike);
                            sb.Append(";");
                            sb.Append(impliedVol.ToString());
                            streamWriter.WriteLine(sb.ToString());
                        }
                    }
                }
            }

            streamWriter.Close();
        }
Esempio n. 23
0
        private double CalculateFor(BlackScholes blackScholes)
        {
            double deltaOne = CalcDeltaOne(blackScholes);
            double deltaTwo = CalcDeltaTwo(blackScholes, deltaOne);

            if (blackScholes.CallOption == CallOption.Call)
            {
                return(CalculateForCallOption(blackScholes, deltaOne, deltaTwo));
            }
            else if (blackScholes.CallOption == CallOption.Put)
            {
                return(CalculateForPutOption(blackScholes, deltaOne, deltaTwo));
            }

            throw new InvalidCallOptionException();
        }
Esempio n. 24
0
        private VolSurface GetVolSurface(SortedDictionary <DateTime, RiskFreeRate> riskFreeRates, OrderBook underlyingOrderBook, List <OptionMarketData> optionsMarketData)
        {
            double     businessDaysInTheYear = 252;
            VolSurface volSurface            = new VolSurface();
            double     spot = underlyingOrderBook.GetPriceMid();

            foreach (OptionMarketData option in optionsMarketData)
            {
                RiskFreeRate riskFreeRate = null;
                riskFreeRates.TryGetValue(option.OptionInfo.ExpiryDate, out riskFreeRate);

                double timeToMaturity = riskFreeRate.BusinessDays / businessDaysInTheYear;

                double bid     = (option.OrderBook.Bid != null) ? option.OrderBook.Bid.Value : 0.00;
                double bidSize = (option.OrderBook.BidSize != null) ? option.OrderBook.BidSize.Value : 0.00;;
                double ask     = (option.OrderBook.Ask != null) ? option.OrderBook.Ask.Value : 0.00;;
                double askSize = (option.OrderBook.AskSize != null) ? option.OrderBook.AskSize.Value : 0.00;;

                BlackScholes bs = new BlackScholes();
                double       bidImpliedVolatility = 0.00;
                double       askImpliedVolatility = 0.00;

                if (bid > 0.00 && bidSize > 0.00)
                {
                    bidImpliedVolatility = bs.GetImpliedVolatility(option.OptionInfo.Type, bid, spot, option.OptionInfo.Strike, riskFreeRate.Rate, timeToMaturity);
                }
                if (ask > 0.00 && askSize > 0.00)
                {
                    askImpliedVolatility = bs.GetImpliedVolatility(option.OptionInfo.Type, ask, spot, option.OptionInfo.Strike, riskFreeRate.Rate, timeToMaturity);
                }

                if (!(bidImpliedVolatility > 0.0000))
                {
                    bidImpliedVolatility = 0.00;
                }
                if (!(askImpliedVolatility > 0.0000))
                {
                    askImpliedVolatility = 0.00;
                }

                VolQuote volQuote = new VolQuote(bidSize, askSize, bidImpliedVolatility, askImpliedVolatility);
                volSurface.Update(option.OptionInfo.ExpiryDate, option.OptionInfo.Strike, option.OptionInfo.Type, volQuote);
            }

            return(volSurface);
        }
Esempio n. 25
0
    private static void binomial_test()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    BINOMIAL_TEST tests BINOMIAL.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    18 February 2012
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        Console.WriteLine("");
        Console.WriteLine("BINOMIAL_TEST:");
        Console.WriteLine("  A demonstration of the binomial method");
        Console.WriteLine("  for option valuation.");

        const double s0    = 2.0;
        const double e     = 1.0;
        const double r     = 0.05;
        const double sigma = 0.25;
        const double t1    = 3.0;
        const int    m     = 256;

        Console.WriteLine("");
        Console.WriteLine("  The asset price at time 0 S0    = " + s0 + "");
        Console.WriteLine("  The exercise price        E     = " + e + "");
        Console.WriteLine("  The interest rate         R     = " + r + "");
        Console.WriteLine("  The asset volatility      SIGMA = " + sigma + "");
        Console.WriteLine("  The expiry date           T1    = " + t1 + "");
        Console.WriteLine("  The number of intervals   M     = " + m + "");

        double c = BlackScholes.binomial(s0, e, r, sigma, t1, m);

        Console.WriteLine("");
        Console.WriteLine("  The option value is " + c + "");
    }
Esempio n. 26
0
    private static void bsf_test()

    //****************************************************************************80
    //
    //  Purpose:
    //
    //    BSF_TEST tests BSF.
    //
    //  Licensing:
    //
    //    This code is distributed under the GNU LGPL license.
    //
    //  Modified:
    //
    //    18 February 2012
    //
    //  Author:
    //
    //    John Burkardt
    //
    {
        Console.WriteLine("");
        Console.WriteLine("BSF_TEST:");
        Console.WriteLine("  A demonstration of the Black-Scholes formula");
        Console.WriteLine("  for option valuation.");

        const double s0    = 2.0;
        const double t0    = 0.0;
        const double e     = 1.0;
        const double r     = 0.05;
        const double sigma = 0.25;
        const double t1    = 3.0;

        Console.WriteLine("");
        Console.WriteLine("  The asset price at time T0 S0    = " + s0 + "");
        Console.WriteLine("  The time                   T0    = " + t0 + "");
        Console.WriteLine("  The exercise price         E     = " + e + "");
        Console.WriteLine("  The interest rate          R     = " + r + "");
        Console.WriteLine("  The asset volatility       SIGMA = " + sigma + "");
        Console.WriteLine("  The expiry date            T1    = " + t1 + "");

        double c = BlackScholes.bsf(s0, t0, e, r, sigma, t1);

        Console.WriteLine("");
        Console.WriteLine("  The option value C = " + c + "");
    }
Esempio n. 27
0
        public static object BSTheta(double Spot, double DivYield, double Vol, double T, double DF, double Strike, int PutCall, object DaysOpt)
        {
            double days = Utils.GetOptionalParameter(DaysOpt, 1);

            CallPut cp = (CallPut)PutCall;

            CommonTypes.Maths.BlackScholes bb = new BlackScholes(cp, T, DF, Vol, DivYield, Spot, Strike);

            if (PutCall == 0)
            {
                return(0);
            }

            double theta = bb.Theta(days);

            return(theta);
        }
        public void Calculate()
        {
            var Calculator = new BlackScholes();

            var Values = new CalculatorValues
            {
                UnderlinePrice = Convert.ToDouble(TextBoxStockPrice.Text),
                RiskFreeRate   = Convert.ToDouble(TextBoxRiskRate.Text) / 100,
                Volatility     = Convert.ToDouble(TextBoxVolatility.Text) / 100,
                Strike         = Convert.ToDouble(TextBoxStrikeOption.Text),
                QtdDaysExpire  = Convert.ToDouble(TextBoxTimeToExpire.Text),
                Dividend       = 0
            };


            TextBoxBSCallPrice.Content = Calculator.CallPremium(Values).ToString("0.000");
            TextBoxBSPutPrice.Content  = Calculator.PutPremium(Values).ToString("0.000");
        }
Esempio n. 29
0
        private void Calculate_Click(object sender, RoutedEventArgs e)
        {
            var option = SelectedOption;

            var volatility = Volatility.Text.To <decimal>() / 100;

            var bs = new BlackScholes(option);

            Delta.Text = bs.Delta(volatility).ToString("0.000");
            Gamma.Text = bs.Gamma(volatility).ToString("0.000000");
            Vega.Text  = bs.Vega(volatility).ToString("0.00");
            Theta.Text = bs.Theta(volatility).ToString("0.00");
            Rho.Text   = bs.Rho(volatility).ToString("0.00");

            if (option.LastTrade != null)
            {
                IV.Text = bs.IV(option.LastTrade.Price).ToString("0.00");
            }
        }
Esempio n. 30
0
        public double GetImpliedVolatilitMay()
        {
            OptionType type   = OptionType.Call;
            double     strike = 26.72;
            double     spot   = 27.00;
            double     price  = 2.17;
            //double volatility = 0.50;
            double riskFreeRate = 0.132343187; // discrete = 0.1415, continuos = ln(1+r) = 0.132343187
            double ttm          = (double)30 / 252;

            BlackScholes bs           = new BlackScholes();
            double       volGuess     = 0.30;
            double       relTolerance = 0.01;
            int          maxAttempts  = 10;

            double impliedVol = bs.GetImpliedVolatility(type, price, spot, strike, riskFreeRate, ttm, volGuess, relTolerance, maxAttempts);

            return(impliedVol);
        }
Esempio n. 31
0
        public void TestCrankNicolson()
        {
            double spot    = 385.5;
            double epsilon = 0.0001;
            double strike  = 400;

            double[] rt = { 0.0425,
                            0.0452,
                            0.0457,
                            0.0462 };
            int[]    tt        = { 1, 32, 63, 93 };
            int[]    divdays   = { 0, 48 };
            double[] divs      = { 20, 10 };
            double   vol       = 0.2046;
            int      steps     = 80;
            double   tStepSize = 0.01;
            DateTime today     = new DateTime(2010, 05, 07);
            DateTime expiry    = new DateTime(2010, 06, 24);
            //string style = "European";
            double t   = expiry.Subtract(today).Days / 365.0 + epsilon; // For CN backwards propagation div time needs to be strictly less than expiry time
            double fwd = EquityAnalytics.GetForwardCCLin365(spot, t, divdays, divs, tt, rt);
            double df  = EquityAnalytics.GetDFCCLin365(0, t, tt, rt);

            BlackScholes  bs  = new BlackScholes(spot, strike, false, t, vol, tt, rt, divdays, divs);
            CrankNicolson lhs = new CrankNicolson(false, false, spot, strike, t, vol, steps, tStepSize, 8.0, divdays, divs, tt, rt);

            double[,] res0 = OptionAnalytics.BlackScholesWithGreeks(false, fwd, strike, vol, t);
            double[] res_cn   = lhs.GetPriceAndGreeks();
            double   pr_bs    = bs.GetPrice();
            double   delta_bs = bs.GetDelta();
            double   gamma_bs = bs.GetGamma();
            double   theta_bs = bs.GetTheta();
            double   pr_cn    = res_cn[0];
            double   delta_cn = res_cn[1];
            double   gamma_cn = res_cn[2];
            double   theta_cn = res_cn[3];

            Assert.AreEqual(pr_cn, pr_bs, 0.50);
            Assert.AreEqual(delta_cn, delta_bs, 0.03);
            Assert.AreEqual(gamma_cn, 0.012931145370580023, 0.005);
            Assert.AreEqual(bs.GetTheta(), theta_cn, 0.01);
        }
Esempio n. 32
0
        private VolSurface GetVolSurface(SortedDictionary<DateTime, RiskFreeRate> riskFreeRates, OrderBook underlyingOrderBook, List<OptionMarketData> optionsMarketData)
        {
            double businessDaysInTheYear = 252;
            VolSurface volSurface = new VolSurface();
            double spot = underlyingOrderBook.GetPriceMid();

            foreach (OptionMarketData option in optionsMarketData)
            {
                RiskFreeRate riskFreeRate = null;
                riskFreeRates.TryGetValue(option.OptionInfo.ExpiryDate, out riskFreeRate);

                double timeToMaturity = riskFreeRate.BusinessDays / businessDaysInTheYear;

                double bid = (option.OrderBook.Bid != null) ? option.OrderBook.Bid.Value : 0.00;
                double bidSize = (option.OrderBook.BidSize != null) ? option.OrderBook.BidSize.Value : 0.00; ;
                double ask = (option.OrderBook.Ask != null) ? option.OrderBook.Ask.Value : 0.00; ;
                double askSize = (option.OrderBook.AskSize != null) ? option.OrderBook.AskSize.Value : 0.00; ;

                BlackScholes bs = new BlackScholes();
                double bidImpliedVolatility = 0.00;
                double askImpliedVolatility = 0.00;

                if (bid > 0.00 && bidSize > 0.00) bidImpliedVolatility = bs.GetImpliedVolatility(option.OptionInfo.Type, bid, spot, option.OptionInfo.Strike, riskFreeRate.Rate, timeToMaturity);
                if (ask > 0.00 && askSize > 0.00) askImpliedVolatility = bs.GetImpliedVolatility(option.OptionInfo.Type, ask, spot, option.OptionInfo.Strike, riskFreeRate.Rate, timeToMaturity);

                if (!(bidImpliedVolatility > 0.0000)) bidImpliedVolatility = 0.00;
                if (!(askImpliedVolatility > 0.0000)) askImpliedVolatility = 0.00;

                VolQuote volQuote = new VolQuote(bidSize, askSize, bidImpliedVolatility, askImpliedVolatility);
                volSurface.Update(option.OptionInfo.ExpiryDate, option.OptionInfo.Strike, option.OptionInfo.Type, volQuote);
            }

            return volSurface;
        }