示例#1
0
        public static double MonteCarloPriceAndGreeks(this AsianOption option, Date valueDate, double spot, double vol, double rate, double div, OptionPriceandGreeks greek, int periods, int numOfSims = 100000)
        {
            var T    = (double)(option._exerciseDate - valueDate) / 365;
            var flag = (double)option._putOrCall;

            double bump  = 0.01;
            var    paths = GBMEquitySimulator.StockPathSimulator(spot, vol, div, rate, T, numOfSims, periods, bump);

            var stockpaths      = paths[0];
            var stockpaths_up   = paths[1];
            var stockpaths_down = paths[2];

            double value = Double.NaN;

            // To do : create monte carlo vega, theta, and rho
            if (greek == OptionPriceandGreeks.Price)
            {
                value = MonteCarloPrice(stockpaths, option._strike, flag, rate, T);
            }
            else if (greek == OptionPriceandGreeks.Delta)
            {
                value = (MonteCarloPrice(stockpaths_up, option._strike, flag, rate, T) - MonteCarloPrice(stockpaths, option._strike, flag, rate, T)) / bump;
            }
            else if (greek == OptionPriceandGreeks.Gamma)
            {
                value = (MonteCarloPrice(stockpaths_up, option._strike, flag, rate, T) - 2 * MonteCarloPrice(stockpaths, option._strike, flag, rate, T) + MonteCarloPrice(stockpaths_down, option._strike, flag, rate, T)) / (bump * bump);
            }

            return(value);
        }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the EuropeanOptionMC class.
 /// </summary>
 /// <param name="parameters">Interface holding Heston Model params.</param>
 /// <param name="monteCarloSimulationSettings">Interface holding Monte carlo simulation settings.</param>
 /// <param name="asianOption">Interface holding asian option.</param>
 public AsianOptionMC(HestonModelParameters parameters,
                      MonteCarloSettings monteCarloSimulationSettings,
                      AsianOption asianOption)
     : base(parameters, monteCarloSimulationSettings, asianOption)
 {
     _MonitoringTimes = asianOption.MonitoringTimes;
 }
示例#3
0
        private void AsianOptionGreekCalc(String ValuationDate = "2015-03-19", Double vol            = 0.28, Double spot     = 1.0, Double strike = 1.03,
                                          string asianType     = "ArithmeticAverage", Boolean isCall = true, Boolean isFixed = true,
                                          double expectedPv    = 0.03368701153344,
                                          double expectedDelta = 0.431553260493781,
                                          double expectedGamma = 4319.00095926793,
                                          double expectedVega  = 0.00146247323594882,
                                          double expectedRho   = -1.62432084616776E-06,
                                          double expectedTheta = -0.000398443365606245
                                          )
        {
            var valuationDate = DateFromStr(ValuationDate);
            var maturityDate  = new Term("176D").Next(valuationDate);
            var calendar      = CalendarImpl.Get("chn");
            var obsDates      = new[] { new Date(2015, 4, 2), new Date(2015, 5, 4), new Date(2015, 6, 2), new Date(2015, 7, 2), new Date(2015, 8, 3), new Date(2015, 9, 2) };

            #region comment
            //var fixings = File.ReadAllLines(@"./Data/HistoricalEquityPrices/hs300.csv")
            //	.Select(x =>
            //	{
            //		var splits = x.Split(',');
            //		return Tuple.Create(new Date(DateTime.Parse(splits[0])), Double.Parse(splits[1]));
            //	}).ToDictionary(x => x.Item1, x => x.Item2);
            //var initialSpot = fixings[startDate];
            //fixings = fixings.Select(x => Tuple.Create(x.Key, x.Value / initialSpot)).Where(x => x.Item1 < startDate).ToDictionary(x => x.Item1, x => x.Item2);
            #endregion comment
            var option = new AsianOption(
                valuationDate,
                maturityDate,
                OptionExercise.European,
                isCall ? OptionType.Call : OptionType.Put,
                ToAsianType(asianType),
                isFixed ? StrikeStyle.Fixed:StrikeStyle.Floating,
                strike,
                InstrumentType.EquityIndex,
                calendar,
                new Act365(),
                CurrencyCode.CNY,
                CurrencyCode.CNY,
                new[] { maturityDate },
                obsDates,
                new Dictionary <Date, double>()
                );
            var market = TestMarket(referenceDate: ValuationDate, vol: vol, spot: spot);

            var analyticalEngine = new AnalyticalAsianOptionEngine();
            var analyticalResult = analyticalEngine.Calculate(option, market, PricingRequest.All);

            //var engine = new GenericMonteCarloEngine(2, 30000);
            //var result = engine.Calculate(option, market, PricingRequest.All);
            //Console.WriteLine("Analytical: {0},{1},{2},{3},{4},{5}", analyticalResult.Pv, analyticalResult.Delta, analyticalResult.Gamma, analyticalResult.Vega, analyticalResult.Rho, analyticalResult.Theta);
            //Console.WriteLine("Monte Carlo: {0},{1},{2},{3},{4},{5}", result.Pv, result.Delta, result.Gamma, result.Vega, result.Rho, result.Theta);

            Assert.AreEqual(analyticalResult.Pv, expectedPv, 1e-1);
            Assert.AreEqual(analyticalResult.Delta, expectedDelta, 1e-1);
            Assert.AreEqual(analyticalResult.Gamma, expectedGamma, 1e4);
            Assert.AreEqual(analyticalResult.Vega, expectedVega, 1e-1);
            Assert.AreEqual(analyticalResult.Rho, expectedRho, 1e-1);
            Assert.AreEqual(analyticalResult.Theta, expectedTheta, 1e-1);
        }
示例#4
0
        public void AsianOptionFact()
        {
            var orgin    = new DateTime(2019, 06, 12);
            var usd      = TestProviderHelper.CurrencyProvider.GetCurrency("USD");
            var fixDates = new[] { orgin };
            var x        = new AsianOption()
            {
                AssetId          = "QS",
                CallPut          = OptionType.C,
                DiscountCurve    = "X",
                FixingDates      = fixDates,
                FxConversionType = FxConversionType.None,
                Notional         = 1,
                PaymentCurrency  = usd,
                AverageStartDate = orgin,
                AverageEndDate   = orgin,
                SpotLag          = 0.Bd(),
                SpotLagRollType  = RollType.F,
                Strike           = 1000
            };

            var fakeModel = new Mock <IAssetFxModel>();
            var c         = new ConstantPriceCurve(100, orgin, TestProviderHelper.CurrencyProvider)
            {
                Currency = usd
            };

            fakeModel.Setup(xx => xx.GetPriceCurve(It.IsAny <string>(), null)).Returns(c);
            fakeModel.Setup(xx => xx.BuildDate).Returns(orgin);

            Assert.Equal(usd, x.Currency);
            Assert.Equal(usd, x.PaymentCurrency);
            var a = x.AssetIds;

            Assert.Contains("QS", a);
            Assert.Single(x.IrCurves(fakeModel.Object));
            Assert.Equal(FxConversionType.None, x.FxType(fakeModel.Object));
            Assert.Equal(orgin, x.LastSensitivityDate);

            var pf = x.PastFixingDates(orgin.AddDays(1));

            Assert.Contains("QS", pf.Keys);

            Assert.True(x.Equals(x));
            var y = (AsianOption)x.Clone();

            y.TradeId = "xxx";
            Assert.False(x.Equals(y));


            var z = (AsianOption)x.SetStrike(0);

            Assert.Equal(0, z.Strike);

            var sd = z.SupervisoryDelta(fakeModel.Object);

            Assert.Equal(1.0, sd);
        }
示例#5
0
        public static string[,] AsianOptionPrice([QuantSAExcelArgument(Description = "The European Option.")] AsianOption option,
                                                 [QuantSAExcelArgument(Description = "The valuation date of the option.")] Date valueDate,
                                                 [QuantSAExcelArgument(Description = "The spot price of the underlying at the value date.")] double spot,
                                                 [QuantSAExcelArgument(Description = "Annualized volatility.")] double vol,
                                                 [QuantSAExcelArgument(Description = "Continuously compounded risk free rate.")] double rate,
                                                 [QuantSAExcelArgument(Description = "Continuously compounded dividend yield.", Default = "0.0")] double div,
                                                 [QuantSAExcelArgument(Description = "The number of averaging periods.")] int periods)
        {
            string[,] price = { { "price", option.MonteCarloPriceAndGreeks(valueDate, spot, vol, rate, div, AsianOptionEx.OptionPriceandGreeks.Price, periods).ToString() } };

            return(price);
        }
示例#6
0
        private void AsianOptionGTJACalc(String ValuationDate = "2018-06-29", Double vol = 0.12, Double spot = 1820, Double strike = 1850, string asianType = "ArithmeticAverage", Boolean isCall = true, Boolean isFixed = true,
                                         double expectedPv    = 0.03368701153344)
        {
            var valuationDate = DateFromStr(ValuationDate);
            var maturityDate  = DateFromStr("2018-11-01");
            var calendar      = CalendarImpl.Get("chn");
            var obsStartDate  = DateFromStr("2018-10-01");
            var obsDates      = calendar.BizDaysBetweenDatesInclEndDay(obsStartDate, maturityDate).ToArray();

            #region comment
            //var fixings = File.ReadAllLines(@"./Data/HistoricalEquityPrices/hs300.csv")
            //	.Select(x =>
            //	{
            //		var splits = x.Split(',');
            //		return Tuple.Create(new Date(DateTime.Parse(splits[0])), Double.Parse(splits[1]));
            //	}).ToDictionary(x => x.Item1, x => x.Item2);
            //var initialSpot = fixings[startDate];
            //fixings = fixings.Select(x => Tuple.Create(x.Key, x.Value / initialSpot)).Where(x => x.Item1 < startDate).ToDictionary(x => x.Item1, x => x.Item2);
            #endregion comment
            var option = new AsianOption(
                valuationDate,
                maturityDate,
                OptionExercise.European,
                isCall ? OptionType.Call : OptionType.Put,
                ToAsianType(asianType),
                isFixed ? StrikeStyle.Fixed : StrikeStyle.Floating,
                strike,
                InstrumentType.CommodityFutures,
                calendar,
                new Act365(),
                CurrencyCode.CNY,
                CurrencyCode.CNY,
                new[] { maturityDate },
                obsDates,
                new Dictionary <Date, double>(),
                notional: 30000
                );
            var market = TestMarket(referenceDate: ValuationDate, vol: vol, spot: spot);

            var analyticalEngine = new AnalyticalAsianOptionEngine();
            var analyticalResult = analyticalEngine.Calculate(option, market, PricingRequest.All);

            //var engine = new GenericMonteCarloEngine(2, 30000);
            //var result = engine.Calculate(option, market, PricingRequest.All);
            //Console.WriteLine("Analytical: {0},{1},{2},{3},{4},{5}", analyticalResult.Pv, analyticalResult.Delta, analyticalResult.Gamma, analyticalResult.Vega, analyticalResult.Rho, analyticalResult.Theta);
            //Console.WriteLine("Monte Carlo: {0},{1},{2},{3},{4},{5}", result.Pv, result.Delta, result.Gamma, result.Vega, result.Rho, result.Theta);

            Assert.AreEqual(analyticalResult.Pv, expectedPv, 1e-1);
        }
示例#7
0
        public void Task_2_7_1()
        {
            // Variance Process Values
            double Kappa = 2;
            double Theta = 0.06;
            double Sigma = 0.4;
            double V0    = 0.04;
            double Rho   = 0.5;

            // Heston Model Params
            double InitialStockPrice = 100;
            double RiskFreeRate      = 0.1;

            // Option Params
            double        StrikePrice     = 100;
            PayoffType    Type            = PayoffType.Call;
            double        Maturity        = 1;
            List <double> MonitoringTimes = new List <double>
            {
                0.75,
                1.00
            };

            // MC Simulation Params
            int NumberOfTrials    = (int)1e5;
            int NumberOfTimeSteps = (int)Math.Ceiling(365 * Maturity);

            VarianceProcessParameters varParams =
                new VarianceProcessParameters(Kappa, Theta, Sigma, V0, Rho);

            HestonModelParameters hestonModel =
                new HestonModelParameters(InitialStockPrice, RiskFreeRate, varParams);

            AsianOption asianOption =
                new AsianOption(StrikePrice, Type, Maturity, MonitoringTimes);

            MonteCarloSettings monteCarloSettings =
                new MonteCarloSettings(NumberOfTrials, NumberOfTimeSteps);

            AsianOptionMC asianOptionMC =
                new AsianOptionMC(hestonModel, monteCarloSettings, asianOption);

            Assert.AreEqual(13.6299, asianOptionMC.Price(1), 1e-1);
        }
示例#8
0
        public void TestAsianOptionPvAgainistHaugerExcel()
        {
            var startDate    = new Date(2015, 03, 19);
            var maturityDate = new Term("183D").Next(startDate);
            var calendar     = CalendarImpl.Get("chn");

            var oneWeek = new Term("7D");
            var dates   = new List <Date>()
            {
                new Date(2015, 03, 20)
            };

            for (int i = 1; i < 27; i++)
            {
                dates.Add(oneWeek.Next(dates[i - 1]));
            }

            var option = new AsianOption(
                startDate,
                maturityDate,
                OptionExercise.European,
                OptionType.Call,
                AsianType.DiscreteArithmeticAverage,
                StrikeStyle.Fixed,
                100,
                InstrumentType.EquityIndex,
                calendar,
                new Act365(),
                CurrencyCode.CNY,
                CurrencyCode.CNY,
                new[] { maturityDate },
                dates.ToArray(),
                new Dictionary <Date, double>()
                );
            var market = TestMarket2();

            var analyticalEngine = new AnalyticalAsianOptionEngineLegacy();
            var result           = analyticalEngine.Calculate(option, market, PricingRequest.All);

            Console.WriteLine("{0},{1},{2},{3},{4}", result.Pv, result.Delta, result.Gamma, result.Vega, result.Rho);
            //Note: originally was 1.9622573116
            Assert.AreEqual(2.91746104388858, result.Pv, 1e-8);
        }
示例#9
0
        private void clearingButton_Click(object sender, EventArgs e)
        {
            sTextBox.Text      = "";
            kTextBox.Text      = "";
            tenorTextbox.Text  = "";
            sigTextBox.Text    = "";
            rTextBox.Text      = "";
            stepsTextBox.Text  = "";
            trialsTextBox.Text = "";
            timerLabel.Text    = "";
            optionTypeComboBox.SelectedIndex = 0;
            outputDataGridView.DataSource    = AsianOption.SetDataTable();

            //reset checkedbox
            for (int i = 0; i < checkedListBox1.Items.Count; i++)
            {
                checkedListBox1.SetItemChecked(i, false);
            }
        }
        private void calculate_Click(object sender, RoutedEventArgs e)
        {
            this.sw.Reset(); this.sw.Start();
            graphPlot             = new GraphPlotting();
            this.DataContext      = graphPlot;
            this.graphs.IsEnabled = true;
            if (this.simulationNumber > 500 && this.steps > 500)
            {
                this.graphs.ToolTip = "Graph may take time to load ";
            }
            else
            {
                this.graphs.ToolTip = "";
            }
            ISecurity underlying = new Stock(this.underlyingPrice);
            Options   option     = null;

            switch (this.kind)
            {
            case OptionKind.ASIAN:
                option = new AsianOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind);
                break;

            case OptionKind.BARRIER:
                option = new BarrierOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind, this.rebate, this.barrierOptiont);
                break;

            case OptionKind.DIGITAL:
                option = new DigitalOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind, this.rebate);
                break;

            case OptionKind.EUROPEAN:
                option = new EuropeanOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind);
                break;

            case OptionKind.LOOKBACK:
                option = new LookbackOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind);
                break;

            case OptionKind.RANGE:
                option = new RangeOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind);
                break;

            default:
                option = new EuropeanOption(underlying.Symbol, underlying, this.maturityDate, this.strike, this.vol, this.type, this.kind);
                break;
            }
            try
            {
                Task work = Task.Factory.StartNew(() =>
                {
                    this.Dispatcher.Invoke(() => this.progress.IsActive = true);
                    option.calulateOptionPriceAndGreeks(this.simulationNumber, this.rate, this.steps, this.anitheticReductionEnabled, this.controlVariateEnabled, this.multithreadingEnabled, plot: this.graphPlot);
                    this.sw.Stop();
                    this.Dispatcher.Invoke(() => { display(option); this.progress.IsActive = false; });
                });
            }
            catch (Exception message)
            {
                MessageBox.Show(message.Message.ToString() + "\n" + message.StackTrace.ToString());
            }
        }
        private void bPriceOptionBook_Click(object sender, RoutedEventArgs e)
        {
            graphPlot          = new GraphPlotting();
            graphs.DataContext = graphPlot;
            Task work = Task.Factory.StartNew(() =>
            {
                var orderBook = model.OrderBookDBs.ToList();
                foreach (var trade in orderBook)
                {
                    if (trade.InstrumentsDB.SecurityTypeDB.TypeName.Equals("Stocks"))
                    {
                        var instrument   = model.StockDBs.Where(x => x.Symbol == trade.InstrumentsDB.Symbol).First();
                        trade.FairPrice  = trade.Price;
                        trade.Delta      = trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity;
                        trade.ProfitLoss = 0;
                        trade.Theta      = 0;
                        trade.Gamma      = 0;
                        trade.Vega       = 0;
                        trade.Rho        = 0;
                        lock (lck)
                        {
                            model.SaveChanges();
                        }
                    }
                    else if (trade.InstrumentsDB.SecurityTypeDB.TypeName.Equals("Options"))
                    {
                        var instrument       = model.OptionsDBs.Where(x => x.Symbol == trade.InstrumentsDB.Symbol).First();
                        Options option       = null;
                        ISecurity underlying = new Stock(instrument.StockDB.LastTradedPrice);
                        switch (instrument.OptionKindDB.OptionKindName)
                        {
                        case "Asian Option":
                            option = new AsianOption(instrument.Symbol, underlying, instrument.MaturityDate, (Double)instrument.StrikePrice, instrument.StockDB.HistoricalVolatility, instrument.OptionType == "CALL" ? OptionType.CALL : OptionType.PUT, OptionKind.ASIAN);
                            break;

                        case "Barrier Option":
                            option = new BarrierOption(instrument.Symbol, underlying, instrument.MaturityDate, (Double)instrument.StrikePrice, instrument.StockDB.HistoricalVolatility, instrument.OptionType == "CALL" ? OptionType.CALL : OptionType.PUT, OptionKind.BARRIER, (Double)instrument.Barrier, (instrument.BarrierOptionType == "downout" ? BarrierOptionType.DOWNOUT : (instrument.BarrierOptionType == "downin" ? BarrierOptionType.DOWNIN : (instrument.BarrierOptionType == "upout" ? BarrierOptionType.UPOUT : BarrierOptionType.UPIN))));
                            break;

                        case "Digital Option":
                            option = new DigitalOption(instrument.Symbol, underlying, instrument.MaturityDate, (Double)instrument.StrikePrice, instrument.StockDB.HistoricalVolatility, instrument.OptionType == "CALL" ? OptionType.CALL : OptionType.PUT, OptionKind.DIGITAL, (Double)instrument.Rebate);
                            break;

                        case "European Option":
                            option = new EuropeanOption(instrument.Symbol, underlying, instrument.MaturityDate, (Double)instrument.StrikePrice, instrument.StockDB.HistoricalVolatility, instrument.OptionType == "CALL" ? OptionType.CALL : OptionType.PUT, OptionKind.EUROPEAN);
                            break;

                        case "Lookback Option":
                            option = new LookbackOption(instrument.Symbol, underlying, instrument.MaturityDate, (Double)instrument.StrikePrice, instrument.StockDB.HistoricalVolatility, instrument.OptionType == "CALL" ? OptionType.CALL : OptionType.PUT, OptionKind.LOOKBACK);
                            break;

                        case "Range Option":
                            option = new RangeOption(instrument.Symbol, underlying, instrument.MaturityDate, (Double)instrument.StrikePrice, instrument.StockDB.HistoricalVolatility, instrument.OptionType == "CALL" ? OptionType.CALL : OptionType.PUT, OptionKind.RANGE);
                            break;

                        default:
                            break;
                        }
                        try
                        {
                            option.calulateOptionPriceAndGreeks(1000, 0.05, (option.ExpiryDate - DateTime.Now).Days, true, option.OptionKind == OptionKind.EUROPEAN ? true : false, true, plot: graphPlot);
                            trade.FairPrice  = Math.Round(option.Price, 4);
                            trade.ProfitLoss = Math.Round((Double)trade.FairPrice - (Double)trade.Price, 4) * (trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity);
                            trade.Delta      = Math.Round(option.Greeks.Delta, 4) * (trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity);
                            trade.Theta      = Math.Round(option.Greeks.Theta, 4) * (trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity);
                            trade.Gamma      = Math.Round(option.Greeks.Gamma, 4) * (trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity);
                            trade.Vega       = Math.Round(option.Greeks.Vega, 4) * (trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity);
                            trade.Rho        = Math.Round(option.Greeks.Rho, 4) * (trade.Position == "BUY" ? trade.Quantity : -1 * trade.Quantity);
                            lock (lck)
                            {
                                model.SaveChanges();
                            }
                        }
                        catch (Exception message)
                        {
                            MessageBox.Show(message.Message.ToString() + "\n" + message.StackTrace.ToString());
                        }
                    }
                }
                this.Dispatcher.Invoke(() => {
                    dataGrid.DataContext = orderBook;
                });
            });
        }
示例#12
0
        public static void Task7()
        {
            // Variance Process Values
            Console.WriteLine("Task 7");
            // Variance Process Values
            double Kappa = 2.0;
            double Theta = 0.06;
            double Sigma = 0.4;
            double V0    = 0.04;
            double Rho   = 0.5;

            // Heston Model Params
            double InitialStockPrice = 100;
            double RiskFreeRate      = 0.1;

            // Option Params
            double     StrikePrice = 100;
            PayoffType Type        = PayoffType.Call;

            double[] Maturity = new double[3] {
                1, 2, 3
            };

            VarianceProcessParameters varParams =
                new VarianceProcessParameters(Kappa, Theta, Sigma, V0, Rho);

            HestonModelParameters hestonModel =
                new HestonModelParameters(InitialStockPrice, RiskFreeRate, varParams);

            // ************Task 7 Print****************
            System.Console.WriteLine("*********************");
            HestonModelParamPrint(varParams, hestonModel);

            // Monitoring Times
            List <double> monTimes1 = new List <double>
            {
                0.75,
                1.00
            };
            List <double> monTimes2 = new List <double>
            {
                0.25, 0.5, 0.75, 1.00, 1.25, 1.5, 1.75
            };
            List <double> monTimes3 = new List <double>
            {
                1.00, 2.00, 3.00
            };
            List <List <double> > MonitoringTimes = new List <List <double> >
            {
                monTimes1, monTimes2, monTimes3
            };

            //Prepare csv
            var    csv     = new StringBuilder();
            String newLine = string.Format("K, T, Price");

            csv.AppendLine(newLine);

            for (int i = 0; i < 3; i++)
            {
                // MC Simulation Params
                int NumberOfTrials    = (int)1e5;
                int NumberOfTimeSteps = (int)Math.Ceiling(365 * Maturity[i]);

                AsianOption asianOption =
                    new AsianOption(StrikePrice, Type, Maturity[i], MonitoringTimes[i]);

                MonteCarloSettings monteCarloSettings =
                    new MonteCarloSettings(NumberOfTrials, NumberOfTimeSteps);

                double price = Heston.HestonAsianOptionPriceMC(hestonModel,
                                                               asianOption, monteCarloSettings);

                System.Console.WriteLine("K={0}, T={1}, C_MC={2}", StrikePrice,
                                         Maturity[i], price);

                newLine = string.Format("{0}, {1}, {2}", StrikePrice, Maturity[i], price);
                csv.AppendLine(newLine);
            }

            //Write to csv
            File.WriteAllText(@"./task7.csv", csv.ToString());

            System.Console.WriteLine("*********************");
            System.Console.WriteLine("\n\n");
        }
示例#13
0
        private void AsianOptionGreekTest(double vol = 0.28, double spot       = 1.0, double strike = 1.03, Boolean isCall = true, string asianType = "ArithmeticAverage", Boolean isFixed = true,
                                          string t0  = "2015-03-19", string t1 = "2015-03-20", double volMove = 0.10, double mktMove = 1e-4, double toleranceInPct = 2)
        {
            var T0      = DateFromStr(t0);
            var T1      = DateFromStr(t1);
            var spotNew = spot + spot * mktMove;
            var volNew  = vol + volMove;

            var maturityDate = new Term("176D").Next(T0);
            var calendar     = CalendarImpl.Get("chn");
            var obsDates     = new[] {
                new Date(2015, 4, 2), new Date(2015, 5, 4), new Date(2015, 6, 2), new Date(2015, 7, 2), new Date(2015, 8, 3), new Date(2015, 9, 2)
            };

            var valuationDay    = t0;
            var valuationDayNew = t1;

            var option = new AsianOption(
                T0,
                maturityDate,
                OptionExercise.European,
                isCall ? OptionType.Call : OptionType.Put,
                ToAsianType(asianType),
                isFixed ? StrikeStyle.Fixed : StrikeStyle.Floating,
                strike,
                InstrumentType.EquityIndex,
                calendar,
                new Act365(),
                CurrencyCode.CNY,
                CurrencyCode.CNY,
                new[] { maturityDate },
                obsDates,
                new Dictionary <Date, double>()
                );
            var market    = TestMarket(referenceDate: t0, vol: vol, spot: spot);
            var marketNew = TestMarket(referenceDate: t1, vol: volNew, spot: spotNew);
            var marketPI  = TestMarket(referenceDate: t0, vol: vol, spot: spotNew);
            var marketVI  = TestMarket(referenceDate: t0, vol: volNew, spot: spot);
            var marketPVC = TestMarket(referenceDate: t0, vol: volNew, spot: spotNew);

            var engine = new AnalyticalAsianOptionEngine();

            var result    = engine.Calculate(option, market, PricingRequest.All);
            var resultNew = engine.Calculate(option, marketNew, PricingRequest.All);
            var resultPI  = engine.Calculate(option, marketPI, PricingRequest.All);
            var resultVI  = engine.Calculate(option, marketVI, PricingRequest.All);
            var resultPVC = engine.Calculate(option, marketPVC, PricingRequest.All);

            var actualPL = resultNew.Pv - result.Pv;

            //price Impact
            //PI = PV(t-1, priceNew) - Pv(t-1)
            var basePv  = result.Pv;
            var PI      = resultPI.Pv - basePv;
            var thetapl = result.Theta * (T1 - T0);

            //vol impact
            //VI = PV(t-1. volNew) - Pv (t-1)
            var VI = resultVI.Pv - basePv;

            //price vol cross impact
            //PVC = PV(t-1. volNew, PriceNew) - Pv (t-1) - (PI+VI)
            var PVC = resultPVC.Pv - basePv - PI - VI;

            var newEstimate    = PI + VI + PVC + thetapl;
            var newUnexplained = actualPL - newEstimate;

            //Time impact
            //TI = PV(t, all OldInfo) - Pv(t-1)

            //TODO:
            //Time/ price cross Impact
            //TPC = PV(t, priceNew) - pv(t-1) - (TI +PI)

            //Time/vol cross impact
            //TVC = PV(t, volNew) - pv(t-1) -(TI+VI)


            //TODO:
            //in case of big move ( vol and spot), we need high order risk to explain pnl
            //var diff = actualPL - esimstatedPL;
            //Assert.AreEqual(true, Math.Abs(diff / actualPL) * 100.0 < toleranceInPct); //pnl well explained in not too extreme moves
            Assert.AreEqual(true, Math.Abs(newUnexplained / actualPL) * 100.0 < toleranceInPct);
        }
示例#14
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            object[] parameters   = e.Argument as object[];
            int      steps        = Convert.ToInt16(parameters[5]);
            int      trials       = Convert.ToInt32(parameters[6]);
            double   s            = Convert.ToDouble(parameters[0]);
            double   k            = Convert.ToDouble(parameters[1]);
            double   t            = Convert.ToDouble(parameters[2]);
            double   sig          = Convert.ToDouble(parameters[3]);
            double   r            = Convert.ToDouble(parameters[4]);
            string   type         = parameters[7].ToString();
            double   exoticAmount = Convert.ToDouble(parameters[8]);

            try
            {
                for (int i = 1; i <= 1; i++)
                {
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        switch (type)
                        {
                        case "None":
                            e.Result = EuropeanOption.GetDataSet(steps, trials, s, k, t, sig, r);
                            break;

                        case "Asian":
                            e.Result = AsianOption.GetDataSet(steps, trials, s, k, t, sig, r);
                            break;

                        case "Barrier":
                            e.Result = BarrierOption.GetDataSet(steps, trials, s, k, t, sig, r, exoticAmount);
                            break;

                        case "Digital":
                            e.Result = DigitalOption.GetDataSet(steps, trials, s, k, t, sig, r, exoticAmount);
                            break;

                        case "Lookback":
                            e.Result = LookBackOption.GetDataSet(steps, trials, s, k, t, sig, r, exoticAmount);
                            break;

                        case "Range":
                            e.Result = RangeOption.GetDataSet(steps, trials, s, k, t, sig, r, exoticAmount);
                            break;

                        default:
                            break;
                        }

                        // Perform a time consuming operation and report progress.
                        Thread.Sleep(100);
                        worker.ReportProgress(i * 100);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#15
0
        private void priceTradeBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem i in ListTrade.Items)
            {
                Int32 tmp = Convert.ToInt32(i.Text);
                Trade tt  = (from q in AppEntities.Trades
                             where q.Id == tmp
                             select q).FirstOrDefault();


                double s   = getLatestPrice(tt.Instrument);
                double k   = Convert.ToDouble(tt.Instrument.Strike);
                double t   = (double)tt.Instrument.Tenor;
                double r   = getInterestRate(tt.Instrument);
                double sig = Convert.ToDouble(textBoxVol.Text) / 100.0;
                int    instrumentTypeId = (Int32)tt.Instrument.InstrumentTypeId;
                int    barrierTypeId    = (Int32)tt.Instrument.BarrierTypeId;
                double barrier          = (double)tt.Instrument.Barrier;
                double rebate           = (double)tt.Instrument.Rebate;

                int     steps = 100, trials = 10000;
                DataSet result = new DataSet();
                Dictionary <String, double> stockMetric = new Dictionary <string, double>();
                stockMetric.Add("Delta", 1);

                switch (instrumentTypeId)
                {
                case 1:
                    stockMetric.Add("Delta", 1);
                    break;

                case 2:
                    result = AsianOption.GetDataSet(steps, trials, s, k, t, sig, r);
                    break;

                case 3:
                    result = EuropeanOption.GetDataSet(steps, trials, s, k, t, sig, r);
                    break;

                case 4:
                    result = BarrierOption.GetDataSet(steps, trials, s, k, t, sig, r, barrier);
                    break;

                case 5:
                    result = RangeOption.GetDataSet(steps, trials, s, k, t, sig, r, rebate);
                    break;

                case 6:
                    result = LookBackOption.GetDataSet(steps, trials, s, k, t, sig, r, 0);
                    break;

                default:
                    break;
                }

                ListViewItem i2;
                i2      = new ListViewItem();
                i2.Text = tt.Id.ToString();
                i2.SubItems.Add(tt.Instrument.Ticker);
                i2.SubItems.Add(tt.Instrument.InstrumentType.TypeName);
                i2.SubItems.Add(tt.IsBuy ? "BUY" : "SELL");
                i2.SubItems.Add(tt.Quantity.ToString());
                i2.SubItems.Add(tt.Price.ToString());
                i2.SubItems.Add("10");
                i2.SubItems.Add("10");
                i2.SubItems.Add("10");
                i2.SubItems.Add("10");
                i2.SubItems.Add("10");
                i2.SubItems.Add("10");
                i2.SubItems.Add("10");
                ListTrade.Items.Add(i2);
            }
        }