示例#1
0
        public static string eqCurveCommodForwardsCurve(
            [ExcelArgument(Description = "curve id ")] string ObjectId,
            [ExcelArgument(Description = "curve name (eg. commod ng exchange) ")] string curvename,
            [ExcelArgument(Description = "tenors ")] object[] dates,
            [ExcelArgument(Description = "quotes ")] double[] quotes,
            [ExcelArgument(Description = "calendar ")] string calendar,
            [ExcelArgument(Description = "day counter ")] string daycounter,
            [ExcelArgument(Description = "trigger ")] object trigger)
        {
            if (ExcelUtil.CallFromWizard())
            {
                return("");
            }

            string callerAddress = ExcelUtil.getActiveCellAddress();

            try
            {
                calendar   = "NULL";
                daycounter = "Actual365Fixed";

                if (dates.Length != quotes.Length)
                {
                    return("size mismatch");
                }

                DateVector   datesvector  = new DateVector(dates.Length);
                DoubleVector quotesvector = new DoubleVector(dates.Length);

                for (int i = 0; i < dates.Length; i++)
                {
                    if ((ExcelUtil.isNull(dates[i])) || (quotes[i] == 0))
                    {
                        continue;
                    }

                    //datesvector.Add(Conversion.ConvertObject<Date>((DateTime)dates[i], "NA"));
                    datesvector.Add(new Date(Convert.ToInt32(dates[i])));
                    quotesvector.Add(quotes[i]);
                }

                CommodityCurveExt curve =
                    new CommodityCurveExt(curvename, datesvector, quotesvector, new NullCalendar(), new Actual365Fixed());

                // Store the curve and return its id
                string id = "CRV@" + ObjectId;
                OHRepository.Instance.storeObject(id, curve, callerAddress);
                id += "#" + (String)DateTime.Now.ToString(@"HH:mm:ss");
                return(id);
            }
            catch (Exception e)
            {
                ExcelUtil.logError(callerAddress, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), e.Message);
                return("#EQ_ERR!");
            }
        }
示例#2
0
        public static object eqIndexesLoadFixingFromFile(
            [ExcelArgument(Description = "trigger ")] object trigger)
        {
            if (ExcelUtil.CallFromWizard())
            {
                return("");
            }

            string callerAddress = ExcelUtil.getActiveCellAddress();

            try
            {
                Xl.Range rng      = ExcelUtil.getActiveCellRange();
                DateTime asofdate = DateTime.Today;

                string[] curves = new string[] { "USDOIS", "USDLIB3M", "USDLIB1M", "USDLIB6M", "USDLIB12M" };
                string   path   = EliteQuant.ConfigManager.Instance.IRRootDir + @"Curves\";
                string   name;
                foreach (var s in curves)
                {
                    string[]     data = System.IO.File.ReadAllLines(path + s + "_Fixing.csv");
                    DateVector   dt   = new DateVector(data.Length);
                    DoubleVector qs   = new DoubleVector(data.Length);

                    foreach (var fixing in data)
                    {
                        if (fixing == "")
                        {
                            continue;
                        }

                        string[] ff = fixing.Split(',');
                        dt.Add(EliteQuant.EQConverter.DateTimeToDate(EliteQuant.EQConverter.StringToDateTime(ff[0])));
                        qs.Add(Convert.ToDouble(ff[1]));
                    }

                    name = s;
                    if (!s.Contains("@"))
                    {
                        name = "IDX@" + s;
                    }

                    string         name2   = EliteQuant.Curves.IndexMapping.ExtIndexName2EQName(name);
                    RealTimeSeries fixings = new RealTimeSeries(dt, qs);
                    IndexManager.instance().setHistory(name2, fixings);
                }

                return(asofdate);
            }
            catch (Exception e)
            {
                ExcelUtil.logError(callerAddress, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), e.Message);
                return("#EQ_ERR!");
            }
        }
示例#3
0
        public static string eqIndexesSetHistory(
            [ExcelArgument(Description = "index name (USDOIS, USDLIB3M) ")] string name,
            [ExcelArgument(Description = "historical dates ")] object[] dates,
            [ExcelArgument(Description = "historical fixings ")] double[] quotes,
            [ExcelArgument(Description = "trigger ")] object trigger)
        {
            if (ExcelUtil.CallFromWizard())
            {
                return("");
            }

            string callerAddress = ExcelUtil.getActiveCellAddress();

            try
            {
                if (dates.Length != quotes.Length)
                {
                    return("size mismatch");
                }

                DateVector   dt = new DateVector(dates.Length);
                DoubleVector qs = new DoubleVector(dates.Length);

                for (int i = 0; i < dates.Length; i++)
                {
                    dt.Add(new Date(Convert.ToInt32(dates[i])));
                    qs.Add(quotes[i]);
                }

                if (!name.Contains('@'))
                {
                    name = "IDX@" + name;
                }

                string name2 = EliteQuant.Curves.IndexMapping.ExtIndexName2EQName(name);

                RealTimeSeries fixings = new RealTimeSeries(dt, qs);
                IndexManager.instance().setHistory(name2, fixings);

                return(name);
            }
            catch (Exception e)
            {
                ExcelUtil.logError(callerAddress, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), e.Message);
                return("#EQ_ERR!");
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Date     todaysDate     = new Date(15, Month.February, 2002);
            Calendar calendar       = new TARGET();
            Date     settlementDate = new Date(19, Month.February, 2002);

            Settings.instance().setEvaluationDate(todaysDate);

            // flat yield term structure impling 1x5 swap at 5%
            Quote       flatRate        = new SimpleQuote(0.04875825);
            FlatForward myTermStructure = new FlatForward(
                settlementDate,
                new QuoteHandle(flatRate),
                new Actual365Fixed());
            RelinkableYieldTermStructureHandle rhTermStructure =
                new RelinkableYieldTermStructureHandle();

            rhTermStructure.linkTo(myTermStructure);

            // Define the ATM/OTM/ITM swaps
            Period fixedLegTenor = new Period(1, TimeUnit.Years);
            BusinessDayConvention fixedLegConvention =
                BusinessDayConvention.Unadjusted;
            BusinessDayConvention floatingLegConvention =
                BusinessDayConvention.ModifiedFollowing;
            DayCounter fixedLegDayCounter =
                new Thirty360(Thirty360.Convention.European);
            Period    floatingLegTenor = new Period(6, TimeUnit.Months);
            double    dummyFixedRate   = 0.03;
            IborIndex indexSixMonths   = new Euribor6M(rhTermStructure);

            Date startDate = calendar.advance(settlementDate, 1, TimeUnit.Years,
                                              floatingLegConvention);
            Date maturity = calendar.advance(startDate, 5, TimeUnit.Years,
                                             floatingLegConvention);
            Schedule fixedSchedule = new Schedule(startDate, maturity,
                                                  fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention,
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, maturity,
                                                  floatingLegTenor, calendar, floatingLegConvention,
                                                  floatingLegConvention, DateGeneration.Rule.Forward, false);
            VanillaSwap swap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, dummyFixedRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            DiscountingSwapEngine swapEngine =
                new DiscountingSwapEngine(rhTermStructure);

            swap.setPricingEngine(swapEngine);
            double fixedATMRate = swap.fairRate();
            double fixedOTMRate = fixedATMRate * 1.2;
            double fixedITMRate = fixedATMRate * 0.8;

            VanillaSwap atmSwap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, fixedATMRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            VanillaSwap otmSwap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, fixedOTMRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());
            VanillaSwap itmSwap = new VanillaSwap(
                VanillaSwap.Type.Payer, 1000.0,
                fixedSchedule, fixedITMRate, fixedLegDayCounter,
                floatSchedule, indexSixMonths, 0.0,
                indexSixMonths.dayCounter());

            atmSwap.setPricingEngine(swapEngine);
            otmSwap.setPricingEngine(swapEngine);
            itmSwap.setPricingEngine(swapEngine);

            // defining the swaptions to be used in model calibration
            PeriodVector swaptionMaturities = new PeriodVector();

            swaptionMaturities.Add(new Period(1, TimeUnit.Years));
            swaptionMaturities.Add(new Period(2, TimeUnit.Years));
            swaptionMaturities.Add(new Period(3, TimeUnit.Years));
            swaptionMaturities.Add(new Period(4, TimeUnit.Years));
            swaptionMaturities.Add(new Period(5, TimeUnit.Years));

            CalibrationHelperVector swaptions = new CalibrationHelperVector();

            // List of times that have to be included in the timegrid
            DoubleVector times = new DoubleVector();

            for (int i = 0; i < numRows; i++)
            {
                int            j      = numCols - i - 1; // 1x5, 2x4, 3x3, 4x2, 5x1
                int            k      = i * numCols + j;
                Quote          vol    = new SimpleQuote(swaptionVols[k]);
                SwaptionHelper helper = new SwaptionHelper(
                    swaptionMaturities[i],
                    new Period(swapLengths[j], TimeUnit.Years),
                    new QuoteHandle(vol),
                    indexSixMonths,
                    indexSixMonths.tenor(),
                    indexSixMonths.dayCounter(),
                    indexSixMonths.dayCounter(),
                    rhTermStructure);
                swaptions.Add(helper);
                times.AddRange(helper.times());
            }

            // Building time-grid
            TimeGrid grid = new TimeGrid(times, 30);

            // defining the models
            // G2 modelG2 = new G2(rhTermStructure));
            HullWhite       modelHW  = new HullWhite(rhTermStructure);
            HullWhite       modelHW2 = new HullWhite(rhTermStructure);
            BlackKarasinski modelBK  = new BlackKarasinski(rhTermStructure);

            // model calibrations

//          Console.WriteLine( "G2 (analytic formulae) calibration" );
//          for (int i=0; i<swaptions.Count; i++)
//              NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
//                  new G2SwaptionEngine( modelG2, 6.0, 16 ) );
//
//          calibrateModel( modelG2, swaptions, 0.05);
//          Console.WriteLine( "calibrated to:" );
//          Console.WriteLine( "a     = " + modelG2.parameters()[0] );
//          Console.WriteLine( "sigma = " + modelG2.parameters()[1] );
//          Console.WriteLine( "b     = " + modelG2.parameters()[2] );
//          Console.WriteLine( "eta   = " + modelG2.parameters()[3] );
//          Console.WriteLine( "rho   = " + modelG2.parameters()[4] );

            Console.WriteLine("Hull-White (analytic formulae) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
                    new JamshidianSwaptionEngine(modelHW));
            }

            calibrateModel(modelHW, swaptions, 0.05);
//          Console.WriteLine( "calibrated to:" );
//            Console.WriteLine( "a = " + modelHW.parameters()[0] );
//            Console.WriteLine( "sigma = " + modelHW.parameters()[1] );


            Console.WriteLine("Hull-White (numerical) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
                    new TreeSwaptionEngine(modelHW2, grid));
            }

            calibrateModel(modelHW2, swaptions, 0.05);
//        std::cout << "calibrated to:\n"
//                  << "a = " << modelHW2->params()[0] << ", "
//                  << "sigma = " << modelHW2->params()[1]
//                  << std::endl << std::endl;


            Console.WriteLine("Black-Karasinski (numerical) calibration");
            for (int i = 0; i < swaptions.Count; i++)
            {
                NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine(
                    new TreeSwaptionEngine(modelBK, grid));
            }

            calibrateModel(modelBK, swaptions, 0.05);
//        std::cout << "calibrated to:\n"
//                  << "a = " << modelBK->params()[0] << ", "
//                  << "sigma = " << modelBK->params()[1]
//                  << std::endl << std::endl;

            // ATM Bermudan swaption pricing

            Console.WriteLine("Payer bermudan swaption struck at {0} (ATM)",
                              fixedATMRate);

            DateVector bermudanDates = new DateVector();
            Schedule   schedule      = new Schedule(startDate, maturity,
                                                    new Period(3, TimeUnit.Months), calendar,
                                                    BusinessDayConvention.Following,
                                                    BusinessDayConvention.Following,
                                                    DateGeneration.Rule.Forward, false);

            for (uint i = 0; i < schedule.size(); i++)
            {
                bermudanDates.Add(schedule.date(i));
            }
            Exercise bermudaExercise = new BermudanExercise(bermudanDates);

            Swaption bermudanSwaption =
                new Swaption(atmSwap, bermudaExercise);

            bermudanSwaption.setPricingEngine(
                new TreeSwaptionEngine(modelHW, 50));
            Console.WriteLine("HW: " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(
                new TreeSwaptionEngine(modelHW2, 50));
            Console.WriteLine("HW (num): " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(
                new TreeSwaptionEngine(modelBK, 50));
            Console.WriteLine("BK (num): " + bermudanSwaption.NPV());

            DateTime endTime = DateTime.Now;
            TimeSpan delta   = endTime - startTime;

            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
示例#5
0
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Option.Type optionType      = Option.Type.Put;
            double      underlyingPrice = 36;
            double      strikePrice     = 40;
            double      dividendYield   = 0.0;
            double      riskFreeRate    = 0.06;
            double      volatility      = 0.2;

            Date todaysDate = new Date(15, Month.May, 1998);

            Settings.instance().setEvaluationDate(todaysDate);

            Date settlementDate = new Date(17, Month.May, 1998);
            Date maturityDate   = new Date(17, Month.May, 1999);

            Calendar calendar = new TARGET();

            DateVector exerciseDates = new DateVector(4);

            for (int i = 1; i <= 4; i++)
            {
                Period forwardPeriod = new Period(3 * i, TimeUnit.Months);
                Date   forwardDate   = settlementDate.Add(forwardPeriod);
                exerciseDates.Add(forwardDate);
            }

            EuropeanExercise europeanExercise =
                new EuropeanExercise(maturityDate);
            BermudanExercise bermudanExercise =
                new BermudanExercise(exerciseDates);
            AmericanExercise americanExercise =
                new AmericanExercise(settlementDate, maturityDate);

            // bootstrap the yield/dividend/vol curves and create a
            // BlackScholesMerton stochastic process
            DayCounter dayCounter = new Actual365Fixed();
            YieldTermStructureHandle flatRateTSH =
                new YieldTermStructureHandle(
                    new FlatForward(settlementDate, riskFreeRate,
                                    dayCounter));
            YieldTermStructureHandle flatDividendTSH =
                new YieldTermStructureHandle(
                    new FlatForward(settlementDate, dividendYield,
                                    dayCounter));
            BlackVolTermStructureHandle flatVolTSH =
                new BlackVolTermStructureHandle(
                    new BlackConstantVol(settlementDate, calendar,
                                         volatility, dayCounter));

            QuoteHandle underlyingQuoteH =
                new QuoteHandle(new SimpleQuote(underlyingPrice));
            BlackScholesMertonProcess stochasticProcess =
                new BlackScholesMertonProcess(underlyingQuoteH,
                                              flatDividendTSH,
                                              flatRateTSH,
                                              flatVolTSH);

            PlainVanillaPayoff payoff =
                new PlainVanillaPayoff(optionType, strikePrice);

            // options
            VanillaOption europeanOption =
                new VanillaOption(payoff, europeanExercise);
            VanillaOption bermudanOption =
                new VanillaOption(payoff, bermudanExercise);
            VanillaOption americanOption =
                new VanillaOption(payoff, americanExercise);

            // report the parameters we are using
            ReportParameters(optionType, underlyingPrice, strikePrice,
                             dividendYield, riskFreeRate,
                             volatility, maturityDate);

            // write out the column headings
            ReportHeadings();

            #region Analytic Formulas

            // Black-Scholes for European
            try {
                europeanOption.setPricingEngine(
                    new AnalyticEuropeanEngine(stochasticProcess));
                ReportResults("Black-Scholes",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Barone-Adesi and Whaley approximation for American
            try {
                americanOption.setPricingEngine(
                    new BaroneAdesiWhaleyEngine(stochasticProcess));
                ReportResults("Barone-Adesi/Whaley",
                              null, null, americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Bjerksund and Stensland approximation for American
            try {
                americanOption.setPricingEngine(
                    new BjerksundStenslandEngine(stochasticProcess));
                ReportResults("Bjerksund/Stensland",
                              null, null, americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Integral
            try {
                europeanOption.setPricingEngine(
                    new IntegralEngine(stochasticProcess));
                ReportResults("Integral",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            uint timeSteps = 801;

            // Finite differences
            try {
                europeanOption.setPricingEngine(
                    new FDEuropeanEngine(stochasticProcess,
                                         timeSteps, timeSteps - 1));
                bermudanOption.setPricingEngine(
                    new FDBermudanEngine(stochasticProcess,
                                         timeSteps, timeSteps - 1));
                americanOption.setPricingEngine(
                    new FDAmericanEngine(stochasticProcess,
                                         timeSteps, timeSteps - 1));
                ReportResults("Finite differences",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            //Variance Gamma
            try
            {
                VarianceGammaProcess vgProcess = new VarianceGammaProcess(underlyingQuoteH,
                                                                          flatDividendTSH,
                                                                          flatRateTSH,
                                                                          volatility, 0.01, 0.0
                                                                          );
                europeanOption.setPricingEngine(
                    new VarianceGammaEngine(vgProcess));
                ReportResults("Variance-Gamma",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            #endregion Analytic Formulas

            #region Binomial Methods

            // Binomial Jarrow-Rudd
            try {
                europeanOption.setPricingEngine(
                    new BinomialJRVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialJRVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialJRVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Jarrow-Rudd",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Cox-Ross-Rubinstein
            try {
                europeanOption.setPricingEngine(
                    new BinomialCRRVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialCRRVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialCRRVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Cox-Ross-Rubinstein",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Additive Equiprobabilities
            try {
                europeanOption.setPricingEngine(
                    new BinomialEQPVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialEQPVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialEQPVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Additive Equiprobabilities",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Trigeorgis
            try {
                europeanOption.setPricingEngine(
                    new BinomialTrigeorgisVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialTrigeorgisVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialTrigeorgisVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Trigeorgis",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Tian
            try {
                europeanOption.setPricingEngine(
                    new BinomialTianVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialTianVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialTianVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Tian",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Leisen-Reimer
            try {
                europeanOption.setPricingEngine(
                    new BinomialLRVanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialLRVanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialLRVanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Leisen-Reimer",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Joshi
            try {
                europeanOption.setPricingEngine(
                    new BinomialJ4VanillaEngine(stochasticProcess, timeSteps));
                bermudanOption.setPricingEngine(
                    new BinomialJ4VanillaEngine(stochasticProcess, timeSteps));
                americanOption.setPricingEngine(
                    new BinomialJ4VanillaEngine(stochasticProcess, timeSteps));
                ReportResults("Binomial Joshi",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            #endregion Binomial Methods

            #region Monte Carlo Methods

            // quantlib appears to use max numeric (int and real) values to test for 'null' (or rather 'default') values

            // MC (crude)
            try {
                int    mcTimeSteps       = 1;
                int    timeStepsPerYear  = int.MaxValue;
                bool   brownianBridge    = false;
                bool   antitheticVariate = false;
                int    requiredSamples   = int.MaxValue;
                double requiredTolerance = 0.02;
                int    maxSamples        = int.MaxValue;
                int    seed = 42;
                europeanOption.setPricingEngine(
                    new MCPREuropeanEngine(stochasticProcess,
                                           mcTimeSteps,
                                           timeStepsPerYear,
                                           brownianBridge,
                                           antitheticVariate,
                                           requiredSamples,
                                           requiredTolerance,
                                           maxSamples, seed));
                ReportResults("MC (crude)", europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // MC (Sobol)
            try {
                int    mcTimeSteps       = 1;
                int    timeStepsPerYear  = int.MaxValue;
                bool   brownianBridge    = false;
                bool   antitheticVariate = false;
                int    requiredSamples   = 32768; // 2^15
                double requiredTolerance = double.MaxValue;
                int    maxSamples        = int.MaxValue;
                int    seed = 0;
                europeanOption.setPricingEngine(
                    new MCLDEuropeanEngine(stochasticProcess,
                                           mcTimeSteps,
                                           timeStepsPerYear,
                                           brownianBridge,
                                           antitheticVariate,
                                           requiredSamples,
                                           requiredTolerance,
                                           maxSamples, seed));
                ReportResults("MC (Sobol)", europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            #endregion Monte Carlo Methods

            DateTime endTime = DateTime.Now;
            TimeSpan delta   = endTime - startTime;
            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
示例#6
0
        private static void Main()
        {
            DateTime startTime = DateTime.Now;

            var todaysDate = new DateTime(2002, 2, 15);

            Settings.instance().setEvaluationDate(todaysDate);

            Calendar calendar       = new TARGET();
            var      settlementDate = new Date(19, Month.February, 2002);

            // flat yield term structure impling 1x5 swap at 5%
            Quote flatRate        = new SimpleQuote(0.04875825);
            var   myTermStructure = new FlatForward(settlementDate, new QuoteHandle(flatRate), new Actual365Fixed());
            var   rhTermStructure = new RelinkableYieldTermStructureHandle();

            rhTermStructure.linkTo(myTermStructure);

            // Define the ATM/OTM/ITM swaps
            var fixedLegTenor = new Period(1, TimeUnit.Years);
            const BusinessDayConvention fixedLegConvention    = BusinessDayConvention.Unadjusted;
            const BusinessDayConvention floatingLegConvention = BusinessDayConvention.ModifiedFollowing;
            DayCounter   fixedLegDayCounter = new Thirty360(Thirty360.Convention.European);
            var          floatingLegTenor   = new Period(6, TimeUnit.Months);
            const double dummyFixedRate     = 0.03;
            IborIndex    indexSixMonths     = new Euribor6M(rhTermStructure);

            Date startDate     = calendar.advance(settlementDate, 1, TimeUnit.Years, floatingLegConvention);
            Date maturity      = calendar.advance(startDate, 5, TimeUnit.Years, floatingLegConvention);
            var  fixedSchedule = new Schedule(startDate, maturity, fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false);
            var  floatSchedule = new Schedule(startDate, maturity, floatingLegTenor, calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Rule.Forward, false);
            var  swap          = new VanillaSwap(VanillaSwap.Type.Payer, 1000.0,
                                                 fixedSchedule, dummyFixedRate, fixedLegDayCounter,
                                                 floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter());
            var swapEngine = new DiscountingSwapEngine(rhTermStructure);

            swap.setPricingEngine(swapEngine);
            double fixedAtmRate = swap.fairRate();
            double fixedOtmRate = fixedAtmRate * 1.2;
            double fixedItmRate = fixedAtmRate * 0.8;

            var atmSwap = new VanillaSwap(VanillaSwap.Type.Payer, 1000.0,
                                          fixedSchedule, fixedAtmRate, fixedLegDayCounter,
                                          floatSchedule, indexSixMonths, 0.0,
                                          indexSixMonths.dayCounter());
            var otmSwap = new VanillaSwap(VanillaSwap.Type.Payer, 1000.0,
                                          fixedSchedule, fixedOtmRate, fixedLegDayCounter,
                                          floatSchedule, indexSixMonths, 0.0,
                                          indexSixMonths.dayCounter());
            var itmSwap = new VanillaSwap(VanillaSwap.Type.Payer, 1000.0,
                                          fixedSchedule, fixedItmRate, fixedLegDayCounter,
                                          floatSchedule, indexSixMonths, 0.0,
                                          indexSixMonths.dayCounter());

            atmSwap.setPricingEngine(swapEngine);
            otmSwap.setPricingEngine(swapEngine);
            itmSwap.setPricingEngine(swapEngine);

            // defining the swaptions to be used in model calibration
            var swaptionMaturities = new PeriodVector
            {
                new Period(1, TimeUnit.Years),
                new Period(2, TimeUnit.Years),
                new Period(3, TimeUnit.Years),
                new Period(4, TimeUnit.Years),
                new Period(5, TimeUnit.Years)
            };

            var swaptions = new CalibrationHelperVector();

            // List of times that have to be included in the timegrid
            var times = new DoubleVector();

            for (int i = 0; i < NUM_ROWS; i++)
            {
                int   j      = NUM_COLS - i - 1; // 1x5, 2x4, 3x3, 4x2, 5x1
                int   k      = i * NUM_COLS + j;
                Quote vol    = new SimpleQuote(SWAPTION_VOLS[k]);
                var   helper = new SwaptionHelper(swaptionMaturities[i], new Period(SWAP_LENGHTS[j], TimeUnit.Years),
                                                  new QuoteHandle(vol),
                                                  indexSixMonths, indexSixMonths.tenor(),
                                                  indexSixMonths.dayCounter(),
                                                  indexSixMonths.dayCounter(),
                                                  rhTermStructure);
                swaptions.Add(helper);
                times.AddRange(helper.times());
            }

            // Building time-grid
            var grid = new TimeGrid(times, 30);

            // defining the models
            // G2 modelG2 = new G2(rhTermStructure));
            var modelHw  = new HullWhite(rhTermStructure);
            var modelHw2 = new HullWhite(rhTermStructure);
            var modelBk  = new BlackKarasinski(rhTermStructure);

            // model calibrations
            Console.WriteLine("Hull-White (analytic formulae) calibration");
            foreach (CalibrationHelper calibrationHelper in swaptions)
            {
                NQuantLibc.as_black_helper(calibrationHelper).setPricingEngine(new JamshidianSwaptionEngine(modelHw));
            }
            CalibrateModel(modelHw, swaptions, 0.05);

            Console.WriteLine("Hull-White (numerical) calibration");
            foreach (CalibrationHelper calibrationHelper in swaptions)
            {
                NQuantLibc.as_black_helper(calibrationHelper).setPricingEngine(new TreeSwaptionEngine(modelHw2, grid));
            }
            CalibrateModel(modelHw2, swaptions, 0.05);

            Console.WriteLine("Black-Karasinski (numerical) calibration");
            foreach (CalibrationHelper calibrationHelper in swaptions)
            {
                NQuantLibc.as_black_helper(calibrationHelper).setPricingEngine(new TreeSwaptionEngine(modelBk, grid));
            }
            CalibrateModel(modelBk, swaptions, 0.05);

            // ATM Bermudan swaption pricing
            Console.WriteLine("Payer bermudan swaption struck at {0} (ATM)", fixedAtmRate);

            var bermudanDates = new DateVector();
            var schedule      = new Schedule(startDate, maturity,
                                             new Period(3, TimeUnit.Months), calendar,
                                             BusinessDayConvention.Following,
                                             BusinessDayConvention.Following,
                                             DateGeneration.Rule.Forward, false);

            for (uint i = 0; i < schedule.size(); i++)
            {
                bermudanDates.Add(schedule.date(i));
            }
            Exercise bermudaExercise = new BermudanExercise(bermudanDates);

            var bermudanSwaption = new Swaption(atmSwap, bermudaExercise);

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw, 50));
            Console.WriteLine("HW: " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelHw2, 50));
            Console.WriteLine("HW (num): " + bermudanSwaption.NPV());

            bermudanSwaption.setPricingEngine(new TreeSwaptionEngine(modelBk, 50));
            Console.WriteLine("BK (num): " + bermudanSwaption.NPV());

            DateTime endTime = DateTime.Now;
            TimeSpan delta   = endTime - startTime;

            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
示例#7
0
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Option.Type optionType = Option.Type.Put;
            double underlyingPrice = 36;
            double strikePrice = 40;
            double dividendYield = 0.0;
            double riskFreeRate = 0.06;
            double volatility = 0.2;

            Date todaysDate = new Date(15, Month.May, 1998);
            Settings.instance().setEvaluationDate(todaysDate);

            Date settlementDate = new Date(17, Month.May, 1998);
            Date maturityDate = new Date(17, Month.May, 1999);

            Calendar calendar = new TARGET();

            DateVector exerciseDates = new DateVector(4);
            for (int i = 1; i <= 4; i++) {
                Period forwardPeriod = new Period(3 * i, TimeUnit.Months);
                Date forwardDate = settlementDate.Add(forwardPeriod);
                exerciseDates.Add(forwardDate);
            }

            EuropeanExercise europeanExercise =
                new EuropeanExercise(maturityDate);
            BermudanExercise bermudanExercise =
                new BermudanExercise(exerciseDates);
            AmericanExercise americanExercise =
                new AmericanExercise(settlementDate, maturityDate);

            // bootstrap the yield/dividend/vol curves and create a
            // BlackScholesMerton stochastic process
            DayCounter dayCounter = new Actual365Fixed();
            YieldTermStructureHandle flatRateTSH =
                new YieldTermStructureHandle(
                                new FlatForward(settlementDate, riskFreeRate,
                                                 dayCounter));
            YieldTermStructureHandle flatDividendTSH =
                new YieldTermStructureHandle(
                                new FlatForward(settlementDate, dividendYield,
                                                dayCounter));
            BlackVolTermStructureHandle flatVolTSH =
                new BlackVolTermStructureHandle(
                                new BlackConstantVol(settlementDate, calendar,
                                                     volatility, dayCounter));

            QuoteHandle underlyingQuoteH =
                new QuoteHandle(new SimpleQuote(underlyingPrice));
            BlackScholesMertonProcess stochasticProcess =
                new BlackScholesMertonProcess(underlyingQuoteH,
                                              flatDividendTSH,
                                              flatRateTSH,
                                              flatVolTSH);

            PlainVanillaPayoff payoff =
                new PlainVanillaPayoff(optionType, strikePrice);

            // options
            VanillaOption europeanOption =
                new VanillaOption(payoff, europeanExercise);
            VanillaOption bermudanOption =
                new VanillaOption(payoff, bermudanExercise);
            VanillaOption americanOption =
                new VanillaOption(payoff, americanExercise);

            // report the parameters we are using
            ReportParameters(optionType, underlyingPrice, strikePrice,
                             dividendYield, riskFreeRate,
                             volatility, maturityDate);

            // write out the column headings
            ReportHeadings();

            #region Analytic Formulas

            // Black-Scholes for European
            try {
                europeanOption.setPricingEngine(
                               new AnalyticEuropeanEngine(stochasticProcess));
                ReportResults("Black-Scholes",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Barone-Adesi and Whaley approximation for American
            try {
                americanOption.setPricingEngine(
                              new BaroneAdesiWhaleyEngine(stochasticProcess));
                ReportResults("Barone-Adesi/Whaley",
                              null, null, americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Bjerksund and Stensland approximation for American
            try {
                americanOption.setPricingEngine(
                             new BjerksundStenslandEngine(stochasticProcess));
                ReportResults("Bjerksund/Stensland",
                              null, null, americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Integral
            try {
                europeanOption.setPricingEngine(
                                       new IntegralEngine(stochasticProcess));
                ReportResults("Integral",
                              europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            uint timeSteps = 801;

            // Finite differences
            try {
                europeanOption.setPricingEngine(
                              new FDEuropeanEngine(stochasticProcess,
                                                   timeSteps, timeSteps - 1));
                bermudanOption.setPricingEngine(
                              new FDBermudanEngine(stochasticProcess,
                                                   timeSteps, timeSteps - 1));
                americanOption.setPricingEngine(
                              new FDAmericanEngine(stochasticProcess,
                                                   timeSteps, timeSteps - 1));
                ReportResults("Finite differences",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            #endregion Analytic Formulas

            #region Binomial Methods

            // Binomial Jarrow-Rudd
            try {
                europeanOption.setPricingEngine(
                          new BinomialVanillaEngine(stochasticProcess,
                                                    "jarrowrudd", timeSteps));
                bermudanOption.setPricingEngine(
                          new BinomialVanillaEngine(stochasticProcess,
                                                    "jarrowrudd", timeSteps));
                americanOption.setPricingEngine(
                          new BinomialVanillaEngine(stochasticProcess,
                                                    "jarrowrudd", timeSteps));
                ReportResults("Binomial Jarrow-Rudd",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Cox-Ross-Rubinstein
            try {
                europeanOption.setPricingEngine(
                   new BinomialVanillaEngine(stochasticProcess,
                                             "coxrossrubinstein", timeSteps));
                bermudanOption.setPricingEngine(
                   new BinomialVanillaEngine(stochasticProcess,
                                             "coxrossrubinstein", timeSteps));
                americanOption.setPricingEngine(
                   new BinomialVanillaEngine(stochasticProcess,
                                             "coxrossrubinstein", timeSteps));
                ReportResults("Binomial Cox-Ross-Rubinstein",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Additive Equiprobabilities
            try {
                europeanOption.setPricingEngine(
                                 new BinomialVanillaEngine(stochasticProcess,
                                                           "eqp", timeSteps));
                bermudanOption.setPricingEngine(
                                 new BinomialVanillaEngine(stochasticProcess,
                                                           "eqp", timeSteps));
                americanOption.setPricingEngine(
                                 new BinomialVanillaEngine(stochasticProcess,
                                                           "eqp", timeSteps));
                ReportResults("Additive Equiprobabilities",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Trigeorgis
            try {
                europeanOption.setPricingEngine(
                          new BinomialVanillaEngine(stochasticProcess,
                                                    "trigeorgis", timeSteps));
                bermudanOption.setPricingEngine(
                          new BinomialVanillaEngine(stochasticProcess,
                                                    "trigeorgis", timeSteps));
                americanOption.setPricingEngine(
                          new BinomialVanillaEngine(stochasticProcess,
                                                    "trigeorgis", timeSteps));
                ReportResults("Binomial Trigeorgis",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Tian
            try {
                europeanOption.setPricingEngine(
                                new BinomialVanillaEngine(stochasticProcess,
                                                          "tian", timeSteps));
                bermudanOption.setPricingEngine(
                                new BinomialVanillaEngine(stochasticProcess,
                                                          "tian", timeSteps));
                americanOption.setPricingEngine(
                                new BinomialVanillaEngine(stochasticProcess,
                                                          "tian", timeSteps));
                ReportResults("Binomial Tian",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Leisen-Reimer
            try {
                europeanOption.setPricingEngine(
                        new BinomialVanillaEngine(stochasticProcess,
                                                  "leisenreimer", timeSteps));
                bermudanOption.setPricingEngine(
                        new BinomialVanillaEngine(stochasticProcess,
                                                  "leisenreimer", timeSteps));
                americanOption.setPricingEngine(
                        new BinomialVanillaEngine(stochasticProcess,
                                                  "leisenreimer", timeSteps));
                ReportResults("Binomial Leisen-Reimer",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // Binomial Joshi
            try {
                europeanOption.setPricingEngine(
                              new BinomialVanillaEngine(stochasticProcess,
                                                        "joshi4", timeSteps));
                bermudanOption.setPricingEngine(
                              new BinomialVanillaEngine(stochasticProcess,
                                                        "joshi4", timeSteps));
                americanOption.setPricingEngine(
                              new BinomialVanillaEngine(stochasticProcess,
                                                        "joshi4", timeSteps));
                ReportResults("Binomial Joshi",
                              europeanOption.NPV(),
                              bermudanOption.NPV(),
                              americanOption.NPV());
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            #endregion Binomial Methods

            #region Monte Carlo Methods

            // quantlib appears to use max numeric (int and real) values to test for 'null' (or rather 'default') values

            // MC (crude)
            try {
                string traits = "pseudorandom";
                int mcTimeSteps = 1;
                int timeStepsPerYear = int.MaxValue;
                bool brownianBridge = false;
                bool antitheticVariate = false;
                int requiredSamples = int.MaxValue;
                double requiredTolerance = 0.02;
                int maxSamples = int.MaxValue;
                int seed = 42;
                europeanOption.setPricingEngine(
                    new MCEuropeanEngine(stochasticProcess,
                                         traits, mcTimeSteps,
                                         timeStepsPerYear,
                                         brownianBridge,
                                         antitheticVariate,
                                         requiredSamples,
                                         requiredTolerance,
                                         maxSamples, seed));
                ReportResults("MC (crude)", europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // MC (Sobol)
            try {
                string traits = "lowdiscrepancy";
                int mcTimeSteps = 1;
                int timeStepsPerYear = int.MaxValue;
                bool brownianBridge = false;
                bool antitheticVariate = false;
                int requiredSamples = 32768;  // 2^15
                double requiredTolerance = double.MaxValue;
                int maxSamples = int.MaxValue;
                int seed = 0;
                europeanOption.setPricingEngine(
                    new MCEuropeanEngine(stochasticProcess,
                                         traits, mcTimeSteps,
                                         timeStepsPerYear,
                                         brownianBridge,
                                         antitheticVariate,
                                         requiredSamples,
                                         requiredTolerance, maxSamples, seed));
                ReportResults("MC (Sobol)", europeanOption.NPV(), null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            // MC (Longstaff Schwartz)
            /*
            try {
                // MCAmericanEngine is not currently exposed in SWIG
                //americanOption.setPricingEngine(new MCAmericanEngine());
                ReportResults("MC (Longstaff Schwartz)", null, null, null);
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
            */

            #endregion Monte Carlo Methods

            DateTime endTime = DateTime.Now;
            TimeSpan delta = endTime - startTime;
            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }
示例#8
0
        public static string eqCurveIRIndex2(
            [ExcelArgument(Description = "index id (USDOIS, USDLIB3M, USDLIB1M ")] string ObjectId,
            [ExcelArgument(Description = "currency (USD, GBP, CAD, EUR, JPY ) ")] string Curncy,
            [ExcelArgument(Description = "tenors ")] object[] dates,
            [ExcelArgument(Description = "discounts ")] double[] discounts,
            [ExcelArgument(Description = "calendar ")] string calendar,
            [ExcelArgument(Description = "day counter ")] string daycounter,
            [ExcelArgument(Description = "id of discount curve ")] string discountId,
            [ExcelArgument(Description = "Interpolation Method (Linear, LogLinear) ")] string interp,
            [ExcelArgument(Description = "trigger ")] object trigger)
        {
            if (ExcelUtil.CallFromWizard())
            {
                return("");
            }

            string callerAddress = ExcelUtil.getActiveCellAddress();

            try
            {
                calendar   = "NULL";
                daycounter = "Actual365Fixed";

                if (dates.Length != discounts.Length)
                {
                    return("size mismatch");
                }

                string interpmethod;
                if (ExcelUtil.isNull(interp))
                {
                    interpmethod = "LOGLINEAR";
                }
                else
                {
                    interpmethod = interp.ToUpper();
                }

                DateVector   datesvector     = new DateVector(dates.Length);
                DoubleVector discountsvector = new DoubleVector(dates.Length);

                for (int i = 0; i < dates.Length; i++)
                {
                    //datesvector.Add(Conversion.ConvertObject<Date>((DateTime)dates[i], "NA"));
                    datesvector.Add(new Date(Convert.ToInt32(dates[i])));
                    discountsvector.Add(discounts[i]);
                }

                YieldTermStructureHandle handle = null;
                if (interpmethod == "LINEAR")
                {
                    handle = new YieldTermStructureHandle(
                        new LinearDiscountCurve(datesvector, discountsvector, new Actual365Fixed(), new NullCalendar()));
                }
                else
                {
                    handle = new YieldTermStructureHandle(
                        new DiscountCurve(datesvector, discountsvector, new Actual365Fixed(), new NullCalendar()));
                }

                // Store the option and return its id
                string id = "CRV@" + ObjectId;
                OHRepository.Instance.storeObject(id, handle, callerAddress);
                id += "#" + (String)DateTime.Now.ToString(@"HH:mm:ss");
                return(id);
            }
            catch (Exception e)
            {
                ExcelUtil.logError(callerAddress, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), e.Message);
                return("#EQ_ERR!");
            }
        }
        public void ConstructSwap(IborIndex idx1 = null, IborIndex idx2 = null)
        {
            _GenericSwap.Type   type    = SwapType == "Payer" ? _GenericSwap.Type.Payer : _GenericSwap.Type.Receiver;
            EliteQuant.Calendar cal_gbp = new EliteQuant.UnitedKingdom(EliteQuant.UnitedKingdom.Market.Exchange);
            bool hasois = SecondLegIndex.Contains("OIS") ? true : false;            // OIS is only in FIXED-OIS pair

            if (IsScheduleGiven)
            {
                //************************** First Leg *******************************
                DoubleVector notional1 = new DoubleVector();
                foreach (var nl in FirstLegNotionals)
                {
                    notional1.Add(nl);
                }
                DateVector sch1 = new DateVector();
                foreach (var dt in FirstLegSchedules)
                {
                    sch1.Add(EliteQuant.EQConverter.DateTimeToDate(EliteQuant.EQConverter.StringToDateTime(dt)));
                }

                Calendar cal1 = EliteQuant.EQConverter.ConvertObject <Calendar>(FirstLegCalendar);
                if (!hasois)
                {
                    cal1 = new EliteQuant.JointCalendar(cal_gbp, cal1, EliteQuant.JointCalendarRule.JoinHolidays);
                }

                DayCounter            dc1  = EliteQuant.EQConverter.ConvertObject <DayCounter>(FirstLegDayCounter);
                BusinessDayConvention bdc1 = EliteQuant.EQConverter.ConvertObject <BusinessDayConvention>(FirstLegConvention);
                Schedule Schedule1         = new Schedule(sch1, cal1, bdc1);

                //************************** Second Leg *******************************
                DoubleVector notional2 = new DoubleVector();
                foreach (var nl in SecondLegNotionals)
                {
                    notional2.Add(nl);
                }
                DateVector sch2 = new DateVector();
                foreach (var dt in SecondLegSchedules)
                {
                    sch2.Add(EliteQuant.EQConverter.DateTimeToDate(EliteQuant.EQConverter.StringToDateTime(dt)));
                }

                Calendar cal2 = EliteQuant.EQConverter.ConvertObject <Calendar>(SecondLegCalendar);
                if (!hasois)
                {
                    cal2 = new EliteQuant.JointCalendar(cal_gbp, cal2, EliteQuant.JointCalendarRule.JoinHolidays);
                }

                DayCounter            dc2  = EliteQuant.EQConverter.ConvertObject <DayCounter>(SecondLegDayCounter);
                BusinessDayConvention bdc2 = EliteQuant.EQConverter.ConvertObject <BusinessDayConvention>(SecondLegConvention);
                Schedule Schedule2         = new Schedule(sch2, cal2, bdc2);

                //************************** swap ******************************
                if (FirstLegIndex == "FIXED")
                {
                    if (hasois)
                    {
                        eqswap_ = new GenericSwap(type, notional2, Schedule2, Schedule2, FirstLegSpread, dc2,
                                                  notional2, Schedule2, Schedule2, idx2, dc2, SecondLegSpread, hasois);
                    }
                    else
                    {
                        eqswap_ = new GenericSwap(type, notional1, Schedule1, Schedule1, FirstLegSpread, dc1,
                                                  notional2, Schedule2, Schedule2, idx2, dc2, SecondLegSpread, hasois);
                    }
                }
                else
                {
                    eqswap_ = new GenericSwap(type, notional1, Schedule1, Schedule1, idx1, dc1,
                                              notional2, Schedule2, Schedule2, idx2, dc2, 0.0, SecondLegSpread, hasois);
                }
            }  // end of schedule given swap construction
            else
            {
                //************************** First Leg *******************************
                Calendar cal1 = EliteQuant.EQConverter.ConvertObject <Calendar>(FirstLegCalendar);
                if (!hasois)
                {
                    cal1 = new EliteQuant.JointCalendar(cal_gbp, cal1, EliteQuant.JointCalendarRule.JoinHolidays);
                }
                DayCounter            dc1  = EliteQuant.EQConverter.ConvertObject <DayCounter>(FirstLegDayCounter);
                BusinessDayConvention bdc1 = EliteQuant.EQConverter.ConvertObject <BusinessDayConvention>(FirstLegConvention);
                Date tradedate             = EliteQuant.EQConverter.DateTimeToDate(EliteQuant.EQConverter.StringToDateTime(TradeDate));
                tradedate = cal1.adjust(tradedate);

                Date startdate;
                if (string.IsNullOrEmpty(SettlementDate))
                {
                    startdate = cal1.advance(tradedate, FixingDays, TimeUnit.Days);
                }
                else
                {
                    startdate = EliteQuant.EQConverter.DateTimeToDate(EliteQuant.EQConverter.StringToDateTime(SettlementDate));
                }

                Date terminatedate;
                if (string.IsNullOrEmpty(MaturityDate))
                {
                    // then tenor should not be zero
                    Period tenor = EliteQuant.EQConverter.ConvertObject <Period>(Tenor);
                    //Calendar nullcal = new NullCalendar();
                    terminatedate = cal1.advance(startdate, tenor);
                }
                else
                {
                    terminatedate = EliteQuant.EQConverter.DateTimeToDate(EliteQuant.EQConverter.StringToDateTime(MaturityDate));
                }

                DateGeneration.Rule dgr1 = EliteQuant.EQConverter.ConvertObject <DateGeneration.Rule>(FirstLegDateGenerationRule);

                Frequency freq1     = EliteQuant.EQConverter.ConvertObject <Frequency>(FirstLegFrequency);
                Schedule  schedule1 = new Schedule(startdate, terminatedate, new Period(freq1), cal1,
                                                   bdc1, bdc1, dgr1, FirstLegEOM);

                //************************** Second Leg *******************************
                Calendar cal2 = EliteQuant.EQConverter.ConvertObject <Calendar>(SecondLegCalendar);
                if (!hasois)
                {
                    cal2 = new EliteQuant.JointCalendar(cal_gbp, cal2, EliteQuant.JointCalendarRule.JoinHolidays);
                }
                DayCounter            dc2  = EliteQuant.EQConverter.ConvertObject <DayCounter>(SecondLegDayCounter);
                BusinessDayConvention bdc2 = EliteQuant.EQConverter.ConvertObject <BusinessDayConvention>(SecondLegConvention);


                DateGeneration.Rule dgr2 = EliteQuant.EQConverter.ConvertObject <DateGeneration.Rule>(SecondLegDateGenerationRule);

                Frequency freq2     = EliteQuant.EQConverter.ConvertObject <Frequency>(SecondLegFrequency);
                Schedule  schedule2 = new Schedule(startdate, terminatedate, new Period(freq2), cal2,
                                                   bdc2, bdc2, dgr2, SecondLegEOM);

                //************************** swap ******************************
                DoubleVector notional1 = new DoubleVector();
                DoubleVector notional2 = new DoubleVector();
                foreach (var nl in FirstLegNotionals)
                {
                    notional1.Add(nl);
                }
                foreach (var nl in SecondLegNotionals)
                {
                    notional2.Add(nl);
                }

                if (FirstLegIndex == "FIXED")
                {
                    if (hasois)
                    {
                        eqswap_ = new GenericSwap(type, notional2, schedule2, schedule2, FirstLegSpread, dc2,
                                                  notional2, schedule2, schedule2, idx2, dc2, SecondLegSpread, hasois);
                    }
                    else
                    {
                        eqswap_ = new GenericSwap(type, notional1, schedule1, schedule1, FirstLegSpread, dc1,
                                                  notional2, schedule2, schedule2, idx2, dc2, SecondLegSpread, hasois);
                    }
                }
                else
                {
                    eqswap_ = new GenericSwap(type, notional1, schedule1, schedule1, idx1, dc1,
                                              notional2, schedule2, schedule2, idx2, dc2, 0.0, SecondLegSpread, hasois);
                }
            } // end of schedule not given swap construction
        }
示例#10
0
        public static string eqInstVanillaOption(
            [ExcelArgument(Description = "id of option to be constructed ")] string ObjectId,
            [ExcelArgument(Description = "Option type E(uropean), A(merican), B(ermudan) ")] string exercisetype,
            [ExcelArgument(Description = "CALL or PUT ")] string optype,
            [ExcelArgument(Description = "Strike price ")] double strikeprice,
            [ExcelArgument(Description = "Expiry Dates (E = 1, A = 2, B = many) ")] object[] dates)
        {
            if (ExcelUtil.CallFromWizard())
            {
                return("");
            }

            string callerAddress = "";

            callerAddress = ExcelUtil.getActiveCellAddress();

            try
            {
                Exercise exercise = null;
                if (exercisetype.ToUpper() == "E")
                {
                    Date maturitydate = EliteQuant.EQConverter.DateTimeToDate(DateTime.FromOADate((double)dates[0]));     // assume first date
                    exercise = new EuropeanExercise(maturitydate);
                }
                else if (exercisetype.ToUpper() == "A")
                {
                    Date earliestdate = EliteQuant.EQConverter.DateTimeToDate(DateTime.FromOADate((double)dates[0]));  // assume first date
                    Date lastdate     = EliteQuant.EQConverter.DateTimeToDate(DateTime.FromOADate((double)dates[1]));  // assume last date
                    exercise = new AmericanExercise(earliestdate, lastdate);
                }
                else if (exercisetype.ToUpper() == "B")
                {
                    DateVector dv = new DateVector();
                    foreach (var dt in dates)
                    {
                        Date dte = EliteQuant.EQConverter.DateTimeToDate(DateTime.FromOADate((double)dt));
                        dv.Add(dte);
                    }
                    exercise = new BermudanExercise(dv);
                }
                else
                {
                    throw new Exception("Unknow exercise type ");
                }

                Option.Type optiontype;
                if (optype.ToUpper() == "CALL")
                {
                    optiontype = Option.Type.Call;
                }
                else if (optype.ToUpper() == "PUT")
                {
                    optiontype = Option.Type.Put;
                }
                else
                {
                    throw new Exception("Unknow option type");
                }

                PlainVanillaPayoff payoff = new PlainVanillaPayoff(optiontype, strikeprice);

                VanillaOption europeanOption = new VanillaOption(payoff, exercise);

                // Store the option and return its id
                string id = "OPTION@" + ObjectId;
                OHRepository.Instance.storeObject(id, europeanOption, callerAddress);
                id += "#" + (String)DateTime.Now.ToString(@"HH:mm:ss");
                return(id);
            }
            catch (Exception e)
            {
                ExcelUtil.logError(callerAddress, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), e.Message);
                return("#EQ_ERR!");
            }
        }
示例#11
-1
        static void Main(string[] args)
        {
            DateTime startTime = DateTime.Now;

            Date todaysDate = new Date(15, Month.February, 2002);
            Calendar calendar = new TARGET();
            Date settlementDate = new Date(19, Month.February, 2002);
            Settings.instance().setEvaluationDate( todaysDate );

            // flat yield term structure impling 1x5 swap at 5%
            Quote flatRate = new SimpleQuote(0.04875825);
            FlatForward myTermStructure = new FlatForward(
                settlementDate,
                new QuoteHandle( flatRate ),
                new Actual365Fixed() );
            RelinkableYieldTermStructureHandle rhTermStructure =
                new RelinkableYieldTermStructureHandle();
            rhTermStructure.linkTo( myTermStructure );

            // Define the ATM/OTM/ITM swaps
            Period fixedLegTenor = new Period(1,TimeUnit.Years);
            BusinessDayConvention fixedLegConvention =
                BusinessDayConvention.Unadjusted;
            BusinessDayConvention floatingLegConvention =
                BusinessDayConvention.ModifiedFollowing;
            DayCounter fixedLegDayCounter =
                new Thirty360( Thirty360.Convention.European );
            Period floatingLegTenor = new Period(6,TimeUnit.Months);
            double dummyFixedRate = 0.03;
            IborIndex indexSixMonths = new Euribor6M( rhTermStructure );

            Date startDate = calendar.advance(settlementDate,1,TimeUnit.Years,
                floatingLegConvention);
            Date maturity = calendar.advance(startDate,5,TimeUnit.Years,
                floatingLegConvention);
            Schedule fixedSchedule = new Schedule(startDate,maturity,
                fixedLegTenor,calendar,fixedLegConvention,fixedLegConvention,
                DateGeneration.Rule.Forward,false);
            Schedule floatSchedule = new Schedule(startDate,maturity,
                floatingLegTenor,calendar,floatingLegConvention,
                floatingLegConvention,DateGeneration.Rule.Forward,false);
            VanillaSwap swap = new VanillaSwap(
                       VanillaSwap.Payer, 1000.0,
                       fixedSchedule, dummyFixedRate, fixedLegDayCounter,
                       floatSchedule, indexSixMonths, 0.0,
                       indexSixMonths.dayCounter());
            DiscountingSwapEngine swapEngine =
                new DiscountingSwapEngine(rhTermStructure);
            swap.setPricingEngine(swapEngine);
            double fixedATMRate = swap.fairRate();
            double fixedOTMRate = fixedATMRate * 1.2;
            double fixedITMRate = fixedATMRate * 0.8;

            VanillaSwap atmSwap = new VanillaSwap(
                       VanillaSwap.Payer, 1000.0,
                       fixedSchedule, fixedATMRate, fixedLegDayCounter,
                       floatSchedule, indexSixMonths, 0.0,
                       indexSixMonths.dayCounter() );
            VanillaSwap otmSwap = new VanillaSwap(
                       VanillaSwap.Payer, 1000.0,
                       fixedSchedule, fixedOTMRate, fixedLegDayCounter,
                       floatSchedule, indexSixMonths, 0.0,
                       indexSixMonths.dayCounter());
            VanillaSwap itmSwap = new VanillaSwap(
                       VanillaSwap.Payer, 1000.0,
                       fixedSchedule, fixedITMRate, fixedLegDayCounter,
                       floatSchedule, indexSixMonths, 0.0,
                       indexSixMonths.dayCounter());
            atmSwap.setPricingEngine(swapEngine);
            otmSwap.setPricingEngine(swapEngine);
            itmSwap.setPricingEngine(swapEngine);

            // defining the swaptions to be used in model calibration
            PeriodVector swaptionMaturities = new PeriodVector();
            swaptionMaturities.Add( new Period(1, TimeUnit.Years) );
            swaptionMaturities.Add( new Period(2, TimeUnit.Years) );
            swaptionMaturities.Add( new Period(3, TimeUnit.Years) );
            swaptionMaturities.Add( new Period(4, TimeUnit.Years) );
            swaptionMaturities.Add( new Period(5, TimeUnit.Years) );

            CalibrationHelperVector swaptions = new CalibrationHelperVector();

            // List of times that have to be included in the timegrid
            DoubleVector times = new DoubleVector();

            for ( int i=0; i<numRows; i++) {
                int j = numCols - i -1; // 1x5, 2x4, 3x3, 4x2, 5x1
                int k = i*numCols + j;
                Quote vol = new SimpleQuote( swaptionVols[k] );
                SwaptionHelper helper = new SwaptionHelper(
                                swaptionMaturities[i],
                               new Period(swapLenghts[j], TimeUnit.Years),
                               new QuoteHandle(vol),
                               indexSixMonths,
                               indexSixMonths.tenor(),
                               indexSixMonths.dayCounter(),
                               indexSixMonths.dayCounter(),
                               rhTermStructure );
                swaptions.Add( helper );
                times.AddRange( helper.times() );
            }

            // Building time-grid
            TimeGrid grid = new TimeGrid( times, 30);

            // defining the models
            // G2 modelG2 = new G2(rhTermStructure));
            HullWhite modelHW = new HullWhite( rhTermStructure );
            HullWhite modelHW2 = new HullWhite( rhTermStructure );
            BlackKarasinski modelBK = new BlackKarasinski( rhTermStructure );

            // model calibrations

//          Console.WriteLine( "G2 (analytic formulae) calibration" );
//          for (int i=0; i<swaptions.Count; i++)
//              swaptions[i].setPricingEngine( new G2SwaptionEngine( modelG2, 6.0, 16 ) );
//
//          calibrateModel( modelG2, swaptions, 0.05);
//          Console.WriteLine( "calibrated to:" );
//          Console.WriteLine( "a     = " + modelG2.parameters()[0] );
//          Console.WriteLine( "sigma = " + modelG2.parameters()[1] );
//          Console.WriteLine( "b     = " + modelG2.parameters()[2] );
//          Console.WriteLine( "eta   = " + modelG2.parameters()[3] );
//          Console.WriteLine( "rho   = " + modelG2.parameters()[4] );

            Console.WriteLine( "Hull-White (analytic formulae) calibration" );
            for (int i=0; i<swaptions.Count; i++)
                swaptions[i].setPricingEngine(
                                       new JamshidianSwaptionEngine(modelHW));

            calibrateModel( modelHW, swaptions, 0.05);
//          Console.WriteLine( "calibrated to:" );
//            Console.WriteLine( "a = " + modelHW.parameters()[0] );
//            Console.WriteLine( "sigma = " + modelHW.parameters()[1] );


            Console.WriteLine( "Hull-White (numerical) calibration" );
            for (int i=0; i<swaptions.Count; i++)
                swaptions[i].setPricingEngine(
                                       new TreeSwaptionEngine(modelHW2,grid));

            calibrateModel(modelHW2, swaptions, 0.05);
//        std::cout << "calibrated to:\n"
//                  << "a = " << modelHW2->params()[0] << ", "
//                  << "sigma = " << modelHW2->params()[1]
//                  << std::endl << std::endl;


            Console.WriteLine( "Black-Karasinski (numerical) calibration" );
            for (int i=0; i<swaptions.Count; i++)
                swaptions[i].setPricingEngine(
                                        new TreeSwaptionEngine(modelBK,grid));

            calibrateModel(modelBK, swaptions, 0.05);
//        std::cout << "calibrated to:\n"
//                  << "a = " << modelBK->params()[0] << ", "
//                  << "sigma = " << modelBK->params()[1]
//                  << std::endl << std::endl;

            // ATM Bermudan swaption pricing

            Console.WriteLine( "Payer bermudan swaption struck at {0} (ATM)",
                               fixedATMRate );

            DateVector bermudanDates = new DateVector();
            Schedule schedule = new Schedule(startDate,maturity,
                new Period(3,TimeUnit.Months),calendar,
                BusinessDayConvention.Following,
                BusinessDayConvention.Following,
                DateGeneration.Rule.Forward,false);

            for (uint i=0; i<schedule.size(); i++)
                bermudanDates.Add( schedule.date( i ) );
            Exercise bermudaExercise = new BermudanExercise( bermudanDates );

            Swaption bermudanSwaption =
                new Swaption( atmSwap, bermudaExercise);
            bermudanSwaption.setPricingEngine(
                              new TreeSwaptionEngine(modelHW, 50));
            Console.WriteLine( "HW: " + bermudanSwaption.NPV() );

            bermudanSwaption.setPricingEngine(
                                       new TreeSwaptionEngine(modelHW2, 50));
            Console.WriteLine( "HW (num): " + bermudanSwaption.NPV() );

            bermudanSwaption.setPricingEngine(
                                       new TreeSwaptionEngine(modelBK, 50));
            Console.WriteLine( "BK (num): " + bermudanSwaption.NPV() );

            DateTime endTime = DateTime.Now;
            TimeSpan delta = endTime - startTime;
            Console.WriteLine();
            Console.WriteLine("Run completed in {0} s", delta.TotalSeconds);
            Console.WriteLine();
        }