Example #1
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 #2
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 #3
0
        public void BuildDates(QLNet.Calendar calendar, QLNet.DayCounter dc)
        {
            _dates.Resize(_tenors.Count);
            Date today = Settings.evaluationDate();

            for (int i = 0; i < _tenors.Count; i++)
            {
                if (_tenors[i].units() == TimeUnit.Days)
                {
                    _dates[i] = calendar.adjust(today + _tenors[i]);
                }
                else
                {
                    _dates[i] = calendar.advance(today, _tenors[i], BusinessDayConvention.Following, true);
                }
            }
            QLNet.Utils.QL_REQUIRE(_dates.Count == _tenors.Count, () => "Date/Tenor mismatch");

            // Build times
            _times.Resize(_dates.Count);
            for (int i = 0; i < _dates.Count; i++)
            {
                _times[i] = dc.yearFraction(today, _dates[i]);
            }

            _timeGrid = new TimeGrid(_times, _times.Count);

            // Log the date grid
            //log();
        }
Example #4
0
 // setup
 public CommonVars()
 {
     calendar = new TARGET();
     today    = calendar.adjust(Date.Today);
     Settings.setEvaluationDate(today);
     faceAmount = 1000000.0;
 }
         // setup
         public CommonVars()
         {
            // force garbage collection
            // garbage collection in .NET is rather weird and we do need when we run several tests in a row
            GC.Collect();

            // data
            calendar = new TARGET();
            settlementDays = 2;
            today = new Date(9, Month.June, 2009);
            compounding = Compounding.Continuous;
            dayCount = new Actual360();
            settlementDate = calendar.advance(today, settlementDays, TimeUnit.Days);

            Settings.setEvaluationDate(today);

            int[] ts = new int[] { 13, 41, 75, 165, 256, 345, 524, 703 };
            double[] r = new double[] { 0.035, 0.033, 0.034, 0.034, 0.036, 0.037, 0.039, 0.040 };
            List<double> rates = new List<double>() { 0.035 };
            List<Date> dates = new List<Date>() { settlementDate };
            for (int i = 0; i < 8; ++i)
            {
               dates.Add(calendar.advance(today, ts[i], TimeUnit.Days));
               rates.Add(r[i]);
            }
            termStructure = new InterpolatedZeroCurve<Linear>(dates, rates, dayCount);
         }
Example #6
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 #7
0
        public BlackConstantVol(Date referenceDate, Calendar cal, Handle<Quote> volatility, DayCounter dc)
            : base(referenceDate, cal, BusinessDayConvention.Following, dc)
        {
            volatility_ = volatility;

            volatility_.registerWith(update);
        }
Example #8
0
        public BlackConstantVol(int settlementDays, Calendar cal, Handle<Quote> volatility, DayCounter dc)
            : base(settlementDays, cal, BusinessDayConvention.Following, dc)
        {
            volatility_ = volatility;

            volatility_.registerWith(update);
        }
         // todo
         // cleanup
         // SavedSettings backup;

         // setup
         public CommonVars()
         {
            calendar = new TARGET();
            today = calendar.adjust(Date.Today);
            Settings.setEvaluationDate(today);
            faceAmount = 1000000.0;
         }
 public CallableBondConstantVolatility(int settlementDays, Calendar calendar, double volatility, DayCounter dayCounter)
    :base(settlementDays, calendar)
 {
    volatility_ = new Handle<Quote>(new SimpleQuote(volatility));
    dayCounter_ = dayCounter;
    maxBondTenor_ = new Period(100,TimeUnit.Years);
 }
      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 #12
0
        public static void CheckHolidayList(IEnumerable<Date> expected, Calendar calendar, int year)
        {
            IEnumerable<Date> calculated = Calendar.holidayList(calendar, new Date(1, Month.January, year), new Date(31, Month.December, year), false);

            int error = 0;

            StringBuilder sb = new StringBuilder();
            sb.Append("Holidays do not match\n");

            foreach (Date date in expected)
            {
                if (!calculated.Contains(date))
                {
                    sb.Append("  >> Holiday expected but not calculated: ")
                        .Append(date.DayOfWeek)
                        .Append(", ")
                        .Append(date)
                        .Append('\n');

                    error++;
                }
            }

            foreach (Date date in calculated)
            {
                if (!expected.Contains(date))
                {
                    sb.Append("  >> Holiday calculated but not expected: ").Append(date.DayOfWeek).Append(", ").Append(date).Append('\n');
                    error++;
                }
            }

            Assert.IsFalse(error > 0, sb.ToString());
        }
Example #13
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 #14
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);
        }
Example #16
0
 public CPILegBase withExCouponPeriod(Period period, Calendar cal, BusinessDayConvention convention, bool endOfMonth = false)
 {
     exCouponPeriod_ = period;
       exCouponCalendar_ = cal;
       exCouponAdjustment_ = convention;
       exCouponEndOfMonth_ = endOfMonth;
       return this;
 }
Example #17
0
        public LocalConstantVol(int settlementDays, Calendar calendar, Handle<Quote> volatility, DayCounter dayCounter)
            : base(settlementDays,calendar)
        {
            volatility_ = volatility;
            dayCounter_ = dayCounter;

            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 #19
0
 public DailyTenorLibor(string familyName, int settlementDays, Currency currency, Calendar financialCenterCalendar, DayCounter dayCounter, Handle<YieldTermStructure> h)
     : base(familyName, new Period(1, TimeUnit.Days), settlementDays, currency, new JointCalendar(new UnitedKingdom(UnitedKingdom.Market.Exchange), financialCenterCalendar, JointCalendar.JointCalendarRule.JoinHolidays), Utils.liborConvention(new Period(1, TimeUnit.Days)), Utils.liborEOM(new Period(1, TimeUnit.Days)), dayCounter, h)
 {
     if (!(currency != new EURCurrency()))
     {
         throw new ApplicationException("for EUR Libor dedicated EurLibor constructor must be used");
     }
 }
Example #20
0
 public EURLibor(Period tenor, Handle<YieldTermStructure> h)
     : base("EURLibor", tenor, 2, new EURCurrency(), new JointCalendar(new UnitedKingdom(UnitedKingdom.Market.Exchange), new TARGET(),
         JointCalendar.JointCalendarRule.JoinHolidays),
         Utils.eurliborConvention(tenor), Utils.eurliborEOM(tenor), new Actual360(), h) {
     target_ = new TARGET();
     if (!(this.tenor().units() != TimeUnit.Days))
         throw new ApplicationException("for daily tenors (" + this.tenor() + ") dedicated DailyTenor constructor must be used");
 }
Example #21
0
 //public ZeroCouponBond(int settlementDays, Calendar calendar, double faceAmount, Date maturityDate,
 //               BusinessDayConvention paymentConvention = Following,
 //               double redemption = 100.0,
 //               Date issueDate = Date());
 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);
 }
Example #22
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();
 }
 public CallableBondConstantVolatility(int settlementDays, Calendar calendar, Handle<Quote> volatility,DayCounter dayCounter)
     :base(settlementDays, calendar)
 {
    volatility_ = volatility;
    dayCounter_ = dayCounter;
    maxBondTenor_ = new Period(100,TimeUnit.Years);
    volatility_.registerWith(update);
 }
Example #24
0
 //! initialize with a fixed reference date
 public TermStructure(Date referenceDate,Calendar calendar = null,DayCounter dc = null)
 {
     moving_ = false;
      updated_ = true;
      calendar_ = calendar;
      referenceDate_ = referenceDate;
      settlementDays_= null;
      dayCounter_ = dc;
 }
 //! 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));
 }
 // 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));
 }
Example #27
0
      //! calculate the reference date based on the global evaluation date
      public TermStructure(int settlementDays, Calendar cal, DayCounter dc = null)
      {
         moving_ = true;
         updated_ = false;
         calendar_ = cal;
         settlementDays_ = settlementDays;
         dayCounter_ = dc;

         Settings.registerWith(update);
      }
Example #28
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 #29
0
 public yoyInflationLeg(Schedule schedule,Calendar cal,
                        YoYInflationIndex index,
                        Period observationLag)
 {
    schedule_ = schedule;
    index_ = index;
    observationLag_ = observationLag;
    paymentAdjustment_ = BusinessDayConvention.ModifiedFollowing;
    paymentCalendar_ = cal;
 }
Example #30
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 #31
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 #32
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 #33
0
        public static object TestCalendars(string CalendarName, DateTime StartDate, DateTime EndDate)
        {
            Type tt = CommonTypes.Utils.FindType(CalendarName, null);

            ql.Calendar cal = (ql.Calendar)Activator.CreateInstance(tt);

            int nDays = (int)(EndDate - StartDate).TotalDays;

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

            for (int i = 0; i < nDays; ++i)
            {
                DateTime date = StartDate.AddDays(i);
                ret[i, 0] = date.ToOADate();
                ret[i, 1] = cal.isHoliday(new ql.Date(date));
            }

            return(ret);
        }
Example #34
0
 protected HazardRateStructure(int settlementDays, Calendar cal, DayCounter dc = null,
                               List <Handle <Quote> > jumps = null, List <Date> jumpDates = null)
     : base(settlementDays, cal, dc, jumps, jumpDates)
 {
 }
Example #35
0
 public ZeroYieldStructure(Date referenceDate, Calendar calendar = null, DayCounter dc         = null,
                           List <Handle <Quote> > jumps          = null, List <Date> jumpDates = null)
     : base(referenceDate, calendar, dc, jumps, jumpDates)
 {
 }
Example #36
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, index.fixingDays()),
                                                                 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, index.fixingDays()),
                                                                      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 #37
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 - 1;

            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_ != null && gearings_.Count > n)
            {
                throw new ApplicationException("too many gearings (" + gearings_.Count +
                                               "), only " + n + " required");
            }

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

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

            if (floors_ != null && 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 #38
0
        public DateGrid(string grid, QLNet.Calendar gridCalendar, DayCounter dayCounter)
        {
            if (grid == "ALPHA")
            {
                // ALPHA is
                // quarterly up to 10Y,
                // annual up to 30Y,
                // quinquennial up to 100Y
                for (int i = 1; i < 40; i++)
                { // 3M up to 39*3M = 117M = 9Y9M
                    Period p = new Period(i * 3, TimeUnit.Months);
                    p.normalize();
                    _tenors.Add(p);
                }
                for (int i = 10; i < 30; i++) // 10Y up to 29Y
                {
                    _tenors.Add(new Period(i, TimeUnit.Years));
                }

                for (int i = 30; i < 105; i += 5) // 30Y up to 100Y
                {
                    _tenors.Add(new Period(i, TimeUnit.Years));
                }
            }
            else if (grid == "BETA")
            {
                // BETA is
                // monthly up to 10Y,
                // quarterly up to 20Y,
                // annually up to 50Y,
                // quinquennial up to 100Y
                for (int i = 1; i < 119; i++)
                {
                    Period p = new Period(i, TimeUnit.Months);
                    p.normalize();
                    _tenors.Add(p);
                }
                for (int i = 40; i < 80; i++)
                {
                    Period p = new Period(3 * i, TimeUnit.Months);
                    p.normalize();
                    _tenors.Add(p);
                }
                for (int i = 20; i < 50; i++)
                {
                    _tenors.Add(new Period(i, TimeUnit.Years));
                }
                for (int i = 50; i <= 100; i += 5)
                {
                    _tenors.Add(new Period(i, TimeUnit.Years));
                }
            }
            else
            { // uniform grid of format "numPillars,spacing" (e.g. 40,1M)
                List <string> tokens = new List <string>();
                //boost::split(tokens, grid, boost::is_any_of(","));
                if (tokens.Count <= 2)
                {
                    // uniform grid of format "numPillars,spacing" (e.g. 40,1M)
                    Period gridTenor = new Period(1, TimeUnit.Years); // default
                    int    gridSize  = 1;                             // atoi(tokens[0].c_str());
                    QLNet.Utils.QL_REQUIRE(gridSize > 0, () => "Invalid DateGrid string " + grid);
                    if (tokens.Count == 2)
                    {
                        //gridTenor = data::parsePeriod(tokens[1]);
                    }
                    if (gridTenor == new Period(1, TimeUnit.Days))
                    {
                        // we have a daily grid. Period and Calendar are not consistant with
                        // working & actual days, so we set the tenor grid
                        Date today = Settings.evaluationDate();
                        Date d     = today;
                        for (int i = 0; i < gridSize; i++)
                        {
                            d = gridCalendar.advance(d, new Period(1, TimeUnit.Days), BusinessDayConvention.Following); // next working day
                            int n = d - today;
                            _tenors.Add(new Period(n, TimeUnit.Days));
                        }
                    }
                    else
                    {
                        for (int i = 0; i < gridSize; i++)
                        {
                            _tenors.Add((i + 1) * gridTenor);
                        }
                    }
                }
                else
                {
                    // New style : 1D,2D,1W,2W,3Y,5Y,....
                    for (int i = 0; i < tokens.Count; i++)
                    {
                        //_tenors.Add(parsePeriod(tokens[i]));
                    }
                }
            }
            BuildDates(gridCalendar, dayCounter);
        }
Example #39
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);
        }
Example #40
0
 protected HazardRateStructure(Date referenceDate, Calendar cal = null, DayCounter dc         = null,
                               List <Handle <Quote> > jumps     = null, List <Date> jumpDates = null)
     : base(referenceDate, cal, dc, jumps, jumpDates)
 {
 }
Example #41
0
        //! constructor for amortizing or non-amortizing bonds.

        /*! Redemptions and maturity are calculated from the coupon
         *      data, if available.  Therefore, redemptions must not be
         *      included in the passed cash flows.
         */
        //public Bond(int settlementDays, Calendar calendar, Date issueDate = Date(), List<CashFlow> coupons = Leg());
        public Bond(int settlementDays, Calendar calendar, Date issueDate)
            : this(settlementDays, calendar, issueDate, new List <CashFlow>())
        {
        }
Example #42
0
 public ZeroYieldStructure(int settlementDays, Calendar calendar, DayCounter dc = null,
                           List <Handle <Quote> > jumps = null, List <Date> jumpDates = null)
     : base(settlementDays, calendar, dc, jumps, jumpDates)
 {
 }
Example #43
0
        //! old constructor for non amortizing bonds.

        /*! \warning The last passed cash flow must be the bond
         *                       redemption. No other cash flow can have a date
         *                       later than the redemption date.
         */
        public Bond(int settlementDays, Calendar calendar, double faceAmount, Date maturityDate, Date issueDate)
            : this(settlementDays, calendar, faceAmount, maturityDate, issueDate, new List <CashFlow>())
        {
        }
Example #44
0
        public override void calculate()
        {
            DayCounter rfdc   = process_.riskFreeRate().link.dayCounter();
            DayCounter divdc  = process_.dividendYield().link.dayCounter();
            DayCounter voldc  = process_.blackVolatility().link.dayCounter();
            Calendar   volcal = process_.blackVolatility().link.calendar();

            double s0 = process_.stateVariable().link.value();

            Utils.QL_REQUIRE(s0 > 0.0, () => "negative or null underlying given");
            double v             = process_.blackVolatility().link.blackVol(arguments_.exercise.lastDate(), s0);
            Date   maturityDate  = arguments_.exercise.lastDate();
            double r             = process_.riskFreeRate().link.zeroRate(maturityDate, rfdc, Compounding.Continuous, Frequency.NoFrequency).value();
            double q             = process_.dividendYield().link.zeroRate(maturityDate, divdc, Compounding.Continuous, Frequency.NoFrequency).value();
            Date   referenceDate = process_.riskFreeRate().link.referenceDate();

            // binomial trees with constant coefficient
            Handle <YieldTermStructure>    flatRiskFree  = new Handle <YieldTermStructure>(new FlatForward(referenceDate, r, rfdc));
            Handle <YieldTermStructure>    flatDividends = new Handle <YieldTermStructure>(new FlatForward(referenceDate, q, divdc));
            Handle <BlackVolTermStructure> flatVol       = new Handle <BlackVolTermStructure>(new BlackConstantVol(referenceDate, volcal, v, voldc));

            StrikedTypePayoff payoff = arguments_.payoff as StrikedTypePayoff;

            Utils.QL_REQUIRE(payoff != null, () => "non-striked payoff given");

            double maturity = rfdc.yearFraction(referenceDate, maturityDate);

            StochasticProcess1D bs = new GeneralizedBlackScholesProcess(process_.stateVariable(),
                                                                        flatDividends, flatRiskFree, flatVol);

            // correct timesteps to ensure a (local) minimum, using Boyle and Lau
            // approach. See Journal of Derivatives, 1/1994,
            // "Bumping up against the barrier with the binomial method"
            // Note: this approach works only for CoxRossRubinstein lattices, so
            // is disabled if T is not a CoxRossRubinstein or derived from it.
            int optimum_steps = timeSteps_;

            if (maxTimeSteps_ > timeSteps_ && s0 > 0 && arguments_.barrier > 0) // boost::is_base_of<CoxRossRubinstein, T>::value &&
            {
                double divisor;
                if (s0 > arguments_.barrier)
                {
                    divisor = Math.Pow(Math.Log(s0 / arguments_.barrier.Value), 2);
                }
                else
                {
                    divisor = Math.Pow(Math.Log(arguments_.barrier.Value / s0), 2);
                }
                if (!Utils.close(divisor, 0))
                {
                    for (int i = 1; i < timeSteps_; ++i)
                    {
                        int optimum = (int)((i * i * v * v * maturity) / divisor);
                        if (timeSteps_ < optimum)
                        {
                            optimum_steps = optimum;
                            break; // found first minimum with iterations>=timesteps
                        }
                    }
                }

                if (optimum_steps > maxTimeSteps_)
                {
                    optimum_steps = maxTimeSteps_; // too high, limit
                }
            }

            TimeGrid grid = new TimeGrid(maturity, optimum_steps);

            ITree tree = getTree_(bs, maturity, optimum_steps, payoff.strike());

            BlackScholesLattice <ITree> lattice = new BlackScholesLattice <ITree>(tree, r, maturity, optimum_steps);

            DiscretizedAsset option = getAsset_(arguments_, process_, grid);

            option.initialize(lattice, maturity);

            // Partial derivatives calculated from various points in the
            // binomial tree
            // (see J.C.Hull, "Options, Futures and other derivatives", 6th edition, pp 397/398)

            // Rollback to third-last step, and get underlying prices (s2) &
            // option values (p2) at this point
            option.rollback(grid[2]);
            Vector va2 = new Vector(option.values());

            Utils.QL_REQUIRE(va2.size() == 3, () => "Expect 3 nodes in grid at second step");
            double p2u = va2[2];                   // up
            double p2m = va2[1];                   // mid
            double p2d = va2[0];                   // down (low)
            double s2u = lattice.underlying(2, 2); // up price
            double s2m = lattice.underlying(2, 1); // middle price
            double s2d = lattice.underlying(2, 0); // down (low) price

            // calculate gamma by taking the first derivate of the two deltas
            double delta2u = (p2u - p2m) / (s2u - s2m);
            double delta2d = (p2m - p2d) / (s2m - s2d);
            double gamma   = (delta2u - delta2d) / ((s2u - s2d) / 2);

            // Rollback to second-last step, and get option values (p1) at
            // this point
            option.rollback(grid[1]);
            Vector va = new Vector(option.values());

            Utils.QL_REQUIRE(va.size() == 2, () => "Expect 2 nodes in grid at first step");
            double p1u = va[1];
            double p1d = va[0];
            double s1u = lattice.underlying(1, 1); // up (high) price
            double s1d = lattice.underlying(1, 0); // down (low) price

            double delta = (p1u - p1d) / (s1u - s1d);

            // Finally, rollback to t=0
            option.rollback(0.0);
            double p0 = option.presentValue();

            // Store results
            results_.value = p0;
            results_.delta = delta;
            results_.gamma = gamma;
            // theta can be approximated by calculating the numerical derivative
            // between mid value at third-last step and at t0. The underlying price
            // is the same, only time varies.
            results_.theta = (p2m - p0) / grid[2];
        }