Exemplo n.º 1
0
	boost::shared_ptr<Parameter> ProcessInfo::ProcessParser_Impl::make_parameter(const std::string& keyName,
							std::map<std::string, std::string>& variable_map,
							std::map<std::string, std::vector<std::string>>& variable_array_map,
							std::map<std::string, Matrix>& variable_matrix_map)
	{
		boost::shared_ptr<Parameter> para;

		if (variable_map.find(keyName) != variable_map.end())
		{
			double value = std::stod(variable_map[keyName]);
			para = boost::shared_ptr<Parameter>(
				new ConstantParameter(value, NoConstraint()));

			return para;
		}

		std::string value_key = keyName + "_PARA_VALUE";
		std::string time_key = keyName + "_PARA_TIME";
		//std::string interpolation_key = keyName + "_CURVE_INTERPOLATION";

		if (variable_array_map.find(value_key) == variable_array_map.end())
			QL_FAIL(value_key << " does not exist.");
		if (variable_array_map.find(time_key) == variable_array_map.end())
			QL_FAIL(time_key << " does not exist.");

		std::vector<std::string> values = variable_array_map[value_key];
		std::vector<Real> value_data;
		std::vector<std::string> times = variable_array_map[time_key];
		std::vector<Real> time_data;

		// converting value
		for (Size i = 0; i < values.size(); i++)
			value_data.push_back(std::stod(values[i]));

		// converting time
		for (Size i = 0; i < times.size(); i++)
			time_data.push_back(std::stod(times[i]));

		para = boost::shared_ptr<Parameter>(
			new PiecewiseConstantParameter(time_data,NoConstraint()));

		for (Size i = 0; i < value_data.size(); i++)
		{
			para->setParam(i, value_data[i]);
		}

		return para;

	}
Exemplo n.º 2
0
    void Gsr::initialize(Real T) {

        volsteptimesArray_ = Array(volstepdates_.size());

        updateTimes();

        QL_REQUIRE(volatilities_.size() == volsteptimes_.size() + 1,
                   "there must be n+1 volatilities ("
                       << volatilities_.size()
                       << ") for n volatility step times ("
                       << volsteptimes_.size() << ")");
        // sigma_ =
        // PiecewiseConstantParameter(volsteptimes_,PositiveConstraint());
        sigma_ = PiecewiseConstantParameter(volsteptimes_, NoConstraint());

        QL_REQUIRE(reversions_.size() == 1 ||
                       reversions_.size() == volsteptimes_.size() + 1,
                   "there must be 1 or n+1 reversions ("
                       << reversions_.size()
                       << ") for n volatility step times ("
                       << volsteptimes_.size() << ")");
        if (reversions_.size() == 1) {
            reversion_ = ConstantParameter(reversions_[0]->value(), NoConstraint());
        } else {
            reversion_ =
                PiecewiseConstantParameter(volsteptimes_, NoConstraint());
        }

        for (Size i = 0; i < sigma_.size(); i++) {
            sigma_.setParam(i, volatilities_[i]->value());
        }
        for (Size i = 0; i < reversion_.size(); i++) {
            reversion_.setParam(i, reversions_[i]->value());
        }

        stateProcess_ = boost::shared_ptr<GsrProcess>(new GsrProcess(
            volsteptimesArray_, sigma_.params(), reversion_.params(), T));

        registerWith(termStructure());

        registerWith(stateProcess_);
        for(Size i=0;i<reversions_.size();++i)
            registerWith(reversions_[i]);

        for(Size i=0;i<volatilities_.size();++i)
            registerWith(volatilities_[i]);

    }
    void FittedBondDiscountCurve::FittingMethod::calculate() {

        FittingCost& costFunction = *costFunction_;
        Constraint constraint = NoConstraint();

        // start with the guess solution, if it exists
        Array x(size(), 0.0);
        if (!curve_->guessSolution_.empty()) {
            x = curve_->guessSolution_;
        }

        Simplex simplex(curve_->simplexLambda_);
        Problem problem(costFunction, constraint, x);

        Natural maxStationaryStateIterations = 100;
        Real rootEpsilon = curve_->accuracy_;
        Real functionEpsilon =  curve_->accuracy_;
        Real gradientNormEpsilon = curve_->accuracy_;

        EndCriteria endCriteria(curve_->maxEvaluations_,
                                maxStationaryStateIterations,
                                rootEpsilon,
                                functionEpsilon,
                                gradientNormEpsilon);

        simplex.minimize(problem,endCriteria);
        solution_ = problem.currentValue();

        numberOfIterations_ = problem.functionEvaluation();
        costValue_ = problem.functionValue();

        // save the results as the guess solution, in case of recalculation
        curve_->guessSolution_ = solution_;
    }
Exemplo n.º 4
0
 PiecewiseConstantParameter(const std::vector<Time>& times,
                            const Constraint& constraint =
                                                      NoConstraint())
 : Parameter(times.size()+1,
             boost::shared_ptr<Parameter::Impl>(
                          new PiecewiseConstantParameter::Impl(times)),
             constraint)
 {}
Exemplo n.º 5
0
    BatesModel::BatesModel(const boost::shared_ptr<BatesProcess> & process)
    : HestonModel(process) {
        arguments_.resize(8);

        arguments_[5] 
                = ConstantParameter(process->nu(),     NoConstraint());
        arguments_[6] 
                = ConstantParameter(process->delta(),  PositiveConstraint());
        arguments_[7] 
                = ConstantParameter(process->lambda(), PositiveConstraint());
        
        generateArguments();
    }
Exemplo n.º 6
0
    void FittedBondDiscountCurve::FittingMethod::calculate() {

        FittingCost& costFunction = *costFunction_;
        Constraint constraint = NoConstraint();

        // start with the guess solution, if it exists
        Array x(size(), 0.0);
        if (!curve_->guessSolution_.empty()) {
            x = curve_->guessSolution_;
        }

        if(curve_->maxEvaluations_ == 0)
        {
            //Don't calculate, simply use given parameters to provide a fitted curve.
            //This turns the fittedbonddiscountcurve into an evaluator of the parametric
            //curve, for example allowing to use the parameters for a credit spread curve
            //calculated with bonds in one currency to be coupled to a discount curve in 
            //another currency. 
            return;
        }
        
        //workaround for backwards compatibility
        ext::shared_ptr<OptimizationMethod> optimization = optimizationMethod_;
        if(!optimization){
            optimization = ext::make_shared<Simplex>(curve_->simplexLambda_);
        }
        Problem problem(costFunction, constraint, x);

        Real rootEpsilon = curve_->accuracy_;
        Real functionEpsilon =  curve_->accuracy_;
        Real gradientNormEpsilon = curve_->accuracy_;

        EndCriteria endCriteria(curve_->maxEvaluations_,
                                curve_->maxStationaryStateIterations_,
                                rootEpsilon,
                                functionEpsilon,
                                gradientNormEpsilon);

        optimization->minimize(problem,endCriteria);
        solution_ = problem.currentValue();

        numberOfIterations_ = problem.functionEvaluation();
        costValue_ = problem.functionValue();

        // save the results as the guess solution, in case of recalculation
        curve_->guessSolution_ = solution_;
    }
    Disposable<std::vector<boost::shared_ptr<CalibrationHelper> > >
    BasketGeneratingEngine::calibrationBasket(
        const boost::shared_ptr<Exercise> &exercise,
        boost::shared_ptr<SwapIndex> standardSwapBase,
        boost::shared_ptr<SwaptionVolatilityStructure> swaptionVolatility,
        const CalibrationBasketType basketType) const {

        QL_REQUIRE(
            !standardSwapBase->forwardingTermStructure().empty(),
            "standard swap base forwarding term structure must not be empty.");
        QL_REQUIRE(
            !standardSwapBase->exogenousDiscount() ||
                !standardSwapBase->discountingTermStructure().empty(),
            "standard swap base discounting term structure must not be empty.");

        std::vector<boost::shared_ptr<CalibrationHelper> > result;

        int minIdxAlive =
            std::upper_bound(exercise->dates().begin(), exercise->dates().end(),
                             Settings::instance().evaluationDate()) -
            exercise->dates().begin();

        boost::shared_ptr<RebatedExercise> rebEx =
            boost::dynamic_pointer_cast<RebatedExercise>(exercise);

        for (Size i = minIdxAlive; i < exercise->dates().size(); i++) {

            Date expiry = exercise->date(i);
            Real rebate = 0.0;
            Date rebateDate = expiry;
            if (rebEx != NULL) {
                rebate = rebEx->rebate(i);
                rebateDate = rebEx->rebatePaymentDate(i);
            }

            boost::shared_ptr<SwaptionHelper> helper;

            switch (basketType) {

            case Naive: {
                Real swapLength = swaptionVolatility->dayCounter().yearFraction(
                    standardSwapBase->valueDate(expiry), underlyingLastDate());
                boost::shared_ptr<SmileSection> sec =
                    swaptionVolatility->smileSection(
                        expiry,
                        static_cast<Size>(swapLength * 12.0 + 0.5) * Months,
                        true);
                Real atmStrike = sec->atmLevel();
                Real atmVol;
                if (atmStrike == Null<Real>())
                    atmVol = sec->volatility(0.03);
                else
                    atmVol = sec->volatility(atmStrike);

                helper = boost::shared_ptr<SwaptionHelper>(new SwaptionHelper(
                    expiry, underlyingLastDate(),
                    Handle<Quote>(boost::make_shared<SimpleQuote>(atmVol)),
                    standardSwapBase->iborIndex(),
                    standardSwapBase->fixedLegTenor(),
                    standardSwapBase->dayCounter(),
                    standardSwapBase->iborIndex()->dayCounter(),
                    standardSwapBase->exogenousDiscount()
                        ? standardSwapBase->discountingTermStructure()
                        : standardSwapBase->forwardingTermStructure(),
                    CalibrationHelper::RelativePriceError, Null<Real>(), 1.0));

                break;
            }

            case MaturityStrikeByDeltaGamma: {

                // determine the npv, first and second order derivatives at
                // $y=0$ of the underlying swap

                const Real h = 0.0001; // finite difference step in $y$, make
                                       // this a parameter of the engine ?
                Real zSpreadDsc =
                    oas_.empty() ? 1.0
                                 : exp(-oas_->value() *
                                       onefactormodel_->termStructure()
                                           ->dayCounter()
                                           .yearFraction(expiry, rebateDate));

                Real npvm = underlyingNpv(expiry, -h) +
                            rebate *
                                onefactormodel_->zerobond(rebateDate, expiry,
                                                          -h, discountCurve_) *
                                zSpreadDsc;
                Real npv = underlyingNpv(expiry, 0.0) +
                           rebate * onefactormodel_->zerobond(
                                        rebateDate, expiry, 0, discountCurve_) *
                               zSpreadDsc;
                Real npvp = underlyingNpv(expiry, h) +
                            rebate *
                                onefactormodel_->zerobond(rebateDate, expiry, h,
                                                          discountCurve_) *
                                zSpreadDsc;

                Real delta = (npvp - npvm) / (2.0 * h);
                Real gamma = (npvp - 2.0 * npv + npvm) / (h * h);

                QL_REQUIRE(npv * npv + delta * delta + gamma * gamma > 0.0,
                           "(npv,delta,gamma) must have a positive norm");

                // debug output
                // std::cout << "EXOTIC npv " << npv << " delta " << delta
                //           << " gamma " << gamma << std::endl;
                // Real xtmp = -5.0;
                // std::cout
                //     << "********************************************EXERCISE "
                //     << expiry << " ******************" << std::endl;
                // std::cout << "globalExoticNpv;";
                // while (xtmp <= 5.0 + QL_EPSILON) {
                //     std::cout << underlyingNpv(expiry, xtmp) << ";";
                //     xtmp += 0.1;
                // }
                // std::cout << std::endl;
                // end debug output

                // play safe, we restrict the maximum maturity so to easily fit
                // in the date class restriction
                Real maxMaturity =
                    swaptionVolatility->dayCounter().yearFraction(
                        expiry, Date::maxDate() - 365);

                boost::shared_ptr<MatchHelper> matchHelper_;
                matchHelper_ = boost::shared_ptr<MatchHelper>(new MatchHelper(
                    underlyingType(), npv, delta, gamma, onefactormodel_,
                    standardSwapBase, expiry, maxMaturity, h));

                // Optimize
                Array initial = initialGuess(expiry);
                QL_REQUIRE(initial.size() == 3,
                           "initial guess must have size 3 (but is "
                               << initial.size() << ")");

                EndCriteria ec(1000, 200, 1E-8, 1E-8, 1E-8); // make these
                                                             // criteria and the
                                                             // optimizer itself
                                                             // parameters of
                                                             // the method ?
                Constraint constraint = NoConstraint();
                Problem p(*matchHelper_, constraint, initial);
                LevenbergMarquardt lm;

                EndCriteria::Type ret = lm.minimize(p, ec);
                QL_REQUIRE(ret != EndCriteria::None &&
                               ret != EndCriteria::Unknown &&
                               ret != EndCriteria::MaxIterations,
                           "optimizer returns error (" << ret << ")");
                Array solution = p.currentValue();

                Real maturity = fabs(solution[1]);

                Size years = (Size)std::floor(maturity);
                maturity -= (Real)years;
                maturity *= 12.0;
                Size months = (Size)std::floor(maturity + 0.5);
                if (years == 0 && months == 0)
                    months = 1; // ensure a maturity of at least one months
                // maturity -= (Real)months; maturity *= 365.25;
                // Size days = (Size)std::floor(maturity);

                Period matPeriod =
                    years * Years + months * Months; //+days*Days;

                // we have to floor the strike of the calibration instrument,
                // see warning in the header
                solution[2] = std::max(solution[2], 0.00001); // floor at 0.1bp

                // also the calibrated nominal may be zero, so we floor it, too
                solution[0] =
                    std::max(solution[0], 0.000001); // float at 0.01bp

                helper = boost::shared_ptr<SwaptionHelper>(new SwaptionHelper(
                    expiry, matPeriod,
                    Handle<Quote>(boost::make_shared<SimpleQuote>(
                        swaptionVolatility->volatility(
                            expiry, matPeriod, solution[2], true))),
                    standardSwapBase->iborIndex(),
                    standardSwapBase->fixedLegTenor(),
                    standardSwapBase->dayCounter(),
                    standardSwapBase->iborIndex()->dayCounter(),
                    standardSwapBase->exogenousDiscount()
                        ? standardSwapBase->discountingTermStructure()
                        : standardSwapBase->forwardingTermStructure(),
                    CalibrationHelper::RelativePriceError, solution[2],
                    fabs(solution[0])));
                break;
            }

            default:
                QL_FAIL("Calibration basket type not known (" << basketType
                                                              << ")");
            }

            result.push_back(helper);
        }

        return result;
    }
Exemplo n.º 8
0
 Parameter()
 : constraint_(NoConstraint()) {}
Exemplo n.º 9
0
 TermStructureFittingParameter(const Handle<YieldTermStructure>& term)
 : Parameter(
           0,
           boost::shared_ptr<Parameter::Impl>(new NumericalImpl(term)),
           NoConstraint())
 {}
Exemplo n.º 10
0
 TermStructureFittingParameter(
                        const boost::shared_ptr<Parameter::Impl>& impl)
 : Parameter(0, impl, NoConstraint()) {}
Exemplo n.º 11
0
 NullParameter()
 : Parameter(
           0,
           boost::shared_ptr<Parameter::Impl>(new NullParameter::Impl),
           NoConstraint())
 {}