void SimpleRangeAccrualRateETI::initializeImpl(const TimeGrid& timeGrid,
				const boost::shared_ptr<YieldTermStructure>& discountCurve,
				const boost::shared_ptr<PathGeneratorFactory>& pathGenFactory)
{
	referenceCalculation_->initialize(timeGrid,discountCurve,pathGenFactory);
	this->payoffDateInfo_->initialize(timeGrid,discountCurve,pathGenFactory);

	this->rangeNum_ = simpleRangeRateList_.size();
	this->assetNum_ = pathGenFactory->numAssets();
	
	Date today = Settings::instance().evaluationDate();
	
	DayCounter dayCounter = Actual365Fixed();

	double fixingStartTime = dayCounter.yearFraction( today , calculationStartDate_ );
	Size fixingStartPosition = timeGrid.closestIndex(fixingStartTime);

	double fixingEndTime = dayCounter.yearFraction( today , calculationEndDate_ );
	Size fixingEndPosition = timeGrid.closestIndex(fixingEndTime);

	Size fixingSize = fixingEndPosition - fixingStartPosition;
	
	this->fixingDatePositions_ = std::valarray<Size>(fixingSize);

	for ( Size position = 0 ; fixingSize ; position++ )
	{
		fixingDatePositions_[position] = fixingStartPosition + position;
	}

	for ( Size rng = 0 ; this->rangeNum_ ; rng++ )
	{
		simpleRangeRateList_[rng]->initialize(timeGrid,discountCurve,pathGenFactory);
	}
	
}
示例#2
0
    HestonSLVMCModel::HestonSLVMCModel(
        const Handle<LocalVolTermStructure>& localVol,
        const Handle<HestonModel>& hestonModel,
        const boost::shared_ptr<BrownianGeneratorFactory>& brownianGeneratorFactory,
        const Date& endDate,
        Size timeStepsPerYear,
        Size nBins,
        Size calibrationPaths,
        const std::vector<Date>& mandatoryDates)
    : localVol_(localVol),
      hestonModel_(hestonModel),
      brownianGeneratorFactory_(brownianGeneratorFactory),
      endDate_(endDate),
      nBins_(nBins),
      calibrationPaths_(calibrationPaths) {

        registerWith(localVol_);
        registerWith(hestonModel_);

        const DayCounter dc = hestonModel_->process()->riskFreeRate()->dayCounter();
        const Date refDate = hestonModel_->process()->riskFreeRate()->referenceDate();

        std::vector<Time> gridTimes;
        gridTimes.reserve(mandatoryDates.size()+1);
        for (Size i=0; i < mandatoryDates.size(); ++i) {
            gridTimes.push_back(dc.yearFraction(refDate, mandatoryDates[i]));

        }
        gridTimes.push_back(dc.yearFraction(refDate, endDate));

        timeGrid_ = boost::make_shared<TimeGrid>(gridTimes.begin(), gridTimes.end(),
                std::max(Size(2), Size(gridTimes.back()*timeStepsPerYear)));
    }
    DiscretizedCallableFixedRateBond::DiscretizedCallableFixedRateBond(
                                          const CallableBond::arguments& args,
                                          const Date& referenceDate,
                                          const DayCounter& dayCounter)
    : arguments_(args) {

        redemptionTime_ = dayCounter.yearFraction(referenceDate,
                                                  args.redemptionDate);

        couponTimes_.resize(args.couponDates.size());
        for (Size i=0; i<couponTimes_.size(); ++i)
            couponTimes_[i] =
                dayCounter.yearFraction(referenceDate,
                                        args.couponDates[i]);

        callabilityTimes_.resize(args.callabilityDates.size());
        for (Size i=0; i<callabilityTimes_.size(); ++i)
            callabilityTimes_[i] =
                dayCounter.yearFraction(referenceDate,
                                        args.callabilityDates[i]);

        // similar to the tree swaption engine, we collapse similar coupon
        // and exercise dates to avoid mispricing. Delete if unnecessary.

        for (Size i=0; i<callabilityTimes_.size(); i++) {
            Time exerciseTime = callabilityTimes_[i];
            for (Size j=0; j<couponTimes_.size(); j++) {
                if (withinNextWeek(exerciseTime, couponTimes_[j]))
                    couponTimes_[j] = exerciseTime;
            }
        }
    }
示例#4
0
void DayCounterTest::testIntraday() {
#ifdef QL_HIGH_RESOLUTION_DATE

    BOOST_TEST_MESSAGE("Testing intraday behavior of day counter ...");

    const Date d1(12, February, 2015);
    const Date d2(14, February, 2015, 12, 34, 17, 1, 230298);

    const Time tol = 100*QL_EPSILON;

    const DayCounter dayCounters[]
        = { ActualActual(), Actual365Fixed(), Actual360() };

    for (Size i=0; i < LENGTH(dayCounters); ++i) {
        const DayCounter dc = dayCounters[i];

        const Time expected = ((12*60 + 34)*60 + 17 + 0.231298)
                             * dc.yearFraction(d1, d1+1)/86400
                             + dc.yearFraction(d1, d1+2);

        BOOST_CHECK_MESSAGE(
            std::fabs(dc.yearFraction(d1, d2) - expected) < tol,
            "can not reproduce result for day counter " << dc.name());

        BOOST_CHECK_MESSAGE(
            std::fabs(dc.yearFraction(d2, d1) + expected) < tol,
            "can not reproduce result for day counter " << dc.name());
    }
#endif
}
DiscretizedSwaption::DiscretizedSwaption(const Swaption::arguments& args,
        const Date& referenceDate,
        const DayCounter& dayCounter)
    : DiscretizedOption(boost::shared_ptr<DiscretizedAsset>(),
                        args.exercise->type(),
                        std::vector<Time>()),
      arguments_(args),exerciseIndex_(new std::vector<std::pair<bool, std::pair<Size, Real> > >) {

    exerciseTimes_.resize(arguments_.exercise->dates().size());
    for (Size i=0; i<exerciseTimes_.size(); ++i)
        exerciseTimes_[i] =
            dayCounter.yearFraction(referenceDate,
                                    arguments_.exercise->date(i));

    // Date adjustments can get time vectors out of synch.
    // Here, we try and collapse similar dates which could cause
    // a mispricing.
    for (Size i=0; i<arguments_.exercise->dates().size(); i++) {
        Date exerciseDate = arguments_.exercise->date(i);
        for (Size j=0; j<arguments_.fixedPayDates.size(); j++) {
            if (withinNextWeek(exerciseDate,
                               arguments_.fixedPayDates[j])
                    // coupons in the future are dealt with below
                    && arguments_.fixedResetDates[j] < referenceDate)
                arguments_.fixedPayDates[j] = exerciseDate;
        }
        for (Size j=0; j<arguments_.fixedResetDates.size(); j++) {
            if (withinPreviousWeek(exerciseDate,
                                   arguments_.fixedResetDates[j]))
                arguments_.fixedResetDates[j] = exerciseDate;
        }
        for (Size j=0; j<arguments_.floatingResetDates.size(); j++) {
            if (withinPreviousWeek(exerciseDate,
                                   arguments_.floatingResetDates[j]))
                arguments_.floatingResetDates[j] = exerciseDate;
        }
    }

    Time lastFixedPayment =
        dayCounter.yearFraction(referenceDate,
                                arguments_.fixedPayDates.back());
    Time lastFloatingPayment =
        dayCounter.yearFraction(referenceDate,
                                arguments_.floatingPayDates.back());
    lastPayment_ = std::max(lastFixedPayment,lastFloatingPayment);

    underlying_ = boost::shared_ptr<DiscretizedAsset>(
                      new DiscretizedSwap(arguments_,
                                          referenceDate,
                                          dayCounter));
    underlyingAsSwap_ = boost::dynamic_pointer_cast<DiscretizedSwap>(underlying_);
    QL_REQUIRE(underlyingAsSwap_ != nullptr, "Underlying must be a DiscreteSwap object.");
}
    void VarianceGammaEngine::calculate() const {

        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,
            "not an European Option");

        boost::shared_ptr<StrikedTypePayoff> payoff =
            boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
        QL_REQUIRE(payoff, "non-striked payoff given");

        DiscountFactor dividendDiscount =
            process_->dividendYield()->discount(
            arguments_.exercise->lastDate());
        DiscountFactor riskFreeDiscount =
            process_->riskFreeRate()->discount(arguments_.exercise->lastDate());

        DayCounter rfdc  = process_->riskFreeRate()->dayCounter();
        Time t = rfdc.yearFraction(process_->riskFreeRate()->referenceDate(),
            arguments_.exercise->lastDate());
    
        Integrand f(payoff,
            process_->x0(),
            t, riskFreeDiscount, dividendDiscount,
            process_->sigma(), process_->nu(), process_->theta());

        SimpsonIntegral integrator(1e-4, 5000);

        Real infinity = 15.0 * std::sqrt(process_->nu() * t);
        results_.value = integrator(f, 0, infinity);
    }
示例#7
0
void SwingOptionTest::testExtOUJumpVanillaEngine() {

    BOOST_TEST_MESSAGE("Testing finite difference pricer for the Kluge model...");

    SavedSettings backup;

    boost::shared_ptr<ExtOUWithJumpsProcess> jumpProcess = createKlugeProcess();

    const Date today = Date::todaysDate();
    Settings::instance().evaluationDate() = today;

    const DayCounter dc = ActualActual();
    const Date maturityDate = today + Period(12, Months);
    const Time maturity = dc.yearFraction(today, maturityDate);

    const Rate irRate = 0.1;
    boost::shared_ptr<YieldTermStructure> rTS(flatRate(today, irRate, dc));
    boost::shared_ptr<StrikedTypePayoff> payoff(
                                     new PlainVanillaPayoff(Option::Call, 30));
    boost::shared_ptr<Exercise> exercise(new EuropeanExercise(maturityDate));

    boost::shared_ptr<PricingEngine> engine(
                 new FdExtOUJumpVanillaEngine(jumpProcess, rTS, 25, 200, 50));

    VanillaOption option(payoff, exercise);
    option.setPricingEngine(engine);
    const Real fdNPV = option.NPV();

    const Size steps = 100;
    const Size nrTrails = 200000;
    TimeGrid grid(maturity, steps);

    typedef PseudoRandom::rsg_type rsg_type;
    typedef MultiPathGenerator<rsg_type>::sample_type sample_type;
    rsg_type rsg = PseudoRandom::make_sequence_generator(
                    jumpProcess->factors()*(grid.size()-1), BigNatural(421));

    GeneralStatistics npv;
    MultiPathGenerator<rsg_type> generator(jumpProcess, grid, rsg, false);

    for (Size n=0; n < nrTrails; ++n) {
        sample_type path = generator.next();

        const Real x = path.value[0].back();
        const Real y = path.value[1].back();

        const Real cashflow = (*payoff)(std::exp(x+y));
        npv.add(cashflow*rTS->discount(maturity));
    }

    const Real mcNPV = npv.mean();
    const Real mcError = npv.errorEstimate();

    if ( std::fabs(fdNPV - mcNPV) > 3.0*mcError) {
        BOOST_ERROR("Failed to reproduce FD and MC prices"
                    << "\n    FD NPV: " << fdNPV
                    << "\n    MC NPV: " << mcNPV
                    << " +/- " << mcError);
    }
}
	Generalized_HullWhite::Generalized_HullWhite(const Handle<YieldTermStructure>& termStructure,
		std::vector<Date> dates,
		std::vector<Real> sigma,
		Real a,
		Real fxVol,
		Real fxCorr)
		: Vasicek(termStructure->forwardRate(0.0, 0.0, Continuous, NoFrequency), a, 0.0, sigma[0], 0.0), a0_(a),
		TermStructureConsistentModel(termStructure), fxVol_(fxVol), fxCorr_(fxCorr)
	{
		a_ = NullParameter();
		b_ = NullParameter();
		lambda_ = NullParameter();

		DayCounter dc = termStructure->dayCounter();

		//volperiods_.push_back(0.0);
		for (Size i=0; i<dates.size()-1; i++)
			volperiods_.push_back(dc.yearFraction(Settings::instance().evaluationDate(), dates[i]));
		sigma_ = PiecewiseConstantParameter(volperiods_, PositiveConstraint());

		for (Size i=0; i< sigma_.size(); i++)
			sigma_.setParam(i, sigma[i]);


		generateArguments();
		registerWith(termStructure);
	}
示例#9
0
    Rate MultiplicativePriceSeasonality::seasonalityCorrection(Rate rate,
                                                               const Date& atDate,
                                                               const DayCounter& dc,
                                                               const Date& curveBaseDate,
                                                               const bool isZeroRate) const {
        // need _two_ corrections in order to get: seasonality = factor[atDate-seasonalityBase] / factor[reference-seasonalityBase]
        // i.e. for ZERO inflation rates you have the true fixing at the curve base so this factor must be normalized to one
        //      for YoY inflation rates your reference point is the year before

        Real factorAt = this->seasonalityFactor(atDate);

        //Getting seasonality correction for either ZC or YoY
        Rate f;
        if (isZeroRate) {
            Rate factorBase = this->seasonalityFactor(curveBaseDate);
            Real seasonalityAt = factorAt / factorBase;
            Time timeFromCurveBase = dc.yearFraction(curveBaseDate, atDate);
            f = std::pow(seasonalityAt, 1/timeFromCurveBase);
        }
        else {
            Rate factor1Ybefore = this->seasonalityFactor(atDate - Period(1,Years));
            f = factorAt / factor1Ybefore;
        }

        return (rate + 1)*f - 1;
    }
FdmDividendHandler::FdmDividendHandler(
    const DividendSchedule& schedule,
    const boost::shared_ptr<FdmMesher>& mesher,
    const Date& referenceDate,
    const DayCounter& dayCounter,
    Size equityDirection)
    : x_(mesher->layout()->dim()[equityDirection]),
      mesher_(mesher),
      equityDirection_(equityDirection) {

    dividends_.reserve(schedule.size());
    dividendDates_.reserve(schedule.size());
    dividendTimes_.reserve(schedule.size());
    for (DividendSchedule::const_iterator iter=schedule.begin();
            iter!=schedule.end(); ++iter) {
        dividends_.push_back((*iter)->amount());
        dividendDates_.push_back((*iter)->date());
        dividendTimes_.push_back(
            dayCounter.yearFraction(referenceDate,(*iter)->date()));
    }

    Array tmp = mesher_->locations(equityDirection);
    Size spacing = mesher_->layout()->spacing()[equityDirection];
    for (Size i = 0; i < x_.size(); ++i) {
        x_[i] = std::exp(tmp[i*spacing]);
    }
}
示例#11
0
    FuturesRateHelper::FuturesRateHelper(const Handle<Quote>& price,
                                         const Date& immDate,
                                         const Date& endDate,
                                         const DayCounter& dayCounter,
                                         const Handle<Quote>& convAdj)
    : RateHelper(price), convAdj_(convAdj) {
        QL_REQUIRE(IMM::isIMMdate(immDate, false),
                   immDate << " is not a valid IMM date");
        earliestDate_ = immDate;

        if (endDate==Date()) {
            latestDate_ = IMM::nextDate(immDate, false);
            latestDate_ = IMM::nextDate(latestDate_, false);
            latestDate_ = IMM::nextDate(latestDate_, false);
        } else { 
            QL_REQUIRE(endDate>immDate,
                       "end date (" << endDate <<
                       ") must be greater than IMM start date (" <<
                       immDate << ")");
            latestDate_ = endDate;
        }

        yearFraction_ = dayCounter.yearFraction(earliestDate_, latestDate_);

        registerWith(convAdj_);
    }
示例#12
0
 FuturesRateHelper::FuturesRateHelper(Real price,
                                      const Date& iborStartDate,
                                      Natural lengthInMonths,
                                      const Calendar& calendar,
                                      BusinessDayConvention convention,
                                      bool endOfMonth,
                                      const DayCounter& dayCounter,
                                      Rate convAdj,
                                      Futures::Type type)
 : RateHelper(price),
   convAdj_(Handle<Quote>(shared_ptr<Quote>(new SimpleQuote(convAdj))))
 {
     switch (type) {
       case Futures::IMM:
         QL_REQUIRE(IMM::isIMMdate(iborStartDate, false),
             iborStartDate << " is not a valid IMM date");
         break;
       case Futures::ASX:
         QL_REQUIRE(ASX::isASXdate(iborStartDate, false),
             iborStartDate << " is not a valid ASX date");
         break;
       default:
         QL_FAIL("unknown futures type (" << Integer(type) << ")");
     }
     earliestDate_ = iborStartDate;
     latestDate_ = calendar.advance(iborStartDate, lengthInMonths*Months,
                                    convention, endOfMonth);
     yearFraction_ = dayCounter.yearFraction(earliestDate_, latestDate_);
 }
示例#13
0
    void ForwardVanillaEngine<Engine>::getOriginalResults() const {

        DayCounter rfdc = process_->riskFreeRate()->dayCounter();
        DayCounter divdc = process_->dividendYield()->dayCounter();
        Time resetTime = rfdc.yearFraction(
                                     process_->riskFreeRate()->referenceDate(),
                                     this->arguments_.resetDate);
        DiscountFactor discQ = process_->dividendYield()->discount(
                                                  this->arguments_.resetDate);

        this->results_.value = discQ * originalResults_->value;
        // I need the strike derivative here ...
        if (originalResults_->delta != Null<Real>() &&
            originalResults_->strikeSensitivity != Null<Real>()) {
            this->results_.delta = discQ * (originalResults_->delta +
                  this->arguments_.moneyness * 
                        originalResults_->strikeSensitivity);
        }
        this->results_.gamma = 0.0;
        this->results_.theta = process_->dividendYield()->
            zeroRate(this->arguments_.resetDate, divdc, Continuous, NoFrequency)
            * this->results_.value;
        if (originalResults_->vega != Null<Real>())
            this->results_.vega  = discQ * originalResults_->vega;
        if (originalResults_->rho != Null<Real>())
            this->results_.rho   = discQ *  originalResults_->rho;
        if (originalResults_->dividendRho != Null<Real>()) {
            this->results_.dividendRho = - resetTime * this->results_.value
               + discQ * originalResults_->dividendRho;
        }
    }
示例#14
0
void DayCounterTest::testOne() {

    BOOST_MESSAGE("Testing 1/1 day counter...");

    Period p[] = { Period(3,Months), Period(6,Months), Period(1,Years) };
    Time expected[] = { 1.0, 1.0, 1.0 };
    Size n = sizeof(p)/sizeof(Period);

    // 1 years should be enough
    Date first(1,January,2004), last(31,December,2004);
    DayCounter dayCounter = OneDayCounter();

    for (Date start = first; start <= last; start++) {
        for (Size i=0; i<n; i++) {
            Date end = start + p[i];
            Time calculated = dayCounter.yearFraction(start,end);
            if (std::fabs(calculated-expected[i]) > 1.0e-12) {
                BOOST_FAIL("from " << start << " to " << end << ":\n"
                           << std::setprecision(12)
                           << "    calculated: " << calculated << "\n"
                           << "    expected:   " << expected[i]);
            }
        }
    }
}
void DefaultProbabilityCurveTest::testFlatHazardRate() {

    BOOST_TEST_MESSAGE("Testing flat hazard rate...");

    Real hazardRate = 0.0100;
    Handle<Quote> hazardRateQuote = Handle<Quote>(
                boost::shared_ptr<Quote>(new SimpleQuote(hazardRate)));
    DayCounter dayCounter = Actual360();
    Calendar calendar = TARGET();
    Size n = 20;

    double tolerance = 1.0e-10;
    Date today = Settings::instance().evaluationDate();
    Date startDate = today;
    Date endDate = startDate;

    FlatHazardRate flatHazardRate(today, hazardRateQuote, dayCounter);

    for(Size i=0; i<n; i++){
        endDate = calendar.advance(endDate, 1, Years);
        Time t = dayCounter.yearFraction(startDate, endDate);
        Probability probability = 1.0 - std::exp(-hazardRate * t);
        Probability computedProbability = flatHazardRate.defaultProbability(t);

        if (std::fabs(probability - computedProbability) > tolerance)
            BOOST_ERROR(
                "Failed to reproduce probability for flat hazard rate\n"
                << std::setprecision(10)
                << "    calculated probability: " << computedProbability << "\n"
                << "    expected probability:   " << probability);
    }
}
示例#16
0
    CmsSpreadRangeAccrualCoupon::CmsSpreadRangeAccrualCoupon(
                const Date& paymentDate,
                Real nominal,
				const boost::shared_ptr<SwapSpreadIndex>& index,
                const Date& startDate,                                  // S
                const Date& endDate,                                    // T
                Natural fixingDays,
                const DayCounter& dayCounter,
                Real gearing,
                Rate spread,
                const Date& refPeriodStart,
                const Date& refPeriodEnd,
                const boost::shared_ptr<Schedule>&  observationsSchedule,
                Real lowerTrigger,                                    // l
                Real upperTrigger                                     // u
        )
    : FloatingRateCoupon(paymentDate, nominal, startDate, endDate,
                         fixingDays, index, gearing, spread,
                         refPeriodStart, refPeriodEnd, dayCounter),
    observationsSchedule_(observationsSchedule),
    lowerTrigger_(lowerTrigger),
    upperTrigger_(upperTrigger){

        QL_REQUIRE(lowerTrigger_<upperTrigger,
                   "lowerTrigger_>=upperTrigger");
        QL_REQUIRE(observationsSchedule_->startDate()==startDate,
                   "incompatible start date");
        QL_REQUIRE(observationsSchedule_->endDate()==endDate,
                   "incompatible end date");

        observationDates_ = observationsSchedule_->dates();
        observationDates_.pop_back();                       //remove end date
        observationDates_.erase(observationDates_.begin()); //remove start date
        observationsNo_ = observationDates_.size();

        const Handle<YieldTermStructure>& rateCurve = index->swapIndex1()->forwardingTermStructure();
        Date referenceDate = rateCurve->referenceDate();

        startTime_ = dayCounter.yearFraction(referenceDate, startDate);
        endTime_ = dayCounter.yearFraction(referenceDate, endDate);
        for(Size i=0;i<observationsNo_;i++) {
            observationTimes_.push_back(
                dayCounter.yearFraction(referenceDate, observationDates_[i]));
        }

     }
示例#17
0
 boost::shared_ptr<path_pricer_type> pathPricer() const {
     Date referenceDate = model_->termStructure()->referenceDate();
     DayCounter dayCounter = model_->termStructure()->dayCounter();
     Time forwardMeasureTime =
         dayCounter.yearFraction(referenceDate,
                                 arguments_.endDates.back());
     return boost::shared_ptr<path_pricer_type>(
              new detail::HullWhiteCapFloorPricer(arguments_, model_,
                                                  forwardMeasureTime));
 }
示例#18
0
        TimeGrid timeGrid() const {

            Date referenceDate = model_->termStructure()->referenceDate();
            DayCounter dayCounter = model_->termStructure()->dayCounter();

            // only add future fixing times...
            std::vector<Time> times;
            for (Size i=0; i<arguments_.fixingDates.size(); i++) {
                if (arguments_.fixingDates[i] > referenceDate)
                    times.push_back(
                          dayCounter.yearFraction(referenceDate,
                                                  arguments_.fixingDates[i]));
            }
            // ...and maturity.
            times.push_back(
                        dayCounter.yearFraction(referenceDate,
                                                arguments_.endDates.back()));
            return TimeGrid(times.begin(), times.end());
        }
示例#19
0
    SubPeriodsCoupon::SubPeriodsCoupon(
                                    const Date& paymentDate,
                                    Real nominal,
                                    const boost::shared_ptr<IborIndex>& index,
                                    const Date& startDate,
                                    const Date& endDate,
                                    Natural fixingDays,
                                    const DayCounter& dayCounter,
                                    Real gearing,
                                    Rate couponSpread,
                                    Rate rateSpread,
                                    const Date& refPeriodStart,
                                    const Date& refPeriodEnd)
    : FloatingRateCoupon(paymentDate, nominal, startDate, endDate,
                         fixingDays, index, gearing, couponSpread,
                         refPeriodStart, refPeriodEnd, dayCounter),
      rateSpread_(rateSpread) {
        const Handle<YieldTermStructure>& rateCurve =
            index->forwardingTermStructure();
        const Date& referenceDate = rateCurve->referenceDate();

        observationsSchedule_ = boost::shared_ptr<Schedule>(new
            Schedule(startDate, endDate,
                     index->tenor(),
                     NullCalendar(),
                     Unadjusted,
                     Unadjusted,
                     DateGeneration::Forward,
                     false));

        observationDates_ = observationsSchedule_->dates();
        observationDates_.pop_back();                       //remove end date
        observations_ = observationDates_.size();

        startTime_ = dayCounter.yearFraction(referenceDate, startDate);
        endTime_ = dayCounter.yearFraction(referenceDate, endDate);

        for (Size i=0; i<observations_; ++i) {
            observationTimes_.push_back(
                dayCounter.yearFraction(referenceDate, observationDates_[i]));
        }
     }
    void TreeSwaptionEngine::calculate() const {

        QL_REQUIRE(arguments_.settlementType==Settlement::Physical,
                   "cash-settled swaptions not priced with tree engine");
        QL_REQUIRE(!model_.empty(), "no model specified");

        Date referenceDate;
        DayCounter dayCounter;

        boost::shared_ptr<TermStructureConsistentModel> tsmodel =
            boost::dynamic_pointer_cast<TermStructureConsistentModel>(*model_);
        if (tsmodel) {
            referenceDate = tsmodel->termStructure()->referenceDate();
            dayCounter = tsmodel->termStructure()->dayCounter();
        } else {
            referenceDate = termStructure_->referenceDate();
            dayCounter = termStructure_->dayCounter();
        }

        boost::shared_ptr<DiscretizedSwaption> swaption(new DiscretizedSwaption(arguments_, referenceDate, dayCounter));
        
        if (additionalResultCalculator_) {
            additionalResultCalculator_->setupDiscretizedAsset(swaption);
        }
        
        boost::shared_ptr<Lattice> lattice;

        if (lattice_) {
            lattice = lattice_;
        } else {
            std::vector<Time> times = swaption->mandatoryTimes();
            TimeGrid timeGrid(times.begin(), times.end(), timeSteps_);
            lattice = model_->tree(timeGrid, additionalResultCalculator_);
        }

        std::vector<Time> stoppingTimes(arguments_.exercise->dates().size());
        for (Size i=0; i<stoppingTimes.size(); ++i)
            stoppingTimes[i] =
                dayCounter.yearFraction(referenceDate,
                                        arguments_.exercise->date(i));

        swaption->initialize(lattice, stoppingTimes.back());

        Time nextExercise =
            *std::find_if(stoppingTimes.begin(),
                          stoppingTimes.end(),
                          std::bind2nd(std::greater_equal<Time>(), 0.0));
        swaption->rollback(nextExercise);
        results_.value = swaption->presentValue();
        if (additionalResultCalculator_) {
            additionalResultCalculator_->calculateAdditionalResults();
            results_.additionalResults = additionalResultCalculator_->additionalResults();
        }
    }
	FdmAutocallStepCondition::FdmAutocallStepCondition(
		const Date& exerciseDates,
		const Date& referenceDate,
		const DayCounter& dayCounter,
		const boost::shared_ptr<FdmMesher> & mesher,
		const boost::shared_ptr<FdmInnerValueCalculator> & calculator,
		const boost::shared_ptr<AutocallCondition> & condition)
		: mesher_(mesher), condition_(condition), calculator_(calculator) {
		exerciseTimes_.reserve(1);
		exerciseTimes_.push_back(dayCounter.yearFraction(referenceDate, exerciseDates));
	}
Time inflationYearFraction(Frequency f, bool indexIsInterpolated,
                           const DayCounter &dayCounter,
                           const Date &d1, const Date &d2) {

    Time t=0;
    if (indexIsInterpolated) {
        // N.B. we do not use linear interpolation between flat
        // fixing forecasts for forecasts.  This avoids awkwardnesses
        // when bootstrapping the inflation curve.
        t = dayCounter.yearFraction(d1, d2);
    } else {
        // I.e. fixing is constant for the whole inflation period.
        // Use the value for half way along the period.
        // But the inflation time is the time between period starts
        std::pair<Date,Date> limD1 = inflationPeriod(d1, f);
        std::pair<Date,Date> limD2 = inflationPeriod(d2, f);
        t = dayCounter.yearFraction(limD1.first, limD2.first);
    }

    return t;
}
 FdmAffineModelTermStructure::FdmAffineModelTermStructure(
     const Array& r,
     const Calendar& cal,
     const DayCounter& dayCounter,
     const Date& referenceDate,
     const Date& modelReferenceDate,
     const boost::shared_ptr<AffineModel>& model)
 : YieldTermStructure(referenceDate, cal, dayCounter),
   r_(r),
   t_(dayCounter.yearFraction(modelReferenceDate, referenceDate)),
   model_(model) {
     registerWith(model_);
 }
示例#24
0
	GeneralizedHullWhite::GeneralizedHullWhite(
        const Handle<YieldTermStructure>& yieldtermStructure,
		const std::vector<Date>& speedstructure,
		const std::vector<Date>& volstructure,
		const std::vector<Real>& speed,
		const std::vector<Real>& vol)
  : OneFactorModel(2), TermStructureConsistentModel(yieldtermStructure),
    speedstructure_(speedstructure),
    volstructure_(volstructure),
    a_(arguments_[0]), sigma_(arguments_[1]) {

        DayCounter dc = yieldtermStructure->dayCounter();

        speedperiods_.push_back(0.0);
        for (Size i=0;i<speedstructure.size()-1;i++)
            speedperiods_.push_back(dc.yearFraction(speedstructure[0],
                                                    speedstructure[i+1]));

        a_ = PiecewiseConstantParameter(speedperiods_, PositiveConstraint());

        volperiods_.push_back(0.0);
        for (Size i=0;i<volstructure.size()-1;i++)
            volperiods_.push_back(dc.yearFraction(volstructure[0],
                                                  volstructure[i+1]));

        sigma_ = PiecewiseConstantParameter(volperiods_, PositiveConstraint());

        a_.setParam(0,speed[0]);
        sigma_.setParam(0,vol[0]);

        for (Size i=1; i< sigma_.size();i++) {
            sigma_.setParam(i,vol[i-1]);
        }
        for (Size i=1; i< a_.size();i++) {
            a_.setParam(i,speed[i-1]);
        }

        registerWith(yieldtermStructure);
	}
示例#25
0
    InterestRate IndexFutures::impliedYield(Real underlyingSpotValue,
                                       Real forwardValue,
                                       Date settlementDate,
                                       Compounding comp,
                                       DayCounter dayCounter) {

        Time t = dayCounter.yearFraction(settlementDate,maturityDate_) ;
		Real compoundingFactor = forwardValue / underlyingSpotValue;
            //(underlyingSpotValue-spotIncome(incomeDiscountCurve_)) ;
        return InterestRate::impliedRate(compoundingFactor,
                                         dayCounter, comp, Annual,
                                         t);
    }
示例#26
0
    FuturesRateHelper::FuturesRateHelper(Real price,
                                         const Date& iborStartDate,
                                         const Date& iborEndDate,
                                         const DayCounter& dayCounter,
                                         Rate convAdj,
                                         Futures::Type type)
    : RateHelper(price),
      convAdj_(Handle<Quote>(shared_ptr<Quote>(new SimpleQuote(convAdj))))
    {
        switch (type) {
          case Futures::IMM:
            QL_REQUIRE(IMM::isIMMdate(iborStartDate, false),
                       iborStartDate << " is not a valid IMM date");
            if (iborEndDate == Date()) {
                // advance 3 months
                latestDate_ = IMM::nextDate(iborStartDate, false);
                latestDate_ = IMM::nextDate(latestDate_, false);
                latestDate_ = IMM::nextDate(latestDate_, false);
            }
            else {
                QL_REQUIRE(iborEndDate>iborStartDate,
                           "end date (" << iborEndDate <<
                           ") must be greater than start date (" <<
                           iborStartDate << ")");
                latestDate_ = iborEndDate;
            }
            break;
          case Futures::ASX:
            QL_REQUIRE(ASX::isASXdate(iborStartDate, false),
                iborStartDate << " is not a valid ASX date");
            if (iborEndDate == Date()) {
                // advance 3 months
                latestDate_ = ASX::nextDate(iborStartDate, false);
                latestDate_ = ASX::nextDate(latestDate_, false);
                latestDate_ = ASX::nextDate(latestDate_, false);
            }
            else {
                QL_REQUIRE(iborEndDate>iborStartDate,
                           "end date (" << iborEndDate <<
                           ") must be greater than start date (" <<
                           iborStartDate << ")");
                latestDate_ = iborEndDate;
            }
            break;
          default:
            QL_FAIL("unknown futures type (" << Integer(type) << ")");
        }
        earliestDate_ = iborStartDate;

        yearFraction_ = dayCounter.yearFraction(earliestDate_, latestDate_);
    }
示例#27
0
 /*! The resulting rate is calculated taking the required
     day-counting rule into account.
 */
 InterestRate equivalentRate(const DayCounter& resultDC,
                             Compounding comp,
                             Frequency freq,
                             Date d1,
                             Date d2,
                             const Date& refStart = Date(),
                             const Date& refEnd = Date()) const {
     QL_REQUIRE(d2>=d1,
                "d1 (" << d1 << ") "
                "later than d2 (" << d2 << ")");
     Time t1 = dc_.yearFraction(d1, d2, refStart, refEnd);
     Time t2 = resultDC.yearFraction(d1, d2, refStart, refEnd);
     return impliedRate(compoundFactor(t1), resultDC, comp, freq, t2);
 }
示例#28
0
 /*! The resulting rate is calculated taking the required
     day-counting rule into account.
 */
 static InterestRate impliedRate(Real compound,
                                 const DayCounter& resultDC,
                                 Compounding comp,
                                 Frequency freq,
                                 const Date& d1,
                                 const Date& d2,
                                 const Date& refStart = Date(),
                                 const Date& refEnd = Date()) {
     QL_REQUIRE(d2>=d1,
                "d1 (" << d1 << ") "
                "later than d2 (" << d2 << ")");
     Time t = resultDC.yearFraction(d1, d2, refStart, refEnd);
     return impliedRate(compound, resultDC, comp, freq, t);
 }
	MCVanillaSwapUCVAEngine::MCVanillaSwapUCVAEngine(
		const Calendar &calender, const DayCounter &dayCounter, Date referenceDate,
		const Handle<YieldTermStructure> &riskFreeTermStructure,
		const boost::shared_ptr<const VanillaSwap> &swap,
		const boost::shared_ptr<const Counterparty> &issuer,
		const boost::shared_ptr<const CoxIngersollRoss> &cirModel,
		const Matrix &corr,
		Size timeStepsPerYear/* = 360*/, bool antitheticVariate/* = true*/,
		Size requiredSamples/* = 50000*/, Real requiredTolerance/* = 0.0001*/, Size maxSamples/* = QL_MAX_INTEGER*/,
		BigNatural seed/* = SeedGenerator::instance().get()*/)
		: MCUCVAEngine(swap, issuer, corr,
		dayCounter.yearFraction(swap->startDate(), swap->maturityDate(), referenceDate, referenceDate),
		riskFreeTermStructure, Null<Size>(), 360, true, requiredSamples, requiredTolerance, maxSamples, seed),
		cirModel_(cirModel)
	{
	}
    inline TimeGrid MCDiscreteAveragingAsianEngine<RNG,S>::timeGrid() const {

        Date referenceDate = process_->riskFreeRate()->referenceDate();
        DayCounter voldc = process_->blackVolatility()->dayCounter();
        std::vector<Time> fixingTimes;
        Size i;
        for (i=0; i<arguments_.fixingDates.size(); i++) {
            if (arguments_.fixingDates[i]>=referenceDate) {
                Time t = voldc.yearFraction(referenceDate,
                    arguments_.fixingDates[i]);
                fixingTimes.push_back(t);
            }
        }

        return TimeGrid(fixingTimes.begin(), fixingTimes.end());
    }