【C++】开源:量化金融计算库QuantLib配置与使用

😏★,°:.☆( ̄▽ ̄)/$:.°★ 😏
这篇文章主要介绍量化交易库QuantLib配置与使用。
无专精则不能成,无涉猎则不能通。——梁启超
欢迎来到我的博客,一起学习,共同进步。
喜欢的朋友可以关注一下,下次更新不迷路🥞

文章目录

    • :smirk:1. 项目介绍
    • :blush:2. 环境配置
    • :satisfied:3. 使用说明

😏1. 项目介绍

官网:https://www.quantlib.org/

项目Github地址:https://github.com/lballabio/QuantLib

QuantLib(Quantitative Finance Library)是一个开源的跨平台软件框架,专为量化金融领域设计和开发。它提供了丰富的金融工具和计算功能,用于衍生品定价、风险管理、投资组合管理等多个领域。以下是关于QuantLib的一些主要特点和用途:

1.开源跨平台:QuantLib是完全开源的,可以在不同操作系统上运行,包括Windows、Linux和Mac OS X。这使得它成为量化金融研究和开发的理想工具,能够在不同的环境中使用和定制。

2.丰富的金融工具:QuantLib支持多种金融工具和衍生品的定价和分析,包括利率衍生品(如利率互换、利率期权)、股票衍生品(如期权)、信用衍生品(如信用违约掉期)、外汇衍生品等。

3.数值方法和模型支持:QuantLib提供了广泛的数值方法和模型,用于衍生品定价和风险管理,如蒙特卡洛模拟、有限差分法、解析方法等。它支持的模型包括Black-Scholes模型、Heston模型、Libor Market Model等。

4.投资组合和风险管理:QuantLib能够处理复杂的投资组合和风险管理需求,包括风险测度、对冲分析、压力测试等,为金融机构和量化交易员提供重要的决策支持工具。

5.易于集成和扩展:QuantLib的设计允许用户根据特定需求进行定制和扩展,通过C++编程接口提供了灵活的扩展性,同时也支持Python等编程语言的接口,使得QuantLib能够与其他系统和库集成使用。

😊2. 环境配置

Ubuntu环境安装QuantLib库:

git clone https://github.com/lballabio/QuantLib # 或者下载release版本 1.34
mkdir build && cd build
cmake ..
make
sudo make install

程序g++编译:g++ -o main main.cpp -lQuantLib

😆3. 使用说明

下面是一个简单示例,计算零息债券的定价:

#include <ql/quantlib.hpp>
#include <iostream>using namespace QuantLib;int main() {// 设置评估日期Date today = Date::todaysDate();Settings::instance().evaluationDate() = today;// 定义债券参数Real faceAmount = 1000.0; // 债券面值Rate couponRate = 0.05; // 年利率Date maturity = today + Period(1, Years); // 到期时间// 创建收益率曲线Rate marketRate = 0.03; // 市场利率Handle<YieldTermStructure> discountCurve(boost::shared_ptr<YieldTermStructure>(new FlatForward(today, marketRate, Actual360())));// 创建零息债券ZeroCouponBond bond(0, NullCalendar(), faceAmount, maturity, Following, 100.0, today);// 创建定价引擎并设置参数bond.setPricingEngine(boost::shared_ptr<PricingEngine>(new DiscountingBondEngine(discountCurve)));// 计算债券价格Real bondPrice = bond.NPV();std::cout << "Zero-coupon bond price: " << bondPrice << std::endl;return 0;
}

此外,还有官方示例里的BasketLosses 计算一组金融资产损失示例(看起来还是很复杂的):

/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *//*!
Copyright (C) 2009 Mark JoshiThis file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license.  You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/#include <ql/qldefines.hpp>
#if !defined(BOOST_ALL_NO_LIB) && defined(BOOST_MSVC)
#  include <ql/auto_link.hpp>
#endif
#include <ql/models/marketmodels/marketmodel.hpp>
#include <ql/models/marketmodels/accountingengine.hpp>
#include <ql/models/marketmodels/pathwiseaccountingengine.hpp>
#include <ql/models/marketmodels/products/multiproductcomposite.hpp>
#include <ql/models/marketmodels/products/multistep/multistepswap.hpp>
#include <ql/models/marketmodels/products/multistep/callspecifiedmultiproduct.hpp>
#include <ql/models/marketmodels/products/multistep/exerciseadapter.hpp>
#include <ql/models/marketmodels/products/multistep/multistepnothing.hpp>
#include <ql/models/marketmodels/products/multistep/multistepinversefloater.hpp>
#include <ql/models/marketmodels/products/pathwise/pathwiseproductswap.hpp>
#include <ql/models/marketmodels/products/pathwise/pathwiseproductinversefloater.hpp>
#include <ql/models/marketmodels/products/pathwise/pathwiseproductcallspecified.hpp>
#include <ql/models/marketmodels/models/flatvol.hpp>
#include <ql/models/marketmodels/callability/swapratetrigger.hpp>
#include <ql/models/marketmodels/callability/swapbasissystem.hpp>
#include <ql/models/marketmodels/callability/swapforwardbasissystem.hpp>
#include <ql/models/marketmodels/callability/nothingexercisevalue.hpp>
#include <ql/models/marketmodels/callability/collectnodedata.hpp>
#include <ql/models/marketmodels/callability/lsstrategy.hpp>
#include <ql/models/marketmodels/callability/upperboundengine.hpp>
#include <ql/models/marketmodels/correlations/expcorrelations.hpp>
#include <ql/models/marketmodels/browniangenerators/mtbrowniangenerator.hpp>
#include <ql/models/marketmodels/browniangenerators/sobolbrowniangenerator.hpp>
#include <ql/models/marketmodels/evolvers/lognormalfwdratepc.hpp>
#include <ql/models/marketmodels/evolvers/lognormalfwdrateeuler.hpp>
#include <ql/models/marketmodels/pathwisegreeks/bumpinstrumentjacobian.hpp>
#include <ql/models/marketmodels/utilities.hpp>
#include <ql/methods/montecarlo/genericlsregression.hpp>
#include <ql/legacy/libormarketmodels/lmlinexpcorrmodel.hpp>
#include <ql/legacy/libormarketmodels/lmextlinexpvolmodel.hpp>
#include <ql/time/schedule.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <ql/time/daycounters/simpledaycounter.hpp>
#include <ql/pricingengines/blackformula.hpp>
#include <ql/pricingengines/blackcalculator.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <ql/math/integrals/segmentintegral.hpp>
#include <ql/math/statistics/convergencestatistics.hpp>
#include <ql/termstructures/volatility/abcd.hpp>
#include <ql/termstructures/volatility/abcdcalibration.hpp>
#include <ql/math/optimization/simplex.hpp>
#include <ql/quotes/simplequote.hpp>
#include <sstream>
#include <iostream>
#include <ctime>using namespace QuantLib;std::vector<std::vector<Matrix>>
theVegaBumps(bool factorwiseBumping, const ext::shared_ptr<MarketModel>& marketModel, bool doCaps) {Real multiplierCutOff = 50.0;Real projectionTolerance = 1E-4;Size numberRates= marketModel->numberOfRates();std::vector<VolatilityBumpInstrumentJacobian::Cap> caps;if (doCaps){Rate capStrike = marketModel->initialRates()[0];for (Size i=0; i< numberRates-1; i=i+1){VolatilityBumpInstrumentJacobian::Cap nextCap;nextCap.startIndex_ = i;nextCap.endIndex_ = i+1;nextCap.strike_ = capStrike;caps.push_back(nextCap);}}std::vector<VolatilityBumpInstrumentJacobian::Swaption> swaptions(numberRates);for (Size i=0; i < numberRates; ++i){swaptions[i].startIndex_ = i;swaptions[i].endIndex_ = numberRates;}VegaBumpCollection possibleBumps(marketModel,factorwiseBumping);OrthogonalizedBumpFinder  bumpFinder(possibleBumps,swaptions,caps,multiplierCutOff, // if vector length grows by more than this discardprojectionTolerance);      // if vector projection before scaling less than this discardstd::vector<std::vector<Matrix>> theBumps;bumpFinder.GetVegaBumps(theBumps);return theBumps;}int Bermudan()
{Size numberRates =20;Real accrual = 0.5;Real firstTime = 0.5;std::vector<Real> rateTimes(numberRates+1);for (Size i=0; i < rateTimes.size(); ++i)rateTimes[i] = firstTime + i*accrual;std::vector<Real> paymentTimes(numberRates);std::vector<Real> accruals(numberRates,accrual);for (Size i=0; i < paymentTimes.size(); ++i)paymentTimes[i] = firstTime + (i+1)*accrual;Real fixedRate = 0.05;std::vector<Real> strikes(numberRates,fixedRate);Real receive = -1.0;// 0. a payer swapMultiStepSwap payerSwap(rateTimes, accruals, accruals, paymentTimes,fixedRate, true);// 1. the equivalent receiver swapMultiStepSwap receiverSwap(rateTimes, accruals, accruals, paymentTimes,fixedRate, false);//exercise schedule, we can exercise on any rate time except the last onestd::vector<Rate> exerciseTimes(rateTimes);exerciseTimes.pop_back();// naive exercise strategy, exercise above a trigger levelstd::vector<Rate> swapTriggers(exerciseTimes.size(), fixedRate);SwapRateTrigger naifStrategy(rateTimes, swapTriggers, exerciseTimes);// Longstaff-Schwartz exercise strategystd::vector<std::vector<NodeData>> collectedData;std::vector<std::vector<Real>> basisCoefficients;// control that does nothing, need it because some control is expectedNothingExerciseValue control(rateTimes);//    SwapForwardBasisSystem basisSystem(rateTimes,exerciseTimes);SwapBasisSystem basisSystem(rateTimes,exerciseTimes);// rebate that does nothing, need it because some rebate is expected// when you break a swap nothing happens.NothingExerciseValue nullRebate(rateTimes);CallSpecifiedMultiProduct dummyProduct =CallSpecifiedMultiProduct(receiverSwap, naifStrategy,ExerciseAdapter(nullRebate));const EvolutionDescription& evolution = dummyProduct.evolution();// parameters for modelsSize seed = 12332; // for Sobol generatorSize trainingPaths = 65536;Size paths = 16384;Size vegaPaths = 16384*64;std::cout << "training paths, " << trainingPaths << "\n";std::cout << "paths, " << paths << "\n";std::cout << "vega Paths, " << vegaPaths << "\n";
#ifdef _DEBUGtrainingPaths = 512;paths = 1024;vegaPaths = 1024;
#endif// set up a calibration, this would typically be done by using a calibratorReal rateLevel =0.05;Real initialNumeraireValue = 0.95;Real volLevel = 0.11;Real beta = 0.2;Real gamma = 1.0;Size numberOfFactors = std::min<Size>(5,numberRates);Spread displacementLevel =0.02;// set up vectorsstd::vector<Rate> initialRates(numberRates,rateLevel);std::vector<Volatility> volatilities(numberRates, volLevel);std::vector<Spread> displacements(numberRates, displacementLevel);ExponentialForwardCorrelation correlations(rateTimes,volLevel, beta,gamma);FlatVol  calibration(volatilities,ext::make_shared<ExponentialForwardCorrelation>(correlations),evolution,numberOfFactors,initialRates,displacements);auto marketModel = ext::make_shared<FlatVol>(calibration);// we use a factory since there is data that will only be known laterSobolBrownianGeneratorFactory generatorFactory(SobolBrownianGenerator::Diagonal, seed);std::vector<Size> numeraires( moneyMarketMeasure(evolution));// the evolver will actually evolve the ratesLogNormalFwdRatePc  evolver(marketModel,generatorFactory,numeraires   // numeraires for each step);auto evolverPtr = ext::make_shared<LogNormalFwdRatePc>(evolver);int t1= clock();// gather data before computing exercise strategycollectNodeData(evolver,receiverSwap,basisSystem,nullRebate,control,trainingPaths,collectedData);int t2 = clock();// calculate the exercise strategy's coefficientsgenericLongstaffSchwartzRegression(collectedData,basisCoefficients);// turn the coefficients into an exercise strategyLongstaffSchwartzExerciseStrategy exerciseStrategy(basisSystem, basisCoefficients,evolution, numeraires,nullRebate, control);//  bermudan swaption to enter into the payer swapCallSpecifiedMultiProduct bermudanProduct =CallSpecifiedMultiProduct(MultiStepNothing(evolution),exerciseStrategy, payerSwap);//  callable receiver swapCallSpecifiedMultiProduct callableProduct =CallSpecifiedMultiProduct(receiverSwap, exerciseStrategy,ExerciseAdapter(nullRebate));// lower bound: evolve all 4 products togheterMultiProductComposite allProducts;allProducts.add(payerSwap);allProducts.add(receiverSwap);allProducts.add(bermudanProduct);allProducts.add(callableProduct);allProducts.finalize();AccountingEngine accounter(evolverPtr,Clone<MarketModelMultiProduct>(allProducts),initialNumeraireValue);SequenceStatisticsInc stats;accounter.multiplePathValues (stats,paths);int t3 = clock();std::vector<Real> means(stats.mean());for (Real mean : means)std::cout << mean << "\n";std::cout << " time to build strategy, " << (t2-t1)/static_cast<Real>(CLOCKS_PER_SEC)<< ", seconds.\n";std::cout << " time to price, " << (t3-t2)/static_cast<Real>(CLOCKS_PER_SEC)<< ", seconds.\n";// vegas// do it twice once with factorwise bumping, once withoutSize pathsToDoVegas = vegaPaths;for (Size i=0; i < 4; ++i){bool allowFactorwiseBumping = i % 2 > 0 ;bool doCaps = i / 2 > 0 ;LogNormalFwdRateEuler evolverEuler(marketModel,generatorFactory,numeraires) ;MarketModelPathwiseSwap receiverPathwiseSwap(  rateTimes,accruals,strikes,receive);Clone<MarketModelPathwiseMultiProduct> receiverPathwiseSwapPtr(receiverPathwiseSwap.clone());//  callable receiver swapCallSpecifiedPathwiseMultiProduct callableProductPathwise(receiverPathwiseSwapPtr,exerciseStrategy);Clone<MarketModelPathwiseMultiProduct> callableProductPathwisePtr(callableProductPathwise.clone());std::vector<std::vector<Matrix>> theBumps(theVegaBumps(allowFactorwiseBumping,marketModel,doCaps));PathwiseVegasOuterAccountingEngineaccountingEngineVegas(ext::make_shared<LogNormalFwdRateEuler>(evolverEuler),callableProductPathwisePtr,marketModel,theBumps,initialNumeraireValue);std::vector<Real> values,errors;accountingEngineVegas.multiplePathValues(values,errors,pathsToDoVegas);std::cout << "vega output \n";std::cout << " factorwise bumping " << allowFactorwiseBumping << "\n";std::cout << " doCaps " << doCaps << "\n";Size r=0;std::cout << " price estimate, " << values[r++] << "\n";for (Size i=0; i < numberRates; ++i, ++r)std::cout << " Delta, " << i << ", " << values[r] << ", " << errors[r] << "\n";Real totalVega = 0.0;for (; r < values.size(); ++r){std::cout << " vega, " << r - 1 -  numberRates<< ", " << values[r] << " ," << errors[r] << "\n";totalVega +=  values[r];}std::cout << " total Vega, " << totalVega << "\n";}// upper boundMTBrownianGeneratorFactory uFactory(seed+142);auto upperEvolver = ext::make_shared<LogNormalFwdRatePc>(ext::make_shared<FlatVol>(calibration),uFactory,numeraires   // numeraires for each step);std::vector<ext::shared_ptr<MarketModelEvolver>> innerEvolvers;std::valarray<bool> isExerciseTime =   isInSubset(evolution.evolutionTimes(),    exerciseStrategy.exerciseTimes());for (Size s=0; s < isExerciseTime.size(); ++s){if (isExerciseTime[s]){MTBrownianGeneratorFactory iFactory(seed+s);auto e = ext::make_shared<LogNormalFwdRatePc>(ext::make_shared<FlatVol>(calibration),uFactory,numeraires,  // numeraires for each steps);innerEvolvers.push_back(e);}}UpperBoundEngine uEngine(upperEvolver,  // does outer pathsinnerEvolvers, // for sub-simulations that do continuation valuesreceiverSwap,nullRebate,receiverSwap,nullRebate,exerciseStrategy,initialNumeraireValue);Statistics uStats;Size innerPaths = 255;Size outerPaths =256;int t4 = clock();uEngine.multiplePathValues(uStats,outerPaths,innerPaths);Real upperBound = uStats.mean();Real upperSE = uStats.errorEstimate();int t5=clock();std::cout << " Upper - lower is, " << upperBound << ", with standard error " << upperSE << "\n";std::cout << " time to compute upper bound is,  " << (t5-t4)/static_cast<Real>(CLOCKS_PER_SEC) << ", seconds.\n";return 0;
}int InverseFloater(Real rateLevel)
{Size numberRates =20;Real accrual = 0.5;Real firstTime = 0.5;Real strike =0.15;Real fixedMultiplier = 2.0;Real floatingSpread =0.0;bool payer = true;std::vector<Real> rateTimes(numberRates+1);for (Size i=0; i < rateTimes.size(); ++i)rateTimes[i] = firstTime + i*accrual;std::vector<Real> paymentTimes(numberRates);std::vector<Real> accruals(numberRates,accrual);std::vector<Real> fixedStrikes(numberRates,strike);std::vector<Real> floatingSpreads(numberRates,floatingSpread);std::vector<Real> fixedMultipliers(numberRates,fixedMultiplier);for (Size i=0; i < paymentTimes.size(); ++i)paymentTimes[i] = firstTime + (i+1)*accrual;MultiStepInverseFloater inverseFloater(rateTimes,accruals,accruals,fixedStrikes,fixedMultipliers,floatingSpreads,paymentTimes,payer);//exercise schedule, we can exercise on any rate time except the last onestd::vector<Rate> exerciseTimes(rateTimes);exerciseTimes.pop_back();// naive exercise strategy, exercise above a trigger levelReal trigger =0.05;std::vector<Rate> swapTriggers(exerciseTimes.size(), trigger);SwapRateTrigger naifStrategy(rateTimes, swapTriggers, exerciseTimes);// Longstaff-Schwartz exercise strategystd::vector<std::vector<NodeData>> collectedData;std::vector<std::vector<Real>> basisCoefficients;// control that does nothing, need it because some control is expectedNothingExerciseValue control(rateTimes);SwapForwardBasisSystem basisSystem(rateTimes,exerciseTimes);
//    SwapBasisSystem basisSystem(rateTimes,exerciseTimes);// rebate that does nothing, need it because some rebate is expected// when you break a swap nothing happens.NothingExerciseValue nullRebate(rateTimes);CallSpecifiedMultiProduct dummyProduct =CallSpecifiedMultiProduct(inverseFloater, naifStrategy,ExerciseAdapter(nullRebate));const EvolutionDescription& evolution = dummyProduct.evolution();// parameters for modelsSize seed = 12332; // for Sobol generatorSize trainingPaths = 65536;Size paths = 65536;Size vegaPaths =16384;#ifdef _DEBUGtrainingPaths = 8192;paths = 8192;vegaPaths = 1024;
#endifstd::cout <<  " inverse floater \n";std::cout << " fixed strikes :  "  << strike << "\n";std::cout << " number rates :  " << numberRates << "\n";std::cout << "training paths, " << trainingPaths << "\n";std::cout << "paths, " << paths << "\n";std::cout << "vega Paths, " << vegaPaths << "\n";// set up a calibration, this would typically be done by using a calibrator//Real rateLevel =0.08;std::cout << " rate level " <<  rateLevel << "\n";Real initialNumeraireValue = 0.95;Real volLevel = 0.11;Real beta = 0.2;Real gamma = 1.0;Size numberOfFactors = std::min<Size>(5,numberRates);Spread displacementLevel =0.02;// set up vectorsstd::vector<Rate> initialRates(numberRates,rateLevel);std::vector<Volatility> volatilities(numberRates, volLevel);std::vector<Spread> displacements(numberRates, displacementLevel);ExponentialForwardCorrelation correlations(rateTimes,volLevel, beta,gamma);FlatVol  calibration(volatilities,ext::make_shared<ExponentialForwardCorrelation>(correlations),evolution,numberOfFactors,initialRates,displacements);auto marketModel = ext::make_shared<FlatVol>(calibration);// we use a factory since there is data that will only be known laterSobolBrownianGeneratorFactory generatorFactory(SobolBrownianGenerator::Diagonal, seed);std::vector<Size> numeraires( moneyMarketMeasure(evolution));// the evolver will actually evolve the ratesLogNormalFwdRatePc  evolver(marketModel,generatorFactory,numeraires   // numeraires for each step);auto evolverPtr = ext::make_shared<LogNormalFwdRatePc>(evolver);int t1= clock();// gather data before computing exercise strategycollectNodeData(evolver,inverseFloater,basisSystem,nullRebate,control,trainingPaths,collectedData);int t2 = clock();// calculate the exercise strategy's coefficientsgenericLongstaffSchwartzRegression(collectedData,basisCoefficients);// turn the coefficients into an exercise strategyLongstaffSchwartzExerciseStrategy exerciseStrategy(basisSystem, basisCoefficients,evolution, numeraires,nullRebate, control);//  callable receiver swapCallSpecifiedMultiProduct callableProduct =CallSpecifiedMultiProduct(inverseFloater, exerciseStrategy,ExerciseAdapter(nullRebate));MultiProductComposite allProducts;allProducts.add(inverseFloater);allProducts.add(callableProduct);allProducts.finalize();AccountingEngine accounter(evolverPtr,Clone<MarketModelMultiProduct>(allProducts),initialNumeraireValue);SequenceStatisticsInc stats;accounter.multiplePathValues (stats,paths);int t3 = clock();std::vector<Real> means(stats.mean());for (Real mean : means)std::cout << mean << "\n";std::cout << " time to build strategy, " << (t2-t1)/static_cast<Real>(CLOCKS_PER_SEC)<< ", seconds.\n";std::cout << " time to price, " << (t3-t2)/static_cast<Real>(CLOCKS_PER_SEC)<< ", seconds.\n";// vegas// do it twice once with factorwise bumping, once withoutSize pathsToDoVegas = vegaPaths;for (Size i=0; i < 4; ++i){bool allowFactorwiseBumping = i % 2 > 0 ;bool doCaps = i / 2 > 0 ;LogNormalFwdRateEuler evolverEuler(marketModel,generatorFactory,numeraires) ;MarketModelPathwiseInverseFloater pathwiseInverseFloater(rateTimes,accruals,accruals,fixedStrikes,fixedMultipliers,floatingSpreads,paymentTimes,payer);Clone<MarketModelPathwiseMultiProduct> pathwiseInverseFloaterPtr(pathwiseInverseFloater.clone());//  callable inverse floaterCallSpecifiedPathwiseMultiProduct callableProductPathwise(pathwiseInverseFloaterPtr,exerciseStrategy);Clone<MarketModelPathwiseMultiProduct> callableProductPathwisePtr(callableProductPathwise.clone());std::vector<std::vector<Matrix>> theBumps(theVegaBumps(allowFactorwiseBumping,marketModel,doCaps));PathwiseVegasOuterAccountingEngineaccountingEngineVegas(ext::make_shared<LogNormalFwdRateEuler>(evolverEuler),//         pathwiseInverseFloaterPtr,callableProductPathwisePtr,marketModel,theBumps,initialNumeraireValue);std::vector<Real> values,errors;accountingEngineVegas.multiplePathValues(values,errors,pathsToDoVegas);std::cout << "vega output \n";std::cout << " factorwise bumping " << allowFactorwiseBumping << "\n";std::cout << " doCaps " << doCaps << "\n";Size r=0;std::cout << " price estimate, " << values[r++] << "\n";for (Size i=0; i < numberRates; ++i, ++r)std::cout << " Delta, " << i << ", " << values[r] << ", " << errors[r] << "\n";Real totalVega = 0.0;for (; r < values.size(); ++r){std::cout << " vega, " << r - 1 -  numberRates<< ", " << values[r] << " ," << errors[r] << "\n";totalVega +=  values[r];}std::cout << " total Vega, " << totalVega << "\n";}// upper boundMTBrownianGeneratorFactory uFactory(seed+142);auto upperEvolver = ext::make_shared<LogNormalFwdRatePc>(ext::make_shared<FlatVol>(calibration),uFactory,numeraires   // numeraires for each step);std::vector<ext::shared_ptr<MarketModelEvolver>> innerEvolvers;std::valarray<bool> isExerciseTime =   isInSubset(evolution.evolutionTimes(),    exerciseStrategy.exerciseTimes());for (Size s=0; s < isExerciseTime.size(); ++s){if (isExerciseTime[s]){MTBrownianGeneratorFactory iFactory(seed+s);auto e = ext::make_shared<LogNormalFwdRatePc>(ext::make_shared<FlatVol>(calibration),uFactory,numeraires ,  // numeraires for each steps);innerEvolvers.push_back(e);}}UpperBoundEngine uEngine(upperEvolver,  // does outer pathsinnerEvolvers, // for sub-simulations that do continuation valuesinverseFloater,nullRebate,inverseFloater,nullRebate,exerciseStrategy,initialNumeraireValue);Statistics uStats;Size innerPaths = 255;Size outerPaths =256;int t4 = clock();uEngine.multiplePathValues(uStats,outerPaths,innerPaths);Real upperBound = uStats.mean();Real upperSE = uStats.errorEstimate();int t5=clock();std::cout << " Upper - lower is, " << upperBound << ", with standard error " << upperSE << "\n";std::cout << " time to compute upper bound is,  " << (t5-t4)/static_cast<Real>(CLOCKS_PER_SEC) << ", seconds.\n";return 0;
}int main()
{try {for (Size i=5; i < 10; ++i)InverseFloater(i/100.0);return 0;} catch (std::exception& e) {std::cerr << e.what() << std::endl;return 1;} catch (...) {std::cerr << "unknown error" << std::endl;return 1;}
}

在这里插入图片描述

以上。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/41835.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【JVM基础篇】Java垃圾回收器介绍

垃圾回收器&#xff08;垃圾回收算法实现&#xff09; 垃圾回收器是垃圾回收算法的具体实现。由于垃圾回收器分为年轻代和老年代&#xff0c;除了G1&#xff08;既能管控新生代&#xff0c;也可以管控老年代&#xff09;之外&#xff0c;新生代、老年代的垃圾回收器必须按照ho…

Redis中list类型操作命令(操作演示、命令语法、返回值、时间复杂度、注意事项等)

文章目录 lpush 命令lrange 命令lpushx 命令rpush 命令rpushx 命令lpop 命令rpop 命令lindex 命令linsert 命令llen 命令lrem 命令ltrim 命令lset 命令blpop 和 brpop lpush 命令 从左侧向列表中插入指定的元素 语法&#xff1a;lpush key value [value……] 时间复杂度&#…

【C语言】自定义类型:联合和枚举

前言 前面我们学习了一种自定义类型&#xff0c;结构体&#xff0c;现在我们学习另外两种自定义类型&#xff0c;联合 和 枚举。 目录 一、联合体 1. 联合体类型的声明 2. 联合体的特点 3. 相同成员联合体和结构体对比 4. 联合体大小的计算 5. 用联合体判断当前机…

C语言实现顺序表字符型数据排序

实现直接插入、冒泡、直接选择排序算法。 #include <stdio.h> #include <stdlib.h>typedef char InfoType;#define n 10 //假设的文件长度&#xff0c;即待排序的记录数目 typedef char KeyType; //假设的关键字类型 typedef struct { //记录类型KeyType…

vue3+vite搭建第一个cesium项目详细步骤及环境配置(附源码)

文章目录 1.创建vuevite项目2.安装 Cesium2.1 安装cesium2.2 安装vite-plugin-cesium插件&#xff08;非必选&#xff09;2.3 新建组件页面map.vue2.4 加载地图 3.完成效果图 1.创建vuevite项目 打开cmd窗口执行以下命令&#xff1a;cesium-vue-app是你的项目名称 npm create…

【LeetCode:3101. 交替子数组计数 + 滑动窗口 + 数学公式】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

转盘输入法-键盘加鼠标版本

序 转盘输入法&#xff0c;给你的聊天加点新意。它不用常见的九宫格或全键盘&#xff0c;而是把字母摆在圆盘上&#xff0c;一滑一滑&#xff0c;字就出来了&#xff0c;新鲜又直接。 键盘加鼠标版本GIF演示 演示软件下载 转盘输入法PC演示版本EXE下载https://download.csdn…

Unity编辑器扩展之Inspector面板扩展

内容将会持续更新&#xff0c;有错误的地方欢迎指正&#xff0c;谢谢! Unity编辑器扩展之Inspector面板扩展 TechX 坚持将创新的科技带给世界&#xff01; 拥有更好的学习体验 —— 不断努力&#xff0c;不断进步&#xff0c;不断探索 TechX —— 心探索、心进取&#xff…

阿里云服务器配置、搭建(针对Spring boot和MySQL项目)

这是一篇极其详细且痛苦的文章&#xff0c;还是在两位后端的大佬手把手教导下、以及我找遍全网所有资料、问了N遍AI、甚至直接申请阿里云工单一对一询问客服一整天、连续清空再上传反复30多次整个项目jar包......总结出来的终极要人命踩坑的问题总结 一、首先购买服务器 其实不…

磁盘分区工具 -- 傲梅分区助手 v10.4.1 技术员版

软件简介 傲梅分区助手是一款功能强大的磁盘分区工具&#xff0c;它专为Windows系统设计&#xff0c;帮助用户更高效地管理他们的硬盘。该软件支持多种分区操作&#xff0c;包括创建、格式化、调整大小、移动、合并和分割分区。此外&#xff0c;它还提供了复制硬盘和分区的功能…

06-6.4.4 拓扑排序

&#x1f44b; Hi, I’m Beast Cheng &#x1f440; I’m interested in photography, hiking, landscape… &#x1f331; I’m currently learning python, javascript, kotlin… &#x1f4eb; How to reach me --> 458290771qq.com 喜欢《数据结构》部分笔记的小伙伴可以…

java基础:方法

一、方法 1、Java方法是语句的集合&#xff0c;它们在一起执行一个功能。 方法是解决一类问题的步骤的有序集合方法包含于类或对象中方法在程序中被创建&#xff0c;在其他地方被引用 2、设计方法的原则&#xff1a;方法的本意是功能块&#xff0c;就是实现某个功能的语句块…

如何选择一家适合自己的商城源码?

商城源码的选择取决于多个因素&#xff0c;包括商城的功能需求、稳定性、易用性、可定制性以及价格等。启山智软作为在市场上被广泛认可且表现优异的商城源码提供商&#xff0c;具有以下的特点和优势&#xff1a; 特点①&#xff1a;国内知名的B2B2C开源商城源码系统&#xff…

BufferReader/BufferWriter使用时出现的问题

项目场景&#xff1a; 在一个文件中有一些数据&#xff0c;需要读取出来并替换成其他字符再写回文件中&#xff0c;需要用Buffer流。 问题描述 文件中的数据丢失&#xff0c;并且在读取前就为空&#xff0c;读取不到数据。 问题代码&#xff1a; File f new File("D:\\…

Python排序,你用对了吗?一文教你sorted和sort的正确姿势!

目录 1、sorted基础用法 🍏 1.1 列表排序入门 1.2 自定义排序规则 1.3 排序稳定性和key函数 2、sort内置方法操作 🔍 2.1 直接修改原列表 2.2 sort高级技巧与性能考量 2.3 案例:数据预处理实战 2.4 高级用法:reverse与cmp_to_key 3、应对复杂数据结构 🌐 3.1…

Yolo系列再次更新——清华发布Yolov10端到端实时对象检测模型

前期我们刚介绍过Yolo系列模型,还以为Yolov9刚刚发布,也许今年不会再有什么更新。但是没有想到打脸如此之快,Yolov10端到端实时对象检测模型强势回归发布。Yolov10端到端实时对象检测 YOLOv10 是清华大学研究人员在YOLO软件包的基础上,引入了一种新的实时目标检测方法,解决…

HTTP协议格式

目录 正文&#xff1a; 1.概述 2.主要特点 3.请求协议格式 4.响应协议格式 5.响应状态码 总结&#xff1a; 正文&#xff1a; 1.概述 HTTP 协议是用于传输超文本数据&#xff08;如 HTML&#xff09;的应用层协议&#xff0c;它建立在传输层协议 TCP/IP 之上。当我们在…

视频参考帧和重构帧复用

1、 视频编码中的参考帧和重构帧 从下图的编码框架可以看出&#xff0c;每编码一帧需要先使用当前帧CU(n)减去当前帧的参考帧CU&#xff08;n&#xff09;得到残差。同时&#xff0c;需要将当前帧的重构帧CU*&#xff08;n&#xff09;输出&#xff0c;然后再读取重构帧进行预测…

七、MyBatis-Plus高级用法:最优化持久层开发-个人版

七、MyBatis-Plus高级用法&#xff1a;最优化持久层开发 目录 文章目录 七、MyBatis-Plus高级用法&#xff1a;最优化持久层开发目录 一、MyBatis-Plus快速入门1.1 简介1.2 快速入门回顾复习 二、MyBatis-Plus核心功能2.1 基于Mapper接口CRUDInsert方法Delete方法Update方法Se…

PyQt5中如何实现指示灯点亮和指示灯熄灭功能

一般上位机界面都会涉及指示灯点亮和指示灯熄灭功能&#xff0c;从网上下载该功能的上位机界面&#xff0c;学习如何使用PyQt5搭建具备指示灯点亮和指示灯熄灭效果的界面。 1. 上位机界面的效果展示 使用PyQt5实现以下界面&#xff0c;界面效果如下&#xff0c;界面图片是从网…