// 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);
         }
예제 #2
0
        // Date calculations
        public override Date maturityDate(Date valueDate)
        {
            Calendar cal           = fixingCalendar();
            Date     fixingDate    = cal.advance(valueDate, -1, TimeUnit.Days);
            Date     nextWednesday = Utils.previousWednesday(fixingDate + 7);

            return(cal.advance(nextWednesday, 1, TimeUnit.Days));
        }
예제 #3
0
        /* Date calculations
         *
         *    See <https://www.theice.com/marketdata/reports/170>.
         */
        public override Date valueDate(Date fixingDate)
        {
            Utils.QL_REQUIRE(isValidFixingDate(fixingDate), () => "Fixing date " + fixingDate + " is not valid");

            // http://www.bba.org.uk/bba/jsp/polopoly.jsp?d=225&a=1412 :
            // In the case of EUR the Value Date shall be two TARGET
            // business days after the Fixing Date.
            return(target_.advance(fixingDate, fixingDays_, TimeUnit.Days));
        }
예제 #4
0
        public override Date valueDate(Date fixingDate)
        {
            if (!(isValidFixingDate(fixingDate)))
            {
                throw new ApplicationException("Fixing date " + fixingDate + " is not valid");
            }

            // http://www.bba.org.uk/bba/jsp/polopoly.jsp?d=225&a=1412 :
            // In the case of EUR the Value Date shall be two TARGET
            // business days after the Fixing Date.
            return(_target.advance(fixingDate, fixingDays_, TimeUnit.Days));
        }
예제 #5
0
        public SwaptionHelper(Period maturity,
                              Period length,
                              Handle <Quote> volatility,
                              IborIndex index,
                              Period fixedLegTenor,
                              DayCounter fixedLegDayCounter,
                              DayCounter floatingLegDayCounter,
                              Handle <YieldTermStructure> termStructure,
                              bool calibrateVolatility /*= false*/)
            : base(volatility, termStructure, calibrateVolatility)
        {
            Calendar calendar   = index.fixingCalendar();
            Period   indexTenor = index.tenor();
            int      fixingDays = index.fixingDays();

            Date exerciseDate = calendar.advance(termStructure.link.referenceDate(),
                                                 maturity,
                                                 index.businessDayConvention());
            Date startDate = calendar.advance(exerciseDate,
                                              fixingDays, TimeUnit.Days,
                                              index.businessDayConvention());
            Date endDate = calendar.advance(startDate, length,
                                            index.businessDayConvention());

            Schedule fixedSchedule = new Schedule(startDate, endDate, fixedLegTenor, calendar,
                                                  index.businessDayConvention(),
                                                  index.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, endDate, index.tenor(), calendar,
                                                  index.businessDayConvention(),
                                                  index.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);

            IPricingEngine swapEngine = new DiscountingSwapEngine(termStructure);

            VanillaSwap temp = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                               fixedSchedule, 0.0, fixedLegDayCounter,
                                               floatSchedule, index, 0.0, floatingLegDayCounter);

            temp.setPricingEngine(swapEngine);
            exerciseRate_ = temp.fairRate();
            swap_         = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0,
                                            fixedSchedule, exerciseRate_, fixedLegDayCounter,
                                            floatSchedule, index, 0.0, floatingLegDayCounter);
            swap_.setPricingEngine(swapEngine);

            Exercise exercise = new EuropeanExercise(exerciseDate);

            swaption_    = new Swaption(swap_, exercise);
            marketValue_ = blackPrice(volatility_.link.value());
        }
예제 #6
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();
        }
예제 #7
0
        public IborCoupon(Date paymentDate,
                          double nominal,
                          Date startDate,
                          Date endDate,
                          int fixingDays,
                          IborIndex iborIndex,
                          double gearing        = 1.0,
                          double spread         = 0.0,
                          Date refPeriodStart   = null,
                          Date refPeriodEnd     = null,
                          DayCounter dayCounter = null,
                          bool isInArrears      = false) :
            base(paymentDate, nominal, startDate, endDate, fixingDays, iborIndex, gearing, spread,
                 refPeriodStart, refPeriodEnd, dayCounter, isInArrears)
        {
            iborIndex_ = iborIndex;

            fixingDate_ = fixingDate();

            Calendar fixingCalendar  = index_.fixingCalendar();
            int      indexFixingDays = index_.fixingDays();

            fixingValueDate_ = fixingCalendar.advance(fixingDate_, indexFixingDays, TimeUnit.Days);

#if QL_USE_INDEXED_COUPON
            fixingEndDate_ = index_->maturityDate(fixingValueDate_);
#else
            if (isInArrears_)
            {
                fixingEndDate_ = index_.maturityDate(fixingValueDate_);
            }
            else
            {
                // par coupon approximation
                Date nextFixingDate = fixingCalendar.advance(accrualEndDate_, -fixingDays_, TimeUnit.Days);
                fixingEndDate_ = fixingCalendar.advance(nextFixingDate, indexFixingDays, TimeUnit.Days);
            }
#endif

            DayCounter dc = index_.dayCounter();
            spanningTime_ = dc.yearFraction(fixingValueDate_, fixingEndDate_);
            Utils.QL_REQUIRE(spanningTime_ > 0.0, () =>
                             "\n cannot calculate forward rate between " +
                             fixingValueDate_ + " and " + fixingEndDate_ +
                             ":\n non positive time (" + spanningTime_ +
                             ") using " + dc.name() + " daycounter");
        }
예제 #8
0
        public Swaption value()
        {
            Date     evaluationDate = Settings.evaluationDate();
            Calendar fixingCalendar = swapIndex_.fixingCalendar();

            fixingDate_ = fixingCalendar.advance(evaluationDate, optionTenor_, optionConvention_);

            if (exerciseDate_ == null)
            {
                exercise_ = new EuropeanExercise(fixingDate_);
            }
            else
            {
                if (exerciseDate_ <= fixingDate_)
                {
                    throw new ArgumentException(
                              "exercise date (" + exerciseDate_ + ") must be less " +
                              "than or equal to fixing date (" + fixingDate_ + ")");
                }
                exercise_ = new EuropeanExercise(exerciseDate_);
            }

            double usedStrike;

            if (strike_ == null)
            {
                // ATM on the forecasting curve
                if (!swapIndex_.forwardingTermStructure().empty())
                {
                    throw new ArgumentException(
                              "no forecasting term structure set to " + swapIndex_.name());
                }
                VanillaSwap temp =
                    swapIndex_.underlyingSwap(fixingDate_);
                temp.setPricingEngine(new DiscountingSwapEngine(
                                          swapIndex_.forwardingTermStructure()));
                usedStrike = temp.fairRate();
            }
            else
            {
                usedStrike = strike_.Value;
            }

            BusinessDayConvention bdc = swapIndex_.fixedLegConvention();

            underlyingSwap_ = new MakeVanillaSwap(swapIndex_.tenor(),
                                                  swapIndex_.iborIndex(),
                                                  usedStrike)
                              .withEffectiveDate(swapIndex_.valueDate(fixingDate_))
                              .withFixedLegCalendar(swapIndex_.fixingCalendar())
                              .withFixedLegDayCount(swapIndex_.dayCounter())
                              .withFixedLegConvention(bdc)
                              .withFixedLegTerminationDateConvention(bdc);

            Swaption swaption = new Swaption(underlyingSwap_, exercise_, delivery_);

            swaption.setPricingEngine(engine_);
            return(swaption);
        }
예제 #9
0
 //! the date at which discount = 1.0 and/or variance = 0.0
 public virtual Date referenceDate()
 {
     if (!updated_)
     {
         Date today = Settings.evaluationDate();
         referenceDate_ = calendar_.advance(today, settlementDays_, TimeUnit.Days);
         updated_       = true;
     }
     return(referenceDate_);
 }
예제 #10
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_);
        }
예제 #11
0
파일: Libor.cs 프로젝트: quant1729/qlnet
 public override Date maturityDate(Date valueDate)
 {
     // Where a deposit is made on the final business day of a
     // particular calendar month, the maturity of the deposit shall
     // be on the final business day of the month in which it matures
     // (not the corresponding date in the month of maturity). Or in
     // other words, in line with market convention, BBA LIBOR rates
     // are dealt on an end-end basis. For instance a one month
     // deposit for value 28th February would mature on 31st March,
     // not the 28th of March.
     return(jointCalendar_.advance(valueDate, tenor_, convention_, endOfMonth()));
 }
예제 #12
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_);
        }
예제 #13
0
        public FuturesRateHelper(Handle<Quote> price, Date immDate, int nMonths, Calendar calendar,
            BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter,
            Handle<Quote> convexityAdjustment)
            : base(price)
        {
            convAdj_ = convexityAdjustment;

            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_);

            convAdj_.registerWith(update);
        }
예제 #14
0
        public BasisSwap value()
        {
            Date startDate;

            if (effectiveDate_ != null)
            {
                startDate = effectiveDate_;
            }
            else
            {
                int  fixingDays    = iborIndex1_.fixingDays();
                Date referenceDate = Settings.evaluationDate();
                Date spotDate      = float1Calendar_.advance(referenceDate, new Period(fixingDays, TimeUnit.Days));
                startDate = spotDate + forwardStart_;
            }

            Date endDate;

            if (terminationDate_ != null)
            {
                endDate = terminationDate_;
            }
            else
            {
                endDate = startDate + swapTenor_;
            }


            Schedule float1Schedule = new Schedule(startDate, endDate,
                                                   float1Tenor_, float1Calendar_,
                                                   float1Convention_, float1TerminationDateConvention_,
                                                   float1Rule_, float1EndOfMonth_,
                                                   float1FirstDate_, float1NextToLastDate_);

            Schedule float2Schedule = new Schedule(startDate, endDate,
                                                   float2Tenor_, float2Calendar_,
                                                   float2Convention_, float2TerminationDateConvention_,
                                                   float2Rule_, float2EndOfMonth_,
                                                   float2FirstDate_, float2NextToLastDate_);


            BasisSwap swap = new BasisSwap(type_, nominal_,
                                           float1Schedule, iborIndex1_, float1Spread_, float1DayCount_,
                                           float2Schedule, iborIndex2_, float2Spread_, float2DayCount_);

            swap.setPricingEngine(engine_);
            return(swap);
        }
예제 #15
0
        public FuturesRateHelper(double price, Date immDate, IborIndex i, 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;

            Calendar cal = i.fixingCalendar();

            latestDate_   = cal.advance(immDate, i.tenor(), i.businessDayConvention());
            yearFraction_ = i.dayCounter().yearFraction(earliestDate_, latestDate_);
        }
예제 #16
0
        public TermStructure(int settlementDays, Calendar cal, DayCounter dc)
        {
            moving_         = true;
            calendar_       = cal;
            updated_        = false;
            settlementDays_ = settlementDays;
            dayCounter_     = dc;

            // observe evaluationDate
            Settings.registerWith(update);

            // verify immediately if calendar and settlementDays are ok
            Date today = Settings.evaluationDate();

            referenceDate_ = calendar_.advance(today, settlementDays_, TimeUnit.Days);
        }
예제 #17
0
        public static AmortizingFixedRateBond makeAmortizingFixedBond(Date startDate,
                                                                      Period bondLength,
                                                                      DayCounter dCounter,
                                                                      Frequency payFrequency,
                                                                      double amount,
                                                                      double rate,
                                                                      Calendar calendar)
        {
            AmortizingFixedRateBond bond;
            Date endDate = calendar.advance(startDate, bondLength);

            Schedule schedule = new Schedule(startDate, endDate, bondLength, calendar, BusinessDayConvention.Unadjusted,
                                             BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);

            bond = new AmortizingFixedRateBond(0, calendar, amount, startDate, bondLength, payFrequency, rate, dCounter);

            return(bond);
        }
예제 #18
0
        public static AmortizingFixedRateBond makeAmortizingFixedBond( Date startDate, 
                                                                     Period bondLength, 
                                                                     DayCounter dCounter, 
                                                                     Frequency payFrequency, 
                                                                     double amount, 
                                                                     double rate,
                                                                     Calendar calendar)
        {
            AmortizingFixedRateBond bond;
             Date endDate = calendar.advance(startDate,bondLength);

             Schedule schedule = new Schedule(startDate,endDate,bondLength,calendar,BusinessDayConvention.Unadjusted,
                                          BusinessDayConvention.Unadjusted,DateGeneration.Rule.Backward,false);

             bond = new AmortizingFixedRateBond(0, calendar, amount, startDate, bondLength, payFrequency, rate, dCounter);

             return bond;
        }
예제 #19
0
        public FuturesRateHelper(Handle <Quote> price, Date immDate, int nMonths, Calendar calendar,
                                 BusinessDayConvention convention, bool endOfMonth, DayCounter dayCounter,
                                 Handle <Quote> convexityAdjustment)
            : base(price)
        {
            convAdj_ = convexityAdjustment;

            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_);

            convAdj_.registerWith(update);
        }
예제 #20
0
        public static MBSFixedRateBond makeMBSFixedBond(Date startDate,
                                                        Period bondLength,
                                                        Period originalLength,
                                                        DayCounter dCounter,
                                                        Frequency payFrequency,
                                                        double amount,
                                                        double WACrate,
                                                        double PassThroughRate,
                                                        PSACurve psaCurve,
                                                        Calendar calendar)
        {
            MBSFixedRateBond bond;
            Date             endDate = calendar.advance(startDate, bondLength);

            Schedule schedule = new Schedule(startDate, endDate, bondLength, calendar, BusinessDayConvention.Unadjusted,
                                             BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);

            bond = new MBSFixedRateBond(0, calendar, amount, startDate, bondLength, originalLength, payFrequency, WACrate, PassThroughRate, dCounter, psaCurve);

            return(bond);
        }
예제 #21
0
        public override void initialize(FloatingRateCoupon coupon)
        {
            coupon_ = coupon as RangeAccrualFloatersCoupon;
            Utils.QL_REQUIRE(coupon_ != null, () => "range-accrual coupon required");
            gearing_ = coupon_.gearing();
            spread_  = coupon_.spread();

            Date paymentDate = coupon_.date();

            IborIndex index = coupon_.index() as IborIndex;

            Utils.QL_REQUIRE(index != null, () => "invalid index");
            Handle <YieldTermStructure> rateCurve = index.forwardingTermStructure();

            discount_       = rateCurve.link.discount(paymentDate);
            accrualFactor_  = coupon_.accrualPeriod();
            spreadLegValue_ = spread_ * accrualFactor_ * discount_;

            startTime_        = coupon_.startTime();
            endTime_          = coupon_.endTime();
            observationTimes_ = coupon_.observationTimes();
            lowerTrigger_     = coupon_.lowerTrigger();
            upperTrigger_     = coupon_.upperTrigger();
            observationsNo_   = coupon_.observationsNo();

            List <Date> observationDates = coupon_.observationsSchedule().dates();

            Utils.QL_REQUIRE(observationDates.Count == observationsNo_ + 2, () => "incompatible size of initialValues vector");
            initialValues_ = new InitializedList <double>(observationDates.Count, 0.0);

            Calendar calendar = index.fixingCalendar();

            for (int i = 0; i < observationDates.Count; i++)
            {
                initialValues_[i] = index.fixing(
                    calendar.advance(observationDates[i], -coupon_.fixingDays, TimeUnit.Days));
            }
        }
예제 #22
0
        protected override void initializeDates()
        {
            earliestDate_ = calendar_.advance(evaluationDate_, new Period(settlementDays_, TimeUnit.Days),
                                              BusinessDayConvention.Following);

            Date maturity = earliestDate_ + tenor_;

            // dummy BMA index with curve/swap arguments
            BMAIndex clonedIndex = new BMAIndex(termStructureHandle_);

            Schedule bmaSchedule = new MakeSchedule().from(earliestDate_).to(maturity)
                                   .withTenor(bmaPeriod_)
                                   .withCalendar(bmaIndex_.fixingCalendar())
                                   .withConvention(bmaConvention_)
                                   .backwards()
                                   .value();

            Schedule liborSchedule = new MakeSchedule().from(earliestDate_).to(maturity)
                                     .withTenor(iborIndex_.tenor())
                                     .withCalendar(iborIndex_.fixingCalendar())
                                     .withConvention(iborIndex_.businessDayConvention())
                                     .endOfMonth(iborIndex_.endOfMonth())
                                     .backwards()
                                     .value();

            swap_ = new BMASwap(BMASwap.Type.Payer, 100.0, liborSchedule, 0.75,             // arbitrary
                                0.0, iborIndex_, iborIndex_.dayCounter(), bmaSchedule, clonedIndex, bmaDayCount_);
            swap_.setPricingEngine(new DiscountingSwapEngine(iborIndex_.forwardingTermStructure()));

            Date d             = calendar_.adjust(swap_.maturityDate(), BusinessDayConvention.Following);
            int  w             = d.weekday();
            Date nextWednesday = (w >= 4) ? d + new Period((11 - w), TimeUnit.Days) :
                                 d + new Period((4 - w), TimeUnit.Days);

            latestDate_ = clonedIndex.valueDate(clonedIndex.fixingCalendar().adjust(nextWednesday));
        }
예제 #23
0
            // setup
            public CommonVars()
            {
                startYears = 1;
                length = 5;
                type = VanillaSwap.Type.Payer;
                nominal = 1000.0;
                settlementDays = 2;
                fixedConvention = BusinessDayConvention.Unadjusted;
                floatingConvention = BusinessDayConvention.ModifiedFollowing;
                fixedFrequency = Frequency.Annual;
                floatingFrequency = Frequency.Semiannual;
                fixedDayCount = new Thirty360();

                termStructure = new RelinkableHandle<YieldTermStructure>();
                termStructure.linkTo(Utilities.flatRate(new Date(19, Month.February, 2002), 0.04875825, new Actual365Fixed()));

                index = new Euribor6M(termStructure);
                calendar = index.fixingCalendar();
                today = calendar.adjust(Date.Today);
                settlement = calendar.advance(today, settlementDays, TimeUnit.Days);
            }
        public OvernightIndexedSwap value()
        {
            Calendar calendar = overnightIndex_.fixingCalendar();
            Date     startDate;

            if (effectiveDate_ != null)
            {
                startDate = effectiveDate_;
            }
            else
            {
                Date referenceDate = Settings.evaluationDate();
                Date spotDate      = calendar.advance(referenceDate,
                                                      new Period(fixingDays_, TimeUnit.Days));
                startDate = spotDate + forwardStart_;
            }

            Date endDate;

            if (terminationDate_ != null)
            {
                endDate = terminationDate_;
            }
            else
            {
                if (endOfMonth_)
                {
                    endDate = calendar.advance(startDate, swapTenor_,
                                               BusinessDayConvention.ModifiedFollowing,
                                               endOfMonth_);
                }
                else
                {
                    endDate = startDate + swapTenor_;
                }
            }

            Schedule schedule = new Schedule(startDate, endDate,
                                             new Period(paymentFrequency_),
                                             calendar,
                                             BusinessDayConvention.ModifiedFollowing,
                                             BusinessDayConvention.ModifiedFollowing,
                                             rule_,
                                             endOfMonth_);

            double?usedFixedRate = fixedRate_;

            if (fixedRate_ == null)
            {
                if (overnightIndex_.forwardingTermStructure().empty())
                {
                    throw new ApplicationException("null term structure set to this instance of "
                                                   + overnightIndex_.name());
                }

                OvernightIndexedSwap temp = new OvernightIndexedSwap(type_, nominal_,
                                                                     schedule,
                                                                     0.0, // fixed rate
                                                                     fixedDayCount_,
                                                                     overnightIndex_, overnightSpread_);

                // ATM on the forecasting curve
                //bool includeSettlementDateFlows = false;
                temp.setPricingEngine(new DiscountingSwapEngine(
                                          overnightIndex_.forwardingTermStructure()));
                usedFixedRate = temp.fairRate();
            }

            OvernightIndexedSwap ois = new OvernightIndexedSwap(type_, nominal_,
                                                                schedule,
                                                                usedFixedRate.Value, fixedDayCount_,
                                                                overnightIndex_, overnightSpread_);

            ois.setPricingEngine(engine_);
            return(ois);
        }
예제 #25
0
 // setup
 public CommonVars()
 {
     nominals = new List<double>() { 100 };
     frequency = Frequency.Semiannual;
     index = (IborIndex)new Euribor6M(termStructure);
     calendar = index.fixingCalendar();
     convention = BusinessDayConvention.ModifiedFollowing;
     Date today = calendar.adjust(Date.Today);
     Settings.setEvaluationDate(today);
     int settlementDays = 2;
     fixingDays = 2;
     settlement = calendar.advance(today, settlementDays, TimeUnit.Days);
     termStructure.linkTo(Utilities.flatRate(settlement, 0.05,
                                   new ActualActual(ActualActual.Convention.ISDA)));
 }
예제 #26
0
        protected override void performCalculations()
        {
            Calendar calendar   = index_.fixingCalendar();
            int      fixingDays = index_.fixingDays();

            Date exerciseDate = exerciseDate_;

            if (exerciseDate == null)
            {
                exerciseDate = calendar.advance(termStructure_.link.referenceDate(),
                                                maturity_,
                                                index_.businessDayConvention());
            }

            Date startDate = calendar.advance(exerciseDate,
                                              fixingDays, TimeUnit.Days,
                                              index_.businessDayConvention());

            Date endDate = endDate_;

            if (endDate == null)
            {
                endDate = calendar.advance(startDate, length_,
                                           index_.businessDayConvention());
            }

            Schedule fixedSchedule = new Schedule(startDate, endDate, fixedLegTenor_, calendar,
                                                  index_.businessDayConvention(),
                                                  index_.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startDate, endDate, index_.tenor(), calendar,
                                                  index_.businessDayConvention(),
                                                  index_.businessDayConvention(),
                                                  DateGeneration.Rule.Forward, false);

            IPricingEngine swapEngine = new DiscountingSwapEngine(termStructure_, false);

            VanillaSwap.Type type = VanillaSwap.Type.Receiver;

            VanillaSwap temp = new VanillaSwap(VanillaSwap.Type.Receiver, nominal_,
                                               fixedSchedule, 0.0, fixedLegDayCounter_,
                                               floatSchedule, index_, 0.0, floatingLegDayCounter_);

            temp.setPricingEngine(swapEngine);
            double forward = temp.fairRate();

            if (!strike_.HasValue)
            {
                exerciseRate_ = forward;
            }
            else
            {
                exerciseRate_ = strike_.Value;
                type          = strike_ <= forward ? VanillaSwap.Type.Receiver : VanillaSwap.Type.Payer;
                // ensure that calibration instrument is out of the money
            }
            swap_ = new VanillaSwap(type, nominal_,
                                    fixedSchedule, exerciseRate_, fixedLegDayCounter_,
                                    floatSchedule, index_, 0.0, floatingLegDayCounter_);
            swap_.setPricingEngine(swapEngine);

            Exercise exercise = new EuropeanExercise(exerciseDate);

            swaption_ = new Swaption(swap_, exercise);

            base.performCalculations();
        }
예제 #27
0
        // creator
        public override List <CashFlow> value()
        {
            if (couponRates_.Count == 0)
            {
                throw new ArgumentException("no coupon rates given");
            }
            if (notionals_.Count == 0)
            {
                throw new ArgumentException("no nominals given");
            }

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

            Calendar schCalendar = schedule_.calendar();

            // first period might be short or long
            Date         start = schedule_[0], end = schedule_[1];
            Date         paymentDate  = calendar_.adjust(end, paymentAdjustment_);
            Date         exCouponDate = null;
            InterestRate rate         = couponRates_[0];
            double       nominal      = notionals_[0];

            if (exCouponPeriod_ != null)
            {
                exCouponDate = exCouponCalendar_.advance(paymentDate,
                                                         -exCouponPeriod_,
                                                         exCouponAdjustment_,
                                                         exCouponEndOfMonth_);
            }
            if (schedule_.isRegular(1))
            {
                if (!(firstPeriodDC_ == null || firstPeriodDC_ == rate.dayCounter()))
                {
                    throw new ArgumentException("regular first coupon does not allow a first-period day count");
                }
                leg.Add(new FixedRateCoupon(nominal, paymentDate, rate, start, end, start, end, exCouponDate));
            }
            else
            {
                Date refer = end - schedule_.tenor();
                refer = schCalendar.adjust(refer, schedule_.businessDayConvention());
                InterestRate r = new InterestRate(rate.rate(),
                                                  (firstPeriodDC_ == null || firstPeriodDC_.empty()) ? rate.dayCounter() : firstPeriodDC_,
                                                  rate.compounding(), rate.frequency());
                leg.Add(new FixedRateCoupon(nominal, paymentDate, r, start, end, refer, end, exCouponDate));
            }

            // regular periods
            for (int i = 2; i < schedule_.Count - 1; ++i)
            {
                start       = end; end = schedule_[i];
                paymentDate = calendar_.adjust(end, paymentAdjustment_);
                if (exCouponPeriod_ != null)
                {
                    exCouponDate = exCouponCalendar_.advance(paymentDate,
                                                             -exCouponPeriod_,
                                                             exCouponAdjustment_,
                                                             exCouponEndOfMonth_);
                }
                if ((i - 1) < couponRates_.Count)
                {
                    rate = couponRates_[i - 1];
                }
                else
                {
                    rate = couponRates_.Last();
                }
                if ((i - 1) < notionals_.Count)
                {
                    nominal = notionals_[i - 1];
                }
                else
                {
                    nominal = notionals_.Last();
                }

                leg.Add(new FixedRateCoupon(nominal, paymentDate, rate, start, end, start, end, exCouponDate));
            }

            if (schedule_.Count > 2)
            {
                // last period might be short or long
                int N = schedule_.Count;
                start       = end; end = schedule_[N - 1];
                paymentDate = calendar_.adjust(end, paymentAdjustment_);
                if (exCouponPeriod_ != null)
                {
                    exCouponDate = exCouponCalendar_.advance(paymentDate,
                                                             -exCouponPeriod_,
                                                             exCouponAdjustment_,
                                                             exCouponEndOfMonth_);
                }

                if ((N - 2) < couponRates_.Count)
                {
                    rate = couponRates_[N - 2];
                }
                else
                {
                    rate = couponRates_.Last();
                }
                if ((N - 2) < notionals_.Count)
                {
                    nominal = notionals_[N - 2];
                }
                else
                {
                    nominal = notionals_.Last();
                }

                if (schedule_.isRegular(N - 1))
                {
                    leg.Add(new FixedRateCoupon(nominal, paymentDate, rate, start, end, start, end, exCouponDate));
                }
                else
                {
                    Date refer = start + schedule_.tenor();
                    refer = schCalendar.adjust(refer, schedule_.businessDayConvention());
                    leg.Add(new FixedRateCoupon(nominal, paymentDate, rate, start, end, start, refer, exCouponDate));
                }
            }
            return(leg);
        }
예제 #28
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);
        }
        public TermStructure(int settlementDays, Calendar cal, DayCounter dc)
        {
            moving_ = true;
            calendar_ = cal;
            updated_ = false;
            settlementDays_ = settlementDays;
            dayCounter_ = dc;

            // observe evaluationDate
            Settings.registerWith(update);

            // verify immediately if calendar and settlementDays are ok
            Date today = Settings.evaluationDate();
            referenceDate_ = calendar_.advance(today, settlementDays_, TimeUnit.Days);
        }
예제 #30
0
            // cleanup
            // SavedSettings backup;
            // setup
            public CommonVars()
            {
                calendar = new TARGET();
                settlementDays = 2;
                Date today = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);
                Date settlement = calendar.advance(today, settlementDays, TimeUnit.Days);

                int deposits = depositData.Length,
                swaps = swapData.Length;

                var instruments = new List<RateHelper>(deposits + swaps);
                for (int i = 0; i < deposits; i++)
                {
                   instruments.Add(new DepositRateHelper(depositData[i].rate / 100, new Period(depositData[i].n, depositData[i].units),
                               settlementDays, calendar, BusinessDayConvention.ModifiedFollowing, true, new Actual360()));
                }

                IborIndex index = new IborIndex("dummy", new Period(6, TimeUnit.Months), settlementDays, new Currency(),
                                            calendar, BusinessDayConvention.ModifiedFollowing, false, new Actual360());
                for (int i = 0; i < swaps; ++i)
                {
                   instruments.Add(new SwapRateHelper(swapData[i].rate / 100, new Period(swapData[i].n, swapData[i].units),
                               calendar, Frequency.Annual, BusinessDayConvention.Unadjusted, new Thirty360(), index));
                }
                termStructure = new PiecewiseYieldCurve<Discount, LogLinear>(settlement, instruments, new Actual360());
                dummyTermStructure = new PiecewiseYieldCurve<Discount, LogLinear>(settlement, instruments, new Actual360());
            }
예제 #31
0
      public static MBSFixedRateBond makeMBSFixedBond(Date startDate,
                                                      Period bondLength,
                                                      Period originalLength,
                                                      DayCounter dCounter,
                                                      Frequency payFrequency,
                                                      double amount,
                                                      double WACrate,
                                                      double PassThroughRate,
                                                      PSACurve psaCurve,
                                                      Calendar calendar)
      {
         MBSFixedRateBond bond;
         Date endDate = calendar.advance(startDate, bondLength);

         Schedule schedule = new Schedule(startDate, endDate, bondLength, calendar, BusinessDayConvention.Unadjusted,
                                          BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);

         bond = new MBSFixedRateBond(0, calendar, amount, startDate, bondLength, originalLength , payFrequency, WACrate, PassThroughRate, dCounter, psaCurve);

         return bond;

      }
예제 #32
0
파일: MakeOIS.cs 프로젝트: igitur/qlnet
        public OvernightIndexedSwap value()
        {
            Date startDate;

            if (effectiveDate_ != null)
            {
                startDate = effectiveDate_;
            }
            else
            {
                Date refDate = Settings.evaluationDate();
                // if the evaluation date is not a business day
                // then move to the next business day
                refDate = calendar_.adjust(refDate);
                Date spotDate = calendar_.advance(refDate, new Period(settlementDays_, TimeUnit.Days));
                startDate = spotDate + forwardStart_;
                if (forwardStart_.length() < 0)
                {
                    startDate = calendar_.adjust(startDate, BusinessDayConvention.Preceding);
                }
                else
                {
                    startDate = calendar_.adjust(startDate, BusinessDayConvention.Following);
                }
            }

            // OIS end of month default
            bool usedEndOfMonth =
                isDefaultEOM_ ? calendar_.isEndOfMonth(startDate) : endOfMonth_;

            Date endDate = terminationDate_;

            if (endDate == null)
            {
                if (usedEndOfMonth)
                {
                    endDate = calendar_.advance(startDate,
                                                swapTenor_,
                                                BusinessDayConvention.ModifiedFollowing,
                                                usedEndOfMonth);
                }
                else
                {
                    endDate = startDate + swapTenor_;
                }
            }



            Schedule schedule = new Schedule(startDate, endDate,
                                             new Period(paymentFrequency_),
                                             calendar_,
                                             BusinessDayConvention.ModifiedFollowing,
                                             BusinessDayConvention.ModifiedFollowing,
                                             rule_,
                                             usedEndOfMonth);

            double?usedFixedRate = fixedRate_;

            if (fixedRate_ == null)
            {
                OvernightIndexedSwap temp = new OvernightIndexedSwap(type_, nominal_,
                                                                     schedule,
                                                                     0.0, // fixed rate
                                                                     fixedDayCount_,
                                                                     overnightIndex_, overnightSpread_);
                if (engine_ == null)
                {
                    Handle <YieldTermStructure> disc = overnightIndex_.forwardingTermStructure();
                    Utils.QL_REQUIRE(!disc.empty(), () => "null term structure set to this instance of " +
                                     overnightIndex_.name());
                    bool           includeSettlementDateFlows = false;
                    IPricingEngine engine = new DiscountingSwapEngine(disc, includeSettlementDateFlows);
                    temp.setPricingEngine(engine);
                }
                else
                {
                    temp.setPricingEngine(engine_);
                }

                usedFixedRate = temp.fairRate();
            }

            OvernightIndexedSwap ois = new OvernightIndexedSwap(type_, nominal_,
                                                                schedule,
                                                                usedFixedRate.Value, fixedDayCount_,
                                                                overnightIndex_, overnightSpread_);

            if (engine_ == null)
            {
                Handle <YieldTermStructure> disc          = overnightIndex_.forwardingTermStructure();
                bool           includeSettlementDateFlows = false;
                IPricingEngine engine = new DiscountingSwapEngine(disc, includeSettlementDateFlows);
                ois.setPricingEngine(engine);
            }
            else
            {
                ois.setPricingEngine(engine_);
            }

            return(ois);
        }
예제 #33
0
파일: T_Swaps.cs 프로젝트: Yenyenx/qlnet
            public CommonVars()
            {
                type = VanillaSwap.Type.Payer;
                settlementDays = 2;
                nominal = 100.0;
                fixedConvention = BusinessDayConvention.Unadjusted;
                floatingConvention = BusinessDayConvention.ModifiedFollowing;
                fixedFrequency = Frequency.Annual;
                floatingFrequency = Frequency.Semiannual;
                fixedDayCount = new Thirty360();

                index = new Euribor(new Period(floatingFrequency), termStructure);

                calendar = index.fixingCalendar();
                today = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);
                settlement = calendar.advance(today, settlementDays, TimeUnit.Days);

                termStructure.linkTo(Utilities.flatRate(settlement, 0.05, new Actual365Fixed()));
            }
예제 #34
0
            public CommonVars()
            {
                settlementDays = 2;
                nominal = 1000000.0;
                fixedConvention = BusinessDayConvention.Unadjusted;

                fixedFrequency = Frequency.Annual;
                fixedDayCount = new Thirty360();

                index =new Euribor6M(termStructure);
                floatingConvention = index.businessDayConvention();
                floatingTenor = index.tenor();
                calendar = index.fixingCalendar();
                today = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);
                settlement = calendar.advance(today, settlementDays, TimeUnit.Days);

                termStructure.linkTo(Utilities.flatRate(settlement, 0.05, new Actual365Fixed()));
            }
예제 #35
0
 public CommonVars()
 {
     type = OvernightIndexedSwap.Type.Payer;
     settlementDays = 2;
     nominal = 100.0;
     fixedEoniaConvention = BusinessDayConvention.ModifiedFollowing;
     floatingEoniaConvention = BusinessDayConvention.ModifiedFollowing;
     fixedEoniaPeriod = new Period(1, TimeUnit.Years);
     floatingEoniaPeriod = new Period(1, TimeUnit.Years);
     fixedEoniaDayCount = new Actual360();
     eoniaIndex = new Eonia(eoniaTermStructure);
     fixedSwapConvention = BusinessDayConvention.ModifiedFollowing;
     fixedSwapFrequency = Frequency.Annual;
     fixedSwapDayCount = new Thirty360();
     swapIndex = (IborIndex) new Euribor3M(swapTermStructure);
     calendar = eoniaIndex.fixingCalendar();
     today = new Date(5, Month.February, 2009);
     //today = calendar.adjust(Date::todaysDate());
     Settings.setEvaluationDate(today);
     settlement = calendar.advance(today,new Period(settlementDays,TimeUnit.Days),BusinessDayConvention.Following);
     eoniaTermStructure.linkTo(Utilities.flatRate(settlement, 0.05,new Actual365Fixed()));
 }
예제 #36
0
            // setup
            public CommonVars()
            {
                // option variables
                nominals = new List<double>{1000000};
                frequency = Frequency.Annual;
                // usual setup
                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);
                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)
                .withConvention(BusinessDayConvention.ModifiedFollowing)
                .withCalendar(new UnitedKingdom())
                .withTenor(new Period(1,TimeUnit.Months)).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);
            }
        public virtual Date settlementDate()
        {
            Date d = calendar_.advance(Settings.evaluationDate(), settlementDays_, TimeUnit.Days);

            return(Date.Max(d, valueDate_));
        }