【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.rhkb.cn/news/367275.html

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

相关文章

【高中数学/基本不等式】已知:a,b皆为正实数,且3a+2b=10 求:3a开方+2b开方的最大值?

【题目】 已知&#xff1a;a,b皆为正实数&#xff0c;且3a2b10 求&#xff1a;3a开方2b开方的最大值&#xff1f; 【解答】 解法一&#xff1a;&#xff08;基本不等式&#xff09; 原式^23a2*根号下(3a*2b)2b102*根号下(3a*2b)<103a2b101020 答&#xff1a;3a开方2b…

[漏洞复现] MetInfo5.0.4文件包含漏洞

[漏洞复现] MetInfo5.0.4文件包含漏洞 MetInfo5.0.4 漏洞代码审计 漏洞出现在about/index.php中&#xff0c;因为利用了动态地址&#xff0c;所以存在漏洞。 漏洞检查语句&#xff08;&#xff01;192.168.109.100是我的服务器ip&#xff0c;需要换成自己的&#xff09;&…

双曲方程初值问题的差分逼近(迎风格式)

稳定性: 数值例子 例一 例二 代码 % function chap4_hyperbolic_1st0rder_1D % test the upwind scheme for 1D hyperbolic equation % u_t + a*u_x = 0,0<x<L,O<t<T, % u(x,0) = |x-1|,0<X<L, % u(0,t) = 1% foundate = 2015-4-22’; % chgedate = 202…

SpringBoot 如何处理跨域请求?你说的出几种方法?

引言&#xff1a;在现代的Web开发中&#xff0c;跨域请求&#xff08;Cross-Origin Resource Sharing&#xff0c;CORS&#xff09;是一个常见的挑战。随着前后端分离架构的流行&#xff0c;前端应用通常运行在一个与后端 API 不同的域名或端口上&#xff0c;这就导致了浏览器的…

方法的用法

一.简介 目前为止我给出的所有的案例都是将代码放在main方法中&#xff0c;就会产生一些问题&#xff1a; 代码冗长&#xff0c;不利于维护变量过多&#xff0c;想不出那么多的变量名没有重用性 那么该如何解决呢&#xff1f; 我们可以编写功能性的代码块&#xff0c;来被ma…

华为DCN之:SDN和NFV

1. SDN概述 1.1 SDN的起源 SDN&#xff08;Software Defined Network&#xff09;即软件定义网络。是由斯坦福大学Clean Slate研究组提出的一种新型网络创新架构。其核心理念通过将网络设备控制平面与数据平面分离&#xff0c;从而实现了网络控制平面的集中控制&#xff0c;为…

【STM32 RTC实时时钟如何配置!超详细的解析和超简单的配置,附上寄存器操作】

STM32 里面RTC模块和时钟配置系统(RCC_BDCR寄存器)处于后备区域&#xff0c;即在系统复位或从待机模式唤醒后&#xff0c;RTC的设置和时间维持不变。因为系统对后备寄存器和RTC相关寄存器有写保护&#xff0c;所以如果想要对后备寄存器和RTC进行访问&#xff0c;则需要通过操作…

PHP校园论坛-计算机毕业设计源码08586

摘 要 本项目旨在基于PHP技术设计与实现一个校园论坛系统&#xff0c;以提供一个功能丰富、用户友好的交流平台。该论坛系统将包括用户注册与登录、帖子发布与回复、个人信息管理等基本功能&#xff0c;并结合社交化特点&#xff0c;增强用户之间的互动性。通过利用PHP语言及其…

14-15 为什么我们现在对阅读如此难以接受

写出来感觉很奇怪&#xff0c;但最近我感觉自己失去了阅读能力。长篇文本对我来说尤其具有挑战性。句子很难读完。更别提章节了。章节有很多段落&#xff0c;而段落又由许多句子组成。 啊。 即使在极少数情况下&#xff0c;我读完了一章&#xff0c;下一页上已经有另一章等着…

什么是自动气象站呢

自动气象站&#xff0c;作为现代气象观测的重要工具&#xff0c;已经深入到我们生活的各个领域&#xff0c;从气象预报到农业生产&#xff0c;再到环境保护&#xff0c;自动气象站都发挥着不可或缺的作用。 自动气象站&#xff0c;顾名思义&#xff0c;是一种能够自动收集、处理…

153. 寻找旋转排序数组中的最小值(中等)

153. 寻找旋转排序数组中的最小值 1. 题目描述2.详细题解3.代码实现3.1 Python3.2 Java 1. 题目描述 题目中转&#xff1a;153. 寻找旋转排序数组中的最小值 2.详细题解 如果不考虑 O ( l o g n ) O(log n) O(logn)的时间复杂度&#xff0c;直接 O ( n ) O(n) O(n)时间复杂…

基于Spring Boot的先进时尚室内管理系统

1 项目介绍 1.1 研究背景 随着21世纪信息技术革命的到来&#xff0c;互联网的普及与发展对人类社会的演变产生了深远影响&#xff0c;跨越了物质生活的丰盈边界&#xff0c;更深层次地滋养了人类的精神文化生活。在过去&#xff0c;囿于地理位置和技术条件的限制&#xff0c;…

【网络】网络基础(一)

网络基础&#xff08;一&#xff09; 文章目录 一、计算机网络背景1.1网络发展1.2认识“协议” 二、网络协议初识2.1OSI七层模型2.2OSI五层模型 三、网络传输基本流程3.1局域网通信3.2网络传输流程不跨子网的网络传输跨子网的网络传输 3.3网络中的地址管理IP地址MAC地址 一、计…

使用conda安装第三方包报错CondaSSLError

使用conda安装第三方包报错CondaSSLError 1. 报错信息2. 解决方法 1. 报错信息 错误描述&#xff1a;刚刚下载的 anaconda 在使用 conda 安装 pytorch 时报错&#xff08;CondaSSLError: OpenSSL appears to be unavailable on this machine. OpenSSL is required to download …

LeetCode题练习与总结:二叉树的后序遍历--145

一、题目描述 给你一棵二叉树的根节点 root &#xff0c;返回其节点值的 后序遍历 。 示例 1&#xff1a; 输入&#xff1a;root [1,null,2,3] 输出&#xff1a;[3,2,1]示例 2&#xff1a; 输入&#xff1a;root [] 输出&#xff1a;[]示例 3&#xff1a; 输入&#xff1a…

2002-2022年各省老年人口抚养比(人口抽样调查)数据

2002-2022年各省老年人口抚养比(人口抽样调查)数据 1、时间&#xff1a;2002-2022年 2、指标&#xff1a;老年人口抚养比 3、来源&#xff1a;国家统计局、统计年鉴 4、范围&#xff1a;31省&#xff0c; 5、缺失情况&#xff1a;无缺失&#xff0c;其中2010年的值取2009、…

Swift 中强大的 Key Paths(键路径)机制趣谈(下)

概览 在上一篇博文 Swift 中强大的 Key Paths(键路径)机制趣谈(上)中,我们介绍了 Swift 语言中键路径机制的基础知识,并举了若干例子讨论了它的一些用武之地。 而在本文中我们将再接再厉,继续有趣的键路径大冒险,为 KeyPaths 画上一个圆满的句号。 在本篇博文中,您将…

JavaScript之深入对象,详细讲讲构造函数与常见内置构造函数

前言&#xff1a;哈喽&#xff0c;大家好&#xff0c;我是前端菜鸟的自我修养&#xff01;今天给大家详细讲讲构造函数与常见内置构造函数&#xff0c;并提供具体代码帮助大家深入理解&#xff0c;彻底掌握&#xff01;原创不易&#xff0c;如果能帮助到带大家&#xff0c;欢迎…

笔记:Git学习之应用场景和使用经验

目标&#xff1a;整理Git工具的应用场景和使用经验 一、开发环境 Git是代码版本控制工具&#xff1b;Github是代码托管平台。 工具组合&#xff1a;VSCode Git 需要安装的软件&#xff1a;vscode、Git 其中vscode需要安装的插件&#xff1a;GitLens、Git History 二、应用…

Unity编辑器工具---版本控制与自动化打包工具

Unity - 特殊文件夹【作用与是否会被打包到build中】 Unity编辑器工具—版本控制与自动化打包工具&#xff1a; 面板显示&#xff1a;工具包含一个面板&#xff0c;用于展示软件的不同版本信息。版本信息&#xff1a;面板上显示主版本号、当前版本号和子版本号。版本控制功能…