//-------------------------------------------------------****MAIN FUNCTION ****------------------------------------------------ int main() { init_devices(); lcd_set_4bit(); lcd_init(); lcd_cursor(1,1); lcd_string("START"); _delay_ms(rand()); //--*** GRIPPER INITAL POSITION ***--- S2 = 0x73; cli(); timer0_init(); TIMSK |= (1 << OCIE0) | (1 << TOIE0); // timer 0 compare match and overflow interrupt enable sei(); pickup(); while(1) { if( bot_id_set == 1) { init_devices2(); init_grid(); dispersion(); localize(); region_division(); break; } } }
void MICROSTRIP::calc() { /* effective permeability */ mur_eff_ms(); /* static impedance */ microstrip_Z0(); /* calculate freq dependence of er and Z0 */ dispersion(); /* calculate electrical lengths */ line_angle(); /* calculate losses */ attenuation(); }
UpperTriangleVanillaSwaptionQuotes_ConstPTR create_UpperTriangleVanillaSwaptionQuotes(LMMTenorStructure_PTR pLMMTenorStructure, const Tenor& tenorfixedleg, const Tenor& tenorfloatleg) { /// Creation of Rebonato Approx ================================== size_t nbFactor = 3; // need to test nbFactor = 3, and nbFactor = size_t correlFullRank = pLMMTenorStructure->get_horizon()+1; size_t correlReducedRank = nbFactor; CorrelationReductionType::CorrelationReductionType correlReductionType = CorrelationReductionType::PCA; double correlAlpha = 0.0; double correlBeta = 0.1; Correlation_PTR correlation(new XY_beta_Correlation(correlFullRank,correlReducedRank, correlReductionType,correlAlpha,correlBeta)); correlation->calculate(); // for print. double a=0.22,b=0.4,c=0.6,d=0.15; double g_constParam = 1.; double shift_constParam = 0.0; Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d); ConstShifted_HGVolatilityParam_PTR pConstShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam(pLMMTenorStructure, abcdParam, g_constParam, shift_constParam)); Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, correlation, pConstShifted_HGVolatilityParam)); //! Dispersion Dispersion dispersion(pVolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmApproxVanillaSwaptionPricer(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); /// End of creation of Rebonato Approx ================================== LiborQuotes_ConstPTR libor_quote_ptr = LiborQuotes::create_LiborInit(pLMMTenorStructure, 0.02); UpperTriangleVanillaSwaptionQuotes_ConstPTR atm_swaption_implied_vol_ptr = UpperTriangleVanillaSwaptionQuotes::create_ATMSwaptionImpliedVol( libor_quote_ptr, tenorfixedleg, tenorfloatleg, pLmmApproxVanillaSwaptionPricer ); //assert( atm_swaption_implied_vol_ptr->check_swaprate_consistency(libor_quote_ptr) ); return atm_swaption_implied_vol_ptr; }
double ResponseTable::dispersionVospr() const { assert(m_values.size() > 0); if(m_values[0].size() < 2) { return disp_at_center(); } assert(m_values[0].size() > 1); double result = 0; int count = 0; for(size_t i = 0; i < m_values.size(); i++) { int freedoms = trusted_values_at(i).size() - 1; double disp = dispersion(i); result += disp * freedoms; count += freedoms; } result = result / (double)count; return result; }
int ResponseTable::ongenericalDispersion(StaticCriteria criteria, double prob) { if(m_values.size() < 1 || m_values[0].size() < 2) return 1; vector<double> dispersions; for(size_t i = 0; i < m_values.size(); i++) dispersions.push_back(dispersion(i)); if(criteria == Fisher) { double minD = dispersions[0], maxD = dispersions[0]; int minF = trusted_values_at(0).size() - 1, maxF = trusted_values_at(0).size() - 1; for(size_t i = 1; i < dispersions.size(); i++) { double d = dispersions[i]; int f = trusted_values_at(i).size() - 1; if(d < minD) { minD = d; minF = f; } if(d > maxD) { maxD = d; maxF = f; } } double Ft = FisherCriteria::GetFisherVal(minF, maxF); double F = 0; if(minD == 0) return false; else F = maxD / minD; return Ft > F ? 1 : 0; } else if(criteria == Kohren) { size_t trusted = trusted_values_at(0).size() - 1; for(size_t i = 1; i < dispersions.size(); i++) if(trusted != trusted_values_at(i).size() - 1) { error = "Проверяемые дисперсии имеют разные степени свободы"; return -1; } double maxDisp = 0, dispSum = 0; for(size_t i = 0; i < dispersions.size(); i++) { dispSum += dispersions[i]; if(maxDisp < dispersions[i]) maxDisp = dispersions[i]; } double Cr = maxDisp / dispSum; double tableVal = KohrenCriteria::GetCriteriaVal(dispersions.size(), trusted_values_at(0).size() - 1); return Cr < tableVal ? 1 : 0; } else if(criteria == Bartlet) { for(size_t i = 0; i < dispersions.size(); i++) if(trusted_values_at(i).size() - 1 < 3) { error = "Степени свободы всех дисперсий должны быть больше 3х"; return -1; } double svDisp = 0; int f_sum = 0; for(size_t i = 0; i < dispersions.size(); i++) { svDisp += dispersions[i] * (trusted_values_at(i).size() - 1); f_sum += trusted_values_at(i).size() - 1; } svDisp /= f_sum; if(svDisp == 0) return 1; double temp = 0; for(size_t i = 0; i < dispersions.size(); i++) temp += (trusted_values_at(i).size() - 1) * log10(dispersions[i]); temp = f_sum * log10(svDisp) - temp; temp *= 2.303; // chislitel double tmp = 0; for(size_t i = 0; i < dispersions.size(); i++) tmp += 1 / (double)(trusted_values_at(i).size() - 1); tmp -= 1 / (double)f_sum; tmp *= 1 / (double)(3 * (dispersions.size() - 1)); tmp += 1; double B = temp / tmp; double val = BartleteCriteria::GetCriteriaVal((int)(f_sum / dispersions.size()), prob); return val > B ? 1 : 0; } }
void Test_McGeneticSwapLMMPricer() { //! Parameters double strike = 0.02; LMM::Index indexStart = 0; LMM::Index indexEnd = 20; Tenor floatingTenor = Tenor::_6M; Tenor fixedTenor = Tenor::_12M; Tenor tenorStruture = Tenor::_6M; size_t horizonYear = 10; LMMTenorStructure_PTR lmmTenorStructure( new LMMTenorStructure(tenorStruture, horizonYear)); cout << "strike: " << strike << endl; cout << "indexStart: " << indexStart << endl; cout << "indexEnd: " << indexEnd << endl; cout << "tenorStrutureYearFraction: " << lmmTenorStructure->get_tenorType().YearFraction() << endl; cout << "floatingVStenorStrutureRatio: " << floatingTenor.ratioTo(tenorStruture) << endl; cout << "fixedVStenorStrutureRatio: " << fixedTenor.ratioTo(tenorStruture) << endl; double fwdRate = 0.02; std::vector<double> liborsInitValue(lmmTenorStructure->get_horizon()+1, fwdRate); cout << "myInitialLibor: "; for (size_t i = 0; i <liborsInitValue.size(); i++) { cout << liborsInitValue[i] << " "; } cout << endl; cout << endl; //VanillaSwap_Chi_Trang VanillaSwap firstVersionVanillaSwap(strike, indexStart , indexEnd, floatingTenor, fixedTenor, lmmTenorStructure); LmmVanillaSwapPricer myVSP(lmmTenorStructure); double FirstVersionSwapPrice = myVSP.swapNPV_Analytical_1(firstVersionVanillaSwap, liborsInitValue); //---------------------------Build Lmm and McLmm's structure-------------------------------------- //! Parameter of h double a = -0.06; double b = 0.17; double c = 0.54; double d = 0.17; Shifted_HGVolatilityParam::ABCDParameter abcdParam (a,b,c,d); //Parameter of hg double g_constParam = 1.0; double shift_constParam = -0.01; ConstShifted_HGVolatilityParam_PTR hgParam( new ConstShifted_HGVolatilityParam(lmmTenorStructure,abcdParam,g_constParam,shift_constParam)); //! Correlation 1 size_t nbFactor = 3; // need to test nbFactor = 3, and nbFactor = size_t correlFullRank = lmmTenorStructure->get_horizon()+1; size_t correlReducedRank = nbFactor; //!"Check Parameters(): Condition not implemented yet." std::cout << "checkParams(): "; CorrelationReductionType::CorrelationReductionType correlReductionType = CorrelationReductionType::PCA; double correlAlpha = 0.0; double correlBeta = 0.1; Correlation_PTR correlation(new XY_beta_Correlation(correlFullRank,correlReducedRank, correlReductionType,correlAlpha,correlBeta)); correlation->calculate(); // for print. correlation->print("test_McTerminalLmm_Correlation.csv"); //hgVolatilityFunction ConstShifted_HGVolatilityFunction_PTR hgVolatilityFunction (new ConstShifted_HGVolatilityFunction(lmmTenorStructure, correlation, hgParam)); hgVolatilityFunction->print("test_McTerminalLmm_Volatility.csv"); //! Dispersion Dispersion dispersion(hgVolatilityFunction); unsigned long seed = 5033; RNGenerator_PTR rnGenerator(new McGenerator(seed)); //build lmm and mcLmm model Lmm_PTR shiftedLmm (new Lmm(dispersion)); McLmm_PTR mcLmm(new McTerminalLmm(shiftedLmm, liborsInitValue, rnGenerator, MCSchemeType::EULER)); //build a McGeneticSwapLMMPricer McGeneticSwapLMMPricer_PTR mcGeneticSwapLMMPricer(new McGeneticSwapLMMPricer(mcLmm)); //build the geneticVanillaSwap GeneticSwap_CONSTPTR vanillaSwap_Genetic=InstrumentFactory::createVanillaSwap( strike,indexStart,indexEnd,floatingTenor,fixedTenor,lmmTenorStructure,1.0); //use Monte Carlo Method size_t nbSimulation=10000; double MonteCarloPrice = mcGeneticSwapLMMPricer->swapNPV(vanillaSwap_Genetic, nbSimulation); //ordinaryGeneticVanillaSwapPricer GeneticVanillaSwapPricer_PTR geneticVanillaSwapPricer(new GeneticVanillaSwapPricer()); double OrdinaryGeneticVanillaSwapPrice = geneticVanillaSwapPricer->geneticVanillaSwap_Analytical(vanillaSwap_Genetic,liborsInitValue); //subVanillaSwap LMM::Index subIndexStart = 10; LMM::Index subIndexEnd = 16; GeneticSwap_CONSTPTR subVanillaSwap_Genetic=InstrumentFactory::createVanillaSwap( strike,subIndexStart,subIndexEnd,floatingTenor,fixedTenor,lmmTenorStructure,1.0); double subMonteCarloPrice = mcGeneticSwapLMMPricer->swapNPV(subVanillaSwap_Genetic, nbSimulation); //subOrdinaryGeneticVanillaSwapPrice double subOrdinaryGeneticVanillaSwapPrice = geneticVanillaSwapPricer->geneticVanillaSwap_Analytical(subVanillaSwap_Genetic,liborsInitValue); //subFirstVersionVanillaSwapPrice VanillaSwap subFirstVersionVanillaSwap(strike, subIndexStart , subIndexEnd, floatingTenor, fixedTenor, lmmTenorStructure); double subFirstVersionSwapPrice = myVSP.swapNPV_Analytical_1(subFirstVersionVanillaSwap, liborsInitValue); cout << "MonteCarloPrice: " << MonteCarloPrice << endl; cout << "OrdinaryGeneticVanillaSwapPrice: " << OrdinaryGeneticVanillaSwapPrice << endl; cout << "FirstVersionSwapPrice: " << FirstVersionSwapPrice << endl; cout << "Difference between MonteCarloPrice and OrdinaryGeneticVanillaSwapPrice: " << MonteCarloPrice-OrdinaryGeneticVanillaSwapPrice << endl; cout << "Difference between OrdinaryGeneticVanillaSwapPrice and FirstVersionSwapPrice: " << OrdinaryGeneticVanillaSwapPrice-FirstVersionSwapPrice << endl; cout << "subMonteCarloPrice: " << subMonteCarloPrice << endl; cout << "subOrdinaryGeneticVanillaSwapPrice: " << subOrdinaryGeneticVanillaSwapPrice << endl; cout << "subFirstVersionSwapPrice: " << subFirstVersionSwapPrice << endl; cout << "Difference between subMonteCarloPrice and subOrdinaryGeneticVanillaSwapPrice: " << subMonteCarloPrice-subOrdinaryGeneticVanillaSwapPrice << endl; cout << "Difference between subOrdinaryGeneticVanillaSwapPrice and subFirstVersionSwapPrice: " << subOrdinaryGeneticVanillaSwapPrice-subFirstVersionSwapPrice << endl; ofstream o; o.open("TestResult_GeneticVanillaSwap_05_06.csv", ios::out | ios::app ); o << endl; o << endl; o << endl; o << "strike: " << strike << endl; o << "indexStart: " << indexStart << endl; o << "indexEnd: " << indexEnd << endl; o << "floatingTenorVSLmmStructureTenorRatio: " << floatingTenor.ratioTo(lmmTenorStructure->get_tenorType()) << endl; o << "fixedTenorVSLmmStructureTenorRatio: " << fixedTenor.ratioTo(lmmTenorStructure->get_tenorType()) << endl; o << "floatingTenorYearFraction: " << floatingTenor.YearFraction() << endl; o << "fixedTenorYearFraction: " << fixedTenor.YearFraction() << endl; o << "horizonYear: " << horizonYear << endl; o << "liborsInitValue: "; for(size_t i=0; i<liborsInitValue.size(); i++) { o << liborsInitValue[i] << " "; } o << endl; o << "nbSimulation: " << nbSimulation << endl; o << "PRICES: " << endl; o << "MonteCarloPrice: " << MonteCarloPrice << endl; o << "OrdinaryGeneticVanillaSwapPrice: " << OrdinaryGeneticVanillaSwapPrice << endl; o << "FirstVersionSwapPrice: " << FirstVersionSwapPrice << endl; o << "Difference between MonteCarloPrice and OrdinaryGeneticVanillaSwapPrice: " << MonteCarloPrice-OrdinaryGeneticVanillaSwapPrice << endl; o << "Difference between OrdinaryGeneticVanillaSwapPrice and FirstVersionSwapPrice: " << OrdinaryGeneticVanillaSwapPrice-FirstVersionSwapPrice << endl; o << "SUBPRICES: "<< endl; o << "subIndexStart: " << subIndexStart << endl; o << "subIndexEnd: " << subIndexEnd << endl; o << "subMonteCarloPrice: " << subMonteCarloPrice << endl; o << "subOrdinaryGeneticVanillaSwapPrice: " << subOrdinaryGeneticVanillaSwapPrice << endl; o << "subFirstVersionSwapPrice: " << subFirstVersionSwapPrice << endl; o << "Difference between subMonteCarloPrice and subOrdinaryGeneticVanillaSwapPrice: " << subMonteCarloPrice-subOrdinaryGeneticVanillaSwapPrice << endl; o << "Difference between subOrdinaryGeneticVanillaSwapPrice and subFirstVersionSwapPrice: " << subOrdinaryGeneticVanillaSwapPrice-subFirstVersionSwapPrice << endl; o.close(); }
static void *trigger_run(void *arg) { int buttons_fd; int flags=0, flags2=0; struct st_caller *caller; buttons_fd = open("/dev/buttons", 0); if (buttons_fd < 0) { perror("open device buttons"); exit(1); } #if 1 for (;;) { char current_buttons[6]; if (read(buttons_fd, current_buttons, sizeof current_buttons) != sizeof current_buttons) { perror("read buttons:"); exit(1); } if (current_buttons[3] == '1' && flags2== 0 ){ usleep(5000); } if (current_buttons[3] == '0' && flags2 == 1){ usleep(5000); } if (current_buttons[3] == '1' && flags2 == 0){ int ret; struct st_matrix *matrix; struct st_action_unit unit; bzero(&unit, sizeof unit); flags2 = 1; pthread_mutex_lock( &plan_mutex); matrix = gmatrix; if (!matrix){ printf("head_caller err, matrix is NULL\n"); pthread_mutex_unlock(&plan_mutex); break; } if (current_buttons[4] == '0' && flags ==1 && ARM_STATE == CALLER_SEND_BUSY){ flags = 0; pthread_mutex_lock( &plan_mutex); caller_op(CALLER_SEND_IDEL); pthread_mutex_unlock( &plan_mutex); printf(" CALLER - BUS = %x\n", ARM_STATE); } ARM_STATE = CALLER_SEND_BUSY; matrix->matrix_state[MATRIX_STATE] = MATRIX_CALLER; unit.dev_addr = matrix->dev.addr; unit.sdata[0] = 1; unit.sdata[1] = 0xff; unit.ssize = 2; ret = dispersion(&unit); if (ret < 0){ printf("head_caller err, dispersion return err\n"); matrix->matrix_state[MATRIX_STATE] = MATRIX_IDLE; pthread_mutex_unlock(&plan_mutex); break; } matrix->matrix_state[MATRIX_STATE] = MATRIX_BUSY; pthread_mutex_unlock( &plan_mutex); } else if ( current_buttons[3] == '0' && flags2 == 1 ){ struct st_matrix *matrix; int ret; matrix = gmatrix; printf("free\n"); //if( matrix->matrix_state[MATRIX_STATE] == MATRIX_BUSY) { // matrix->matrix_state[MATRIX_STATE] = MATRIX_CALLER; ret = matrix_load_state(matrix); if( ret < 0) matrix->matrix_state[MATRIX_STATE] = MATRIX_ERR; else matrix->matrix_state[MATRIX_STATE] = MATRIX_IDLE; //} { struct st_action_unit new_unit; struct st_select_amp *amp; bzero(&new_unit, sizeof(new_unit)); for( amp= gselect_amp; amp; amp = amp->next) { if( amp->select_state[SELECT_AMP_STATE] == SELECT_AMP_BUSY){ int ret; amp->select_state[SELECT_AMP_STATE] = SELECT_AMP_CALLER; ret = select_amp_load_state(amp); if( ret < 0){ amp->select_state[SELECT_AMP_STATE] = SELECT_AMP_ERR; continue; } amp->select_state[SELECT_AMP_STATE] = SELECT_AMP_IDLE; } } } ARM_STATE = CALLER_SEND_IDEL; flags2 = 0; } if(current_buttons[4] == '1' && flags == 0 && ARM_STATE == CALLER_SEND_IDEL) { usleep(5000); } if( current_buttons[4] == '1' && flags == 0 && ARM_STATE == CALLER_SEND_IDEL) { int ret; flags =1; pthread_mutex_lock( &plan_mutex); ret = caller_op( CALLER_SEND_LOOP ); if( ret < 0 ){ flags = 0; pthread_mutex_unlock( &plan_mutex); } pthread_mutex_unlock( &plan_mutex); for(caller=gcaller; caller; caller = caller->next) { printf("caller: \n\taddr=%x\n\tstate = %x\n", caller->dev.addr, caller->caller_state); } printf(" CALLER - BUS = %x\n", ARM_STATE); }else if (current_buttons[4] == '0' && flags ==1 && ARM_STATE == CALLER_SEND_BUSY){ flags = 0; pthread_mutex_lock( &plan_mutex); caller_op(CALLER_SEND_IDEL); pthread_mutex_unlock( &plan_mutex); for(caller=gcaller; caller; caller = caller->next) { printf("caller: \n\taddr=%x\n\tstate = %x\n", caller->dev.addr, caller->caller_state); } printf(" CALLER - BUS = %x\n", ARM_STATE); // system("madplay /0.mp3"); } sleep(1); } #endif close(buttons_fd); return NULL; }
typename std::enable_if<sizeof...(Args) == D, real_type>::type dispersion(std::tuple<Args...> in){ auto f = [this](Args... in){return dispersion(in...);}; return tuple_tools::unfold_tuple(f,in); };
/** Returns an analytic std::function of the dispersion. */ ArgFunType get_dispersion(){ return tools::extract_tuple_f(std::function<real_type(arg_tuple)>([this](arg_tuple in){return dispersion(in);})); }
Shifted_HGVolatilityFunction_PTR JB_marketData_LMM_ABCD_calibration(const LmmCalibrationConfig& config, LmmSwaptionMarketData_PTR pLmmSwaptionMarketData) { std::string base_name = pLmmSwaptionMarketData->get_MarketDataBaseFileName() ; size_t nbYear = pLmmSwaptionMarketData->get_nbYear(); Tenor tenorfixedleg = Tenor::_1YR ; // A corriger Tenor tenorfloatleg = Tenor::_6M ; size_t fixedfloatRatio = tenorfixedleg.ratioTo(tenorfloatleg); //create LMM components LMMTenorStructure_PTR pLMMTenorStructure( new LMMTenorStructure(tenorfloatleg,nbYear) ); ConstShifted_HGVolatilityParam_PTR pNoShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam(pLMMTenorStructure, config.vol_abcd_ , 1., 0.)); //! create correlation Correlation_PTR pCorrelation = JB_create_InitCorrelation(config); Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, pCorrelation, pNoShifted_HGVolatilityParam)); Dispersion dispersion(pVolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); //! Create Approximation Rebonato LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmVanillaSwaptionApproxPricer_Rebonato(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); pLmmVanillaSwaptionApproxPricer_Rebonato->update_VolatilityParam(pNoShifted_HGVolatilityParam); LmmBaseCostFunction_PTR abcd_costFucntion (new LmmABCDCostFunction ( pLmmVanillaSwaptionApproxPricer_Rebonato , pLmmSwaptionMarketData->get_LiborQuotes() , pLmmSwaptionMarketData->get_SwaptionQuotes_ATM() , pNoShifted_HGVolatilityParam )); QuantLib::Array init_abcd(4); init_abcd[0]=config.vol_abcd_.a_; init_abcd[1]=config.vol_abcd_.b_; init_abcd[2]=config.vol_abcd_.c_; init_abcd[3]=config.vol_abcd_.d_; size_t maxIterations = 1000; size_t minStatIterations = 100; double rootEpsilon =1e-14; double functionEpsilon =1e-14; double gradientNormEpsilon =0; LmmABCDCalibrator lmm_abcd_calibrator(init_abcd, maxIterations, rootEpsilon,functionEpsilon,abcd_costFucntion); lmm_abcd_calibrator.add_ConstraintCell(std::pair<size_t,size_t>(1,1) ); lmm_abcd_calibrator.add_ConstraintCell(std::pair<size_t,size_t>(2,2) ); lmm_abcd_calibrator.add_ConstraintCell(std::pair<size_t,size_t>(1,3) ); lmm_abcd_calibrator.add_ConstraintCell(std::pair<size_t,size_t>(3,1) ); //lmm_abcd_calibrator.add_ConstraintCell(std::pair<size_t,size_t>(6,6) ); //lmm_abcd_calibrator.add_ConstraintCell(std::pair<size_t,size_t>(8,8) ); lmm_abcd_calibrator.activate_PositiveConstraint(); lmm_abcd_calibrator.solve(); std::string result_file =base_name + "_abcd_calibration_result.csv"; lmm_abcd_calibrator.printPlusPlus(result_file); std::string calibrated_abcd_file = base_name + "_abcd_calibrated.csv"; pNoShifted_HGVolatilityParam->print(calibrated_abcd_file); // print in a common file { std::string common_result_file_name = "calib_result_ABCD.csv"; std::string full_common_result_file = LMMPATH::get_Root_OutputPath() + common_result_file_name ; std::ofstream final_result ; final_result.open(full_common_result_file.c_str(), std::ios::app); final_result<<std::endl<<std::endl<< "============= Test At "<<LMMPATH::get_TimeDateNow() <<",,,,,, Error LInf, "<<lmm_abcd_calibrator.get_QuoteError_LInf() <<std::endl ; final_result<< lmm_abcd_calibrator.get_BaseGeneral_Result_Info(); final_result.close(); } return pVolatilityFunction; }
inline real_type LatticeDMFTSC<LatticeT>::dispersion(const std::tuple<ArgTypes...>& kpoints) const { static_assert(sizeof...(ArgTypes) == _D, "Number of points mismatch!" ); std::function<real_type(ArgTypes...)> f1 = [&](ArgTypes... kpoints)->real_type{return dispersion(kpoints...);}; auto f2 =tools::tuple_f(f1); return std::real(f2(kpoints)); }
Shifted_HGVolatilityFunction_PTR JB_marketData_LMM_shift_Calibration( const LmmCalibrationConfig& config , LmmSwaptionMarketData_PTR pLmmSwaptionMarketData , Shifted_HGVolatilityFunction_PTR param_h_g_function ) { assert(!config.use_local_calib_); size_t nbYear= pLmmSwaptionMarketData->get_nbYear(); std::string base_file_name = pLmmSwaptionMarketData->get_MarketDataBaseFileName(); Tenor tenorfixedleg = Tenor::_1YR ; Tenor tenorfloatleg = Tenor::_6M ; size_t fixedfloatRatio = tenorfixedleg.ratioTo(tenorfloatleg); std::string base_name; base_name = base_file_name+"_shift_gMatrix_Calibration" ; Shifted_HGVolatilityParam_PTR param_h_g = param_h_g_function->get_ShiftedHGVolatilityParam_PTR(); //create LMM components LMMTenorStructure_PTR pLMMTenorStructure( new LMMTenorStructure(tenorfloatleg,nbYear) ); const double a=param_h_g->get_ABCD().a_; const double b=param_h_g->get_ABCD().b_; const double c=param_h_g->get_ABCD().c_; const double d=param_h_g->get_ABCD().d_; Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d); const Shifted_HGVolatilityParam::LowerTriangularMatrix& gMatrix=param_h_g->get_gMatrix(); QuantLib::Array shiftValues_QL = param_h_g->get_ArrayFrom_Shift(); std::vector<double> shiftValues(shiftValues_QL.size()); for(size_t i=0; i<shiftValues_QL.size(); i++) shiftValues[i]=shiftValues_QL[i]; //const std::vector<double> shiftedVector(gMatrix.size1(), 0.0); ConstShifted_HGVolatilityParam_PTR pShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam( pLMMTenorStructure, abcdParam, gMatrix, shiftValues)); Shifted_HGVolatilityFunction_PTR pShifted_VolatilityFunction (new ConstShifted_HGVolatilityFunction( pLMMTenorStructure, param_h_g_function->get_Correlation_PTR(), pShifted_HGVolatilityParam)); Dispersion dispersion(pShifted_VolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmVanillaSwaptionApproxPricer_Rebonato(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); // create gMatrixMapping //size_t g_matrix_size = GMatrixMapping::get_gSizeFromNbYear(nbYear,fixedfloatRatio ); //size_t delegate_matrix_size = GMatrixMapping::get_gDelegateSizeFromHorizon(pLMMTenorStructure->get_horizon() ,fixedfloatRatio ); //UpperTriangularDoubleMatrix empty_delegate_matrix(delegate_matrix_size,delegate_matrix_size); //pShifted_HGVolatilityParam->reset_g_matrix(gMatrix); pLmmVanillaSwaptionApproxPricer_Rebonato->update_VolatilityParam(pShifted_HGVolatilityParam); // Create const function //LmmPenalty_PTR pLmmPenalty(new LmmPenalty(config.penalty_time_homogeneity_,config.penalty_libor_) ); //LmmBaseCostFunction_PTR pLmmCostFunction(new LmmGlobal_gCostFunction // ( // pLmmVanillaSwaptionApproxPricer_Rebonato, // pLmmSwaptionMarketData->get_LiborQuotes(), // pLmmSwaptionMarketData->get_SwaptionQuotes_ATM(), // pGMatrixMapping, // pNoShifted_HGVolatilityParam, // pLmmPenalty // ) ); const double const_rate=0.02; const double quoted_strike_bump=0.0001; LmmSwaptionMarketData_PTR lmmSwaptionMarketData(new LmmSwaptionMarketData(tenorfixedleg, tenorfloatleg, gMatrix.size1()+3)); LmmSkewCostFunction lmmSkewCostFunction( pLmmVanillaSwaptionApproxPricer_Rebonato // pricer , pLmmSwaptionMarketData->get_LiborQuotes() , quoted_strike_bump , pLmmSwaptionMarketData->get_SwaptionQuotes_skew()// instrument to calibrate , param_h_g ); //for(size_t i = 0; i < 3; i++) //{ // for (size_t j = 1; j < nbYear-i; j++) // { // lmmSkewCostFunction.addContraintCell(std::pair<size_t,size_t>(j,nbYear-i-j)); // } //} //costumize swaptions weights //UpperTriangularDoubleMatrix swpm_weight_matrix = pLmmCostFunction->get_SwaptionWeightMatrix(); //swpm_weight_matrix(7,1)=1e-6; //swpm_weight_matrix(10,1)=1e-6; //swpm_weight_matrix(5,3)=0.; //pLmmCostFunction->reset_SwaptionWeightMatrix(swpm_weight_matrix); // Create Calibrator QuantLib::Array init_shift(gMatrix.size1(),0.01); LmmShiftCalibrator lmmShiftCalibrator ( init_shift , 200 //maxIter , 1e-11 //x_epsilon , 1e-11 //f_epsilon , lmmSkewCostFunction ); //if(config.use_positive_constraint_) // lmmShiftCalibrator.activate_PositiveConstraint(); lmmShiftCalibrator.solve(); std::ostringstream file_result_stream;file_result_stream<<base_name<<"_result.csv"; std::string file_calibration_result(file_result_stream.str()); lmmShiftCalibrator.printPlusPlus(file_calibration_result); std::ostringstream file_vol_stream; file_vol_stream<<base_name<<".csv"; std::string file_calibrated_vol(file_vol_stream.str() ); param_h_g->print(file_calibrated_vol); pLmmSwaptionMarketData->print("pLmmSwaptionMarketData.csv"); //std::ostringstream file_result_stream;file_result_stream<<base_name<<penalty_info_str<<"_result.csv"; //std::string file_calibration_result(file_result_stream.str()); //lmmShiftCalibrator.printPlusPlus(file_calibration_result); //std::ostringstream file_vol_stream;file_vol_stream<<base_name<<penalty_info_str<<"_vol.csv"; //std::string file_calibrated_vol(file_vol_stream.str() ); //pShifted_HGVolatilityParam->print( file_calibrated_vol ); //{ // std::string common_result_file_name = "calib_result_Shift_gGlobal.csv"; // std::string full_common_result_file = LMMPATH::get_Root_OutputPath() + common_result_file_name ; // std::ofstream final_result ; // final_result.open(full_common_result_file.c_str(), std::ios::app); // final_result<<std::endl<<std::endl<< "============= Test At "<<LMMPATH::get_TimeDateNow() // <<",,,,,, Error LInf, "<<lmmShiftCalibrator.get_QuoteError_LInf() <<std::endl ; // final_result<< lmmShiftCalibrator.get_BaseGeneral_Result_Info(); // final_result.close(); //} return pShifted_VolatilityFunction; }
GMatrix_Vol_gMapping JB_marketData_LMM_Global_gCalibration( const LmmCalibrationConfig& config , LmmSwaptionMarketData_PTR pLmmSwaptionMarketData , Shifted_HGVolatilityFunction_PTR shifted_HGVolatilityFunction , Correlation_PTR found_correlation_ptr , GMatrixMapping_PTR init_gMapping ) { assert(!config.use_local_calib_); //? size_t nbYear = pLmmSwaptionMarketData->get_nbYear(); //nbYear std::string base_file_name = pLmmSwaptionMarketData->get_MarketDataBaseFileName(); Tenor tenorfixedleg = Tenor::_1YR ; Tenor tenorfloatleg = Tenor::_6M ; size_t fixedfloatRatio = tenorfixedleg.ratioTo(tenorfloatleg); std::string base_name; base_name = base_file_name+"_gMatrixGlobalCalibration" ; Shifted_HGVolatilityParam_PTR shifted_HGVolatilityParam = shifted_HGVolatilityFunction->get_ShiftedHGVolatilityParam_PTR(); //create LMM components LMMTenorStructure_PTR pLMMTenorStructure( new LMMTenorStructure(tenorfloatleg,nbYear) ); const double a=shifted_HGVolatilityParam->get_ABCD().a_; const double b=shifted_HGVolatilityParam->get_ABCD().b_; const double c=shifted_HGVolatilityParam->get_ABCD().c_; const double d=shifted_HGVolatilityParam->get_ABCD().d_; QuantLib::Array shiftValues_QL = shifted_HGVolatilityParam->get_ArrayFrom_Shift(); std::vector<double> shiftValues(shiftValues_QL.size()); for(size_t i=0; i<shiftValues_QL.size(); i++) shiftValues[i]=shiftValues_QL[i]; const Shifted_HGVolatilityParam::LowerTriangularMatrix pGMatrix(shifted_HGVolatilityParam->get_gMatrix()); Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d); ConstShifted_HGVolatilityParam_PTR pShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam( pLMMTenorStructure, abcdParam, pGMatrix, shiftValues)); Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, found_correlation_ptr, pShifted_HGVolatilityParam)); Dispersion dispersion(pVolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmVanillaSwaptionApproxPricer_Rebonato(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); // create gMatrixMapping size_t g_matrix_size = GMatrixMapping::get_gSizeFromNbYear(nbYear,fixedfloatRatio ); size_t delegate_matrix_size = GMatrixMapping::get_gDelegateSizeFromHorizon(pLMMTenorStructure->get_horizon() ,fixedfloatRatio ); UpperTriangularDoubleMatrix empty_delegate_matrix(delegate_matrix_size,delegate_matrix_size); GMatrixMapping_PTR pGMatrixMapping; if(init_gMapping) { pGMatrixMapping = init_gMapping; } else { //initiate gMatrixMapping all gDelegate to 1 pGMatrixMapping.reset( new GMatrixMapping(g_matrix_size, empty_delegate_matrix, pLmmSwaptionMarketData->get_SwaptionQuotes_ATM()->get_UpperTriangularIndexPairMatrix()) ); QuantLib::Array g_delegate_vector = pGMatrixMapping->get_DelegateArray(); for(size_t i=0;i<g_delegate_vector.size();++i) g_delegate_vector[i] = 1.; pGMatrixMapping->reset_gDelegate(g_delegate_vector); } pShifted_HGVolatilityParam->reset_g_matrix( pGMatrixMapping->get_g_Ref() ); pLmmVanillaSwaptionApproxPricer_Rebonato->update_VolatilityParam(pShifted_HGVolatilityParam); // Create const function LmmPenalty_PTR pLmmPenalty(new LmmPenalty(config.penalty_time_homogeneity_,config.penalty_libor_) ); LmmBaseCostFunction_PTR pLmmCostFunction(new LmmGlobal_gCostFunction ( pLmmVanillaSwaptionApproxPricer_Rebonato, pLmmSwaptionMarketData->get_LiborQuotes(), pLmmSwaptionMarketData->get_SwaptionQuotes_ATM(), pGMatrixMapping, pShifted_HGVolatilityParam, pLmmPenalty ) ); //costumize swaptions weights UpperTriangularDoubleMatrix swpm_weight_matrix = pLmmCostFunction->get_SwaptionWeightMatrix(); //swpm_weight_matrix(7,1)=1e-6; //swpm_weight_matrix(10,1)=1e-6; //swpm_weight_matrix(5,3)=0.; pLmmCostFunction->reset_SwaptionWeightMatrix(swpm_weight_matrix); //std::ostringstream file_costfunc_stream;file_costfunc_stream<<base_name<<"Calibration_"<<nbYear<<"YR_pel_time"<<penalty_time_homogene<<"_pel_lib"<<penalty_libor <<"_LmmCostFunction.csv"; //pLmmCostFunction->print( file_costfunc_stream.str() ); // Create Calibrator LmmGlobal_gCalibrator lmmCalibrator ( *pGMatrixMapping.get() , 200 //maxIter , 1e-11 //x_epsilon , 1e-11 //f_epsilon , pLmmCostFunction ); if(config.use_positive_constraint_) lmmCalibrator.activate_PositiveConstraint(); lmmCalibrator.solve(); std::string penalty_info_str; if( !pLmmPenalty->isEmpty() ) { const double pT = config.penalty_time_homogeneity_; const double pL = config.penalty_libor_ ; std::ostringstream pel; pel<<"_pT_"<<pT<<"_pL_"<<pL; penalty_info_str = pel.str(); } std::ostringstream file_result_stream;file_result_stream<<base_name<<penalty_info_str<<"_result.csv"; std::string file_calibration_result(file_result_stream.str()); lmmCalibrator.printPlusPlus(file_calibration_result); std::ostringstream file_gDelegate_stream;file_gDelegate_stream<<base_name<<penalty_info_str<<"_gDelegate.csv"; std::string file_gDelegate_vol(file_gDelegate_stream.str() ); pGMatrixMapping->print(file_gDelegate_vol); std::ostringstream file_vol_stream;file_vol_stream<<base_name<<penalty_info_str<<"_vol.csv"; std::string file_calibrated_vol(file_vol_stream.str() ); pShifted_HGVolatilityParam->print( file_calibrated_vol ); config.result_quote_error_l2 = lmmCalibrator.get_QuoteError_L2(); config.result_quote_error_l1 = lmmCalibrator.get_QuoteError_L1(); config.result_quote_error_linf = lmmCalibrator.get_QuoteError_LInf(); if( !pLmmPenalty->isEmpty() ) { config.result_pelTime_error_l2 = lmmCalibrator.get_PenaltyTimeHomogeneity_L2(); config.result_pelTime_error_l1 = lmmCalibrator.get_PenaltyTimeHomogeneity_L1(); config.result_pelTime_error_linf = lmmCalibrator.get_PenaltyTimeHomogeneity_L_INF(); config.result_pelLibor_error_l2 = lmmCalibrator.get_PenaltySmoothMaturity_L2(); config.result_pelLibor_error_l1 = lmmCalibrator.get_PenaltySmoothMaturity_L1(); config.result_pelLibor_error_linf = lmmCalibrator.get_PenaltySmoothMaturity_L_INF(); } { std::string common_result_file_name = "calib_result_gGlobal.csv"; std::string full_common_result_file = LMMPATH::get_Root_OutputPath() + common_result_file_name ; std::ofstream final_result ; final_result.open(full_common_result_file.c_str(), std::ios::app); final_result<<std::endl<<std::endl<< "============= Test At "<<LMMPATH::get_TimeDateNow() <<",,,,,, Error LInf, "<<lmmCalibrator.get_QuoteError_LInf() <<std::endl ; final_result<< lmmCalibrator.get_BaseGeneral_Result_Info(); final_result.close(); } return GMatrix_Vol_gMapping(pVolatilityFunction,pGMatrixMapping); }
Correlation_PTR JB_marketData_LMM_Correlation_calibration(const LmmCalibrationConfig& config, LmmSwaptionMarketData_PTR pLmmSwaptionMarketData , const QuantLib::Array& found_abcd) { size_t nbYear = pLmmSwaptionMarketData->get_nbYear(); std::string base_name = pLmmSwaptionMarketData->get_MarketDataBaseFileName() ; Tenor tenorfixedleg = Tenor::_1YR ; Tenor tenorfloatleg = Tenor::_6M ; size_t fixedfloatRatio = tenorfixedleg.ratioTo(tenorfloatleg); //create LMM components LMMTenorStructure_PTR pLMMTenorStructure( new LMMTenorStructure(tenorfloatleg,nbYear) ); const double a=found_abcd[0],b=found_abcd[1],c=found_abcd[2],d=found_abcd[3]; Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d); ConstShifted_HGVolatilityParam_PTR pNoShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam(pLMMTenorStructure, abcdParam, 1., 0.)); //! create correlation Correlation_PTR pCorrelation = JB_create_InitCorrelation(config); Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, pCorrelation, pNoShifted_HGVolatilityParam)); Dispersion dispersion(pVolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); //! Create Approximation Rebonato LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmVanillaSwaptionApproxPricer_Rebonato(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); pLmmVanillaSwaptionApproxPricer_Rebonato->update_VolatilityParam(pNoShifted_HGVolatilityParam); LmmBaseCostFunction_PTR pLmmCorrelationCostFunction(new LmmCorrelationCostFunction ( pLmmVanillaSwaptionApproxPricer_Rebonato , pLmmSwaptionMarketData->get_LiborQuotes() , pLmmSwaptionMarketData->get_SwaptionQuotes_ATM() , pCorrelation ) ); ////// Correlation calibrator QuantLib::Array xy_correlation_init = pCorrelation->get_ArrayFrom_Correlation(); QuantLib::Size maxIterations =1000; QuantLib::Size minStatIterations =100; QuantLib::Real rootEpsilon = 1e-8; QuantLib::Real functionEpsilon = 1e-8; LmmCorrelationCalibrator lmmCorrelationCalibrator ( xy_correlation_init , maxIterations , rootEpsilon ,functionEpsilon , pLmmCorrelationCostFunction ); lmmCorrelationCalibrator.solve(); std::string result_file =base_name + "_correlation_calibration_result.csv"; lmmCorrelationCalibrator.printPlusPlus(result_file); std::string calibrated_correlation_file =base_name + "_correlation_calibrated.csv"; Correlation_PTR calibrated_correl_ptr = lmmCorrelationCalibrator.get_Found_Correlation() ; calibrated_correl_ptr->print(calibrated_correlation_file); // print in a common file { std::string common_result_file_name = "calib_result_Correlation.csv"; std::string full_common_result_file = LMMPATH::get_Root_OutputPath() + common_result_file_name ; std::ofstream final_result ; final_result.open(full_common_result_file.c_str(), std::ios::app); final_result<<std::endl<<std::endl<< "============= Test At "<<LMMPATH::get_TimeDateNow() <<",,,,,, Error LInf, "<<lmmCorrelationCalibrator.get_QuoteError_LInf() <<std::endl ; final_result<< lmmCorrelationCalibrator.get_BaseGeneral_Result_Info(); final_result.close(); } return calibrated_correl_ptr ; }
void marketData_LMM_Local_gCalibration( const LmmCalibrationConfig& config , LmmSwaptionMarketData_PTR pLmmSwaptionMarketData , const QuantLib::Array& abcd_param , Correlation_PTR found_correlation_ptr , GMatrixMapping_PTR init_gMapping ) { assert(config.use_local_calib_); size_t nbYear = pLmmSwaptionMarketData->get_nbYear(); std::string base_file_name = pLmmSwaptionMarketData->get_MarketDataBaseFileName(); Tenor tenorfixedleg = Tenor::_1YR ; Tenor tenorfloatleg = Tenor::_6M ; size_t fixedfloatRatio = tenorfixedleg.ratioTo(tenorfloatleg); std::string base_name; base_name = base_file_name+"_gMatrixLocalCalibration" ; //create LMM components LMMTenorStructure_PTR pLMMTenorStructure( new LMMTenorStructure(tenorfloatleg,nbYear) ); const double a=abcd_param[0]; const double b=abcd_param[1]; const double c=abcd_param[2]; const double d=abcd_param[3]; Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d); ConstShifted_HGVolatilityParam_PTR pNoShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam(pLMMTenorStructure, abcdParam, 1., 0.)); Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, found_correlation_ptr , pNoShifted_HGVolatilityParam)); Dispersion dispersion(pVolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmVanillaSwaptionApproxPricer_Rebonato(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); // create gMatrixMapping size_t g_matrix_size = GMatrixMapping::get_gSizeFromNbYear(nbYear,fixedfloatRatio ); size_t delegate_matrix_size = GMatrixMapping::get_gDelegateSizeFromHorizon(pLMMTenorStructure->get_horizon() ,fixedfloatRatio ); UpperTriangularDoubleMatrix empty_delegate_matrix(delegate_matrix_size,delegate_matrix_size); GMatrixMapping_PTR pGMatrixMapping; if(init_gMapping) { pGMatrixMapping = init_gMapping; } else { //initiate gMatrixMapping all gDelegate to 1 pGMatrixMapping.reset( new GMatrixMapping(g_matrix_size, empty_delegate_matrix, pLmmSwaptionMarketData->get_SwaptionQuotes_ATM()->get_UpperTriangularIndexPairMatrix()) ); QuantLib::Array g_delegate_vector = pGMatrixMapping->get_DelegateArray(); for(size_t i=0;i<g_delegate_vector.size();++i) g_delegate_vector[i] = 1.; pGMatrixMapping->reset_gDelegate(g_delegate_vector); } pNoShifted_HGVolatilityParam->reset_g_matrix( pGMatrixMapping->get_g_Ref() ); pLmmVanillaSwaptionApproxPricer_Rebonato->update_VolatilityParam(pNoShifted_HGVolatilityParam); LmmBaseCostFunction_PTR pLmmCostFunction(new LmmLocal_gCostFunction ( pLmmVanillaSwaptionApproxPricer_Rebonato, pLmmSwaptionMarketData->get_LiborQuotes(), pLmmSwaptionMarketData->get_SwaptionQuotes_ATM(), pGMatrixMapping, pNoShifted_HGVolatilityParam ) ); //costumize swaptions weights UpperTriangularDoubleMatrix swpm_weight_matrix = pLmmCostFunction->get_SwaptionWeightMatrix(); //swpm_weight_matrix(7,1)=1e-6; //swpm_weight_matrix(10,1)=1e-6; //swpm_weight_matrix(5,3)=0.; pLmmCostFunction->reset_SwaptionWeightMatrix(swpm_weight_matrix); // Create Calibrator LmmLocal_gCalibrator lmmCalibrator ( *pGMatrixMapping.get() , 3000 //maxIter , 1e-11 //x_epsilon , 1e-11 //f_epsilon , pLmmCostFunction ); if(config.use_positive_constraint_) lmmCalibrator.activate_PositiveConstraint(); lmmCalibrator.solve(); std::ostringstream file_result_stream;file_result_stream<<base_name<<"_result.csv"; std::string file_calibration_result(file_result_stream.str()); lmmCalibrator.printPlusPlus(file_calibration_result); std::ostringstream file_gDelegate_stream;file_gDelegate_stream<<base_name<<"_gDelegate.csv"; std::string file_gDelegate_vol(file_gDelegate_stream.str() ); pGMatrixMapping->print(file_gDelegate_vol); std::ostringstream file_vol_stream;file_vol_stream<<base_name<<"_vol.csv"; std::string file_calibrated_vol(file_vol_stream.str() ); pNoShifted_HGVolatilityParam->print( file_calibrated_vol ); { std::string common_result_file_name = "calib_result_gLocal.csv"; std::string full_common_result_file = LMMPATH::get_Root_OutputPath() + common_result_file_name ; std::ofstream final_result ; final_result.open(full_common_result_file.c_str(), std::ios::app); final_result<<std::endl<<std::endl<< "============= Test At "<<LMMPATH::get_TimeDateNow() <<",,,,,, Error LInf, "<<lmmCalibrator.get_QuoteError_LInf() <<std::endl ; final_result<< lmmCalibrator.get_BaseGeneral_Result_Info(); final_result.close(); } }
GMatrixMapping_PTR marketData_LMM_CascadeExact_calibration( const LmmCalibrationConfig& config , LmmSwaptionMarketData_PTR pLmmSwaptionMarketData , const QuantLib::Array& abcd_param , Correlation_PTR found_correlation_ptr ) { size_t nbYear = pLmmSwaptionMarketData->get_nbYear(); std::string base_file_name = pLmmSwaptionMarketData->get_MarketDataBaseFileName(); Tenor tenorfixedleg = Tenor::_1YR ; Tenor tenorfloatleg = Tenor::_6M ; size_t fixedfloatRatio = tenorfixedleg.ratioTo(tenorfloatleg); std::string base_name=base_file_name +"_gMatrixCascadeCalibration" ; std::ostringstream file_lmm_mkt_stream;file_lmm_mkt_stream<<base_name<<"_Quotation_"<<nbYear<<"YR_.csv"; pLmmSwaptionMarketData->print(file_lmm_mkt_stream.str()); //create LMM components LMMTenorStructure_PTR pLMMTenorStructure( new LMMTenorStructure(tenorfloatleg,nbYear) ); const double a=abcd_param[0]; const double b=abcd_param[1]; const double c=abcd_param[2]; const double d=abcd_param[3]; //const double a=0.0438867,b=0.0179444,c=0.554972,d=0.121429;/// ATTENTION< TEMPORARY, TODELETE and uses abcd calibrator above Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d); ConstShifted_HGVolatilityParam_PTR pNoShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam(pLMMTenorStructure, abcdParam, 1., 0.)); Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, found_correlation_ptr, pNoShifted_HGVolatilityParam)); Dispersion dispersion(pVolatilityFunction); Lmm_PTR lmm_ptr(new Lmm(dispersion) ); LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmVanillaSwaptionApproxPricer_Rebonato(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr)); // create gMatrixMapping size_t g_matrix_size = GMatrixMapping::get_gSizeFromNbYear(nbYear,fixedfloatRatio ); size_t delegate_matrix_size = GMatrixMapping::get_gDelegateSizeFromHorizon(pLMMTenorStructure->get_horizon() ,fixedfloatRatio ); UpperTriangularDoubleMatrix empty_delegate_matrix(delegate_matrix_size,delegate_matrix_size); GMatrixMapping_PTR pGMatrixMapping( new GMatrixMapping(g_matrix_size, empty_delegate_matrix, pLmmSwaptionMarketData->get_SwaptionQuotes_ATM()->get_UpperTriangularIndexPairMatrix()) ); //initiate gMatrixMapping all gDelegate to 1 QuantLib::Array g_delegate_vector = pGMatrixMapping->get_DelegateArray(); for(size_t i=0;i<g_delegate_vector.size();++i) g_delegate_vector[i] = 1.; pGMatrixMapping->reset_gDelegate(g_delegate_vector); pNoShifted_HGVolatilityParam->reset_g_matrix( pGMatrixMapping->get_g_Ref() ); pLmmVanillaSwaptionApproxPricer_Rebonato->update_VolatilityParam(pNoShifted_HGVolatilityParam); LmmBaseCostFunction_PTR pLmmCascadeCostFunction ( new LmmCascade_gCostFunction ( pLmmVanillaSwaptionApproxPricer_Rebonato ,pLmmSwaptionMarketData->get_LiborQuotes() ,pLmmSwaptionMarketData->get_SwaptionQuotes_ATM() ,pGMatrixMapping ,pNoShifted_HGVolatilityParam ) ); UpperTriangularDoubleMatrix copy_weight_matrix = pLmmCascadeCostFunction->get_SwaptionWeightMatrix(); //copy_weight_matrix(2,1)=1000; pLmmCascadeCostFunction->reset_SwaptionWeightMatrix(copy_weight_matrix); LmmCascade_gCalibrator lmmCalibrator ( *pGMatrixMapping.get() , 100000 // config.maxIter , 1e-12 // config.x_epsilon , 1e-10 // config.f_epsilon , pLmmCascadeCostFunction ); if(config.use_positive_constraint_) lmmCalibrator.activate_PositiveConstraint(); lmmCalibrator.solve(); std::ostringstream file_vol_stream;file_vol_stream<<base_name<<"_vol.csv"; std::string file_calibrated_vol(file_vol_stream.str() ); pNoShifted_HGVolatilityParam->print( file_calibrated_vol ); std::ostringstream file_result_stream;file_result_stream<<base_name<<"_result.csv"; std::string file_calibration_result(file_result_stream.str()); lmmCalibrator.printPlusPlus(file_calibration_result); std::ostringstream file_gDelegate_stream;file_gDelegate_stream<<base_name<<"_gDelegate.csv"; std::string file_gDelegate_vol(file_gDelegate_stream.str() ); pGMatrixMapping->print(file_gDelegate_vol); // print in a common file { std::string common_result_file_name = "calib_result_gCascade.csv"; std::string full_common_result_file = LMMPATH::get_Root_OutputPath() + common_result_file_name ; std::ofstream final_result ; final_result.open(full_common_result_file.c_str(), std::ios::app); final_result<<std::endl<<std::endl<< "============= Test At "<<LMMPATH::get_TimeDateNow() <<",,,,,, Error LInf, "<<lmmCalibrator.get_QuoteError_LInf() <<std::endl ; final_result<< lmmCalibrator.get_BaseGeneral_Result_Info(); final_result.close(); } return pGMatrixMapping; }