Example #1
0
        public FixedRateBond(int settlementDays, double faceAmount, Schedule schedule,
            List<double> coupons, DayCounter accrualDayCounter,
            BusinessDayConvention paymentConvention, double redemption, Date issueDate)
            : this(settlementDays, faceAmount, schedule, coupons, accrualDayCounter,
				   paymentConvention, redemption, issueDate, new Calendar())
        {
        }
Example #2
0
        public SwapRateHelper(double rate, Period tenor, Calendar calendar,
            Frequency fixedFrequency, BusinessDayConvention fixedConvention, DayCounter fixedDayCount,
            IborIndex iborIndex)
            : this(rate, tenor, calendar, fixedFrequency, fixedConvention, fixedDayCount, iborIndex,
		                      	     new Handle<Quote>(), new Period(0, TimeUnit.Days))
        {
        }
Example #3
0
        public FloatingRateBond(int settlementDays, double faceAmount, Schedule schedule, IborIndex index, DayCounter paymentDayCounter,
                                BusinessDayConvention paymentConvention, int fixingDays, List<double> gearings, List<double> spreads,
                                List<double> caps, List<double> floors, bool inArrears, double redemption, Date issueDate)
            : base(settlementDays, schedule.calendar(), issueDate) {
            maturityDate_ = schedule.endDate();
            cashflows_ = new IborLeg(schedule, index)
                            .withPaymentDayCounter(paymentDayCounter)
                            .withFixingDays(fixingDays)
                            .withGearings(gearings)
                            .withSpreads(spreads)
                            .withCaps(caps)
                            .withFloors(floors)
                            .inArrears(inArrears)
                            .withNotionals(faceAmount)
                            .withPaymentAdjustment(paymentConvention);

            addRedemptionsToCashflows(new List<double>() { redemption });

            if (cashflows().Count == 0)
                throw new ApplicationException("bond with no cashflows!");
            if (redemptions_.Count != 1)
                throw new ApplicationException("multiple redemptions created");

            index.registerWith(update);
        }
      public AmortizingFixedRateBond(
                          int settlementDays,
                          List<double> notionals,
                          Schedule schedule,
                          List<double> coupons,
                          DayCounter accrualDayCounter,
                          BusinessDayConvention paymentConvention = BusinessDayConvention.Following,
                          Date issueDate = null)
         :base(settlementDays, schedule.calendar(), issueDate)
      {
         frequency_ = schedule.tenor().frequency();
         dayCounter_ = accrualDayCounter;
         schedule_ = schedule;

         maturityDate_ = schedule.endDate();

         cashflows_ = new FixedRateLeg(schedule)
             .withCouponRates(coupons, accrualDayCounter)
             .withNotionals(notionals)
             .withPaymentAdjustment(paymentConvention).value();
             

         addRedemptionsToCashflows();

         if ( cashflows().empty())
            throw new ApplicationException("bond with no cashflows!");
      }
Example #5
0
 public ZeroCouponBond(int settlementDays, Calendar calendar, double faceAmount, Date maturityDate, BusinessDayConvention paymentConvention, double redemption, Date issueDate)
     : base(settlementDays, calendar, issueDate)
 {
     maturityDate_ = maturityDate;
     Date redemptionDate = calendar_.adjust(maturityDate, paymentConvention);
     setSingleRedemption(faceAmount, redemption, redemptionDate);
 }
      public AmortizingFixedRateBond(
                          int settlementDays,
                          Calendar calendar,
                          double faceAmount,
                          Date startDate,
                          Period bondTenor,
                          Frequency sinkingFrequency,
                          double coupon,
                          DayCounter accrualDayCounter,
                          BusinessDayConvention paymentConvention = BusinessDayConvention.Following,
                          Date issueDate = null)
         :base(settlementDays, calendar, issueDate)
      {
         frequency_ = sinkingFrequency;
         dayCounter_ = accrualDayCounter;

         Utils.QL_REQUIRE( bondTenor.length() > 0,() =>
                  "bond tenor must be positive. "
                  + bondTenor + " is not allowed." );

         maturityDate_ = startDate + bondTenor;
         maturityDate_ = startDate + bondTenor;
         schedule_ = sinkingSchedule(startDate, bondTenor, sinkingFrequency, calendar);
         cashflows_ = new FixedRateLeg(schedule_)
                        .withCouponRates(coupon, accrualDayCounter)
                        .withNotionals(sinkingNotionals(bondTenor, sinkingFrequency, coupon, faceAmount))        
                        .withPaymentAdjustment(paymentConvention).value();

         addRedemptionsToCashflows();

      }
Example #7
0
        public SwaptionVolatilityDiscrete(List<Period> optionTenors,
                                   List<Period> swapTenors,
                                   int settlementDays,
                                   Calendar cal,
                                   BusinessDayConvention bdc,
                                   DayCounter dc)
            : base(settlementDays, cal, bdc, dc)
        {
            nOptionTenors_ = optionTenors.Count;
            optionTenors_ = optionTenors;
            optionDates_ = new InitializedList<Date>(nOptionTenors_);
            optionTimes_ = new InitializedList<double>(nOptionTenors_);
            optionDatesAsReal_ = new InitializedList<double>(nOptionTenors_);
            nSwapTenors_ = swapTenors.Count;
            swapTenors_ = swapTenors;
            swapLengths_ = new InitializedList<double>(nSwapTenors_);

            checkOptionTenors();
            initializeOptionDatesAndTimes();

            checkSwapTenors();
            initializeSwapLengths();

            optionInterpolator_ = new LinearInterpolation(optionTimes_,
                                            optionTimes_.Count,
                                            optionDatesAsReal_);
            optionInterpolator_.update();
            optionInterpolator_.enableExtrapolation();
            evaluationDate_ = Settings.evaluationDate();
            Settings.registerWith(update);
        }
Example #8
0
        public SwaptionVolatilityDiscrete(List<Period> optionTenors,
                                   List<Period> swapTenors,
                                   Date referenceDate,
                                   Calendar cal,
                                   BusinessDayConvention bdc,
                                   DayCounter dc)
            : base(referenceDate, cal, bdc, dc)
        {
            nOptionTenors_ = optionTenors.Count;
            optionTenors_ = optionTenors;
            optionDates_ = new InitializedList<Date>(nOptionTenors_);
            optionTimes_ = new InitializedList<double>(nOptionTenors_);
            optionDatesAsReal_ = new InitializedList<double>(nOptionTenors_);
            nSwapTenors_ = swapTenors.Count;
            swapTenors_ = swapTenors;
            swapLengths_ = new InitializedList<double>(nSwapTenors_);

            checkOptionTenors();
            initializeOptionDatesAndTimes();

            checkSwapTenors();
            initializeSwapLengths();

            optionInterpolator_ = new LinearInterpolation(optionTimes_,
                                            optionTimes_.Count,
                                            optionDatesAsReal_);

            optionInterpolator_.update();
            optionInterpolator_.enableExtrapolation();
        }
Example #9
0
        public FloatingRateBond(int settlementDays, double faceAmount, Schedule schedule, IborIndex index,
            DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, int fixingDays,
            List<double> gearings, List<double> spreads)
            : this(settlementDays, faceAmount, schedule, index, paymentDayCounter, BusinessDayConvention.Following,
				   fixingDays, gearings, spreads, new List<double>(), new List<double>(), false, 100, null)
        {
        }
Example #10
0
      //! fixed-rate bond
      /*! \ingroup instruments

          \test calculations are tested by checking results against
                cached values.
      */
 

      //! simple annual compounding coupon rates      
      public FixedRateBond(int settlementDays, double faceAmount, Schedule schedule,List<double> coupons, 
                           DayCounter accrualDayCounter, BusinessDayConvention paymentConvention = BusinessDayConvention.Following,
                           double redemption = 100, Date issueDate = null,Calendar paymentCalendar = null,
			                  Period exCouponPeriod = null,
                           Calendar exCouponCalendar = null,
									BusinessDayConvention exCouponConvention = BusinessDayConvention.Unadjusted,
                           bool exCouponEndOfMonth = false)
         : base(settlementDays, paymentCalendar == null ? schedule.calendar() : paymentCalendar, 
                issueDate) 
      {
         frequency_ = schedule.tenor().frequency();
         dayCounter_ = accrualDayCounter;
         maturityDate_ = schedule.endDate();

         cashflows_ = new FixedRateLeg(schedule)
            .withCouponRates(coupons, accrualDayCounter)
				.withExCouponPeriod(exCouponPeriod,
										  exCouponCalendar,
										  exCouponConvention,
										  exCouponEndOfMonth)
            .withPaymentCalendar(calendar_)
            .withNotionals(faceAmount)
            .withPaymentAdjustment(paymentConvention); 

         addRedemptionsToCashflows(new List<double>() { redemption });

         if (cashflows().Count == 0)
            throw new ApplicationException("bond with no cashflows!");

         if (redemptions_.Count != 1)
            throw new ApplicationException("multiple redemptions created");
      }
Example #11
0
 public DepositRateHelper(double rate, Period tenor, int fixingDays, Calendar calendar,
     BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter)
     : base(rate)
 {
     iborIndex_ = new IborIndex("no-fix", tenor, fixingDays, new Currency(), calendar, convention,
                                endOfMonth, dayCounter, termStructureHandle_);
     initializeDates();
 }
Example #12
0
 public IborIndex(string familyName, Period tenor, int settlementDays, Currency currency,
          Calendar fixingCalendar, BusinessDayConvention convention, bool endOfMonth,
          DayCounter dayCounter)
     : this(familyName, tenor, settlementDays, currency,
            fixingCalendar, convention, endOfMonth,
            dayCounter, new Handle<YieldTermStructure>())
 {
 }
        //! fixed reference date, floating market data
        public ConstantOptionletVolatility(Date referenceDate, Calendar cal, BusinessDayConvention bdc,
                                           Handle<Quote> vol, DayCounter dc)
            : base(referenceDate, cal, bdc, dc)
        {
            volatility_ = vol;

            volatility_.registerWith(update);
        }
        //! floating reference date, floating market data
        public ConstantOptionletVolatility(int settlementDays, Calendar cal, BusinessDayConvention bdc,
                                           Handle<Quote> vol, DayCounter dc)
            : base(settlementDays, cal, bdc, dc)
        {
            volatility_ = vol;

            volatility_.registerWith(update);
        }
Example #15
0
 public CPILegBase withExCouponPeriod(Period period, Calendar cal, BusinessDayConvention convention, bool endOfMonth = false)
 {
     exCouponPeriod_ = period;
       exCouponCalendar_ = cal;
       exCouponAdjustment_ = convention;
       exCouponEndOfMonth_ = endOfMonth;
       return this;
 }
 // fixed reference date, fixed market data
 public ConstantCapFloorTermVolatility(Date referenceDate,
                                     Calendar cal,
                                     BusinessDayConvention bdc,
                                     double volatility,
                                     DayCounter dc)
     : base(referenceDate, cal, bdc, dc)
 {
     volatility_ = new Handle<Quote>(new SimpleQuote(volatility));
 }
        //public FixedRateBondHelper(Quote cleanPrice, int settlementDays, double faceAmount, Schedule schedule,
        //                   List<double> coupons, DayCounter dayCounter,
        //                   BusinessDayConvention paymentConv = Following,
        //                   double redemption = 100.0,
        //                   Date issueDate = null);
        public FixedRateBondHelper(Handle<Quote> cleanPrice, int settlementDays, double faceAmount, Schedule schedule,
                                   List<double> coupons, DayCounter dayCounter, BusinessDayConvention paymentConvention,
                                   double redemption, Date issueDate)
            : base(cleanPrice, new FixedRateBond(settlementDays, faceAmount, schedule,
                                                 coupons, dayCounter, paymentConvention,
                                                 redemption, issueDate)) {

            fixedRateBond_ = bond_ as FixedRateBond;
        }
 //! floating reference date, fixed market data
 public ConstantCapFloorTermVolatility(int settlementDays,
                                     Calendar cal,
                                     BusinessDayConvention bdc,
                                     double volatility,
                                     DayCounter dc)
     : base(settlementDays, cal, bdc, dc)
 {
     volatility_ = new Handle<Quote>(new SimpleQuote(volatility));
 }
Example #19
0
 //! fixed reference date, fixed market data
 public ConstantSwaptionVolatility( Date referenceDate,
                            Calendar cal,
                            BusinessDayConvention bdc,
                            double vol,
                            DayCounter dc)
     : base(referenceDate, cal, bdc, dc)
 {
     volatility_ = new Handle<Quote>(new SimpleQuote(vol));
     maxSwapTenor_ = new Period(100, TimeUnit.Years);
 }
Example #20
0
 public MakeSwaption(SwapIndex swapIndex,
     Period optionTenor,
     double strike)
 {
     swapIndex_ = swapIndex;
     delivery_ = Settlement.Type.Physical;
     optionTenor_ = optionTenor;
     optionConvention_ = BusinessDayConvention.ModifiedFollowing;
     strike_ = strike;
 }
Example #21
0
        //! \name Constructors
        /*! If strike is given in the constructor, can calculate the
            NPV of the contract via NPV().

            If strike/forward price is desired, it can be obtained via
            forwardPrice(). In this case, the strike variable in the
            constructor is irrelevant and will be ignored.
        */
        //@{
		//Handle<YieldTermStructure> discountCurve = Handle<YieldTermStructure>(),
		//Handle<YieldTermStructure> incomeDiscountCurve = Handle<YieldTermStructure>());
		public FixedRateBondForward(Date valueDate, Date maturityDate, Position.Type type, double strike, int settlementDays,
									DayCounter dayCounter, Calendar calendar, BusinessDayConvention businessDayConvention,
									FixedRateBond fixedCouponBond,
									Handle<YieldTermStructure> discountCurve,
									Handle<YieldTermStructure> incomeDiscountCurve) 
			: base(dayCounter, calendar, businessDayConvention, settlementDays, new ForwardTypePayoff(type, strike),
				   valueDate, maturityDate, discountCurve) {
			fixedCouponBond_ = fixedCouponBond;
	        incomeDiscountCurve_ = incomeDiscountCurve;
			incomeDiscountCurve_.registerWith(update);
		}
Example #22
0
 //! fixed reference date, floating market data
 public ConstantSwaptionVolatility(Date referenceDate,
                            Calendar cal,
                            BusinessDayConvention bdc,
                            Handle<Quote> vol,
                            DayCounter dc)
     : base(referenceDate, cal, bdc, dc)
 {
     volatility_ = vol;
     maxSwapTenor_ = new Period(100, TimeUnit.Years);
     volatility_.registerWith(update);
 }
Example #23
0
        public FRARateHelper(double rate, int monthsToStart, int monthsToEnd, int fixingDays, Calendar calendar,
            BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter)
            : base(rate)
        {
            periodToStart_ = new Period(monthsToStart, TimeUnit.Months);

            if (!(monthsToEnd > monthsToStart)) throw new ArgumentException("monthsToEnd must be grater than monthsToStart");
            iborIndex_ = new IborIndex("no-fix", new Period(monthsToEnd - monthsToStart, TimeUnit.Months), fixingDays,
                                       new Currency(), calendar, convention, endOfMonth, dayCounter, termStructureHandle_);
            initializeDates();
        }
Example #24
0
        public IborIndex(string familyName, Period tenor, int settlementDays, Currency currency,
                     Calendar fixingCalendar, BusinessDayConvention convention, bool endOfMonth,
                     DayCounter dayCounter, Handle<YieldTermStructure> h) :
            base(familyName, tenor, settlementDays, currency, fixingCalendar, dayCounter) {
            convention_ = convention;
            termStructure_ = h;
            endOfMonth_ = endOfMonth;

            // observer interface
            if (!termStructure_.empty())
                termStructure_.registerWith(update);
        }
Example #25
0
        // overloaded constructors
        public FuturesRateHelper(double price, Date immDate, int nMonths, Calendar calendar, BusinessDayConvention convention,
            bool endOfMonth, DayCounter dayCounter, double convAdj)
            : base(price)
        {
            convAdj_ = new Handle<Quote>(new SimpleQuote(convAdj));

            if (!IMM.isIMMdate(immDate, false)) throw new ArgumentException(immDate + "is not a valid IMM date");
            earliestDate_ = immDate;

            latestDate_ = calendar.advance(immDate, new Period(nMonths, TimeUnit.Months), convention, endOfMonth);
            yearFraction_ = dayCounter.yearFraction(earliestDate_, latestDate_);
        }
      public BasisSwap(Type type, double nominal,
                         Schedule float1Schedule, IborIndex iborIndex1, double spread1, DayCounter float1DayCount,
                         Schedule float2Schedule, IborIndex iborIndex2, double spread2, DayCounter float2DayCount,
                         BusinessDayConvention? paymentConvention) :
         base(2)
      {
         type_ = type;
         nominal_ = nominal;
         floating1Schedule_ = float1Schedule;
         spread1_ = spread1;
         floating1DayCount_ = float1DayCount;
         iborIndex1_ = iborIndex1;
         floating2Schedule_ = float2Schedule;
         spread2_ = spread2;
         floating2DayCount_ = float2DayCount;
         iborIndex2_ = iborIndex2;

         if (paymentConvention.HasValue)
            paymentConvention_ = paymentConvention.Value;
         else
            paymentConvention_ = floating1Schedule_.businessDayConvention();

         List<CashFlow> floating1Leg = new IborLeg(float1Schedule, iborIndex1)
                                     .withPaymentDayCounter(float1DayCount)
                                     .withSpreads(spread1)
                                     .withNotionals(nominal)
                                     .withPaymentAdjustment(paymentConvention_);

         List<CashFlow> floating2Leg = new IborLeg(float2Schedule, iborIndex2)
                                     .withPaymentDayCounter(float2DayCount)
                                     .withSpreads(spread2)
                                     .withNotionals(nominal)
                                     .withPaymentAdjustment(paymentConvention_);

         foreach (var cf in floating1Leg)
            cf.registerWith(update);
         foreach (var cf in floating2Leg)
            cf.registerWith(update);


         legs_[0] = floating1Leg;
         legs_[1] = floating2Leg;
         if (type_ == Type.Payer)
         {
            payer_[0] = -1;
            payer_[1] = +1;
         }
         else
         {
            payer_[0] = +1;
            payer_[1] = -1;
         }
      }
Example #27
0
        //public FloatingRateBond(int settlementDays, double faceAmount, Date startDate, Date maturityDate, Frequency couponFrequency,
        //                        Calendar calendar, IborIndex index, DayCounter accrualDayCounter,
        //                        BusinessDayConvention accrualConvention = Following,
        //                        BusinessDayConvention paymentConvention = Following,
        //                        int fixingDays = Null<Natural>(),
        //                        List<double> gearings = std::vector<Real>(1, 1.0),
        //                        List<double> spreads = std::vector<Spread>(1, 0.0),
        //                        List<double> caps = std::vector<Rate>(),
        //                        List<double> floors = std::vector<Rate>(),
        //                        bool inArrears = false,
        //                        double redemption = 100.0,
        //                        Date issueDate = Date(),
        //                        Date stubDate = Date(),
        //                        DateGeneration.Rule rule = DateGeneration::Backward,
        //                        bool endOfMonth = false)
        public FloatingRateBond(int settlementDays, double faceAmount, Date startDate, Date maturityDate, Frequency couponFrequency,
                                Calendar calendar, IborIndex index, DayCounter accrualDayCounter,
                                BusinessDayConvention accrualConvention, BusinessDayConvention paymentConvention,
                                int fixingDays, List<double> gearings, List<double> spreads, List<double> caps,
                                List<double> floors, bool inArrears, double redemption, Date issueDate,
                                Date stubDate, DateGeneration.Rule rule, bool endOfMonth)
            : base(settlementDays, calendar, issueDate) {

            maturityDate_ = maturityDate;

            Date firstDate, nextToLastDate;
            switch (rule) {
                case DateGeneration.Rule.Backward:
                    firstDate = null;
                    nextToLastDate = stubDate;
                    break;
                case DateGeneration.Rule.Forward:
                    firstDate = stubDate;
                    nextToLastDate = null;
                    break;
              case DateGeneration.Rule.Zero:
              case DateGeneration.Rule.ThirdWednesday:
              case DateGeneration.Rule.Twentieth:
              case DateGeneration.Rule.TwentiethIMM:
                    throw new ApplicationException("stub date (" + stubDate + ") not allowed with " + rule + " DateGeneration::Rule");
                default:
                    throw new ApplicationException("unknown DateGeneration::Rule (" + rule + ")");
            }

            Schedule schedule = new Schedule(startDate, maturityDate_, new Period(couponFrequency), calendar_,
                                             accrualConvention, accrualConvention, rule, endOfMonth, firstDate, nextToLastDate);

            cashflows_ = new IborLeg(schedule, index)
                            .withPaymentDayCounter(accrualDayCounter)
                            .withFixingDays(fixingDays)
                            .withGearings(gearings)
                            .withSpreads(spreads)
                            .withCaps(caps)
                            .withFloors(floors)
                            .inArrears(inArrears)
                            .withNotionals(faceAmount)
                            .withPaymentAdjustment(paymentConvention);

            addRedemptionsToCashflows(new List<double>() { redemption });

            if (cashflows().Count == 0)
                throw new ApplicationException("bond with no cashflows!");
            if (redemptions_.Count != 1)
                throw new ApplicationException("multiple redemptions created");

            index.registerWith(update);
        }
Example #28
0
        public CPIBond(int settlementDays,
                double faceAmount,
                bool growthOnly,
                double baseCPI,
                Period observationLag,
                ZeroInflationIndex cpiIndex,
                InterpolationType observationInterpolation,
                Schedule schedule,
                List<double> fixedRate,
                DayCounter accrualDayCounter,
                BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing,
                Date issueDate = null,
                Calendar paymentCalendar = null,
                Period exCouponPeriod = null,
                Calendar exCouponCalendar = null,
					 BusinessDayConvention exCouponConvention = BusinessDayConvention.Unadjusted,
                bool exCouponEndOfMonth = false)                
            :base(settlementDays, paymentCalendar == null ? schedule.calendar() : paymentCalendar, issueDate)
        {
            frequency_ = schedule.tenor().frequency();
            dayCounter_ = accrualDayCounter;
            growthOnly_ = growthOnly;
            baseCPI_=baseCPI;
            observationLag_ = observationLag;
            cpiIndex_= cpiIndex;
            observationInterpolation_ = observationInterpolation;

            maturityDate_ = schedule.endDate();

            // a CPIleg know about zero legs and inclusion of base inflation notional
            cashflows_ = new CPILeg(schedule, cpiIndex_,
                                    baseCPI_, observationLag_)
             .withSubtractInflationNominal(growthOnly_)
             .withObservationInterpolation(observationInterpolation_)
             .withPaymentDayCounter(accrualDayCounter)
             .withFixedRates(fixedRate)
             .withPaymentCalendar(calendar_)
             .withExCouponPeriod(exCouponPeriod,
                                exCouponCalendar,
                                exCouponConvention,
                                exCouponEndOfMonth)
             .withNotionals(faceAmount)
             .withPaymentAdjustment(paymentConvention);
            

            calculateNotionalsFromCashflows();

            cpiIndex_.registerWith(update);

            foreach ( CashFlow i in cashflows_) 
                i.registerWith(update);
        }
Example #29
0
        public SwapIndex(string familyName, Period tenor, int settlementDays, Currency currency, Calendar calendar, Period fixedLegTenor, BusinessDayConvention fixedLegConvention, DayCounter fixedLegDayCounter, IborIndex iborIndex, Handle<YieldTermStructure> discountingTermStructure)
            : base(familyName, tenor, settlementDays, currency, calendar, fixedLegDayCounter)
        {
            tenor_ = tenor;
            iborIndex_ = iborIndex;
            fixedLegTenor_ = fixedLegTenor;
            fixedLegConvention_ = fixedLegConvention;
            exogenousDiscount_ = true;

            discount_ = discountingTermStructure ?? new Handle<YieldTermStructure>();

            iborIndex_.registerWith(update);
        }
 //! \name Constructor
 //! calculate the reference date based on the global evaluation date
 public YoYOptionletVolatilitySurface(int settlementDays,
                                    Calendar cal,
                                    BusinessDayConvention bdc,
                                    DayCounter dc,
                                    Period observationLag,
                                    Frequency frequency,
                                    bool indexIsInterpolated)
     : base(settlementDays, cal, bdc, dc)
 {
     baseLevel_ = null;
      observationLag_ = observationLag;
      frequency_ = frequency;
      indexIsInterpolated_ = indexIsInterpolated;
 }
Example #31
0
        //! default constructor

        /*! \warning term structures initialized by means of this
         *           constructor must manage their own reference date
         *           by overriding the referenceDate() method.
         */

        protected LocalVolTermStructure(BusinessDayConvention bdc = BusinessDayConvention.Following, DayCounter dc = null)
            : base(bdc, dc)
        {
        }
            // setup
            public CommonVars()
            {
                // option variables
                nominals = new List <double>()
                {
                    1000000
                };
                frequency = Frequency.Annual;
                // usual setup
                volatility = 0.01;
                length     = 7;
                calendar   = new UnitedKingdom();
                convention = BusinessDayConvention.ModifiedFollowing;
                Date today = new Date(13, Month.August, 2007);

                evaluationDate = calendar.adjust(today);
                Settings.setEvaluationDate(evaluationDate);
                settlementDays = 0;
                fixingDays     = 0;
                settlement     = calendar.advance(today, settlementDays, TimeUnit.Days);
                startDate      = settlement;
                dc             = new Thirty360();

                // yoy index
                //      fixing data
                Date     from        = new Date(1, Month.January, 2005);
                Date     to          = new Date(13, Month.August, 2007);
                Schedule rpiSchedule = new MakeSchedule().from(from).to(to)
                                       .withTenor(new Period(1, TimeUnit.Months))
                                       .withCalendar(new UnitedKingdom())
                                       .withConvention(BusinessDayConvention.ModifiedFollowing).value();

                double[] fixData = { 189.9,  189.9, 189.6, 190.5, 191.6, 192.0,
                                     192.2,  192.2, 192.6, 193.1, 193.3, 193.6,
                                     194.1,  193.4, 194.2, 195.0, 196.5, 197.7,
                                     198.5,  198.5, 199.2, 200.1, 200.4, 201.1,
                                     202.7,  201.6, 203.1, 204.4, 205.4, 206.2,
                                     207.3, -999.0, -999 };
                // link from yoy index to yoy TS
                bool interp = false;

                iir = new YYUKRPIr(interp, hy);
                for (int i = 0; i < rpiSchedule.Count; i++)
                {
                    iir.addFixing(rpiSchedule[i], fixData[i]);
                }

                YieldTermStructure nominalFF = new FlatForward(evaluationDate, 0.05, new ActualActual());

                nominalTS.linkTo(nominalFF);

                // now build the YoY inflation curve
                Period observationLag = new Period(2, TimeUnit.Months);

                Datum[] yyData =
                {
                    new Datum(new Date(13, Month.August, 2008),  2.95),
                    new Datum(new Date(13, Month.August, 2009),  2.95),
                    new Datum(new Date(13, Month.August, 2010),  2.93),
                    new Datum(new Date(15, Month.August, 2011), 2.955),
                    new Datum(new Date(13, Month.August, 2012), 2.945),
                    new Datum(new Date(13, Month.August, 2013), 2.985),
                    new Datum(new Date(13, Month.August, 2014),  3.01),
                    new Datum(new Date(13, Month.August, 2015), 3.035),
                    new Datum(new Date(13, Month.August, 2016), 3.055), // note that
                    new Datum(new Date(13, Month.August, 2017), 3.075), // some dates will be on
                    new Datum(new Date(13, Month.August, 2019), 3.105), // holidays but the payment
                    new Datum(new Date(15, Month.August, 2022), 3.135), // calendar will roll them
                    new Datum(new Date(13, Month.August, 2027), 3.155),
                    new Datum(new Date(13, Month.August, 2032), 3.145),
                    new Datum(new Date(13, Month.August, 2037), 3.145)
                };

                // now build the helpers ...
                List <BootstrapHelper <YoYInflationTermStructure> > helpers =
                    makeHelpers(yyData, yyData.Length, iir,
                                observationLag,
                                calendar, convention, dc);

                double baseYYRate = yyData[0].rate / 100.0;
                PiecewiseYoYInflationCurve <Linear> pYYTS = new PiecewiseYoYInflationCurve <Linear>(
                    evaluationDate, calendar, dc, observationLag,
                    iir.frequency(), iir.interpolated(), baseYYRate,
                    new Handle <YieldTermStructure>(nominalTS), helpers);

                pYYTS.recalculate();
                yoyTS = pYYTS as YoYInflationTermStructure;


                // make sure that the index has the latest yoy term structure
                hy.linkTo(pYYTS);
            }
Example #33
0
 public SwapIndex(string familyName, Period tenor, int settlementDays, Currency currency, Calendar calendar, Period fixedLegTenor, BusinessDayConvention fixedLegConvention, DayCounter fixedLegDayCounter, IborIndex iborIndex, YieldTermStructureHandle discountCurve) : this(NQuantLibcPINVOKE.new_SwapIndex__SWIG_1(familyName, Period.getCPtr(tenor), settlementDays, Currency.getCPtr(currency), Calendar.getCPtr(calendar), Period.getCPtr(fixedLegTenor), (int)fixedLegConvention, DayCounter.getCPtr(fixedLegDayCounter), IborIndex.getCPtr(iborIndex), YieldTermStructureHandle.getCPtr(discountCurve)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Example #34
0
        public static List <CashFlow> FloatingDigitalLeg <InterestRateIndexType, FloatingCouponType, DigitalCouponType>(List <double> nominals,
                                                                                                                        Schedule schedule,
                                                                                                                        InterestRateIndexType index,
                                                                                                                        DayCounter paymentDayCounter,
                                                                                                                        BusinessDayConvention paymentAdj,
                                                                                                                        List <int> fixingDays,
                                                                                                                        List <double> gearings,
                                                                                                                        List <double> spreads,
                                                                                                                        bool isInArrears,
                                                                                                                        List <double> callStrikes,
                                                                                                                        Position.Type callPosition,
                                                                                                                        bool isCallATMIncluded,
                                                                                                                        List <double> callDigitalPayoffs,
                                                                                                                        List <double> putStrikes,
                                                                                                                        Position.Type putPosition,
                                                                                                                        bool isPutATMIncluded,
                                                                                                                        List <double> putDigitalPayoffs,
                                                                                                                        DigitalReplication replication)
            where InterestRateIndexType : InterestRateIndex, new()
            where FloatingCouponType : FloatingRateCoupon, new()
            where DigitalCouponType : DigitalCoupon, new()
        {
            int n = schedule.Count;

            if (nominals.Count == 0)
            {
                throw new ArgumentException("no nominal given");
            }
            if (nominals.Count > n)
            {
                throw new ArgumentException(
                          "too many nominals (" + nominals.Count + "), only " + n + " required");
            }
            if (gearings != null && gearings.Count > n)
            {
                throw new ArgumentException(
                          "too many gearings (" + gearings.Count + "), only " + n + " required");
            }
            if (spreads != null && spreads.Count > n)
            {
                throw new ArgumentException(
                          "too many spreads (" + spreads.Count + "), only " + n + " required");
            }
            if (callStrikes.Count > n)
            {
                throw new ArgumentException(
                          "too many nominals (" + callStrikes.Count + "), only " + n + " required");
            }
            if (putStrikes.Count > n)
            {
                throw new ArgumentException(
                          "too many nominals (" + putStrikes.Count + "), only " + n + " required");
            }


            List <CashFlow> leg = new List <CashFlow>();

            // the following is not always correct
            Calendar calendar = schedule.calendar();

            Date refStart, start, refEnd, end;
            Date paymentDate;

            for (int i = 0; i < n; ++i)
            {
                refStart    = start = schedule.date(i);
                refEnd      = end = schedule.date(i + 1);
                paymentDate = calendar.adjust(end, paymentAdj);
                if (i == 0 && !schedule.isRegular(i + 1))
                {
                    BusinessDayConvention bdc = schedule.businessDayConvention();
                    refStart = calendar.adjust(end - schedule.tenor(), bdc);
                }
                if (i == n - 1 && !schedule.isRegular(i + 1))
                {
                    BusinessDayConvention bdc = schedule.businessDayConvention();
                    refEnd = calendar.adjust(start + schedule.tenor(), bdc);
                }
                if (Utils.Get(gearings, i, 1.0) == 0.0)   // fixed coupon
                {
                    leg.Add(new
                            FixedRateCoupon(Utils.Get(nominals, i, 1.0),
                                            paymentDate,
                                            Utils.Get(spreads, i, 1.0),
                                            paymentDayCounter,
                                            start, end, refStart, refEnd));
                }
                else     // floating digital coupon
                {
                    FloatingCouponType underlying = new FloatingCouponType().factory(
                        Utils.Get(nominals, i, 1.0),
                        paymentDate, start, end,
                        Utils.Get(fixingDays, i, index.fixingDays()),
                        index,
                        Utils.Get(gearings, i, 1.0),
                        Utils.Get(spreads, i, 0.0),
                        refStart, refEnd,
                        paymentDayCounter, isInArrears) as FloatingCouponType;

                    DigitalCouponType digitalCoupon = new DigitalCouponType().factory(
                        underlying,
                        Utils.toNullable(Utils.Get(callStrikes, i, Double.MinValue)),
                        callPosition,
                        isCallATMIncluded,
                        Utils.toNullable(Utils.Get(callDigitalPayoffs, i, Double.MinValue)),
                        Utils.toNullable(Utils.Get(putStrikes, i, Double.MinValue)),
                        putPosition,
                        isPutATMIncluded,
                        Utils.toNullable(Utils.Get(putDigitalPayoffs, i, Double.MinValue)),
                        replication) as DigitalCouponType;

                    leg.Add(digitalCoupon);
                }
            }
            return(leg);
        }
 public FuturesRateHelper(double price, Date immDate, uint nMonths, Calendar calendar, BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter) : this(NQuantLibcPINVOKE.new_FuturesRateHelper__SWIG_2(price, Date.getCPtr(immDate), nMonths, Calendar.getCPtr(calendar), (int)convention, endOfMonth, DayCounter.getCPtr(dayCounter)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
 public CreditDefaultSwap(Protection.Side side, double notional, double spread, Schedule schedule, BusinessDayConvention paymentConvention, DayCounter dayCounter, bool settlesAccrual, bool paysAtDefaultTime) : this(NQuantLibcPINVOKE.new_CreditDefaultSwap__SWIG_0((int)side, notional, spread, Schedule.getCPtr(schedule), (int)paymentConvention, DayCounter.getCPtr(dayCounter), settlesAccrual, paysAtDefaultTime), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Example #37
0
 public MakeSchedule withTerminationDateConvention(BusinessDayConvention conv)
 {
     terminationDateConvention_ = conv;
     return(this);
 }
 public CreditDefaultSwap(Protection.Side side, double notional, double upfront, double spread, Schedule schedule, BusinessDayConvention paymentConvention, DayCounter dayCounter) : this(NQuantLibcPINVOKE.new_CreditDefaultSwap__SWIG_5((int)side, notional, upfront, spread, Schedule.getCPtr(schedule), (int)paymentConvention, DayCounter.getCPtr(dayCounter)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Example #39
0
        public void testSwaptionPricing()
        {
            //"Testing forward swap and swaption pricing...");

            //SavedSettings backup;

            const int size  = 10;
            const int steps = 8 * size;

            #if QL_USE_INDEXED_COUPON
            const double tolerance = 1e-6;
            #else
            const double tolerance = 1e-12;
            #endif

            List <Date>   dates = new List <Date>();
            List <double> rates = new List <double>();
            dates.Add(new Date(4, 9, 2005));
            dates.Add(new Date(4, 9, 2011));
            rates.Add(0.04);
            rates.Add(0.08);

            IborIndex index = makeIndex(dates, rates);

            LiborForwardModelProcess process = new LiborForwardModelProcess(size, index);

            LmCorrelationModel corrModel = new LmExponentialCorrelationModel(size, 0.5);

            LmVolatilityModel volaModel = new LmLinearExponentialVolatilityModel(process.fixingTimes(),
                                                                                 0.291, 1.483, 0.116, 0.00001);

            // set-up pricing engine
            process.setCovarParam((LfmCovarianceParameterization)
                                  new LfmCovarianceProxy(volaModel, corrModel));

            // set-up a small Monte-Carlo simulation to price swations
            List <double> tmp = process.fixingTimes();

            TimeGrid grid = new TimeGrid(tmp, steps);

            List <int> location = new List <int>();
            for (int i = 0; i < tmp.Count; ++i)
            {
                location.Add(grid.index(tmp[i]));
            }

            ulong     seed     = 42;
            const int nrTrails = 5000;
            LowDiscrepancy.icInstance = new InverseCumulativeNormal();

            IRNG rsg = (InverseCumulativeRsg <RandomSequenceGenerator <MersenneTwisterUniformRng>
                                              , InverseCumulativeNormal>)
                       new PseudoRandom().make_sequence_generator(process.factors() * (grid.size() - 1), seed);



            MultiPathGenerator <IRNG> generator = new MultiPathGenerator <IRNG>(process,
                                                                                grid,
                                                                                rsg, false);

            LiborForwardModel liborModel = new LiborForwardModel(process, volaModel, corrModel);

            Calendar              calendar   = index.fixingCalendar();
            DayCounter            dayCounter = index.forwardingTermStructure().link.dayCounter();
            BusinessDayConvention convention = index.businessDayConvention();

            Date settlement = index.forwardingTermStructure().link.referenceDate();

            SwaptionVolatilityMatrix m = liborModel.getSwaptionVolatilityMatrix();

            for (int i = 1; i < size; ++i)
            {
                for (int j = 1; j <= size - i; ++j)
                {
                    Date fwdStart    = settlement + new Period(6 * i, TimeUnit.Months);
                    Date fwdMaturity = fwdStart + new Period(6 * j, TimeUnit.Months);

                    Schedule schedule = new Schedule(fwdStart, fwdMaturity, index.tenor(), calendar,
                                                     convention, convention, DateGeneration.Rule.Forward, false);

                    double      swapRate    = 0.0404;
                    VanillaSwap forwardSwap = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                                              schedule, swapRate, dayCounter,
                                                              schedule, index, 0.0, index.dayCounter());
                    forwardSwap.setPricingEngine(new DiscountingSwapEngine(index.forwardingTermStructure()));

                    // check forward pricing first
                    double expected   = forwardSwap.fairRate();
                    double calculated = liborModel.S_0(i - 1, i + j - 1);

                    if (Math.Abs(expected - calculated) > tolerance)
                    {
                        Assert.Fail("Failed to reproduce fair forward swap rate"
                                    + "\n    calculated: " + calculated
                                    + "\n    expected:   " + expected);
                    }

                    swapRate    = forwardSwap.fairRate();
                    forwardSwap =
                        new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                        schedule, swapRate, dayCounter,
                                        schedule, index, 0.0, index.dayCounter());
                    forwardSwap.setPricingEngine(new DiscountingSwapEngine(index.forwardingTermStructure()));

                    if (i == j && i <= size / 2)
                    {
                        IPricingEngine engine =
                            new LfmSwaptionEngine(liborModel, index.forwardingTermStructure());
                        Exercise exercise =
                            new EuropeanExercise(process.fixingDates()[i]);

                        Swaption swaption =
                            new Swaption(forwardSwap, exercise);
                        swaption.setPricingEngine(engine);

                        GeneralStatistics stat = new GeneralStatistics();

                        for (int n = 0; n < nrTrails; ++n)
                        {
                            Sample <MultiPath> path = (n % 2 != 0) ? generator.antithetic()
                                                     : generator.next();

                            //Sample<MultiPath> path = generator.next();
                            List <double> rates_ = new InitializedList <double>(size);
                            for (int k = 0; k < process.size(); ++k)
                            {
                                rates_[k] = path.value[k][location[i]];
                            }
                            List <double> dis = process.discountBond(rates_);

                            double npv = 0.0;
                            for (int k = i; k < i + j; ++k)
                            {
                                npv += (swapRate - rates_[k])
                                       * (process.accrualEndTimes()[k]
                                          - process.accrualStartTimes()[k]) * dis[k];
                            }
                            stat.add(Math.Max(npv, 0.0));
                        }

                        if (Math.Abs(swaption.NPV() - stat.mean())
                            > stat.errorEstimate() * 2.35)
                        {
                            Assert.Fail("Failed to reproduce swaption npv"
                                        + "\n    calculated: " + stat.mean()
                                        + "\n    expected:   " + swaption.NPV());
                        }
                    }
                }
            }
        }
Example #40
0
        public static Leg FixedRateLeg(Schedule schedule, DayCounter dayCount, DoubleVector nominals, DoubleVector couponRates, BusinessDayConvention paymentAdjustment)
        {
            Leg ret = new Leg(NQuantLibcPINVOKE.FixedRateLeg__SWIG_1(Schedule.getCPtr(schedule), DayCounter.getCPtr(dayCount), DoubleVector.getCPtr(nominals), DoubleVector.getCPtr(couponRates), (int)paymentAdjustment), true);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #41
0
        public static Leg IborLeg(DoubleVector nominals, Schedule schedule, IborIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, UnsignedIntVector fixingDays)
        {
            Leg ret = new Leg(NQuantLibcPINVOKE.IborLeg__SWIG_5(DoubleVector.getCPtr(nominals), Schedule.getCPtr(schedule), IborIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, UnsignedIntVector.getCPtr(fixingDays)), true);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #42
0
        public static Leg CmsZeroLeg(DoubleVector nominals, Schedule schedule, SwapIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention, UnsignedIntVector fixingDays, DoubleVector gearings, DoubleVector spreads, DoubleVector caps)
        {
            Leg ret = new Leg(NQuantLibcPINVOKE.CmsZeroLeg__SWIG_1(DoubleVector.getCPtr(nominals), Schedule.getCPtr(schedule), SwapIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention, UnsignedIntVector.getCPtr(fixingDays), DoubleVector.getCPtr(gearings), DoubleVector.getCPtr(spreads), DoubleVector.getCPtr(caps)), true);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #43
0
        public static Leg CmsZeroLeg(DoubleVector nominals, Schedule schedule, SwapIndex index, DayCounter paymentDayCounter, BusinessDayConvention paymentConvention)
        {
            Leg ret = new Leg(NQuantLibcPINVOKE.CmsZeroLeg__SWIG_5(DoubleVector.getCPtr(nominals), Schedule.getCPtr(schedule), SwapIndex.getCPtr(index), DayCounter.getCPtr(paymentDayCounter), (int)paymentConvention), true);

            if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
            {
                throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Example #44
0
        public CmsRateBond(int settlementDays,
                           double faceAmount,
                           Schedule schedule,
                           SwapIndex index,
                           DayCounter paymentDayCounter,
                           BusinessDayConvention paymentConvention = BusinessDayConvention.Following,
                           int fixingDays         = 0,
                           List <double> gearings = null,
                           List <double> spreads  = null,
                           List <double> caps     = null,
                           List <double> floors   = null,
                           bool inArrears         = false,
                           double redemption      = 100.0,
                           Date issueDate         = null)
            : base(settlementDays, schedule.calendar(), issueDate)
        {
            // Optional value check
            if (gearings == null)
            {
                gearings = new List <double>()
                {
                    1
                }
            }
            ;
            if (spreads == null)
            {
                spreads = new List <double>()
                {
                    0
                }
            }
            ;
            if (caps == null)
            {
                caps = new List <double>();
            }
            if (floors == null)
            {
                floors = new List <double>();
            }

            maturityDate_ = schedule.endDate();
            cashflows_    = new CmsLeg(schedule, index)
                            .withPaymentDayCounter(paymentDayCounter)
                            .withFixingDays(fixingDays)
                            .withGearings(gearings)
                            .withSpreads(spreads)
                            .withCaps(caps)
                            .withFloors(floors)
                            .inArrears(inArrears)
                            .withNotionals(faceAmount)
                            .withPaymentAdjustment(paymentConvention);

            addRedemptionsToCashflows(new List <double>()
            {
                redemption
            });

            if (cashflows().Count == 0)
            {
                throw new ApplicationException("bond with no cashflows!");
            }
            if (redemptions_.Count != 1)
            {
                throw new ApplicationException("multiple redemptions created");
            }

            index.registerWith(update);
        }
    }
}
Example #45
0
        /// <summary>
        /// rule based constructor
        /// </summary>
        /// <param name="effectiveDate"></param>
        /// <param name="terminationDate"></param>
        /// <param name="tenor"></param>
        /// <param name="calendar"></param>
        /// <param name="convention"></param>
        /// <param name="terminationDateConvention"></param>
        /// <param name="rule"></param>
        /// <param name="endOfMonth"></param>
        /// <param name="firstDate"></param>
        /// <param name="nextToLastDate"></param>
        public Schedule(Date effectiveDate,
                        Date terminationDate,
                        Period tenor,
                        Calendar calendar,
                        BusinessDayConvention convention,
                        BusinessDayConvention terminationDateConvention,
                        DateGeneration.Rule rule,
                        bool endOfMonth,
                        Date firstDate      = null,
                        Date nextToLastDate = null)
        {
            calendar_       = calendar ?? new NullCalendar();
            firstDate_      = firstDate == effectiveDate ? null : firstDate;
            nextToLastDate_ = nextToLastDate == terminationDate ? null : nextToLastDate;

            tenor_      = tenor;
            convention_ = convention;
            terminationDateConvention_ = terminationDateConvention;
            rule_       = rule;
            endOfMonth_ = allowsEndOfMonth(tenor) && endOfMonth;

            // sanity checks
            Utils.QL_REQUIRE(terminationDate != null, () => "null termination date");

            // in many cases (e.g. non-expired bonds) the effective date is not
            // really necessary. In these cases a decent placeholder is enough
            if (effectiveDate == null && firstDate == null && rule == DateGeneration.Rule.Backward)
            {
                Date evalDate = Settings.evaluationDate();
                Utils.QL_REQUIRE(evalDate < terminationDate, () => "null effective date");
                int y;
                if (nextToLastDate != null)
                {
                    y             = (nextToLastDate - evalDate) / 366 + 1;
                    effectiveDate = nextToLastDate - new Period(y, TimeUnit.Years);
                }
                else
                {
                    y             = (terminationDate - evalDate) / 366 + 1;
                    effectiveDate = terminationDate - new Period(y, TimeUnit.Years);
                }
                // More accurate , is the previous coupon date
                if (effectiveDate > evalDate)
                {
                    effectiveDate = effectiveDate - new Period(tenor_.length(), TimeUnit.Months);
                }
                else if (effectiveDate + new Period(tenor_.length(), TimeUnit.Months) < evalDate)
                {
                    effectiveDate = effectiveDate + new Period(tenor_.length(), TimeUnit.Months);
                }
            }
            else
            {
                Utils.QL_REQUIRE(effectiveDate != null, () => "null effective date");
            }

            Utils.QL_REQUIRE(effectiveDate < terminationDate, () =>
                             "effective date (" + effectiveDate +
                             ") later than or equal to termination date (" +
                             terminationDate + ")"
                             );

            if (tenor_.length() == 0)
            {
                rule_ = DateGeneration.Rule.Zero;
            }
            else
            {
                Utils.QL_REQUIRE(tenor.length() > 0, () => "non positive tenor (" + tenor + ") not allowed");
            }

            if (firstDate_ != null)
            {
                switch (rule_.Value)
                {
                case DateGeneration.Rule.Backward:
                case DateGeneration.Rule.Forward:
                    Utils.QL_REQUIRE(firstDate_ > effectiveDate &&
                                     firstDate_ < terminationDate, () =>
                                     "first date (" + firstDate_ + ") out of effective-termination date range [" +
                                     effectiveDate + ", " + terminationDate + ")");
                    // we should ensure that the above condition is still verified after adjustment
                    break;

                case DateGeneration.Rule.ThirdWednesday:
                    Utils.QL_REQUIRE(IMM.isIMMdate(firstDate_, false), () => "first date (" + firstDate_ + ") is not an IMM date");
                    break;

                case DateGeneration.Rule.Zero:
                case DateGeneration.Rule.Twentieth:
                case DateGeneration.Rule.TwentiethIMM:
                case DateGeneration.Rule.OldCDS:
                case DateGeneration.Rule.CDS:
                case DateGeneration.Rule.CDS2015:
                    Utils.QL_FAIL("first date incompatible with " + rule_.Value + " date generation rule");
                    break;

                default:
                    Utils.QL_FAIL("unknown rule (" + rule_.Value + ")");
                    break;
                }
            }

            if (nextToLastDate_ != null)
            {
                switch (rule_.Value)
                {
                case DateGeneration.Rule.Backward:
                case DateGeneration.Rule.Forward:
                    Utils.QL_REQUIRE(nextToLastDate_ > effectiveDate && nextToLastDate_ < terminationDate, () =>
                                     "next to last date (" + nextToLastDate_ + ") out of effective-termination date range (" +
                                     effectiveDate + ", " + terminationDate + "]");
                    // we should ensure that the above condition is still verified after adjustment
                    break;

                case DateGeneration.Rule.ThirdWednesday:
                    Utils.QL_REQUIRE(IMM.isIMMdate(nextToLastDate_, false), () => "next-to-last date (" + nextToLastDate_ +
                                     ") is not an IMM date");
                    break;

                case DateGeneration.Rule.Zero:
                case DateGeneration.Rule.Twentieth:
                case DateGeneration.Rule.TwentiethIMM:
                case DateGeneration.Rule.OldCDS:
                case DateGeneration.Rule.CDS:
                case DateGeneration.Rule.CDS2015:
                    Utils.QL_FAIL("next to last date incompatible with " + rule_.Value + " date generation rule");
                    break;

                default:
                    Utils.QL_FAIL("unknown rule (" + rule_.Value + ")");
                    break;
                }
            }

            // calendar needed for endOfMonth adjustment
            Calendar nullCalendar = new NullCalendar();
            int      periods = 1;
            Date     seed = new Date(), exitDate = new Date();

            switch (rule_.Value)
            {
            case DateGeneration.Rule.Zero:
                tenor_ = new Period(0, TimeUnit.Years);
                dates_.Add(effectiveDate);
                dates_.Add(terminationDate);
                isRegular_.Add(true);
                break;

            case DateGeneration.Rule.Backward:
                dates_.Add(terminationDate);

                seed = terminationDate;
                if (nextToLastDate_ != null)
                {
                    dates_.Insert(0, nextToLastDate_);
                    Date temp = nullCalendar.advance(seed, -periods * tenor_, convention_, endOfMonth_.Value);
                    if (temp != nextToLastDate_)
                    {
                        isRegular_.Insert(0, false);
                    }
                    else
                    {
                        isRegular_.Insert(0, true);
                    }
                    seed = nextToLastDate_;
                }
                exitDate = effectiveDate;
                if (firstDate_ != null)
                {
                    exitDate = firstDate_;
                }

                while (true)
                {
                    Date temp = nullCalendar.advance(seed, -periods * tenor_, convention_, endOfMonth_.Value);
                    if (temp < exitDate)
                    {
                        if (firstDate_ != null && (calendar_.adjust(dates_.First(), convention_) !=
                                                   calendar_.adjust(firstDate_, convention_)))
                        {
                            dates_.Insert(0, firstDate_);
                            isRegular_.Insert(0, false);
                        }
                        break;
                    }
                    else
                    {
                        // skip dates that would result in duplicates
                        // after adjustment
                        if (calendar_.adjust(dates_.First(), convention_) != calendar_.adjust(temp, convention_))
                        {
                            dates_.Insert(0, temp);
                            isRegular_.Insert(0, true);
                        }
                        ++periods;
                    }
                }

                if (calendar_.adjust(dates_.First(), convention) != calendar_.adjust(effectiveDate, convention))
                {
                    dates_.Insert(0, effectiveDate);
                    isRegular_.Insert(0, false);
                }

                break;

            case DateGeneration.Rule.Twentieth:
            case DateGeneration.Rule.TwentiethIMM:
            case DateGeneration.Rule.ThirdWednesday:
            case DateGeneration.Rule.OldCDS:
            case DateGeneration.Rule.CDS:
            case DateGeneration.Rule.CDS2015:
                Utils.QL_REQUIRE(!endOfMonth, () => "endOfMonth convention incompatible with " + rule_.Value + " date generation rule");
                goto case DateGeneration.Rule.Forward;   // fall through

            case DateGeneration.Rule.Forward:
                if (rule_.Value == DateGeneration.Rule.CDS ||
                    rule_.Value == DateGeneration.Rule.CDS2015)
                {
                    dates_.Add(previousTwentieth(effectiveDate, rule_.Value));
                }
                else
                {
                    dates_.Add(effectiveDate);
                }

                seed = dates_.Last();
                if (firstDate_ != null)
                {
                    dates_.Add(firstDate_);
                    Date temp = nullCalendar.advance(seed, periods * tenor_, convention_, endOfMonth_.Value);
                    if (temp != firstDate_)
                    {
                        isRegular_.Add(false);
                    }
                    else
                    {
                        isRegular_.Add(true);
                    }
                    seed = firstDate_;
                }
                else if (rule_.Value == DateGeneration.Rule.Twentieth ||
                         rule_.Value == DateGeneration.Rule.TwentiethIMM ||
                         rule_.Value == DateGeneration.Rule.OldCDS ||
                         rule_.Value == DateGeneration.Rule.CDS ||
                         rule_.Value == DateGeneration.Rule.CDS2015)
                {
                    Date next20th = nextTwentieth(effectiveDate, rule_.Value);
                    if (rule_ == DateGeneration.Rule.OldCDS)
                    {
                        // distance rule inforced in natural days
                        long stubDays = 30;
                        if (next20th - effectiveDate < stubDays)
                        {
                            // +1 will skip this one and get the next
                            next20th = nextTwentieth(next20th + 1, rule_.Value);
                        }
                    }
                    if (next20th != effectiveDate)
                    {
                        dates_.Add(next20th);
                        isRegular_.Add(false);
                        seed = next20th;
                    }
                }

                exitDate = terminationDate;
                if (nextToLastDate_ != null)
                {
                    exitDate = nextToLastDate_;
                }
                if (rule_ == DateGeneration.Rule.CDS2015 &&
                    nextTwentieth(terminationDate, rule_.Value) == terminationDate &&
                    terminationDate.month() % 2 == 1)
                {
                    exitDate = nextTwentieth(terminationDate + 1, rule_.Value);
                }
                while (true)
                {
                    Date temp = nullCalendar.advance(seed, periods * tenor_, convention_, endOfMonth_.Value);
                    if (temp > exitDate)
                    {
                        if (nextToLastDate_ != null &&
                            (calendar_.adjust(dates_.Last(), convention_) != calendar_.adjust(nextToLastDate_, convention_)))
                        {
                            dates_.Add(nextToLastDate_);
                            isRegular_.Add(false);
                        }
                        break;
                    }
                    else
                    {
                        // skip dates that would result in duplicates
                        // after adjustment
                        if (calendar_.adjust(dates_.Last(), convention_) != calendar_.adjust(temp, convention_))
                        {
                            dates_.Add(temp);
                            isRegular_.Add(true);
                        }
                        ++periods;
                    }
                }

                if (calendar_.adjust(dates_.Last(), terminationDateConvention_.Value) !=
                    calendar_.adjust(terminationDate, terminationDateConvention_.Value))
                {
                    if (rule_.Value == DateGeneration.Rule.Twentieth ||
                        rule_.Value == DateGeneration.Rule.TwentiethIMM ||
                        rule_.Value == DateGeneration.Rule.OldCDS ||
                        rule_.Value == DateGeneration.Rule.CDS)
                    {
                        dates_.Add(nextTwentieth(terminationDate, rule_.Value));
                        isRegular_.Add(true);
                    }
                    else if (rule_ == DateGeneration.Rule.CDS2015)
                    {
                        Date tentativeTerminationDate = nextTwentieth(terminationDate, rule_.Value);
                        if (tentativeTerminationDate.month() % 2 == 0)
                        {
                            dates_.Add(tentativeTerminationDate);
                            isRegular_.Add(true);
                        }
                    }
                    else
                    {
                        dates_.Add(terminationDate);
                        isRegular_.Add(false);
                    }
                }
                break;

            default:
                Utils.QL_FAIL("unknown rule (" + rule_.Value + ")");
                break;
            }

            // adjustments
            if (rule_ == DateGeneration.Rule.ThirdWednesday)
            {
                for (int i = 1; i < dates_.Count - 1; ++i)
                {
                    dates_[i] = Date.nthWeekday(3, DayOfWeek.Wednesday, dates_[i].Month, dates_[i].Year);
                }
            }

            if (endOfMonth && calendar_.isEndOfMonth(seed))
            {
                // adjust to end of month
                if (convention_ == BusinessDayConvention.Unadjusted)
                {
                    for (int i = 1; i < dates_.Count - 1; ++i)
                    {
                        dates_[i] = Date.endOfMonth(dates_[i]);
                    }
                }
                else
                {
                    for (int i = 1; i < dates_.Count - 1; ++i)
                    {
                        dates_[i] = calendar_.endOfMonth(dates_[i]);
                    }
                }
                if (terminationDateConvention_ != BusinessDayConvention.Unadjusted)
                {
                    dates_[0] = calendar_.endOfMonth(dates_.First());
                    dates_[dates_.Count - 1] = calendar_.endOfMonth(dates_.Last());
                }
                else
                {
                    // the termination date is the first if going backwards,
                    // the last otherwise.
                    if (rule_ == DateGeneration.Rule.Backward)
                    {
                        dates_[dates_.Count - 1] = Date.endOfMonth(dates_.Last());
                    }
                    else
                    {
                        dates_[0] = Date.endOfMonth(dates_.First());
                    }
                }
            }
            else
            {
                // first date not adjusted for CDS schedules
                if (rule_ != DateGeneration.Rule.OldCDS)
                {
                    dates_[0] = calendar_.adjust(dates_[0], convention_);
                }
                for (int i = 1; i < dates_.Count - 1; ++i)
                {
                    dates_[i] = calendar_.adjust(dates_[i], convention_);
                }

                // termination date is NOT adjusted as per ISDA specifications, unless otherwise specified in the
                // confirmation of the deal or unless we're creating a CDS schedule
                if (terminationDateConvention_.Value != BusinessDayConvention.Unadjusted &&
                    rule_.Value != DateGeneration.Rule.CDS &&
                    rule_.Value != DateGeneration.Rule.CDS2015)
                {
                    dates_[dates_.Count - 1] = calendar_.adjust(dates_.Last(), terminationDateConvention_.Value);
                }
            }

            // Final safety checks to remove extra next-to-last date, if
            // necessary.  It can happen to be equal or later than the end
            // date due to EOM adjustments (see the Schedule test suite
            // for an example).
            if (dates_.Count >= 2 && dates_[dates_.Count - 2] >= dates_.Last())
            {
                isRegular_[isRegular_.Count - 2] = (dates_[dates_.Count - 2] == dates_.Last());
                dates_[dates_.Count - 2]         = dates_.Last();

                dates_.RemoveAt(dates_.Count - 1);
                isRegular_.RemoveAt(isRegular_.Count - 1);
            }

            if (dates_.Count >= 2 && dates_[1] <= dates_.First())
            {
                isRegular_[1] = (dates_[1] == dates_.First());
                dates_[1]     = dates_.First();
                dates_.RemoveAt(0);
                isRegular_.RemoveAt(0);
            }

            Utils.QL_REQUIRE(dates_.Count > 1,
                             () => "degenerate single date (" + dates_[0] + ") schedule" +
                             "\n seed date: " + seed +
                             "\n exit date: " + exitDate +
                             "\n effective date: " + effectiveDate +
                             "\n first date: " + firstDate +
                             "\n next to last date: " + nextToLastDate +
                             "\n termination date: " + terminationDate +
                             "\n generation rule: " + rule_.Value +
                             "\n end of month: " + endOfMonth_.Value);
        }
Example #46
0
 /// <summary>
 /// Advances the given date as specified by the given period and
 /// returns the result.
 /// </summary>
 /// <remarks>The input date is not modified.</remarks>
 public Date advance(Date d, Period p, BusinessDayConvention c = BusinessDayConvention.Following, bool endOfMonth = false)
 {
     return(advance(d, p.length(), p.units(), c, endOfMonth));
 }
Example #47
0
 public MakeSchedule withConvention(BusinessDayConvention conv)
 {
     convention_ = conv;
     return(this);
 }
Example #48
0
        /// <summary>
        /// Adjusts a non-business day to the appropriate near business day  with respect
        /// to the given convention.
        /// </summary>
        public Date adjust(Date d, BusinessDayConvention c = BusinessDayConvention.Following)
        {
            if (d == null)
            {
                throw new ArgumentException("null date");
            }
            if (c == BusinessDayConvention.Unadjusted)
            {
                return(d);
            }

            Date d1 = d;

            if (c == BusinessDayConvention.Following || c == BusinessDayConvention.ModifiedFollowing ||
                c == BusinessDayConvention.HalfMonthModifiedFollowing)
            {
                while (isHoliday(d1))
                {
                    d1++;
                }
                if (c == BusinessDayConvention.ModifiedFollowing || c == BusinessDayConvention.HalfMonthModifiedFollowing)
                {
                    if (d1.Month != d.Month)
                    {
                        return(adjust(d, BusinessDayConvention.Preceding));
                    }
                    if (c == BusinessDayConvention.HalfMonthModifiedFollowing)
                    {
                        if (d.Day <= 15 && d1.Day > 15)
                        {
                            return(adjust(d, BusinessDayConvention.Preceding));
                        }
                    }
                }
            }
            else if (c == BusinessDayConvention.Preceding || c == BusinessDayConvention.ModifiedPreceding)
            {
                while (isHoliday(d1))
                {
                    d1--;
                }
                if (c == BusinessDayConvention.ModifiedPreceding && d1.Month != d.Month)
                {
                    return(adjust(d, BusinessDayConvention.Following));
                }
            }
            else if (c == BusinessDayConvention.Nearest)
            {
                Date d2 = d;
                while (isHoliday(d1) && isHoliday(d2))
                {
                    d1++;
                    d2--;
                }
                if (isHoliday(d1))
                {
                    return(d2);
                }
                else
                {
                    return(d1);
                }
            }
            else
            {
                Utils.QL_FAIL("unknown business-day convention");
            }
            return(d1);
        }
Example #49
0
        public static List <CashFlow> FloatingLeg <InterestRateIndexType, FloatingCouponType, CappedFlooredCouponType>(List <double> nominals,
                                                                                                                       Schedule schedule,
                                                                                                                       InterestRateIndexType index,
                                                                                                                       DayCounter paymentDayCounter,
                                                                                                                       BusinessDayConvention paymentAdj,
                                                                                                                       List <int> fixingDays,
                                                                                                                       List <double> gearings,
                                                                                                                       List <double> spreads,
                                                                                                                       List <double> caps,
                                                                                                                       List <double> floors,
                                                                                                                       bool isInArrears,
                                                                                                                       bool isZero)
            where InterestRateIndexType : InterestRateIndex, new()
            where FloatingCouponType : FloatingRateCoupon, new()
            where CappedFlooredCouponType : CappedFlooredCoupon, new()
        {
            int n = schedule.Count;

            if (nominals.Count == 0)
            {
                throw new ArgumentException("no notional given");
            }
            if (nominals.Count > n)
            {
                throw new ArgumentException(
                          "too many nominals (" + nominals.Count + "), only " + n + " required");
            }
            if (gearings != null && gearings.Count > n)
            {
                throw new ArgumentException(
                          "too many gearings (" + gearings.Count + "), only " + n + " required");
            }
            if (spreads != null && spreads.Count > n)
            {
                throw new ArgumentException(
                          "too many spreads (" + spreads.Count + "), only " + n + " required");
            }
            if (caps != null && caps.Count > n)
            {
                throw new ArgumentException(
                          "too many caps (" + caps.Count + "), only " + n + " required");
            }
            if (floors != null && floors.Count > n)
            {
                throw new ArgumentException(
                          "too many floors (" + floors.Count + "), only " + n + " required");
            }
            if (isZero && isInArrears)
            {
                throw new ArgumentException("in-arrears and zero features are not compatible");
            }

            List <CashFlow> leg = new List <CashFlow>();

            // the following is not always correct
            Calendar calendar = schedule.calendar();

            Date refStart, start, refEnd, end;
            Date lastPaymentDate = calendar.adjust(schedule[n - 1], paymentAdj);

            for (int i = 0; i < n - 1; ++i)
            {
                refStart = start = schedule[i];
                refEnd   = end = schedule[i + 1];
                Date paymentDate = isZero ? lastPaymentDate : calendar.adjust(end, paymentAdj);
                if (i == 0 && !schedule.isRegular(i + 1))
                {
                    refStart = calendar.adjust(end - schedule.tenor(), schedule.businessDayConvention());
                }
                if (i == n - 1 && !schedule.isRegular(i + 1))
                {
                    refEnd = calendar.adjust(start + schedule.tenor(), schedule.businessDayConvention());
                }

                if (Utils.Get(gearings, i, 1) == 0)                                 // fixed coupon
                {
                    leg.Add(new FixedRateCoupon(Utils.Get(nominals, i),
                                                paymentDate,
                                                Utils.effectiveFixedRate(spreads, caps, floors, i),
                                                paymentDayCounter,
                                                start, end, refStart, refEnd));
                }
                else
                {
                    if (Utils.noOption(caps, floors, i))
                    {
                        leg.Add(new FloatingCouponType().factory(Utils.Get(nominals, i),
                                                                 paymentDate, start, end,
                                                                 Utils.Get(fixingDays, i, 2),
                                                                 index,
                                                                 Utils.Get(gearings, i, 1),
                                                                 Utils.Get(spreads, i),
                                                                 refStart, refEnd, paymentDayCounter,
                                                                 isInArrears));
                    }
                    else
                    {
                        leg.Add(new CappedFlooredCouponType().factory(Utils.Get(nominals, i),
                                                                      paymentDate, start, end,
                                                                      Utils.Get(fixingDays, i, 2),
                                                                      index,
                                                                      Utils.Get(gearings, i, 1),
                                                                      Utils.Get(spreads, i),
                                                                      Utils.toNullable(Utils.Get(caps, i, Double.MinValue)),
                                                                      Utils.toNullable(Utils.Get(floors, i, Double.MinValue)),
                                                                      refStart, refEnd, paymentDayCounter,
                                                                      isInArrears));
                    }
                }
            }
            return(leg);
        }
Example #50
0
 public new OvernightLeg withPaymentAdjustment(BusinessDayConvention convention)
 {
     paymentAdjustment_ = convention;
     return(this);
 }
Example #51
0
        public static List <CashFlow> yoyInflationLeg(List <double> notionals_,
                                                      Schedule schedule_,
                                                      BusinessDayConvention paymentAdjustment_,
                                                      YoYInflationIndex index_,
                                                      List <double> gearings_,
                                                      List <double> spreads_,
                                                      DayCounter paymentDayCounter_,
                                                      List <double> caps_,
                                                      List <double> floors_,
                                                      Calendar paymentCalendar_,
                                                      List <int> fixingDays_,
                                                      Period observationLag_)
        {
            int n = schedule_.Count;

            if (notionals_.empty())
            {
                throw new ApplicationException("no notional given");
            }

            if (notionals_.Count > n)
            {
                throw new ApplicationException("too many nominals (" + notionals_.Count +
                                               "), only " + n + " required");
            }
            if (gearings_.Count > n)
            {
                throw new ApplicationException("too many gearings (" + gearings_.Count +
                                               "), only " + n + " required");
            }

            if (spreads_.Count > n)
            {
                throw new ApplicationException("too many spreads (" + spreads_.Count +
                                               "), only " + n + " required");
            }

            if (caps_.Count > n)
            {
                throw new ApplicationException("too many caps (" + caps_.Count +
                                               "), only " + n + " required");
            }

            if (floors_.Count > n)
            {
                throw new ApplicationException("too many floors (" + floors_.Count +
                                               "), only " + n + " required");
            }


            List <CashFlow> leg = new List <CashFlow>(n);

            Calendar calendar = paymentCalendar_;

            Date refStart, start, refEnd, end;
            Date lastPaymentDate = calendar.adjust(schedule_.date(n), paymentAdjustment_);

            for (int i = 0; i < n; ++i)
            {
                refStart = start = schedule_.date(i);
                refEnd   = end = schedule_.date(i + 1);
                Date paymentDate = calendar.adjust(end, paymentAdjustment_);
                if (i == 0 && !schedule_.isRegular(i + 1))
                {
                    BusinessDayConvention bdc = schedule_.businessDayConvention();
                    refStart = schedule_.calendar().adjust(end - schedule_.tenor(), bdc);
                }
                if (i == n - 1 && !schedule_.isRegular(i + 1))
                {
                    BusinessDayConvention bdc = schedule_.businessDayConvention();
                    refEnd = schedule_.calendar().adjust(start + schedule_.tenor(), bdc);
                }
                if (Utils.Get(gearings_, i, 1.0) == 0.0)
                {
                    // fixed coupon
                    leg.Add(new FixedRateCoupon(Utils.Get(notionals_, i, 1.0),
                                                paymentDate,
                                                Utils.effectiveFixedRate(spreads_, caps_,
                                                                         floors_, i),
                                                paymentDayCounter_,
                                                start, end, refStart, refEnd));
                }
                else
                {
                    // yoy inflation coupon
                    if (Utils.noOption(caps_, floors_, i))
                    {
                        // just swaplet
                        YoYInflationCoupon coup = new YoYInflationCoupon(paymentDate,
                                                                         Utils.Get(notionals_, i, 1.0),
                                                                         start, end,
                                                                         Utils.Get(fixingDays_, i, 0),
                                                                         index_,
                                                                         observationLag_,
                                                                         paymentDayCounter_,
                                                                         Utils.Get(gearings_, i, 1.0),
                                                                         Utils.Get(spreads_, i, 0.0),
                                                                         refStart, refEnd);

                        // in this case you can set a pricer
                        // straight away because it only provides computation - not data
                        YoYInflationCouponPricer pricer = new YoYInflationCouponPricer();
                        coup.setPricer(pricer);
                        leg.Add(coup);
                    }
                    else
                    {
                        // cap/floorlet
                        leg.Add(new CappedFlooredYoYInflationCoupon(
                                    paymentDate,
                                    Utils.Get(notionals_, i, 1.0),
                                    start, end,
                                    Utils.Get(fixingDays_, i, 0),
                                    index_,
                                    observationLag_,
                                    paymentDayCounter_,
                                    Utils.Get(gearings_, i, 1.0),
                                    Utils.Get(spreads_, i, 0.0),
                                    Utils.toNullable(Utils.Get(caps_, i, Double.MinValue)),
                                    Utils.toNullable(Utils.Get(floors_, i, Double.MinValue)),
                                    refStart, refEnd));
                    }
                }
            }

            return(leg);
        }
Example #52
0
 public SpreadCdsHelper(double spread, Period tenor, int settlementDays, Calendar calendar, Frequency frequency, BusinessDayConvention convention, DateGeneration.Rule rule, DayCounter dayCounter, double recoveryRate, YieldTermStructureHandle discountCurve) : this(NQuantLibcPINVOKE.new_SpreadCdsHelper__SWIG_5(spread, Period.getCPtr(tenor), settlementDays, Calendar.getCPtr(calendar), (int)frequency, (int)convention, (int)rule, DayCounter.getCPtr(dayCounter), recoveryRate, YieldTermStructureHandle.getCPtr(discountCurve)), true)
 {
     if (NQuantLibcPINVOKE.SWIGPendingException.Pending)
     {
         throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Example #53
0
        public static Tuple <Date, double>[] Calibrate(
            string name,
            Date referenceDate,
            IMarketInstrument[] marketInstruments,
            BusinessDayConvention bda,
            IDayCount daycount,
            ICalendar calendar,
            Compound compound,
            Interpolation interpolation,
            YieldCurveTrait trait,
            CurrencyCode currency,
            IMarketCondition baseMarket = null,
            Expression <Func <IMarketCondition, object> >[] expression = null,
            double initialValue = double.NaN,
            double initialGuess = 0.05,
            //double xmin = -0.9999,
            double xmin = -0.5,
            double xmax = 1.0
            )
        {
            var accuracy = 1.0e-14;

            if (marketInstruments.Any(x => x.Instrument is CreditDefaultSwap) || trait == YieldCurveTrait.DiscountCurve)
            {
                initialValue = 1.0;
                initialGuess = 1.0;
                xmin         = 1.0e-64;
            }

            var len    = marketInstruments.Length;
            var points = marketInstruments.Select(x => Tuple.Create(x.Instrument.GetCalibrationDate(), initialGuess)).ToList();

            var calibrationStartIndex = 0;

            if (!double.IsNaN(initialValue))
            {
                points.Insert(0, Tuple.Create(referenceDate, initialValue));
                calibrationStartIndex = 1;
            }

            if (interpolation == Interpolation.ForwardFlat)
            {
                //forward flat interpolation, the final instrument is not needed in calibration
                points = points.Take(len - 1).ToList();
                points.Insert(0, Tuple.Create(referenceDate, 0.05));
                calibrationStartIndex = 0;
            }
            else if (trait == YieldCurveTrait.ForwardCurve)
            {
                points.Insert(0, Tuple.Create(referenceDate, 0.05));
                calibrationStartIndex = 1;
            }

            baseMarket = baseMarket ?? new MarketCondition(x => x.ValuationDate.Value = referenceDate);
            expression = expression ?? new Expression <Func <IMarketCondition, object> >[]
            {
                x => x.DiscountCurve,
                x => x.FixingCurve
            };

            IYieldCurve calibratedCurve = new YieldCurve(name, referenceDate, points.ToArray(), bda, daycount, calendar, currency, compound, interpolation, trait, baseMarket);
            var         finalInstrument = marketInstruments.Last();
            var         smooth          = (finalInstrument.Instrument is InterestRateSwap);

            double preCalibrationValue = 0.0;

            if (smooth)
            {
                preCalibrationValue = finalInstrument.Instrument.ModelValue(
                    baseMarket.UpdateCondition(expression.Select(ex => (IUpdateMktConditionPack) new UpdateMktConditionPack <IYieldCurve>(ex, calibratedCurve)).ToArray()),
                    finalInstrument.CalibMethod);
            }

            while (true)
            {
                for (var i = 0; i < len; ++i)
                {
                    var calibrateFunc = new CalibrateMarketInstrument(marketInstruments[i], calibratedCurve, baseMarket, i + calibrationStartIndex, expression);
                    //Note: alternative brent solver gives same result, but slower convergence,
                    //var calibrateFunc = new CalibrateMarketInstrument2(marketInstruments[i], calibratedCurve, baseMarket, i + calibrationStartIndex, expression);
                    double finalR;
                    try
                    {
                        finalR = BrentZero.Solve(calibrateFunc, xmin, xmax, accuracy);
                        //finalR = BrentZero2<IUnivariateFunction>.DoSolve(calibrateFunc, xmin, xmax, 0.05, 0);
                    }
                    catch (Exception ex)
                    {
                        throw new PricingLibraryException(string.Format("Error when bootstrapping {0}th point", i));
                    }
                    calibratedCurve = UpdateKeyRate(calibratedCurve, i + calibrationStartIndex, finalR);
                }

                if (!smooth)
                {
                    break;
                }
                else
                {
                    var postCalibrationValue = finalInstrument.Instrument.ModelValue(
                        baseMarket.UpdateCondition(expression.Select(ex => (IUpdateMktConditionPack) new UpdateMktConditionPack <IYieldCurve>(ex, calibratedCurve)).ToArray()),
                        finalInstrument.CalibMethod);
                    if (Math.Abs(postCalibrationValue - preCalibrationValue) < 1e-12)
                    {
                        break;
                    }
                    preCalibrationValue = postCalibrationValue;
                }
            }

            //if initial value is provided for 0D, 不插0D
            if (!double.IsNaN(initialValue))
            {
                return(calibratedCurve.KeyPoints.ToArray());
            }

            //NEVER EVER insert points at the end, inset at MOST ONE point at the beginning
            return(new[] { Tuple.Create(referenceDate, calibratedCurve.KeyPoints[0].Item2) }            // Insert 0D point to avoid interpolation jump at the beginning
                   .Union(calibratedCurve.KeyPoints)
                   .ToArray());
        }
Example #54
0
        //! default constructor

        /*! \warning term structures initialized by means of this
         *           constructor must manage their own reference date
         *           by overriding the referenceDate() method.
         */
        public BlackVolatilityTermStructure(BusinessDayConvention bdc = BusinessDayConvention.Following,
                                            DayCounter dc             = null)
            : base(bdc, dc)
        {
        }
Example #55
0
 public MakeSwaption withOptionConvention(BusinessDayConvention bdc)
 {
     optionConvention_ = bdc;
     return(this);
 }
Example #56
0
 //! calculate the reference date based on the global evaluation date
 protected LocalVolTermStructure(int settlementDays, Calendar cal, BusinessDayConvention bdc = BusinessDayConvention.Following,
                                 DayCounter dc = null)
     : base(settlementDays, cal, bdc, dc)
 {
 }
        //! default constructor

        /*! \warning term structures initialized by means of this
         *           constructor must manage their own reference date
         *           by overriding the referenceDate() method.
         */

        protected BlackVarianceTermStructure(BusinessDayConvention bdc = BusinessDayConvention.Following,
                                             DayCounter dc             = null)
            : base(bdc, dc)
        {
        }
Example #58
0
 //! initialize with a fixed reference date
 protected LocalVolTermStructure(Date referenceDate, Calendar cal = null,
                                 BusinessDayConvention bdc        = BusinessDayConvention.Following, DayCounter dc = null)
     : base(referenceDate, cal, bdc, dc)
 {
 }
Example #59
0
            // setup
            public CommonVars()
            {
                backup    = new SavedSettings();
                cleaner   = new IndexHistoryCleaner();
                nominalUK = new RelinkableHandle <YieldTermStructure>();
                cpiUK     = new RelinkableHandle <ZeroInflationTermStructure>();
                hcpi      = new RelinkableHandle <ZeroInflationTermStructure>();
                zciisD    = new List <Date>();
                zciisR    = new List <double>();
                hii       = new RelinkableHandle <ZeroInflationIndex>();

                nominals = new InitializedList <double>(1, 1000000);
                // option variables
                frequency = Frequency.Annual;
                // usual setup
                volatility = 0.01;
                length     = 7;
                calendar   = new UnitedKingdom();
                convention = BusinessDayConvention.ModifiedFollowing;
                Date today = new Date(25, Month.November, 2009);

                evaluationDate = calendar.adjust(today);
                Settings.setEvaluationDate(evaluationDate);
                settlementDays = 0;
                fixingDays     = 0;
                settlement     = calendar.advance(today, settlementDays, TimeUnit.Days);
                startDate      = settlement;
                dcZCIIS        = new ActualActual();
                dcNominal      = new ActualActual();

                // uk rpi index
                //      fixing data
                Date     from        = new Date(20, Month.July, 2007);
                Date     to          = new Date(20, Month.November, 2009);
                Schedule rpiSchedule = new MakeSchedule().from(from).to(to)
                                       .withTenor(new Period(1, TimeUnit.Months))
                                       .withCalendar(new UnitedKingdom())
                                       .withConvention(BusinessDayConvention.ModifiedFollowing).value();

                double[] fixData =
                {
                    206.1,  207.3, 208.0, 208.9, 209.7, 210.9,
                    209.8,  211.4, 212.1, 214.0, 215.1, 216.8,
                    216.5,  217.2, 218.4, 217.7,   216,
                    212.9,  210.1, 211.4, 211.3, 211.5,
                    212.8,  213.4, 213.4, 213.4, 214.4,
                    -999.0, -999.0
                };

                // link from cpi index to cpi TS
                bool interp = false;// this MUST be false because the observation lag is only 2 months

                // for ZCIIS; but not for contract if the contract uses a bigger lag.
                ii = new UKRPI(interp, hcpi);
                for (int i = 0; i < rpiSchedule.Count; i++)
                {
                    ii.addFixing(rpiSchedule[i], fixData[i], true); // force overwrite in case multiple use
                }

                Datum[] nominalData =
                {
                    new Datum(new Date(26, Month.November,  2009),   0.475),
                    new Datum(new Date(2,  Month.December,  2009), 0.47498),
                    new Datum(new Date(29, Month.December,  2009), 0.49988),
                    new Datum(new Date(25, Month.February,  2010), 0.59955),
                    new Datum(new Date(18, Month.March,     2010), 0.65361),
                    new Datum(new Date(25, Month.May,       2010), 0.82830),
                    new Datum(new Date(17, Month.June,      2010),     0.7),
                    new Datum(new Date(16, Month.September, 2010), 0.78960),
                    new Datum(new Date(16, Month.December,  2010), 0.93762),
                    new Datum(new Date(17, Month.March,     2011), 1.12037),
                    new Datum(new Date(22, Month.September, 2011), 1.52011),
                    new Datum(new Date(25, Month.November,  2011), 1.78399),
                    new Datum(new Date(26, Month.November,  2012), 2.41170),
                    new Datum(new Date(25, Month.November,  2013), 2.83935),
                    new Datum(new Date(25, Month.November,  2014), 3.12888),
                    new Datum(new Date(25, Month.November,  2015), 3.34298),
                    new Datum(new Date(25, Month.November,  2016), 3.50632),
                    new Datum(new Date(27, Month.November,  2017), 3.63666),
                    new Datum(new Date(26, Month.November,  2018), 3.74723),
                    new Datum(new Date(25, Month.November,  2019), 3.83988),
                    new Datum(new Date(25, Month.November,  2021), 4.00508),
                    new Datum(new Date(25, Month.November,  2024), 4.16042),
                    new Datum(new Date(26, Month.November,  2029), 4.15577),
                    new Datum(new Date(27, Month.November,  2034), 4.04933),
                    new Datum(new Date(25, Month.November,  2039), 3.95217),
                    new Datum(new Date(25, Month.November,  2049), 3.80932),
                    new Datum(new Date(25, Month.November,  2059), 3.80849),
                    new Datum(new Date(25, Month.November,  2069), 3.72677),
                    new Datum(new Date(27, Month.November,  2079), 3.63082)
                };
                int nominalDataLength = 30 - 1;

                List <Date>   nomD = new List <Date>();
                List <double> nomR = new List <double>();

                for (int i = 0; i < nominalDataLength; i++)
                {
                    nomD.Add(nominalData[i].date);
                    nomR.Add(nominalData[i].rate / 100.0);
                }
                YieldTermStructure nominal = new InterpolatedZeroCurve <Linear>(nomD, nomR, dcNominal);

                nominalUK.linkTo(nominal);

                // now build the zero inflation curve
                observationLag                   = new Period(2, TimeUnit.Months);
                contractObservationLag           = new Period(3, TimeUnit.Months);
                contractObservationInterpolation = InterpolationType.Flat;

                Datum[] zciisData =
                {
                    new Datum(new Date(25, Month.November, 2010),  3.0495),
                    new Datum(new Date(25, Month.November, 2011),    2.93),
                    new Datum(new Date(26, Month.November, 2012),  2.9795),
                    new Datum(new Date(25, Month.November, 2013),   3.029),
                    new Datum(new Date(25, Month.November, 2014),  3.1425),
                    new Datum(new Date(25, Month.November, 2015),   3.211),
                    new Datum(new Date(25, Month.November, 2016),  3.2675),
                    new Datum(new Date(25, Month.November, 2017),  3.3625),
                    new Datum(new Date(25, Month.November, 2018),   3.405),
                    new Datum(new Date(25, Month.November, 2019),    3.48),
                    new Datum(new Date(25, Month.November, 2021),   3.576),
                    new Datum(new Date(25, Month.November, 2024),   3.649),
                    new Datum(new Date(26, Month.November, 2029),   3.751),
                    new Datum(new Date(27, Month.November, 2034), 3.77225),
                    new Datum(new Date(25, Month.November, 2039),    3.77),
                    new Datum(new Date(25, Month.November, 2049),   3.734),
                    new Datum(new Date(25, Month.November, 2059), 3.714)
                };
                zciisDataLength = 17;
                for (int i = 0; i < zciisDataLength; i++)
                {
                    zciisD.Add(zciisData[i].date);
                    zciisR.Add(zciisData[i].rate);
                }

                // now build the helpers ...
                List <BootstrapHelper <ZeroInflationTermStructure> > helpers = makeHelpers(zciisData, zciisDataLength, ii,
                                                                                           observationLag, calendar, convention, dcZCIIS);

                // we can use historical or first ZCIIS for this
                // we know historical is WAY off market-implied, so use market implied flat.
                double baseZeroRate = zciisData[0].rate / 100.0;
                PiecewiseZeroInflationCurve <Linear> pCPIts = new PiecewiseZeroInflationCurve <Linear>(
                    evaluationDate, calendar, dcZCIIS, observationLag, ii.frequency(), ii.interpolated(), baseZeroRate,
                    new Handle <YieldTermStructure>(nominalUK), helpers);

                pCPIts.recalculate();
                cpiUK.linkTo(pCPIts);

                // make sure that the index has the latest zero inflation term structure
                hcpi.linkTo(pCPIts);
            }
            // setup
            public CommonVars()
            {
                // data
                calendar       = new TARGET();
                settlementDays = 2;
                today          = calendar.adjust(Date.Today);
                Settings.Instance.setEvaluationDate(today);
                settlement         = calendar.advance(today, settlementDays, TimeUnit.Days);
                fixedLegConvention = BusinessDayConvention.Unadjusted;
                fixedLegFrequency  = Frequency.Annual;
                fixedLegDayCounter = new Thirty360(Thirty360.Thirty360Convention.European);
                bondSettlementDays = 3;
                bondDayCounter     = new ActualActual();
                bondConvention     = BusinessDayConvention.Following;
                bondRedemption     = 100.0;
                bmaFrequency       = Frequency.Quarterly;
                bmaConvention      = BusinessDayConvention.Following;
                bmaDayCounter      = new ActualActual();

                deposits = depositData.Length;
                fras     = fraData.Length;
                swaps    = swapData.Length;
                bonds    = bondData.Length;
                bmas     = bmaData.Length;

                // market elements
                rates     = new List <SimpleQuote>(deposits + swaps);
                fraRates  = new List <SimpleQuote>(fras);
                prices    = new List <SimpleQuote>(bonds);
                fractions = new List <SimpleQuote>(bmas);
                for (int i = 0; i < deposits; i++)
                {
                    rates.Add(new SimpleQuote(depositData[i].rate / 100));
                }
                for (int i = 0; i < swaps; i++)
                {
                    rates.Add(new SimpleQuote(swapData[i].rate / 100));
                }
                for (int i = 0; i < fras; i++)
                {
                    fraRates.Add(new SimpleQuote(fraData[i].rate / 100));
                }
                for (int i = 0; i < bonds; i++)
                {
                    prices.Add(new SimpleQuote(bondData[i].price));
                }
                for (int i = 0; i < bmas; i++)
                {
                    fractions.Add(new SimpleQuote(bmaData[i].rate / 100));
                }

                // rate helpers
                instruments = new List <RateHelper>(deposits + swaps);
                fraHelpers  = new List <RateHelper>(fras);
                bondHelpers = new List <RateHelper>(bonds);
                schedules   = new List <Schedule>(bonds);
                bmaHelpers  = new List <RateHelper>(bmas);

                IborIndex euribor6m = new Euribor6M();

                for (int i = 0; i < deposits; i++)
                {
                    Handle <Quote> r = new Handle <Quote>(rates[i]);
                    instruments.Add(new DepositRateHelper(r, new Period(depositData[i].n, depositData[i].units),
                                                          euribor6m.fixingDays(), calendar,
                                                          euribor6m.businessDayConvention(),
                                                          euribor6m.endOfMonth(),
                                                          euribor6m.dayCounter()));
                }
                for (int i = 0; i < swaps; i++)
                {
                    Handle <Quote> r = new Handle <Quote>(rates[i + deposits]);
                    instruments.Add(new SwapRateHelper(r, new Period(swapData[i].n, swapData[i].units), calendar,
                                                       fixedLegFrequency, fixedLegConvention, fixedLegDayCounter, euribor6m));
                }

                Euribor3M euribor3m = new Euribor3M();

                for (int i = 0; i < fras; i++)
                {
                    Handle <Quote> r = new Handle <Quote>(fraRates[i]);
                    fraHelpers.Add(new FraRateHelper(r, fraData[i].n, fraData[i].n + 3,
                                                     euribor3m.fixingDays(),
                                                     euribor3m.fixingCalendar(),
                                                     euribor3m.businessDayConvention(),
                                                     euribor3m.endOfMonth(),
                                                     euribor3m.dayCounter()));
                }

                for (int i = 0; i < bonds; i++)
                {
                    Handle <Quote> p        = new Handle <Quote>(prices[i]);
                    Date           maturity = calendar.advance(today, bondData[i].n, bondData[i].units);
                    Date           issue    = calendar.advance(maturity, -bondData[i].length, TimeUnit.Years);
                    List <double>  coupons  = new List <double>()
                    {
                        bondData[i].coupon / 100.0
                    };
                    schedules.Add(new Schedule(issue, maturity, new Period(bondData[i].frequency), calendar,
                                               bondConvention, bondConvention, DateGeneration.Rule.Backward, false));
                    bondHelpers.Add(new FixedRateBondHelper(p, bondSettlementDays, bondRedemption, schedules[i],
                                                            coupons, bondDayCounter, bondConvention, bondRedemption, issue));
                }
            }