Examples of StopClock


Examples of org.jquantlib.samples.util.StopClock

    public void run() {

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        //Let's take todays date to explore the date interface
        final Date today = Date.todaysDate();
        System.out.println("Today's date is = "+today);

        //Get the Month enum and the month's integer equivalent of this date
        final Month month = today.month();
        final int integerEquivalentOfMonth = today.month().value();
        System.out.println("The month of today's date is = "+month);
        System.out.println("The integer equivalent of this month as obtained from the date is = "+integerEquivalentOfMonth);
        System.out.println("The integer equivalent of the date as obtained from the Month is also = "+month.value());

        //Get the weekday
        final Weekday weekDayOfThisDate = today.weekday();
        System.out.println("The weekday of this date is = "+weekDayOfThisDate);

        //Get the day of the date for it's month
        System.out.println("The day of the date as a day in this date's month(1-31) is = "+today.dayOfMonth());

        //Get the day of the date for it's year
        System.out.println("The day of the date as day in it's year(1-366) is = "+today.dayOfYear());

        //Check if the date belongs to a leap year
        if (Date.isLeap(today.year())) {
            System.out.println("Today's date belong to leap year");
        }

        //Get the next nextWeekdayDate of this date's month having weekday as TUESDAY
        final Date nextWeekdayDate = Date.nextWeekday(today,Weekday.Tuesday);
        System.out.println("The date of the next weekday is = "+nextWeekdayDate);

        //Get the 4th weekdayDate of this date's month having weekday as TUESDAY
        final Date fourthWeekdayDate = Date.nthWeekday(4, Weekday.Tuesday, today.month(), today.year());
        System.out.println("The fourthWeekdayDate which is TUESDAY is = "+fourthWeekdayDate);

        //Let's try getting the first date of the month to which today's date belong to
        final Date dateEndOfMonth = Date.endOfMonth(today);
        final int dayOfEndOfMonth = dateEndOfMonth.dayOfMonth();
        final Date dateStartOfMonth = dateEndOfMonth.add(-dayOfEndOfMonth+1);
        System.out.println("The first date of the month to which todays date belong to is = "+dateStartOfMonth);

        //Let's try getting the first date of the month to which today's date belong to using Period
        final Period period = new Period(-today.dayOfMonth()+1,TimeUnit.Days);
        Date dateStartOfMonthUsingPeriod = today.add(period);
        System.out.println("The first date of the month to which today's date belong to using period is = "+dateStartOfMonthUsingPeriod);

        //Let's use adjust function to get the same result as obtained above
        dateStartOfMonthUsingPeriod = today.add(period);
        System.out.println("The first date of the month to which today's date belong to using adjustment of period is = "+dateStartOfMonthUsingPeriod);


        //<================Let's do some date comparisons========================>

        //Startdate of the month is less than endDate of this dates month
        if(dateStartOfMonthUsingPeriod.le(dateEndOfMonth)){
            System.out.println("Start date is less than end date?");
        }

        //EndDate of the month is greater than Startdate  of this dates month
        if(dateEndOfMonth.ge(dateStartOfMonthUsingPeriod)){
            System.out.println("End date is greater than start date");
        }

        //Let's increment today's date till the endOfMonth
        Date date = today.clone();
        while (!date.eq(dateEndOfMonth)) {
            date.inc();
        }
        System.out.println("The date variable has been incremented to endOfMonth and is = "+date);

        // Let's decrement the same till beginning of the month
        date = today.clone();
        while (!date.eq(dateStartOfMonth)) {
            date.dec();
        }
        System.out.println("The date variable has been decremented to startOfMonth and is = "+date);

        // Let's update the todaysDate with the date just after it as the date is updatable
        today.addAssign(1);
        System.out.println("Today's date dateToday has been updated to = "+today);

        //Let's change the dateToday to current date
        today.subAssign(1);
        System.out.println("Today's date dateToday has been updated to = "+today);

        clock.stopClock();
        clock.log();

    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

    try {

        final StopClock clock = new StopClock();
            clock.startClock();

      /* @Time */      final Number maturity = new Double(1.0 / 12.0); // 1 month
      /* @Real */     final Number strike = new Double(100);
      /* @Real */     final Number underlying = new Double(100);
      /* @Volatility */  final Number volatility = new Double(0.20); // 20%
      /* @Rate */        final Number riskFreeRate = new Double(0.05); // 5%
      final Option.Type Call = Option.Type.Call;

      final ReplicationError rp = new ReplicationError(Call, maturity, strike, underlying, volatility, riskFreeRate);

      final int scenarios = 50000;
      int hedgesNum;

      hedgesNum = 21;
      rp.compute(hedgesNum, scenarios);

      hedgesNum = 84;
      rp.compute(hedgesNum, scenarios);

      clock.stopClock();
      clock.log();
    }

    catch(final Exception ex){
      ex.printStackTrace();
      //QL.info(ex.getMessage());
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

        QL.validateExperimentalMode();

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        // set up dates
        final Calendar calendar = new Target();
        final Date todaysDate = new Date(15, Month.May, 1998);
        final Date settlementDate = new Date(17, Month.May, 1998);
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

    public void run() {

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();
        QL.info("Started calculation at: " + clock.getElapsedTime());
        /*********************
         *** MARKET DATA ***
         *********************/

        final Calendar calendar = new Target();

        // FIXME: outdated...
        Date settlementDate = new Date(18, Month.September, 2008);
        // must be a business day
        settlementDate = calendar.adjust(settlementDate);

        final int fixingDays = 3;
        final int settlementDays = 3;

        final Date todaysDate = calendar.advance(settlementDate, -fixingDays, TimeUnit.Days);
        new Settings().setEvaluationDate(todaysDate);

        QL.info("Evaluation date: " + todaysDate.weekday() + ", " + todaysDate);
        QL.info("Settlement date: " + settlementDate.weekday() + ", " + settlementDate);

        // Building of the bonds discounting yield curve

        /*********************
         *** RATE HELPERS ***
         *********************/

        // RateHelpers are built from the above quotes together with
        // other instrument dependent infos. Quotes are passed in
        // relinkable handles which could be relinked to some other
        // data source later.
       
        // Common data
       
        // ZC rates for the short end
        final double zc3mQuote = 0.0096;
        final double zc6mQuote = 0.0145;
        final double zc1yQuote = 0.0194;

        final Quote zc3mRate = new SimpleQuote(zc3mQuote);
        final Quote zc6mRate = new SimpleQuote(zc6mQuote);
        final Quote zc1yRate = new SimpleQuote(zc1yQuote);

        final DayCounter zcBondsDayCounter = new Actual365Fixed();

        final RateHelper zc3m = new DepositRateHelper(
                new Handle<Quote>(zc3mRate), new Period(3, TimeUnit.Months),
                fixingDays, calendar,
                BusinessDayConvention.ModifiedFollowing, true, zcBondsDayCounter);
        final RateHelper zc6m = new DepositRateHelper(
                new Handle<Quote>(zc6mRate), new Period(6, TimeUnit.Months),
                fixingDays, calendar,
                BusinessDayConvention.ModifiedFollowing, true, zcBondsDayCounter);
        final RateHelper zc1y = new DepositRateHelper(
                new Handle<Quote>(zc1yRate), new Period(1, TimeUnit.Years),
                fixingDays, calendar,
                BusinessDayConvention.ModifiedFollowing, true, zcBondsDayCounter);

        // setup bonds
        final double redemption = 100.0;
        final int numberOfBonds = 5;

        final Date issueDates[] = {
                new Date(15, Month.March,    2005),
                new Date(15, Month.June,     2005),
                new Date(30, Month.June,     2006),
                new Date(15, Month.November, 2002),
                new Date(15, Month.May,      1987) };

        final Date maturities[] = {
                new Date(31, Month.August, 2010),
                new Date(31, Month.August, 2011),
                new Date(31, Month.August, 2013),
                new Date(15, Month.August, 2018),
                new Date(15, Month.May,    2038) };

        final double couponRates[] = 0.02375,
                        0.04625,
                        0.03125,
                        0.04000,
                        0.04500
                        };

        final double marketQuotes[] = { 100.390625,
                        106.21875,
                        100.59375,
                        101.6875,
                        102.140625
                        };

        final List<SimpleQuote> quote = new ArrayList<SimpleQuote>(numberOfBonds);
        final List<RelinkableHandle<Quote>> quoteHandle = new ArrayList<RelinkableHandle<Quote>>(numberOfBonds);
        for (int i = 0; i < numberOfBonds; i++) {
          final SimpleQuote sq = new SimpleQuote(marketQuotes[i]);
          final RelinkableHandle<Quote> handle = new RelinkableHandle<Quote>(sq);
            quote.add(sq);
            quoteHandle.add(handle);  
        }

        // Definition of the rate helpers
//        final List<FixedRateBondHelper<YieldTermStructure>> bondsHelpers = new ArrayList<FixedRateBondHelper<YieldTermStructure>>();
        final List<FixedRateBondHelper> bondsHelpers = new ArrayList<FixedRateBondHelper>();

        for (int i = 0; i < numberOfBonds; i++) {
            final Schedule schedule = new Schedule(
                    issueDates[i], maturities[i],
                    new Period(Frequency.Semiannual),
                    new UnitedStates(UnitedStates.Market.GOVERNMENTBOND),
                    BusinessDayConvention.Unadjusted,
                    BusinessDayConvention.Unadjusted,
                    DateGeneration.Rule.Backward,
                    false);
            final FixedRateBondHelper bondHelper = new FixedRateBondHelper(
                            quoteHandle.get(i),
                            settlementDays,
                            100.0,
                            schedule,
                            new double[]{ couponRates[i] },
                            new ActualActual(ActualActual.Convention.Bond),
                            BusinessDayConvention.Unadjusted,
                            redemption,
                            issueDates[i]);

            bondsHelpers.add(bondHelper);
        }

        /*********************
         ** CURVE BUILDING **
         *********************/

        // Any DayCounter would be fine.
        // ActualActual::ISDA ensures that 30 years is 30.0
        final DayCounter termStructureDayCounter = new ActualActual(ActualActual.Convention.ISDA);

        final double tolerance = 1.0e-15;

        // A depo-bond curve
        final List<RateHelper> bondInstruments = new ArrayList<RateHelper>();

        // Adding the ZC bonds to the curve for the short end
        bondInstruments.add(zc3m);
        bondInstruments.add(zc6m);
        bondInstruments.add(zc1y);

        // Adding the Fixed rate bonds to the curve for the long end
        for (int i = 0; i < numberOfBonds; i++) {
            bondInstruments.add(bondsHelpers.get(i));
        }
        final RateHelper[] instruments1 = new RateHelper[bondInstruments.size()];
        bondInstruments.toArray(instruments1);
        final Handle[] jumps1 = new Handle[0];
        final Date[] jumpDates1 = new Date[0];
        final double tolerance1 = 1.0e-15;
        final LogLinear interpolator = null;
        final IterativeBootstrap bootstrap = null;
       
        final YieldTermStructure  bondDiscountingTermStructur =
                 new PiecewiseYieldCurve<Discount,LogLinear,IterativeBootstrap>(
                     Discount.class, LogLinear.class, IterativeBootstrap.class,
                     settlementDate,
                     instruments1,
                     termStructureDayCounter,
                     jumps1,
                     jumpDates1,
                     tolerance1,
                     interpolator,
                     bootstrap){/* anonymous */};

        // Building of the Libor forecasting curve
        // deposits
        final double d1wQuote = 0.043375;
        final double d1mQuote = 0.031875;
        final double d3mQuote = 0.0320375;
        final double d6mQuote = 0.03385;
        final double d9mQuote = 0.0338125;
        final double d1yQuote = 0.0335125;
        // swaps
        final double s2yQuote = 0.0295;
        final double s3yQuote = 0.0323;
        final double s5yQuote = 0.0359;
        final double s10yQuote = 0.0412;
        final double s15yQuote = 0.0433;

        /********************
         *** QUOTES ***
         ********************/

        // SimpleQuote stores a value which can be manually changed;
        // other Quote subclasses could read the value from a database
        // or some kind of data feed.

        // deposits
        final Quote d1wRate = (new SimpleQuote(d1wQuote));
        final Quote d1mRate = (new SimpleQuote(d1mQuote));
        final Quote d3mRate = (new SimpleQuote(d3mQuote));
        final Quote d6mRate = (new SimpleQuote(d6mQuote));
        final Quote d9mRate = (new SimpleQuote(d9mQuote));
        final Quote d1yRate = (new SimpleQuote(d1yQuote));
        // swaps
        final Quote s2yRate = (new SimpleQuote(s2yQuote));
        final Quote s3yRate = (new SimpleQuote(s3yQuote));
        final Quote s5yRate = (new SimpleQuote(s5yQuote));
        final Quote s10yRate = (new SimpleQuote(s10yQuote));
        final Quote s15yRate = (new SimpleQuote(s15yQuote));

        /*********************
         *** RATE HELPERS ***
         *********************/

        // RateHelpers are built from the above quotes together with
        // other instrument dependant infos. Quotes are passed in
        // relinkable handles which could be relinked to some other
        // data source later.

        // deposits
        final DayCounter depositDayCounter = new Actual360();

        final RateHelper d1w = new DepositRateHelper(
                  new Handle<Quote>(d1wRate),
                  new Period(1, TimeUnit.Weeks),
                  fixingDays, calendar,
                  BusinessDayConvention.ModifiedFollowing,
                  true, depositDayCounter);
        final RateHelper d1m = new DepositRateHelper(
                  new Handle<Quote>(d1mRate),
                  new Period(1, TimeUnit.Months),
                  fixingDays, calendar,
                  BusinessDayConvention.ModifiedFollowing,
                  true, depositDayCounter);
        final RateHelper d3m = new DepositRateHelper(
                  new Handle<Quote>(d3mRate),
                  new Period(3, TimeUnit.Months),
                  fixingDays, calendar,
                  BusinessDayConvention.ModifiedFollowing,
                  true, depositDayCounter);
        final RateHelper d6m = new DepositRateHelper(
                  new Handle<Quote>(d6mRate),
                  new Period(6, TimeUnit.Months),
                  fixingDays, calendar,
                  BusinessDayConvention.ModifiedFollowing,
                  true, depositDayCounter);
        final RateHelper d9m = new DepositRateHelper(
                new Handle<Quote>(d9mRate),
                new Period(9, TimeUnit.Months),
                fixingDays, calendar,
                BusinessDayConvention.ModifiedFollowing,
                true, depositDayCounter);
        final RateHelper d1y = new DepositRateHelper(
                new Handle<Quote>(d1yRate),
                new Period(1, TimeUnit.Years),
                fixingDays, calendar,
                BusinessDayConvention.ModifiedFollowing,
                true, depositDayCounter);

        // setup swaps
        final Frequency swFixedLegFrequency = Frequency.Annual;
        final BusinessDayConvention swFixedLegConvention = BusinessDayConvention.Unadjusted;
        final DayCounter swFixedLegDayCounter = new Thirty360(Convention.European);
        final IborIndex  swFloatingLegIndex = new Euribor6M(new Handle<YieldTermStructure>());

        // TODO and FIXME: not sure whether the class stuff works properly
        // final IborIndex swFloatingLegIndex = Euribor.getEuribor6M(new Handle<YieldTermStructure>(YieldTermStructure.class)); //FIXME::RG::Handle
//        final YieldTermStructure nullYieldTermStructure = new AbstractYieldTermStructure() {
//            @Override
//            protected double discountImpl(final double t) {
//                throw new UnsupportedOperationException();
//            }
//            @Override
//            public Date maxDate() {
//                throw new UnsupportedOperationException();
//            }
//        };
//        final IborIndex swFloatingLegIndex = new Euribor6M(new Handle<YieldTermStructure>(nullYieldTermStructure));


        final Period forwardStart = new Period(1, TimeUnit.Days);
       
        final RateHelper s2y = new SwapRateHelper(
              new Handle<Quote>(s2yRate),
              new Period(2, TimeUnit.Years),
              calendar,
              swFixedLegFrequency,
              swFixedLegConvention,
              swFixedLegDayCounter,
              swFloatingLegIndex,
              new Handle<Quote>(),
              forwardStart);
         final RateHelper s3y = new SwapRateHelper(
                 new Handle<Quote>(s3yRate),
                 new Period(3, TimeUnit.Years),
                 calendar,
                 swFixedLegFrequency,
                 swFixedLegConvention,
                 swFixedLegDayCounter,             
                 swFloatingLegIndex,
                 new Handle<Quote>(),
                 forwardStart);
        final RateHelper  s5y = new SwapRateHelper(
                new Handle<Quote>(s5yRate),
                new Period(5, TimeUnit.Years),
                calendar,
                swFixedLegFrequency,
                swFixedLegConvention,
                swFixedLegDayCounter,
                swFloatingLegIndex,
                new Handle<Quote>(),
                forwardStart);
        final RateHelper s10y = new SwapRateHelper(
                new Handle<Quote>(s10yRate),
                new Period(10, TimeUnit.Years),
                calendar,
                swFixedLegFrequency,
                swFixedLegConvention,
                swFixedLegDayCounter,
                swFloatingLegIndex,
                new Handle<Quote>(),
                forwardStart);
        final RateHelper  s15y = new SwapRateHelper(
                new Handle<Quote>(s15yRate),
                new Period(15, TimeUnit.Years),
                calendar,
                swFixedLegFrequency,
                swFixedLegConvention,
                swFixedLegDayCounter,
                swFloatingLegIndex,
                new Handle<Quote>(),
                forwardStart);

         /*********************
         ** CURVE BUILDING **
         *********************/
       
         // Any DayCounter would be fine.
         // ActualActual::ISDA ensures that 30 years is 30.0
       
         // A depo-swap curve
         final List<RateHelper> depoSwapInstruments = new ArrayList<RateHelper>();
         depoSwapInstruments.add(d1w);
         depoSwapInstruments.add(d1m);
         depoSwapInstruments.add(d3m);
         depoSwapInstruments.add(d6m);
         depoSwapInstruments.add(d9m);
         depoSwapInstruments.add(d1y);
         depoSwapInstruments.add(s2y);
         depoSwapInstruments.add(s3y);
         depoSwapInstruments.add(s5y);
         depoSwapInstruments.add(s10y);
         depoSwapInstruments.add(s15y);
        
         final RateHelper[] instruments = new RateHelper[depoSwapInstruments.size()];
         depoSwapInstruments.toArray(instruments);
         final Handle[] jumps= new Handle[0];//]<Quote>[]) new ArrayList<Handle<Quote>>().toArray();
         final Date[] jumpDates = new Date[0];// new ArrayList<Date>().toArray();
        
         final YieldTermStructure  depoSwapTermStructure =
             new PiecewiseYieldCurve<Discount,LogLinear,IterativeBootstrap>(
                 Discount.class, LogLinear.class, IterativeBootstrap.class,
                 settlementDate,
                 instruments,
                 termStructureDayCounter,
                 jumps,
                 jumpDates,
                 tolerance,
            interpolator,/*Hack*/
             bootstrap /*Hack*/){/* anonymous */};

         // Term structures that will be used for pricing:
         // the one used for discounting cash flows
         final RelinkableHandle<YieldTermStructure> discountingTermStructure = new RelinkableHandle<YieldTermStructure>();
         // the one used for forward rate forecasting
         final RelinkableHandle<YieldTermStructure> forecastingTermStructure = new RelinkableHandle<YieldTermStructure>();
       
         /*********************
         * BONDS TO BE PRICED *
         **********************/
       
         // Common data
         final double faceAmount = 100;
       
         // Pricing engine
        final PricingEngine  bondEngine = new DiscountingBondEngine(discountingTermStructure);
       
         // Zero coupon bond
         final ZeroCouponBond zeroCouponBond = new ZeroCouponBond(
                           settlementDays,
                           new UnitedStates(UnitedStates.Market.GOVERNMENTBOND),
                           faceAmount,
                           new Date(15,Month.August,2013),
                           BusinessDayConvention.Following,
                           116.92,
                           new Date(15,Month.August,2003));
       
         zeroCouponBond.setPricingEngine(bondEngine);
       
         // Fixed 4.5% US Treasury Note
         final Schedule fixedBondSchedule = new Schedule(
                     new Date(15, Month.May, 2007),
                     new Date(15,Month.May,2017),
                     new Period(Frequency.Semiannual),
                     new UnitedStates(UnitedStates.Market.GOVERNMENTBOND),
                     BusinessDayConvention.Unadjusted,
                     BusinessDayConvention.Unadjusted,
                     DateGeneration.Rule.Backward, false);
       
         final FixedRateBond fixedRateBond = new FixedRateBond(
                     settlementDays,
                     faceAmount,
                     fixedBondSchedule,
                     new double[]{0.045},
                     new ActualActual(ActualActual.Convention.Bond),
                     BusinessDayConvention.ModifiedFollowing,
                     100.0,
                     new Date(15, Month.May, 2007));
       
         fixedRateBond.setPricingEngine(bondEngine);
       
         // Floating rate bond (3M USD Libor + 0.1%)
         // Should and will be priced on another curve later...
       
         final RelinkableHandle<YieldTermStructure> liborTermStructure = new RelinkableHandle<YieldTermStructure>();
         final IborIndex libor3m =  new USDLibor(new Period(3, TimeUnit.Months), liborTermStructure);
         libor3m.addFixing(new Date(17, Month.July, 2008), 0.0278625);
       
         final Schedule floatingBondSchedule = new Schedule(
                     new Date(21, Month.October, 2005),
                     new Date(21, Month.October, 2010), new Period(Frequency.Quarterly),
                     new UnitedStates(UnitedStates.Market.NYSE),
                     BusinessDayConvention.Unadjusted,
                     BusinessDayConvention.Unadjusted,
                     DateGeneration.Rule.Backward, true);
       
         final FloatingRateBond floatingRateBond = new FloatingRateBond(
                     settlementDays,
                     faceAmount,
                     floatingBondSchedule,
                     libor3m,
                     new Actual360(),
                     BusinessDayConvention.ModifiedFollowing,
                     2,                    
                     new Array(1).fill(1.0)//Gearings                    
                     new Array(1).fill(0.001),//Spreads
                     new Array(0),         // Caps
                     new Array(0),         // Floors
                     true,             // Fixing in arrears
                     100.0,
                     new Date(21, Month.October, 2005));
       
         floatingRateBond.setPricingEngine(bondEngine);
              
         // optionLet volatilities
         final double volatility = 0.0;
         final Handle<OptionletVolatilityStructure> vol =
               new Handle<OptionletVolatilityStructure>(
                     new ConstantOptionletVolatility(
                         settlementDays,
                         calendar,
                         BusinessDayConvention.ModifiedFollowing,
                         volatility,
                         new Actual365Fixed()));
       
         // Coupon pricers
         final IborCouponPricer pricer = new BlackIborCouponPricer(vol);
         PricerSetter.setCouponPricer(floatingRateBond.cashflows(),pricer);
       
         // Yield curve bootstrapping
         forecastingTermStructure.linkTo(depoSwapTermStructure);
         discountingTermStructure.linkTo(bondDiscountingTermStructur);
       
         // We are using the depo & swap curve to estimate the future Libor
         // rates
         liborTermStructure.linkTo(depoSwapTermStructure);
       
         /***************
         * BOND PRICING *
         ****************/
       
        QL.info("Results:");
       
         System.out.println("                 "
             + "  " "ZC"
             + "  " "Fixed"
             + "  " "Floating"
             );
               
         System.out.println( "Net present value"
               "  " + zeroCouponBond.NPV()
               "  " + fixedRateBond.NPV()
               "  " + floatingRateBond.NPV());
               
        System.out.println("Clean Price      "
            + "  " +zeroCouponBond.cleanPrice()
            + "  " +fixedRateBond.cleanPrice()
            + "  " + floatingRateBond.cleanPrice()
            );
       
        System.out.println("Dirty price      "
              + " " + zeroCouponBond.dirtyPrice()
              + " " + fixedRateBond.dirtyPrice()
              + " " + floatingRateBond.dirtyPrice()
              );
       
        System.out.println( "Accrued coupon  "
          + " " + zeroCouponBond.accruedAmount()
          + " " + fixedRateBond.accruedAmount()
          + " " + floatingRateBond.accruedAmount()
            );

        System.out.println( "Previous coupon "
          + " " + "N/A"  //zeroCouponBond
          + " " + fixedRateBond.previousCoupon()
          + " " + floatingRateBond.previousCoupon()
            );

        System.out.println( "Next coupon     "
          + " " + "N/A"  //zeroCouponBond
          + " " + fixedRateBond.nextCoupon()
          + " " + floatingRateBond.nextCoupon()
            );
        System.out.println( "Yield           "
          + " " + zeroCouponBond.yield(new Actual360(),Compounding.Compounded, Frequency.Annual)
          + " " + fixedRateBond.yield(new Actual360(),Compounding.Compounded, Frequency.Annual)
          + " " + floatingRateBond.yield(new Actual360(),Compounding.Compounded, Frequency.Annual)
            );

         // Other computations
        System.out.println("Sample indirect computations (for the floating rate bond): " );
        System.out.println( "Yield to Clean Price: " +
            floatingRateBond.cleanPrice(floatingRateBond.yield(new Actual360(),Compounding.Compounded,Frequency.Annual),new Actual360(),Compounding.Compounded,Frequency.Annual,settlementDate)
        );
       
        System.out.println("Clean Price to Yield: " +
         floatingRateBond.yield(floatingRateBond.cleanPrice(),new Actual360(),Compounding.Compounded,Frequency.Annual,settlementDate)
        );
       
         /* "Yield to Price"
           "Price to Yield"
         */
        clock.stopClock();
        clock.log();
    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

    public void run() {

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        // <=========================Basic Calendar functions==============================>
        //Let's take UnitedStates New-York-Stock-Exchange calendar
        final Calendar unitedStatesCalendar = new UnitedStates(Market.NYSE);
        System.out.println("The name of this calendar is = "+ unitedStatesCalendar.name());
        // Let's get the list of holidays from todays date till the date obtained by advancing today's date by 90 days
        final Date dateToday = Date.todaysDate();
        final Date dateAdvanced = dateToday.add(90);
        final List<Date> holidayList = UnitedStates.holidayList(unitedStatesCalendar,dateToday, dateAdvanced, true);
        System. out.println("The holidays between dateToday = " + dateToday+ " till the date dateAdvanced = " + dateAdvanced+ " are as shown below");
        final StringBuffer bufferToHoldHolidays = new StringBuffer();
        for (final Date date : holidayList) {
            bufferToHoldHolidays.append(date +"::");
        }
        System. out.println("The holidays separated by :: are = "+ bufferToHoldHolidays);

        // Let's get the business days between dateToday and dateAdvanced as obtained above by advancing
        // today's date by 90 days as shown below and checking if the incremented date isBusinessDate
        final List<Date> businessDaysInBetweenUsingIsBusDay = new ArrayList<Date>();
        Date dateTodayTemp = dateToday.clone();
        for (; !dateTodayTemp.eq(dateAdvanced); dateTodayTemp.inc()) {
            if (unitedStatesCalendar.isBusinessDay(dateTodayTemp)) {
                businessDaysInBetweenUsingIsBusDay.add(dateTodayTemp);
            }
        }

        final Long sizeOfBusinessDays = Long.parseLong(Integer.toString((businessDaysInBetweenUsingIsBusDay.size())));
        // Let's get the business days between dateToday and dateAdvanced as obtained above by advancing
        // today's date by 90 days using calendar api businessDaysBetween
        final long sizeOfBusinessDaysUsingCalApi = unitedStatesCalendar.businessDaysBetween(dateToday, dateAdvanced, true, true);
        // Check if the sizes obtained are same as they both represent same set of business days
        if (sizeOfBusinessDays == sizeOfBusinessDaysUsingCalApi) {
            System.out.println("The sizes are same");
        }

        // Let's get the same business days using calendars isHoliday API
        final List<Date> businessDaysInBetweenUsingIsHolDay = new ArrayList<Date>();
        dateTodayTemp = dateToday.clone();
        for (; !dateTodayTemp.eq(dateAdvanced); dateTodayTemp.inc()) {
            if (!unitedStatesCalendar.isHoliday(dateTodayTemp)) {
                businessDaysInBetweenUsingIsHolDay.add(dateTodayTemp);
            }
        }

        //Essentially the lists businessDaysInBetweenUsingIsBusDay and businessDaysInBetweenUsingIsHolDay are same
        if (businessDaysInBetweenUsingIsBusDay.equals(businessDaysInBetweenUsingIsHolDay)) {
            System.out.println("The lists businessDaysInBetweenUsingIsBusDay and businessDaysInBetweenUsingIsHolDay are same");
        }

        // <========================Let's use some Calendar airthmetics==============================>
        // Get the first holiday from today
        final Date firstHolidayDate = dateToday.clone();
        while (!unitedStatesCalendar.isHoliday(firstHolidayDate)) {
            firstHolidayDate.inc();
        }

        // Check to see if firstHoliday is holiday
        if (unitedStatesCalendar.isHoliday(firstHolidayDate)) {
            System.out.println("FirstHolidayDate = " + firstHolidayDate+ " is a holiday date");
        }

        // Advance the first holiday date using calendars's advance(date) API and get the nexBusinessDay
        final Date nextBusinessDay = unitedStatesCalendar.advance(firstHolidayDate, new Period(1, TimeUnit.Days));
        if (unitedStatesCalendar.isBusinessDay(nextBusinessDay)) {
            System.out.println("NextBusinessDayFromFirstHolidayFromToday = "+ nextBusinessDay + " is a business date");
        }

        // Adjust todaysDate using different businessDayConventions

        // Using FOLLOWING as a business day convention
        final Date nextFollowingBusinessDay = unitedStatesCalendar.adjust(dateToday,BusinessDayConvention.Following);
        if (unitedStatesCalendar.isBusinessDay(nextFollowingBusinessDay)) {
            System. out.println("NextFollowingBusinessDate = "+ nextFollowingBusinessDay+ " from today is a business date");
        }

        // Using MODIFIED_FOLLOWING as a business day convention
        final Date nextModified_FollowingBusinessDay = unitedStatesCalendar.adjust(dateToday, BusinessDayConvention.ModifiedFollowing);
        if (unitedStatesCalendar.isBusinessDay(nextModified_FollowingBusinessDay)) {
            System.out.println("NextModified_FollowingBusinessDate = "+ nextModified_FollowingBusinessDay+ " from today is a business date");
        }

        // Using PRECEDING as a business day convention
        final Date nextPrecidingBusinessDay = unitedStatesCalendar.adjust(dateToday,BusinessDayConvention.Preceding);
        if (unitedStatesCalendar.isBusinessDay(nextPrecidingBusinessDay)) {
            System.out.println("NextPrecidingBusinessDay = "+ nextPrecidingBusinessDay+ " from today is a business date");
        }

        // Using MODIFIED_PRECEDING as a business day convention
        final Date nextModified_PrecidingBusinessDay = unitedStatesCalendar.adjust(dateToday, BusinessDayConvention.ModifiedPreceding);
        if (unitedStatesCalendar.isBusinessDay(nextModified_PrecidingBusinessDay)) {
            System.out.println("NextModified_PrecidingBusinessDay = "+ nextModified_PrecidingBusinessDay+ " from today is a business date");
        }

        // Using UNADJUSTED as a business day convention
        final Date nextUnadjustedBusinessDay = unitedStatesCalendar.adjust(dateToday,BusinessDayConvention.Unadjusted);
        if (unitedStatesCalendar.isBusinessDay(nextModified_PrecidingBusinessDay)) {
            System.out.println("NextUnadjustedBusinessDay = "+ nextUnadjustedBusinessDay+ " from today is a business date and is same as today");
        }

        // Advance the current date using calendars's advance(date,n,unit) where n = 10 and unit=DAYS
        Date advancedDate = unitedStatesCalendar.advance(dateToday, 10,TimeUnit.Days);
        System.out.println("Next business date when today's date is advanced by 10 days = "+ advancedDate);

        // Advance the current date using calendars's advance(date,n,unit) where n = 10 and unit=WEEKS
        advancedDate = unitedStatesCalendar.advance(dateToday, 10, TimeUnit.Weeks);
        System.out.println("Next business date when today's date is advanced by 10 weeks = "+ advancedDate);

        // Advance the current date using calendars's advance(date,n,unit) where n = 10 and unit=MONTHS
        advancedDate = unitedStatesCalendar.advance(dateToday, 10, TimeUnit.Months);
        System.out.println("Next business date when today's date is advanced by 10 months = "+ advancedDate);

        // Advance the current date using calendars's advance(date,n,unit) where n = 10 and unit=YEARS
        advancedDate = unitedStatesCalendar.advance(dateToday, 10, TimeUnit.Years);
        System.out.println("Next business date when today's date is advanced by 10 years = "+ advancedDate);

        // Advance the current date using calendars's advance(date,period-->lenth=1,Unit=Days,BusinessDayConvention=FOLLOWING)
        advancedDate = unitedStatesCalendar.advance(dateToday,new Period(1, TimeUnit.Days), BusinessDayConvention.Following);
        System.out.println("Next business date when today's date is advanced 1 day = "+ advancedDate);

        // Advance the current date using calendars's advance(date,period-->lenth=1,Unit=WEEKS,BusinessDayConvention=MODIFIED_FOLLOWING)
        advancedDate = unitedStatesCalendar.advance(dateToday,new Period(1, TimeUnit.Weeks),BusinessDayConvention.ModifiedFollowing);
        System.out.println("Next business date when today's date is advanced 1 week = "+ advancedDate);

        // Advance the current date using calendars's advance(date,period-->lenth=1,Unit=MONTHS,BusinessDayConvention=MODIFIED_PRECEDING)
        advancedDate = unitedStatesCalendar.advance(dateToday,new Period(1, TimeUnit.Months),BusinessDayConvention.ModifiedPreceding);
        System.out.println("Next business date when today's date is advanced 1 month = "+ advancedDate);

        // Advance the current date using calendars's advance(date,period-->lenth=1,Unit=YEARS,BusinessDayConvention=PRECEDING)
        advancedDate = unitedStatesCalendar.advance(dateToday,new Period(1, TimeUnit.Years), BusinessDayConvention.Preceding);
        System.out.println("Next business date when today's date is advanced 1 year = "+ advancedDate);

        //<==================Joining Calendars===============================>
        final Calendar unitedStatesCalendarGvtBondCalendar = new UnitedStates(Market.GOVERNMENTBOND);
        final Calendar jointCalendar = new JointCalendar(unitedStatesCalendar,unitedStatesCalendarGvtBondCalendar,JointCalendarRule.JoinBusinessDays);

        //The above joint calendar has been obtained by joining businessdays of newyork stock exchange and government bond calendar
        //which means a day will be a business day for the joint calendar if it is a business day for both of the calendars used
        //(NYSE,GovtBond) and will be a holiday if the day is a holiday in atleast one of the calendars.

        //Let's get the list of holidays for the joint calendar from the date today to date advanced(obtained by advancing date today by 90 days)
        final List<Date> listOfHoliDays = jointCalendar.holidayList(jointCalendar, dateToday, dateAdvanced, true);

        //Now let's get the same holiday list between dateToday and dateAdvanced using isBusinessDay API
        final List<Date> holidayListObtainedUsingCalAPI = new ArrayList<Date>();
        final Date start = dateToday.clone();
        for (; !start.eq(dateAdvanced); start.inc()) {
            if (jointCalendar.isHoliday(start)){
                holidayListObtainedUsingCalAPI.add(start.clone());
            }
        }

        //Essentially both the lists obtained above are same
        if(listOfHoliDays.equals(holidayListObtainedUsingCalAPI)){
            System.out.println("Lists listOfHoliDays and holidayListObtainedUsingCalAPI of joint calendar are same");
        }

        clock.stopClock();
        clock.log();
    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

        QL.validateExperimentalMode();

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        final Date todaysDate = new Date(15, February, 2002);

        // TODO: code review :: please verify against QL/C++ code
        final Calendar calendar = new Calendar() {
            public String getName() {
                return "";
            }

            @Override
            public boolean isWeekend(final Weekday w) {
                throw new UnsupportedOperationException();
            }
        };

        final Date settlementDate = new Date(19, February, 2002);
        new Settings().setEvaluationDate(todaysDate);

        // TODO: code review :: please verify against QL/C++ code

        clock.stopClock();
        clock.log();
    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

    @Override
    public void run() {

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        // set up dates
        final Calendar calendar = new Target();
        final Date todaysDate = new Date(15, Month.May, 1998);
        final Date settlementDate = new Date(17, Month.May, 1998);
        new Settings().setEvaluationDate(todaysDate);

        // our options
        final Option.Type type = Option.Type.Put;
        final double strike = 40.0;
        final double underlying = 36.0;
        /*@Rate*/final double riskFreeRate = 0.06;
        final double volatility = 0.2;
        final double dividendYield = 0.00;


        final Date maturity = new Date(17, Month.May, 1999);
        final DayCounter dayCounter = new Actual365Fixed();

        // define line formatting
        //              "         1         2         3         4         5         6         7         8         9"
        //              "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
        //              "                            Method      European      Bermudan      American";
        //              "================================== ============= ============= ============="
        //              "12345678901234567890123456789012345678901234 123.567890123 123.567890123 123.567890123";
        final String fmt    = "%34s %13.9f %13.9f %13.9f\n";
        final String fmttbd = "%34s %13.9f %13.9f %13.9f  (TO BE DONE)\n";

        // write column headings
        //                 "         1         2         3         4         5         6         7         8"
        //                 "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
        System.out.println("                            Method      European      Bermudan      American");
        System.out.println("================================== ============= ============= =============");

        // Define exercise for European Options
        final Exercise europeanExercise = new EuropeanExercise(maturity);

        // Define exercise for Bermudan Options
    final int bermudanForwards = 4;
    final Date[] exerciseDates = new Date[bermudanForwards];
    for (int i = 1; i <= bermudanForwards; i++) {
            exerciseDates[i-1] = settlementDate.add(new Period(3*i, TimeUnit.Months));
        }
      final Exercise bermudanExercise = new BermudanExercise(exerciseDates);

        // Define exercise for American Options
        final Exercise americanExercise = new AmericanExercise(settlementDate, maturity);

        // bootstrap the yield/dividend/volatility curves
        final Handle<Quote> underlyingH = new Handle<Quote>(new SimpleQuote(underlying));
        final Handle<YieldTermStructure> flatDividendTS = new Handle<YieldTermStructure>(new FlatForward(settlementDate, dividendYield, dayCounter));
        final Handle<YieldTermStructure> flatTermStructure = new Handle<YieldTermStructure>(new FlatForward(settlementDate, riskFreeRate, dayCounter));
        final Handle<BlackVolTermStructure> flatVolTS = new Handle<BlackVolTermStructure>(new BlackConstantVol(settlementDate, calendar, volatility, dayCounter));
        final Payoff payoff = new PlainVanillaPayoff(type, strike);

        final BlackScholesMertonProcess bsmProcess = new BlackScholesMertonProcess(underlyingH, flatDividendTS, flatTermStructure, flatVolTS);

        // European Options
        final VanillaOption europeanOption = new EuropeanOption(payoff, europeanExercise);

        // Bermudan options (can be thought as a collection of European Options)
        final VanillaOption bermudanOption = new VanillaOption(payoff, bermudanExercise);

        // American Options
        final VanillaOption americanOption = new VanillaOption(payoff, americanExercise);


        // Analytic formulas:

        // Black-Scholes for European
        String method = "Black-Scholes";
        europeanOption.setPricingEngine(new AnalyticEuropeanEngine(bsmProcess));
        System.out.printf(fmt, method, europeanOption.NPV(), Double.NaN, Double.NaN );

        // Barone-Adesi and Whaley approximation for American
        method = "Barone-Adesi/Whaley";
        americanOption.setPricingEngine(new BaroneAdesiWhaleyApproximationEngine(bsmProcess));
        System.out.printf(fmt, method, Double.NaN, Double.NaN, americanOption.NPV() );

        // Bjerksund and Stensland approximation for American
        method = "Bjerksund/Stensland";
        americanOption.setPricingEngine(new BjerksundStenslandApproximationEngine(bsmProcess));
        System.out.printf(fmt, method, Double.NaN, Double.NaN, americanOption.NPV() );

        // Ju Quadratic approximation for American
        method = "Ju Quadratic";
        americanOption.setPricingEngine(new JuQuadraticApproximationEngine(bsmProcess));
        System.out.printf(fmt, method, Double.NaN, Double.NaN, americanOption.NPV() );

        // Integral
        method = "Integral";
        europeanOption.setPricingEngine(new IntegralEngine(bsmProcess));
        System.out.printf(fmt, method, europeanOption.NPV(), Double.NaN, Double.NaN );

        int timeSteps = 801;

        // Binomial method
        method = "Binomial Jarrow-Rudd";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<JarrowRudd>(JarrowRudd.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<JarrowRudd>(JarrowRudd.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<JarrowRudd>(JarrowRudd.class, bsmProcess, timeSteps));
        double bNPV = Double.NaN;
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        method = "Binomial Cox-Ross-Rubinstein";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<CoxRossRubinstein>(CoxRossRubinstein.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<CoxRossRubinstein>(CoxRossRubinstein.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<CoxRossRubinstein>(CoxRossRubinstein.class, bsmProcess, timeSteps));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        method = "Additive EquiProbabilities";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<AdditiveEQPBinomialTree>(AdditiveEQPBinomialTree.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<AdditiveEQPBinomialTree>(AdditiveEQPBinomialTree.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<AdditiveEQPBinomialTree>(AdditiveEQPBinomialTree.class, bsmProcess, timeSteps));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        method = "Binomial Trigeorgis";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<Trigeorgis>(Trigeorgis.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<Trigeorgis>(Trigeorgis.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<Trigeorgis>(Trigeorgis.class, bsmProcess, timeSteps));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        method = "Binomial Tian";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<Tian>(Tian.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<Tian>(Tian.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<Tian>(Tian.class, bsmProcess, timeSteps));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        method = "Binomial Leisen-Reimer";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<LeisenReimer>(LeisenReimer.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<LeisenReimer>(LeisenReimer.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<LeisenReimer>(LeisenReimer.class, bsmProcess, timeSteps));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        method = "Binomial Joshi";
        europeanOption.setPricingEngine(new BinomialVanillaEngine<Joshi4>(Joshi4.class, bsmProcess, timeSteps));
        bermudanOption.setPricingEngine(new BinomialVanillaEngine<Joshi4>(Joshi4.class, bsmProcess, timeSteps));
        americanOption.setPricingEngine(new BinomialVanillaEngine<Joshi4>(Joshi4.class, bsmProcess, timeSteps));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );


        //
        //
        //

        // Finite differences
        method = "Finite differences";
        europeanOption.setPricingEngine(new FDEuropeanEngine(bsmProcess, timeSteps, timeSteps-1, false));
        bermudanOption.setPricingEngine(new FDBermudanEngine(bsmProcess, timeSteps, timeSteps-1));
        americanOption.setPricingEngine(new FDAmericanEngine(bsmProcess, timeSteps, timeSteps-1, false));
        if (System.getProperty("EXPERIMENTAL") != null) {
            bNPV = bermudanOption.NPV();
        }
        System.out.printf(fmt, method, europeanOption.NPV(), bNPV, americanOption.NPV() );

        //
        //
        //


        // Monte Carlo Method
        timeSteps = 1;
        final int mcSeed = 42;
        final int nSamples = 32768; // 2^15
        final int maxSamples = 1048576; // 2^20

        method = "Monte Carlo (crude)";
        System.out.printf(fmttbd, method, Double.NaN, Double.NaN, Double.NaN );
        // ========================================================================================
        //        europeanOption.setPricingEngine(
        //            new MCEuropeanEngine(
        //                "PseudoRandom", timeSteps, 252,
        //                false, false, false,
        //                nSamples, 0.02, maxSamples, mcSeed));
        //        System.out.printf(fmt, method, europeanOption.NPV(), Double.NaN, Double.NaN);
        // ========================================================================================

        method = "Monte Carlo (Sobol)";
        System.out.printf(fmttbd, method, Double.NaN, Double.NaN, Double.NaN );
        //        europeanOption.setPricingEngine(
        //            new MCEuropeanEngine(
        //                "LowDiscrepancy", timeSteps, 252,
        //                false, false, false,
        //                nSamples, 0.02, maxSamples, mcSeed));
        //        System.out.printf(fmt, method, europeanOption.NPV(), Double.NaN, Double.NaN);
        //

        method = "Monte Carlo (Longstaff Schwartz)";
        System.out.printf(fmttbd, method, Double.NaN, Double.NaN, Double.NaN );
        //        MakeMCAmericanEngine<PseudoRandom>().withSteps(100)
        //            .withAntitheticVariate()
        //            .withCalibrationSamples(4096)
        //            .withTolerance(0.02)
        // .           withSeed(mcSeed);
        //        System.out.printf(fmt, method, europeanOption.NPV(), Double.NaN, Double.NaN);

        clock.stopClock();
        clock.log();

    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

        QL.validateExperimentalMode();

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        final Date today  = Date.todaysDate();
        final Date date10 = today.clone().addAssign(10);
        final Date date15 = today.clone().addAssign(15);
        final Date date18 = today.clone().addAssign(18);
        final Date date20 = today.clone().addAssign(20);
        final Date date25 = today.clone().addAssign(25);
        final Date date30 = today.clone().addAssign(30);
        final Date date40 = today.clone().addAssign(40);


        System.out.println("//============================StochasticProcess1D/LinearDiscretization=========================");

        //Creating stock quote handle
        final SimpleQuote stockQuote = new SimpleQuote(5.6);
        final RelinkableHandle<Quote>  handleToStockQuote = new RelinkableHandle<Quote>(stockQuote);

        //Creating black volatility term structure

        //Following is the time axis
        final Date[] dates = { date10.clone(), date15.clone(), date20.clone(), date25.clone(), date30.clone(), date40.clone() };

        //Following is the volatility axis
        final double[] volatilities = {0.1,0.2,0.3,0.4,0.5,0.6};

        //Following is the curve
        final BlackVarianceTermStructure varianceCurve = new BlackVarianceCurve(today, dates,volatilities, new Actual365Fixed(), false);
        ((BlackVarianceCurve)varianceCurve).setInterpolation();

        //Dividend termstructure
        final SimpleQuote dividendQuote = new SimpleQuote(0.3);
        final RelinkableHandle<Quote>  handleToInterestRateQuote = new RelinkableHandle<Quote>(dividendQuote);
        final YieldTermStructure dividendTermStructure = new FlatForward(2,new UnitedStates(Market.NYSE),handleToInterestRateQuote, new Actual365Fixed(), Compounding.Continuous,Frequency.Daily);

        //Risk free term structure
        final SimpleQuote riskFreeRateQuote = new SimpleQuote(0.3);
        final RelinkableHandle<Quote>  handleToRiskFreeRateQuote = new RelinkableHandle<Quote>(riskFreeRateQuote);
        final YieldTermStructure riskFreeTermStructure = new FlatForward(2,new UnitedStates(Market.NYSE),handleToRiskFreeRateQuote, new Actual365Fixed(), Compounding.Continuous,Frequency.Daily);

        //Creating the process
        final StochasticProcess1D process = new GeneralizedBlackScholesProcess(handleToStockQuote,new RelinkableHandle<YieldTermStructure>(dividendTermStructure),new RelinkableHandle<YieldTermStructure>(riskFreeTermStructure),new RelinkableHandle<BlackVolTermStructure>(varianceCurve),new EulerDiscretization());

        //Calculating the drift of the stochastic process after time = 18th day from today with value of the stock as specified from the quote
        //The drift = (riskFreeForwardRate - dividendForwardRate) - (Variance/2)
        System.out.println("The drift of the process after time = 18th day from today with value of the stock as specified from the quote = "+process.drift(process.time(date18.clone()), handleToStockQuote.currentLink().value()));

        //Calculating the diffusion of the process after time = 18th day from today with value of the stock as specified from the quote
        //The diffusion = volatiltiy of the stochastic process
        System.out.println("The diffusion of the process after time = 18th day from today with value of the stock as specified from the quote = "+process.diffusion(process.time(date18.clone()), handleToStockQuote.currentLink().value()));

        //Calulating the standard deviation of the process after time = 18th day from today with value of the stock as specified from the quote
        //The standard deviation = volatility*sqrt(dt)
        System.out.println("The stdDeviation of the process after time = 18th day from today with value of the stock as specified from the quote = "+process.stdDeviation(process.time(date18.clone()), handleToStockQuote.currentLink().value(), 0.01));

        //Calulating the variance of the process after time = 18th day from today with value of the stock as specified from the quote
        //The variance = volatility*volatility*dt
        System.out.println("The variance of the process after time = 18th day from today with value of the stock as specified from the quote = "+process.variance(process.time(date18.clone()), handleToStockQuote.currentLink().value(), 0.01));

        //Calulating the expected value of the stock quote after time = 18th day from today with the current value of the stock as specified from the quote
        //The expectedValue = intialValue*exp(drift*dt)-----can be obtained by integrating----->dx/x= drift*dt
        System.out.println("Expected value = "+process.expectation(process.time(date18.clone()), handleToStockQuote.currentLink().value(), 0.01));

        //Calulating the exact value of the stock quote after time = 18th day from today with the current value of the stock as specified from the quote
        //The exact value = intialValue*exp(drift*dt)*exp(volatility*sqrt(dt))-----can be obtained by integrating----->dx/x= drift*dt+volatility*sqrt(dt)
        System.out.println("Exact value = "+process.evolve(process.time(date18.clone()), 6.7, .001, new NormalDistribution().op(Math.random())));

        //Calculating the drift of the stochastic process after time = 18th day from today with value of the stock as specified from the quote
        //The drift = (riskFreeForwardRate - dividendForwardRate) - (Variance/2)
        final Array drift = process.drift(process.time(date18.clone()), new Array(1).fill(5.6));
        System.out.println("The drift of the process after time = 18th day from today with value of the stock as specified from the quote");

        //Calculating the diffusion of the process after time = 18th day from today with value of the stock as specified from the quote
        //The diffusion = volatiltiy of the stochastic process
        final Matrix diffusion = process.diffusion(process.time(date18.clone()), new Array(1).fill(5.6));
        System.out.println("The diffusion of the process after time = 18th day from today with value of the stock as specified from the quote");

        //Calulating the standard deviation of the process after time = 18th day from today with value of the stock as specified from the quote
        //The standard deviation = volatility*sqrt(dt)
        final Matrix stdDeviation = process.stdDeviation(process.time(date18.clone()), new Array(1).fill(5.6), 0.01);
        System.out.println("The stdDeviation of the process after time = 18th day from today with value of the stock as specified from the quote");

        //Calulating the expected value of the stock quote after time = 18th day from today with the current value of the stock as specified from the quote
        //The expectedValue = intialValue*exp(drift*dt)-----can be obtained by integrating----->dx/x= drift*dt
        final Array expectation = process.expectation(process.time(date18.clone()), new Array(1).fill(5.6), 0.01);
        System.out.println("Expected value = "+expectation.first());

        //Calulating the exact value of the stock quote after time = 18th day from today with the current value of the stock as specified from the quote
        //The exact value = intialValue*exp(drift*dt)*exp(volatility*sqrt(dt))-----can be obtained by integrating----->dx/x= drift*dt+volatility*sqrt(dt)
        final Array evolve = process.evolve(process.time(date18.clone()), new Array(1).fill(6.7), .001, new Array(1).fill(new NormalDistribution().op(Math.random()) ));
        System.out.println("Exact value = "+evolve.first());

        //Calculating covariance of the process
        final Matrix covariance = process.covariance(process.time(date18.clone())new Array(1).fill(5.6), 0.01);
        System.out.println("Covariance = "+covariance.get(0, 0));

        clock.stopClock();
        clock.log();
    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

    public void run() {

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();

        final Date today  = Date.todaysDate();
        final Date date10 = today.clone().addAssign(10);
        final Date date12 = today.clone().addAssign(12);
        final Date date15 = today.clone().addAssign(15);
        final Date date16 = today.clone().addAssign(16);
        final Date date17 = today.clone().addAssign(17);
        final Date date20 = today.clone().addAssign(20);
        final Date date22 = today.clone().addAssign(22);
        final Date date25 = today.clone().addAssign(25);
        final Date date26 = today.clone().addAssign(26);
        final Date date27 = today.clone().addAssign(27);
        final Date date30 = today.clone().addAssign(30);
        final Date date32 = today.clone().addAssign(32);
        final Date date35 = today.clone().addAssign(35);
        final Date date37 = today.clone().addAssign(37);
        final Date date40 = today.clone().addAssign(40);
        final Date date50 = today.clone().addAssign(50);


        System.out.println("//===============================BlackConstantVol termstructure==================================");

        //Let's explore BlackConstantVolatility by calculating blackVolatility,blackForwardVolatility,blackVariance and blackForwardVariance
        //Following example explains that when volatility is assumed to be constant BlackConstantVol termstructure can be used to represent
        //such a volatility termstructure.
        final SimpleQuote volatilityQuote = new SimpleQuote(0.3);
        final RelinkableHandle<Quote>  handleToVolatilityQuote = new RelinkableHandle<Quote>(volatilityQuote);
        BlackVolatilityTermStructure constantVolatility = new BlackConstantVol(2,new UnitedStates(Market.NYSE),handleToVolatilityQuote, new Actual365Fixed());

        //Calculating blackVolatility using maturity as 10 days after today and strike as 20
        Double volatility1 = constantVolatility.blackVol(date10.clone(), 20);
        System.out.println("BlackVolatility = "+volatility1);

        //Calculating blackVolatility using maturity as 20 days after today and strike as 30
        Double volatility2 = constantVolatility.blackVol(date20.clone(), 30);
        System.out.println("BlackVolatility = "+volatility2);

        //Calculating blackVolatility using maturity as 30 days after today and strike as 40
        Double volatility3 = constantVolatility.blackVol(date30.clone(), 40);
        System.out.println("BlackVolatility = "+volatility3);

        //The volatilities calculated above are same as it's constant volatility termstructure
        if(volatility1.equals(volatility2) && volatility2.equals(volatility3)){
            System.out.println("All the volatilities calculated above are same and = "+volatility1);
        }

        //Calculating blackForwardVolatility between 10 days after today and 15 days after today with strike as 20
        Double forwardVolatility1 = constantVolatility.blackForwardVol(date10.clone(), date15.clone(), 20, true);
        System.out.println("BlackForwardVolatility = "+forwardVolatility1);

        //Calculating blackForwardVolatility between 20 days after today and 25 days after today with strike as 40
        Double forwardVolatility2 = constantVolatility.blackForwardVol(date10.clone(), date15.clone(), 20, true);
        System.out.println("BlackForwardVolatility = "+forwardVolatility2);

        //Calculating blackForwardVolatility between 27 days after today and 35 days after today with strike as 60
        Double forwardVolatility3 = constantVolatility.blackForwardVol(date27.clone(), date35.clone(), 60, true);
        System.out.println("BlackForwardVolatility = "+forwardVolatility3);

        //The volatilities calculated above are same as it's constant volatility termstructure
        if(forwardVolatility1.equals(forwardVolatility2) && forwardVolatility2.equals(forwardVolatility3)){
            System.out.println("All the forward volatilities calculated above are same and = "+forwardVolatility1);
        }else{
            System.out.println("The forward volatilities may not be constant");
        }

        //Calculating blackVariance
        System.out.println("BlackVariance = "+constantVolatility.blackVariance(date10.clone(), 20));

        //Calculating blackForwardVariance
        System.out.println("BlackForwardVariance = "+constantVolatility.blackForwardVariance(date10.clone(), date15.clone(), 20, true));

        //As BlackConstantVol termstructure has been initialized using relinkable handle so lets change the observable SimpleQuote of this handle
        //and see the change getting reflected to all the calculations done above.
        volatilityQuote.setValue(0.04) ;
        constantVolatility = new BlackConstantVol(2,new UnitedStates(Market.NYSE),handleToVolatilityQuote, new Actual365Fixed());

        //Calculating blackVolatility using maturity as 10 days after today and strike as 20
        volatility1 = constantVolatility.blackVol(date10.clone(), 20);
        System.out.println("BlackVolatility = "+volatility1);

        //Calculating blackVolatility using maturity as 20 days after today and strike as 30
        volatility2 = constantVolatility.blackVol(date20.clone(), 30);
        System.out.println("BlackVolatility = "+volatility2);

        volatility3 = constantVolatility.blackVol(date30.clone(), 40);
        System.out.println("BlackVolatility = "+volatility3);

        //The volatilities calculated above are same as it's constant volatility termstructure
        if(volatility1.equals(volatility2) && volatility2.equals(volatility3)){
            System.out.println("All the volatilities calculated above are same and = "+volatility1);
        }

        //Calculating blackForwardVolatility between 10 days after today and 15 days after today with strike as 20
        forwardVolatility1 = constantVolatility.blackForwardVol(date10.clone(), date15.clone(), 20, true);
        System.out.println("BlackForwardVolatility = "+forwardVolatility1);

        //Calculating blackForwardVolatility between 20 days after today and 25 days after today with strike as 40
        forwardVolatility2 = constantVolatility.blackForwardVol(date10.clone(), date15.clone(), 20, true);
        System.out.println("BlackForwardVolatility = "+forwardVolatility2);

        //Calculating blackForwardVolatility between 27 days after today and 35 days after today with strike as 60
        forwardVolatility3 = constantVolatility.blackForwardVol(date27.clone(), date35.clone(), 60, true);
        System.out.println("BlackForwardVolatility = "+forwardVolatility3);

        //The volatilities calculated above are same as it's constant volatility termstructure
        if(forwardVolatility1.equals(forwardVolatility2) && forwardVolatility2.equals(forwardVolatility3)){
            System.out.println("All the volatilities calculated above are same and = "+forwardVolatility1);
        }else{
            System.out.println("The forward volatilities may not be constant");
        }

        //Calculating blackVariance
        System.out.println("BlackVariance = "+constantVolatility.blackVariance(date10.clone(), 20));

        //Calculating blackForwardVariance
        System.out.println("BlackForwardVariance = "+constantVolatility.blackForwardVariance(date10.clone(), date15.clone(), 20, true));

        System.out.println("//===============================BlackVarianceCurve================================");

        //Let's create black variance curve and calculate volatilities/variances by interpolating on
        //the created curve for a given strike.

        //-- Date today = DateFactory.getFactory().getTodaysDate();

        //Following is the time axis
        final Date[] dates = {date10.clone(), date15.clone(), date20.clone(), date25.clone(), date30.clone(), date40.clone() };

        //Following is the volatility axis
        final double[] volatilities = {0.1,0.2,0.3,0.4,0.5,0.6};

        //Following is the curve
        final BlackVarianceTermStructure varianceCurve = new BlackVarianceCurve(today,dates,volatilities, new Actual365Fixed(), false);
        ((BlackVarianceCurve)varianceCurve).setInterpolation();

        //Calculating blackVolatility using maturity as 12 days after today and strike as 20
        volatility1 = varianceCurve.blackVol(date12.clone(), 20);
        System.out.println("Interpolated BlackVolatility on BlackVarianceCurve = "+volatility1);

        //Calculating blackVolatility using maturity as 22 days after today and strike as 30
        volatility2 = varianceCurve.blackVol(date22.clone(), 30);
        System.out.println("Interpolated BlackVolatility on BlackVarianceCurve = "+volatility2);

        //Calculating blackVolatility using maturity as 32 days after today and strike as 40
        volatility3 = varianceCurve.blackVol(date32.clone(), 40);
        System.out.println("Interpolated BlackVolatility on BlackVarianceCurve = "+volatility3);


        //Calculating blackForwardVolatility between 12 days after today and 16 days after today with strike as 20
        forwardVolatility1 = varianceCurve.blackForwardVol(date12.clone(), date16.clone(), 20, true);
        System.out.println("Interpolated BlackForwardVolatility on BlackVarianceCurve = "+forwardVolatility1);

        //Calculating blackForwardVolatility between 22 days after today and 26 days after today with strike as 40
        forwardVolatility2 = varianceCurve.blackForwardVol(date22.clone(), date26.clone(), 40, true);
        System.out.println("Interpolated BlackForwardVolatility on BlackVarianceCurve = "+forwardVolatility2);

        //Calculating blackForwardVolatility between 27 days after today and 35 days after today with strike as 60
        forwardVolatility3 = varianceCurve.blackForwardVol(date27.clone(), date35.clone(), 60, true);
        System.out.println("Interpolated BlackForwardVolatility on BlackVarianceCurve = "+forwardVolatility3);


        //Calculating blackVariance using maturity as 12 days after today and strike as 20
        System.out.println("Interpolated BlackVariance on BlackVarianceCurve = "+varianceCurve.blackVariance(date12.clone(), 20));

        //Calculating blackForwardVariance between 12 days after today and 16 days after today with strike as 20
        System.out.println("Interpolated BlackForwardVariance on BlackVarianceCurve = "+varianceCurve.blackForwardVariance(date12.clone(), date16.clone(), 20, true));

        System.out.println("//===============================BlackVarianceSurface================================");

        //Let's create black variance surface and calculate volatilities/variances by interpolating on
        //the created curve for a given strike.

        //-- today = DateFactory.getFactory().getTodaysDate();

        //Following is the time axis
        final Date[] datesAxis = {date10.clone(), date15.clone(), date20.clone(), date25.clone(), date30.clone(), date40.clone() };

        final Array strikeAxis = new Array(new double[] {10,20,35,40,56,60});

        //Following is the volatility surface on which interpolations will be done
        final Matrix volatilityMatrix = new Matrix(new double[][] {
                {0.01,0.02,0.03,0.04,0.05,0.06},
                {0.02,0.03,0.04,0.05,0.06,0.07},
                {0.03,0.04,0.05,0.06,0.07,0.08},
                {0.3,0.5,0.6,0.7,0.8,0.9},
                {0.1,0.4,0.6,0.7,0.8,0.9},
                {0.2,0.5,0.6,0.7,0.8,0.9}
        });


        //Following is the variance surface where variance = f(strike,maturity) and f = function
        final BlackVarianceTermStructure varianceSurface = new BlackVarianceSurface(
                today, datesAxis,
                strikeAxis, volatilityMatrix, new Actual365Fixed(),
                Extrapolation.InterpolatorDefaultExtrapolation,
                Extrapolation.InterpolatorDefaultExtrapolation);
        ((BlackVarianceSurface)varianceSurface).setInterpolation(null);

        //As the surface has been set up to do interpolations so let's start calculating the volatilities for strikes
        //and maturities lying between the points as mentioned by strikesAxis and dateAxis.
        //Calculating blackVolatility using maturity as 12 days after today and strike as 18
        volatility1 = varianceSurface.blackVol(date12.clone(), 18);
        System.out.println("Interpolated BlackVolatility on BlackVarianceSurface = "+volatility1);

        //Calculating blackVolatility using maturity as 22 days after today and strike as 33
        volatility2 = varianceSurface.blackVol(date22.clone(), 33);
        System.out.println("Interpolated BlackVolatility on BlackVarianceSurface = "+volatility2);

        //Calculating blackVolatility using maturity as 32 days after today and strike as 45
        volatility3 = varianceSurface.blackVol(date32.clone(), 45);
        System.out.println("Interpolated BlackVolatility on BlackVarianceSurface = "+volatility3);


        //Calculating blackForwardVolatility between 12 days after today and 16 days after today with strike as 20
        forwardVolatility1 = varianceSurface.blackForwardVol(date12.clone(), date16.clone(), 20, true);
        System.out.println("Interpolated BlackForwardVolatility on BlackVarianceSurface = "+forwardVolatility1);

        //Calculating blackForwardVolatility between 22 days after today and 26 days after today with strike as 40
        forwardVolatility2 = varianceSurface.blackForwardVol(date22.clone(), date26.clone(), 40, true);
        System.out.println("Interpolated BlackForwardVolatility on BlackVarianceSurface = "+forwardVolatility2);

        //Calculating blackForwardVolatility between 27 days after today and 35 days after today with strike as 50
        forwardVolatility3 = varianceSurface.blackForwardVol(date27.clone(), date35.clone(), 50, true);
        System.out.println("Interpolated BlackForwardVolatility on BlackVarianceSurface = "+forwardVolatility3);


        //Calculating blackVariance using maturity as 12 days after today and strike as 20
        System.out.println("Interpolated BlackVariance on BlackVarianceSurface = "+varianceSurface.blackVariance(date12.clone(), 20));

        //Calculating blackForwardVariance between 12 days after today and 16 days after today with strike as 20
        System.out.println("Interpolated BlackForwardVariance on BlackVarianceSurface = "+varianceSurface.blackForwardVariance(date12.clone(), date16.clone(), 20, true));

        System.out.println("//================================ImpliedVolTermStructure=============================");

        //As mentioned in the java docs the implied volatility termstructure remains linked to
        //the underlying termstructure and changes to same are linked to ImpliedVolTermStructure
        //as well.

        //Lets use underlying as varianceCurve defined above by creating a relinkable handle as shown below
        final RelinkableHandle<BlackVolTermStructure> varianceCurveHandle = new RelinkableHandle<BlackVolTermStructure>(varianceCurve);
        final BlackVarianceTermStructure impliedVolTermStructure = new ImpliedVolTermStructure(varianceCurveHandle, today);

        //Calculating blackVolatility using maturity as 12 days after today and strike as 20
        volatility1 = varianceCurve.blackVol(date12.clone(), 20);
        final double impliedVolatility1 = impliedVolTermStructure.blackVol(date12.clone(), 20);

        if(volatility1 == impliedVolatility1){
            System.out.println("Interpolated BlackVolatility on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+volatility1);
        }

        //Calculating blackVolatility using maturity as 22 days after today and strike as 30
        volatility2 = varianceCurve.blackVol(date22.clone(), 30);
        final double impliedVolatility2 = impliedVolTermStructure.blackVol(date22.clone(), 30);
        if(volatility2 == impliedVolatility2){
            System.out.println("Interpolated BlackVolatility on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+volatility2);
        }

        //Calculating blackVolatility using maturity as 32 days after today and strike as 40
        volatility3 = varianceCurve.blackVol(date32.clone(), 40);
        final double impliedVolatility3 = impliedVolTermStructure.blackVol(date32.clone(), 40);
        if(volatility3 == impliedVolatility3){
            System.out.println("Interpolated BlackVolatility on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+volatility3);
        }


        //Calculating blackForwardVolatility between 12 days after today and 16 days after today with strike as 20
        forwardVolatility1 = varianceCurve.blackForwardVol(date12.clone(), date16.clone(), 20, true);
        final double impliedForwardVolatility1 = impliedVolTermStructure.blackForwardVol(date12.clone(), date16.clone(), 20, true);
        if(forwardVolatility1 == impliedForwardVolatility1){
            System.out.println("Interpolated BlackForwardVolatility on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+forwardVolatility1);
        }

        //Calculating blackForwardVolatility between 22 days after today and 26 days after today with strike as 40
        forwardVolatility2 = varianceCurve.blackForwardVol(date22.clone(), date26.clone(), 40, true);
        final double impliedForwardVolatility2 = impliedVolTermStructure.blackForwardVol(date22.clone(), date26.clone(), 40, true);
        if(forwardVolatility2 == impliedForwardVolatility2){
            System.out.println("Interpolated BlackForwardVolatility on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+forwardVolatility2);
        }

        //Calculating blackForwardVolatility between 27 days after today and 35 days after today with strike as 60
        forwardVolatility3 = varianceCurve.blackForwardVol(date27.clone(), date35.clone(), 60, true);
        final double impliedForwardVolatility3 = impliedVolTermStructure.blackForwardVol(date27.clone(), date35.clone(), 60, true);
        if(forwardVolatility3 == impliedForwardVolatility3){
            System.out.println("Interpolated BlackForwardVolatility on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+forwardVolatility3);
        }


        //Calculating blackVariance using maturity as 12 days after today and strike as 20
        final double variance = varianceCurve.blackVariance(date12.clone(), 20);
        final double impliedVariance = impliedVolTermStructure.blackVariance(date12.clone(), 20);
        if(variance == impliedVariance){
            System.out.println("Interpolated BlackVariance on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+varianceCurve.blackVariance(date12.clone(), 20));
        }

        //Calculating blackForwardVariance between 12 days after today and 16 days after today with strike as 20
        final double forwardVariance = varianceCurve.blackForwardVariance(date12.clone(), date16.clone(), 20, true);
        final double impliedForwardVariance = impliedVolTermStructure.blackForwardVariance(date12.clone(), date16.clone(), 20, true);
        if(forwardVariance == impliedForwardVariance){
            System.out.println("Interpolated BlackForwardVariance on BlackVarianceCurve is same for varianceCurve and ImpliedVolTermStructure derived on it and = "+varianceCurve.blackForwardVariance(date12.clone(), date16.clone(), 20, true));
        }

        System.out.println("//================================LocalConstantVol=======================================");

        //LocalConstantVolatility is essentially same as BlackConstantVol and is a local volatility version of BlackConstantVol

        //Let's set the quoteValue = 0.05 and use the constantVolatility a BlackConstantVol
        volatilityQuote.setValue(0.05);
        final LocalVolTermStructure localConstantVolatility = new LocalConstantVol(2,new UnitedStates(Market.NYSE),handleToVolatilityQuote, new Actual365Fixed());

        //Calculating blackVolatility using maturity as 10 days after today and strike as 20
        if(constantVolatility.blackVol(date10.clone(), 20) == localConstantVolatility.localVol(date10.clone(), 20,true)){
            System.out.println("BlackVolatility and LocalVolatility are same and are = "+localConstantVolatility.localVol(date10.clone(), 20,true));
        }

        //Calculating blackVolatility using maturity as 20 days after today and strike as 30
        if(constantVolatility.blackVol(date20.clone(), 30) == localConstantVolatility.localVol(date20.clone(), 30,true)){
            System.out.println("BlackVolatility and LocalVolatility are same and are = "+localConstantVolatility.localVol(date20.clone(), 30,true));
        }

        //Calculating blackVolatility using maturity as 30 days after today and strike as 40
        if(constantVolatility.blackVol(date30.clone(), 40) == localConstantVolatility.localVol(date30.clone(), 40,true)){
            System.out.println("BlackVolatility and LocalVolatility are same and are = "+localConstantVolatility.localVol(date30.clone(), 40,true));
        }

        System.out.println("//================================LocalVolCurve==========================================");

        //LocalVolatility curve wraps BlackVarianceCurve and uses it to calculate the interpolated local volatility
        final LocalVolTermStructure localVolatilityCurve = new LocalVolCurve(new RelinkableHandle<BlackVarianceCurve>((BlackVarianceCurve)varianceCurve));

        //Calculating blackVolatility using maturity as 12 days after today and strike as 20
        volatility1 = localVolatilityCurve.localVol(date12.clone(), 20,true);
        System.out.println("Interpolated BlackVolatility on LocalVolCurve = "+volatility1);

        //Calculating blackVolatility using maturity as 22 days after today and strike as 30
        volatility2 = localVolatilityCurve.localVol(date22.clone(), 30,true);
        System.out.println("Interpolated BlackVolatility on LocalVolCurve = "+volatility2);

        //Calculating blackVolatility using maturity as 32 days after today and strike as 40
        volatility3 = localVolatilityCurve.localVol(date32.clone(), 40,true);
        System.out.println("Interpolated BlackVolatility on LocalVolCurve = "+volatility3);


        //TODO
        // System.out.println("//================================LocalVolSurface========================================");

        clock.stopClock();
        clock.log();
    }
View Full Code Here

Examples of org.jquantlib.samples.util.StopClock

    @Override
    public void run() {

        QL.info("::::: " + this.getClass().getSimpleName() + " :::::");

        final StopClock clock = new StopClock();
        clock.startClock();
        QL.info("Started calculation at: " + clock.getElapsedTime());

        // actually never used.....
        final Option.Type type = Option.Type.Put;

        final double underlying = 36.0;
        final double spreadRate = 0.005;

        final double dividendYield = 0.02;
        final double riskFreeRate = 0.06;
        final double volatility = 0.20;

        final int settlementDays = 3;
        final int length = 5;
        final double redemption = 100.0;
        final double conversionRatio = redemption/underlying;

        final Calendar calendar = new Target();
        //adjust today to the next business day...
        final Date today = calendar.adjust(Date.todaysDate());
        QL.info("Today's date is adjusted by the default business day convention is: " + today.shortDate());
        // set the evaluation date to the adjusted today's date
        new Settings().setEvaluationDate(today);
        QL.info("Set the global evaluation date to the adjusted today's date: " + today.shortDate());

        //Set up settlement, exercise and issue dates
        final Date settlementDate = calendar.advance(today, settlementDays, TimeUnit.Days);
        QL.info("SettlementDate is: " + settlementDate.shortDate());
        QL.info("Check that we haven't messed up with references --> today's date is still: " + today.shortDate());
        final Date exerciseDate = calendar.advance(settlementDate, length, TimeUnit.Years);
        QL.info("Excercise date is: " + exerciseDate.shortDate());
        final Date issueDate = calendar.advance(exerciseDate, -length, TimeUnit.Years);
        QL.info("Issue date is: " + issueDate.shortDate());

        //Fix business day convention and compounding?? frequency
        final BusinessDayConvention convention = BusinessDayConvention.ModifiedFollowing;
        final Frequency frequency = Frequency.Annual;

        final Schedule schedule = new Schedule(
                issueDate, exerciseDate,
                new Period(frequency), calendar,
                convention, convention,
                DateGeneration.Rule.Backward, false);

        final DividendSchedule dividends = new DividendSchedule();
        final CallabilitySchedule callability = new CallabilitySchedule();

        final double[] coupons = new double[] { 1.0, 0.05 };

        final DayCounter bondDayCount = new Thirty360();

        // Call dates, years 2, 4
        final int[] callLength = { 2, 4 };
        // Put dates year 3
        final int[] putLength = { 3 };

        final double[] callPrices = {101.5, 100.85};
        final double[] putPrices = { 105.0 };

        for(int i=0; i<callLength.length; i++){
            callability.add(
                    new SoftCallability(
                        new Callability.Price(callPrices[i], Callability.Price.Type.Clean),
                        schedule.date(callLength[i]),
                        1.20));
        }

        for (int j=0; j<putLength.length; j++) {
            callability.add(
                    new Callability(
                            new Callability.Price(putPrices[j],Callability.Price.Type.Clean),
                            Callability.Type.Put,
                            schedule.date(putLength[j])));
        }

        // Assume dividends are paid every 6 months.
        for (final Date d = today.add(new Period(6, TimeUnit.Months)); d.lt(exerciseDate); d.addAssign(new Period(6, TimeUnit.Months))) {
            dividends.add(new FixedDividend(1.0, d));
        }

        final DayCounter dayCounter = new Actual365Fixed();
        /*@Time*/ final double maturity = dayCounter.yearFraction(settlementDate,exerciseDate);

        System.out.println("option type = "+type);
        System.out.println("Time to maturity = "+maturity);
        System.out.println("Underlying price = "+underlying);
        System.out.println("Risk-free interest rate = "+riskFreeRate);
        System.out.println("Dividend yield = "+dividendYield);
        System.out.println("Volatility = "+volatility);
        System.out.println("");
        System.out.println("");


        // define line formatting
        //              "         1         2         3         4         5         6         7         8         9"
        //              "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"
        //              "                         Tree type      European      American";
        //              "================================== ============= ============="
        //              "1234567890123456789012345678901234 123.567890123 123.567890123";
        final String fmt    = "%34s %13.9f %13.9f\n";
        final String fmttbd = "%34s %13.9f %13.9f (TO BE DONE)\n";


        // write column headings
        //                 "         1         2         3         4         5         6         7         8"
        //                 "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
        System.out.println("Tsiveriotis-Fernandes method");
        System.out.println("                         Tree type      European      American");
        System.out.println("================================== ============= =============");


        final Exercise europeanExercise = new EuropeanExercise(exerciseDate);
        final Exercise americanExercise = new AmericanExercise(settlementDate,exerciseDate);

        final Handle<Quote> underlyingH = new Handle<Quote>(new SimpleQuote(underlying));
        final Handle<YieldTermStructure> flatTermStructure = new Handle<YieldTermStructure>(
                new FlatForward(settlementDate, riskFreeRate, dayCounter));
        final Handle<YieldTermStructure> flatDividendTS = new Handle<YieldTermStructure>(
                new FlatForward(settlementDate, dividendYield, dayCounter));
        final Handle<BlackVolTermStructure> flatVolTS = new Handle<BlackVolTermStructure>(
                new BlackConstantVol(settlementDate, calendar, volatility, dayCounter));

        final BlackScholesMertonProcess stochasticProcess = new BlackScholesMertonProcess(
                underlyingH, flatDividendTS, flatTermStructure, flatVolTS);

        final int timeSteps = 801;

        final Handle<Quote> creditSpread = new Handle<Quote>(new SimpleQuote(spreadRate));

        //XXX rate and discountCurve not being used in original QuantLib/C++ sources
        // final Quote rate = new SimpleQuote(riskFreeRate);
        //
        // final Handle<YieldTermStructure> discountCurve = new Handle<YieldTermStructure>(
        //         new FlatForward(today, new Handle<Quote>(rate), dayCounter));

        final ConvertibleFixedCouponBond europeanBond = new ConvertibleFixedCouponBond(
                europeanExercise, conversionRatio, dividends, callability,
                creditSpread, issueDate, settlementDays,
                coupons, bondDayCount, schedule, redemption);

        final ConvertibleFixedCouponBond americanBond = new ConvertibleFixedCouponBond(
                americanExercise, conversionRatio, dividends, callability,
                creditSpread, issueDate, settlementDays,
                coupons, bondDayCount, schedule, redemption);

        String method;
        PricingEngine engine;

        method = "Jarrow-Rudd";
        engine = new BinomialConvertibleEngine<JarrowRudd>(JarrowRudd.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );

        method = "Cox-Ross-Rubinstein";
        engine = new BinomialConvertibleEngine<CoxRossRubinstein>(CoxRossRubinstein.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );

        method = "Additive equiprobabilities";
        engine = new BinomialConvertibleEngine<AdditiveEQPBinomialTree>(AdditiveEQPBinomialTree.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );

        method = "Trigeorgis";
        engine = new BinomialConvertibleEngine<Trigeorgis>(Trigeorgis.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );

        method = "Tian";
        engine = new BinomialConvertibleEngine<Tian>(Tian.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );

        method = "Leisen-Reimer";
        engine = new BinomialConvertibleEngine<LeisenReimer>(LeisenReimer.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );

        method = "Joshi";
        engine = new BinomialConvertibleEngine<Joshi4>(Joshi4.class, stochasticProcess, timeSteps);
        europeanBond.setPricingEngine(engine);
        americanBond.setPricingEngine(engine);
        System.out.printf(fmt, method, europeanBond.NPV(), americanBond.NPV() );


        clock.stopClock();
        clock.log();
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.