当前位置: 首页>>代码示例>>C++>>正文


C++ DayCounter::yearFraction方法代码示例

本文整理汇总了C++中DayCounter::yearFraction方法的典型用法代码示例。如果您正苦于以下问题:C++ DayCounter::yearFraction方法的具体用法?C++ DayCounter::yearFraction怎么用?C++ DayCounter::yearFraction使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DayCounter的用法示例。


在下文中一共展示了DayCounter::yearFraction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: initializeImpl

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);
	}
	
}
开发者ID:minikie,项目名称:OTCDerivativesCalculatorModule,代码行数:35,代码来源:simpleRangeAccrualRateETI.cpp

示例2: registerWith

    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)));
    }
开发者ID:BGC-nglass,项目名称:quantlib,代码行数:33,代码来源:hestonslvmcmodel.cpp

示例3:

    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;
            }
        }
    }
开发者ID:21hub,项目名称:QuantLib,代码行数:32,代码来源:discretizedcallablefixedratebond.cpp

示例4: testIntraday

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
}
开发者ID:grantathon,项目名称:nquantlib64,代码行数:30,代码来源:daycounters.cpp

示例5: DiscretizedSwap

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.");
}
开发者ID:hardlianotion,项目名称:earlyprob,代码行数:53,代码来源:discretizedswaption.cpp

示例6: calculate

    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);
    }
开发者ID:androidYibo,项目名称:documents,代码行数:29,代码来源:analyticvariancegammaengine.cpp

示例7: testExtOUJumpVanillaEngine

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);
    }
}
开发者ID:EuroPlusFinance,项目名称:Software,代码行数:60,代码来源:swingoption.cpp

示例8: Vasicek

	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);
	}
开发者ID:fder78,项目名称:MyQuantLib,代码行数:27,代码来源:generalized_hullwhite.cpp

示例9: seasonalityCorrection

    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;
    }
开发者ID:AAthresh,项目名称:quantlib,代码行数:26,代码来源:seasonality.cpp

示例10:

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]);
    }
}
开发者ID:androidYibo,项目名称:documents,代码行数:27,代码来源:fdmdividendhandler.cpp

示例11: RateHelper

    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_);
    }
开发者ID:wavelet3000,项目名称:quantlib,代码行数:26,代码来源:ratehelpers.cpp

示例12: RateHelper

 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_);
 }
开发者ID:ErikBrodin,项目名称:quantlib,代码行数:29,代码来源:ratehelpers.cpp

示例13: zeroRate

    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;
        }
    }
开发者ID:SePTimO7,项目名称:QuantLib,代码行数:31,代码来源:forwardengine.hpp

示例14: testOne

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]);
            }
        }
    }
}
开发者ID:simonshakeshaft,项目名称:quantlib,代码行数:25,代码来源:daycounters.cpp

示例15: testFlatHazardRate

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);
    }
}
开发者ID:androidYibo,项目名称:documents,代码行数:32,代码来源:defaultprobabilitycurves.cpp


注:本文中的DayCounter::yearFraction方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。