RQuantLib/ChangeLog0000644000175000017500000006517712271347110012621 0ustar00eddedd2014-01-26 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.11 * R/inline.R: For now, revert to using Rcpp:::Rcpp.plugin.maker() as only unreleased Rcpp exports this right now; will use '::' later 2014-01-15 Dirk Eddelbuettel * src/utils.cpp: Make the epoch-offset between QL and R an internal const here, rather than accessing it from R's Date class * DESCRIPTION: Update Depends and Imports relationships * R/inline.R: Call Rcpp::LdFlags() now that it is exported * R/inline.R: Idem for Rcpp::Rcpp.plugin.maker() * man/AsianOption.Rd: Indent to less that 90 columns * man/BinaryOption.Rd: Idem * man/BondUtilities.Rd: Idem * man/Calendars.Rd: Idem * man/EuropeanOptionArrays.Rd: Idem * man/FixedRateBond.Rd: Idem * man/ImpliedVolatility.Rd: Idem * R/mod.R: Do not attempt to load modules for now 2013-05-26 Dirk Eddelbuettel * R/inline.R: Adding a plugin for use by Rcpp attribute or inline * inst/include/rquantlib.h: Moved from src/ to expose the RQuantLib API for use by the plugin (and the header file / API needs to be properly defined; this file is probably too large) * src/Makevars.in: Adjust for header file move * src/Makevars.win: Idem 2013-02-17 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.10 * man/Bond.Rd: Use a flat discount curve in example * man/DiscountCurve.Rd: Idem * man/FixedRateBond.Rd: Idem * man/FLoatingRateBond.Rd: Idem * man/ZeroCouponBond.Rd: Idem * R/arrays.R (plotOptionSurface): Use explicit `rgl::' prefix for all functions from the rgl package to suppress spurious codetools warning * demo/OptionSurfaces.R: Reindented * cleanup: Simplified and updated 2012-12-02 Dirk Eddelbuettel * src/discount.cpp (DiscountCurve): R-devel on Windows now longer likes a data.frame instantiation here, so passing back as list and ... * R/discount.R (DiscountCurve.default): ... making it a data.frame here. 2012-12-01 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.9 * src/vanilla.cpp (AmericanOption): Support engine choice, adding "CrankNicolson" to the default "BaroneAdesiWhaley" as the former adds delta + gamma -- thanks to Bryan Lewis for the suggestion * R/option.R: Support new the new 'engine' option * man/AmericanOption.Rd: Document new 'engine' option * src/bonds.cpp: Remove remaining std::cout use * src/curve.cpp: Idem * src/zero.cpp: Idem 2011-12-27 Dirk Eddelbuettel * src/Makevars.win: Add -I"$(BOOSTLIB)" which is what other CRAN packages depending on Boost do 2011-09-11 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.8 2011-09-10 Dirk Eddelbuettel * R/dayCounter.R: Added new function 'setEvaluationDate' as a simple pass-through function to set a date as the QuantLib evaluation date * src/daycounter.cpp: C++ part of setEvaluationDate() * man/Calendars.Rd: Documentation for setEvaluationDate() 2011-09-09 Dirk Eddelbuettel * src/discount.cpp (DiscountCurve): Cache the (global) value of QuantLib::Settings::instance().evaluationDate() and reset it at end, with thanks to Helmut Heiming for the bug report. 2011-05-02 Dirk Eddelbuettel * configure.in: If g++ version 4.6 or newer is detected, add the -fpermissive option (which was also required in a Debian-only fix release of 0.3.7 which was made today) 2011-04-04 Dirk Eddelbuettel * src/Makevars.win: Simplified using lib${R_ARCH} 2011-04-03 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.7 * man/ConvertibleBond.Rd: Commented-out URLs with 70+ character length as they trigger a bug when the corresponding latex manual is typeset with the a4 style file. Thanks to Uwe Ligges for spotting this. * man/Enum.Rd: Idem * man/FittedBondCurve.Rd: Idem * src/Makevars.win: Adjust link command to '-lQuantLib', and support 32 and 64 bit builds of the QuantLib library 2011-02-21 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.6 * src/bermudan.cpp: Added two explicit casts to double scalar * src/utils.cpp: Idem 2010-11-15 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.5 * DESCRIPTION: Added RUnit to Suggests: * src/bonds.cpp: Use std::vector< RelinkableHandle < Quote > > to store a vector of quotes, rather than a variable length array which g++ -pedantic and the ISO C++ standard both dislike * src/zero.cpp: Idem * man/Calendars.Rd: Folded manual pages adjust.Rd, advance.Rd, businessDaysBetween.Rd, dayCount.Rd, yearFraction into this. * man/ConvertibleBond.Rd: Folded manual pages ConvertibleFixedCouponBond.Rd, ConvertibleFloatingCouponBond.Rd, and ConvertibleZeroCouponBond.Rd into this one. * man/FixedRateBond.Rd: Folded manual pages FixedRateBondYield.Rd FixedRateBondPriceByYield.Rd into this one. * man/ZeroCouponBond.Rd: Folded manual pages ZeroPriceByYield.Rd and ZeroYield.Rd into this one. * tests/RQuantlib.Rout.save: Updated to results from running against QuantLib 1.0.1 which affected one yield computation at the third decimal, as well as one date calculation. 2010-11-01 Dirk Eddelbuettel * man/AmericanOption.Rd: Correction to how generics are documented * man/AmericanOptionImpliedVolatility.Rd: Idem * man/BarrierOption.Rd: Idem * man/BinaryOptionImpliedVolatility.Rd: Idem * man/BinaryOption.Rd: Idem * man/EuropeanOptionImpliedVolatility.Rd: Idem * man/EuropeanOption.Rd: Idem * man/Bond.Rd: Idem * man/CallableBond.Rd: Idem * man/ConvertibleFixedCouponBond.Rd: Idem * man/ConvertibleFloatingCouponBond.Rd: Idem * man/ConvertibleZeroCouponBond.Rd: Idem * man/FixedRateBondPriceByYield.Rd: Idem * man/FixedRateBond.Rd: Idem * man/FixedRateBondYield.Rd: Idem * man/FloatingRateBond.Rd: Idem * man.ImpliedVolatility.Rd: Idem * man/Option.Rd: Idem * man/ZeroCouponBond.Rd: Idem * man/ZeroPriceByYield.Rd: Idem * man/ZeroYield.Rd: Idem * R/bond.R: Standardised generics * DESCRIPTION: Added Suggests: zoo 2010-08-09 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.4 * src/rquantlib.h: No longer use 'using namespace QuantLib' * src/asian.cpp: Switch to explicitly reference all QuantLib objects * src/barrier_binary.cpp: Idem * src/bermudan.cpp: Idem * src/bonds.cpp: Idem * src/calendars.cpp: Idem * src/curves.cpp: Idem * src/daycounter.cpp: Idem * src/discount.cpp: Idem * src/hullwhite.cpp: Idem * src/implieds.cpp: Idem * src/utils.cpp: Idem * src/vanilla.cpp: Idem * src/zero.cpp: Idem 2010-08-07 Dirk Eddelbuettel * R/arrays.R: Rewrote EuropeanOptionArrays() to have vectorisation on the C++ side rather than in R; external interface unchanged and the old implementation is still available as a fallback if needed * src/vanilla.cpp: New function EuropeanOptionArrays() looping over a grid defined by vectors of any two of the six possible numeric inputs * man/EuropeanOptionArrays.Rd: Updated accordingly * R/arrays.R: New function plotOptionSurface() (from existing demo) * man/EuropeanOptionArrays.Rd: Added documentation * src/*cpp: Drop QL_ prefix from functions called from R * R/*: Drop QL_ prefix in functions called by .Call() 2010-08-06 Dirk Eddelbuettel * src/rquantlib.hpp: Renamed to rquantlib.h to suppress a warning in the upcoming R release (as requested by Kurt Hornik) * src/*.cpp: Adjust to '#include ' instead 2010-08-03 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.3 2010-08-02 Dirk Eddelbuettel * inst/unitTests/runit.options.R: Updated asian option test for arithmetic averaging based on QuantLib's test-suite code * R/asian.R: Removed two unused parameters, updated use of maturity used only for geometric averaging * man/asian.Rd: Corresponding manual page update * src/Makevars.win: Simplified Makefile.win into Makevars.win and updated to e.g. the new sub-arch path for Rscript.exe 2010-07-05 Khanh Nguyen * src/asian.cpp: Added arithmetic average case * R/asian.R: Idem * man/asian.Rd: Idem 2010-06-30 Dirk Eddelbuettel * inst/unitTests/runit.calendar.R: Beginnings of calendar unit tests 2010-06-23 Dirk Eddelbuettel * src/*: Converted remainder of code to new Rcpp API 2010-06-20 Dirk Eddelbuettel * R/calendar.R: New helper function setCalendarContext() setting calendar, fixingDays and settleDate * src/calendar.cpp: Implementation, setting RQLContext * man/setCalendarContext.Rd: Documentation * src/bermudan.cpp: take calendar info from RQLContext * src/discount.cpp: idem * src/utils.cpp: idem * src/*.cpp: Some minor cleanup and reindentation, ensure Settings::instance().evaluationDate() is set 2010-06-19 Dirk Eddelbuettel * src/bonds.cpp: Converted to new API * src/utils.cpp: Factored-out utility functions from bonds.cpp * src/rquantlib.hpp: Declarations for new utility functions * src/bonds.cpp: Some refactoring 2010-06-18 Dirk Eddelbuettel * src/bonds.cpp: Converted to new API 2010-06-17 Dirk Eddelbuettel * src/curves.cpp: Converted to new API * src/discount.cpp: Idem * src/hullwhite.cpp: Idem * src/bermudan.cpp: Idem 2010-06-16 Dirk Eddelbuettel * src/utils.cpp: Added simple getOptionType() helper * src/rquantlib.hpp: Added simple getOptionType() helper definition * src/*cpp: Use getOptionType() * src/asian.cpp: Converted to new API * src/barrier_binary.cpp: Idem * src/implieds.cpp: Idem * src/cbond.cpp: Idem * src/daycounter.cpp: Idem * src/zero.cpp: Idem 2010-06-15 Dirk Eddelbuettel * src/vanilla.cpp: Converted to new API 2010-06-14 Dirk Eddelbuettel * src/calendars.cpp: Yet more simplification from "new" Rcpp API * R/calendars.R: Simpler too as we get simpler result objects back 2010-06-12 Dirk Eddelbuettel * src/calendars.cpp: More code simplification using "new" Rcpp API * src/utils.cpp: Add Brazil + South Korea to getCalendar() * src/calendars.cpp: Move getCalendar() into this file 2010-06-11 Dirk Eddelbuettel * src/calendars.cpp: Simplified code by using more of Rcpp's new API * DESCRIPTION: Encode "Rcpp (>= 0.8.2.2)" aka current SVN * DESCRIPTION: Switch to 'LinkingTo: Rcpp' * configure.in: No longer need CxxFlags for Rcpp thanks to LinkingTo * src/Makefile.win: Idem 2010-06-09 Dirk Eddelbuettel * man/DiscountCurve.Rd: Uncomment futures entries as there are numerical issues (in QuantLib) with the spline curve fit when present 2010-04-29 Dirk Eddelbuettel * src/*.cpp: Suppress a few g++ warnings * src/calendar.cpp: Added South Korea and Brazil 2010-04-21 Dirk Eddelbuettel * inst/unitTests/runitOptions.R: Updated binary option test 2010-04-05 Khanh Nguyen * R/hullWhiteCalibration.R: added Hull-White calibration * src/hullwhite.cpp: added Hull-White calibration 2010-02-12 Khanh Nguyen * R/*,src/*: Remove some deprecated fixed income code * tests/*: Remove corresponding tests 2010-01-23 Dirk Eddelbuettel * NAMESPACE: Some small cleanups 2010-01-22 Khanh Nguyen * NAMESPACE: Added, filled with functions and methods * R/*Bond.R: add default values to bond functions, especially the date parameters (dayCounter, settlement days, compounding frequency,..) so that it is less confusing when using the functions. * man/*Bond.Rd: idem * New examples that use default values for bonds. 2010-01-14 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.2 which works with QuantLib 0.9.9 (as well as with the brand-new first beta for QuantLib 1.0.0) * src/Makefile.win: Keep QL 0.9.9 hard-coded until 1.0.0 is out 2010-01-14 Khanh Nguyen * pkg/R/calendars.R: Fix generic function issue with advance * src/dayCounter.cpp: Added dayCounter functions * pkg/R/dayCounter.R: idem * man/dayCount.R: idem * man/yearFraction.R: idem * man/advance.R: idem 2010-01-13 Dirk Eddelbuettel * src/asian.cpp: updated for Rcpp (>= 0.7.0), switched to explicit Rf_error() and Rf_length() where needed with R_NO_REMAP defined * src/barrier_binary.cpp: idem * src/bermudan.cpp: idem * src/bonds.cpp: idem * src/discount.cpp: idem * src/implieds.cpp: idem * src/rquantlib.hpp: idem * src/utils.cpp: idem * src/vanilla.cpp: idem * DESCRIPTION: Depends on Rcpp (>= 0.7.0) 2010-01-12 Khanh Nguyen * src/calendars.cpp: Add new calendaring functionality * src/calendars.hpp: idem * R/calendars.R: idem * man/endOfMonth.Rd: idem * man/isHoliday.Rd: idem * man/holidayList.Rd: idem * man/businessDaysBetween.Rd: idem * man/adjust.Rd: idem * man/isEndOfMonth.Rd: idem * man/isWeekend.Rd: idem 2009-12-12 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.1 for QuantLib 0.9.9 * src/Makefile.win: Update to QL 0.9.9 as well 2009-11-02 Dirk Eddelbuettel * man/*.Rd: Commented-out a few empty sections as noticed by R 2.10.0 * man/*.Rd: Update the curve data for the curve examples using data from QuantLib's Examples/Swap/swapvaluation.cpp; with QuantLib 0.9.9 all numerical issues appear to be gone * man/*.Rd: Some minor white-space changes * src/*cpp: Small updates for QuantLib 0.9.9: - FDEuropeanEngine now needs a template argument for the scheme, current default is CrankNicholson - NULL_RateHelper construct no longer works, so we test the return from getRateHelper() via ptr.get() == NULL 2009-10-16 Dirk Eddelbuettel * man/DiscountCurve.Rd: Change as per QL 0.9.7's Swap/swapvaluation.cpp 2009-09-06 Dirk Eddelbuettel * src/Makefile.win: Small rewrite to automatically build over all included .cpp files and some other fixes 2009-09-05 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.0 reflecting all the excellent Google Summer of Code 2009 work by Khanh Nguyen as well as other small enhancements [ Changes by Khanh Nguyen below ] * R/bond.R: Added pricing functionality for various new instrument * R/discount.R: Idem * src/bonds.cpp: Idem * src/discount.cpp: Idem * src/utils.cpp: Idem * man/Bond.Rd: Added documentaiont for new functions * man/CallableBond.Rd: Idem * man/ConvertibleFixedCouponBond.Rd: Idem * man/ConvertibleFloatingCouponBond.Rd: Idem * man/ConvertibleZeroCouponBond.Rd: Idem * man/Enum.Rd: Idem * man/FittedBondCurve.Rd: Idem * man/FixedRateBond.Rd: Idem * man/FixedRateBondCurve.Rd: Idem * man/FixedRateBondPriceByYield.Rd: Idem * man/FixedRateBondYield.Rd: Idem * man/FloatingRateBond.Rd: Idem * man/ZeroCouponBond.Rd: Idem * man/ZeroPriceByYield.Rd: Idem * man/ZeroYield.Rd: Idem * rests/RQuantLib.R: Added tests for new functions * rests/RQuantLib.Rout.save: Added tests ouput for new functions [ Changes by Dirk Eddelbuettel below ] * man/BondUtilities.Rd: Added documentation for new function * R/calendars.R: Add support to access QuantLib calendars from R * src/calendars.cpp Idem * man/Calendars.Rd: Idem * src/bonds.cpp: Small C++ fixes to suppres g++ warnings * INDEX: Updated via 'R CMD build --force' * inst/QuantLib-License.txt: Updated to version from QL 0.9.7 2009-03-30 Dirk Eddelbuettel * src/{barrier_binary,implied,vanilla}.cpp: More direct initialization of option parameters * man/*.Rd: Corrected use of quotes which do not need escapes 2009-03-03 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.11, updated for Rcpp 0.6.4 * src/{*.cpp,rquantlib.hpp}: Updated for Rcpp 0.6.4 and the requirement to explicit reference all object from namespace std, e.g. now use std::string * src/*: Updated all copyright notices to 2009 2008-12-04 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.10, updated for QL 0.9.7 and Rcpp 0.6.1 * configure.in: Updated for new scheme of external Rcpp package, added explicit check for Rscript, added some more messages, make sure Rscript is looked for inside R_HOME as well * RcppSrc/: removed, we now use Rcpp (>= 0.6.1) * configure.win: Just check for QUANTLIB_ROOT variable, no more building of RcppSrc/ as we use the externally supplied Rcpp package * R/RcppVersion: removed as Rcpp is no longer include * man/RcppVersion.Rd: removed as Rcpp is no longer include * src/Makefile.win: Updated to reflect external Rcpp use * src/rquantlib.hpp: include Rcpp.h, not .hpp; define dateFromR() * src/utils.cpp: Added dateFromR() to deal with different date offsets between R (using the Unix epoch) and QL (using spreadsheet conventions) * src/bermudan.cpp: A few small changes related to external Rcpp * src/discount.cpp: A few small changes related to external Rcpp 2008-08-09 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.9, updated for QL 0.9.6 * configure.in: Updated for 0.9.6 * src/curves.cpp: Minor updates for QL 0.9.6 API changes 2008-01-01 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.8, updated for QL 0.9.0 * R/option.R: For BinaryOption, added new arguments 'binType' and 'excType' to select the type of Binary (cash, asset or gap) and exercise (european or american). * RcppSrc/Rcpp.cpp,src/*cpp: Added const char* casts for Rprintf * src/BinaryOptions.cpp: Support new binType and excType arguments * src/*cpp: Generally updated for QL 0.9.0 changes * src/discount.cpp: New boolean variable flatQuotes * man/{BinaryOption,DiscountCurve}.Rd: Updated for new arguments * inst/unitTests: Added unit testing using the RUnit package 2007-07-01 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.7, updated for QL 0.8.1 * configure.in: Require QuantLib 0.8.1, and Boost 1.34.0 2007-06-30 Dominick Samperi * src/bermudan.cpp, src/curves.cpp: Updated for QL 0.8.1 2007-02-25 Dirk Eddelbuettel * DESCRIPTION: Relase 0.2.6 updated for Quantlib 0.4.0 * configure.in: Require Quantlib 0.4.0 2007-02-24 Dominick Samperi * src/bermudan.cpp: Several updates for Quantlib 0.4.0 2006-11-10 Dirk Eddelbuettel * man/*.Rd: Updates to default method docs suggested by Kurt Hornik 2006-11-06 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.5 updated for QuantLib 0.3.14 * src/*.cpp: Several minor changes for class renaming and interface changes on the QuantLib side of things 2006-08-14 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.4 updated for QuantLib 0.3.13; this required some changes in the fixed-income functions * configure.in: Tests for QuantLib version 0.3.13 * tests/RQuantLib.R: Added the beginnings of unit-tests * tests/RQuantLib.Rout.save: Control output for unit tests 2006-07-23 Dirk Eddelbuettel * DESCRIPTION: Release 0.2.3 using the new RcppTemplate version 4.2 * src/*: RcppTemplate is now used for all R/C++ interfaces features from the new RcppTemplate 2006-03-30 Dirk Eddelbuettel * Release 0.2.2 once more with thanks to Dominick 2006-03-23 Dominick Samperi * configure.in, configure.win, inst/lib/Makefile, inst/lib/Makefile.win, src/Makefile, src/Makefile.win, cleanup: modified to support use of RcppTemplate V2.2. RQuantLib shared library (or DLL) is created by linking against RcppSrc/libRcpp.a. Tested against QuantLib 0.3.12. * Rcpp.{cpp,hpp}: added latest versions from RcppTemplate package. 2006-01-10 Dirk Eddelbuettel * Release 0.2.1 with thanks to Dominick 2006-01-10 Dominick Samperi * man/DiscountCurve.Rd: Fixed typo and commented out rates needing to be fractions in fixed formating in DiscountCurve example * src/Rcpp.{hpp,cpp},src/{curves,discount,bermudan}.cpp: modified to throw exceptions instead of calling R's error() function. 2005-10-27 Dominick Samperi * src/Rcpp.{hpp,cpp}: Some minor adjustments. Moved matrix and vector indexing into header file. * src/rquantlib.hpp: Added ifdef to protect against multiple includes. 2005-10-26 Dirk Eddelbuettel * Preparing release 0.2.0 regrouping the numerous changes -- contributed mostly by Dominick -- since the 0.1.13 release 2005-10-13 Dominick Samperi * src/Rcpp.{hpp,cpp}: Improved error messages 2005-10-08 Dominick Samperi * src/Rcpp.cpp: Implemented Rcpp, R/C++ interface classes, and modified discount.cpp and bermudan.cpp to use it. * src/Rcpp.hpp: Header files for latter. 2005-10-03 Dominick Samperi * inst/Boost-License.txt, inst/QuantLib-License.txt: License files for Boost and QuantLib. * Windows is now supported using a binary package that does not require the user to install a compiler, Boost, or QuantLib. Had to add Makefile.win, configure.win, etc. * R/discount.R: new DiscountCurve function that constructs the spot term structure of interest rates based on market observables like deposit rates, futures prices, FRA rates, and swap rates. Supports the fitting of discount factors, forward rates, or zero coupon rates, using linear, log-linear, and cubic spline interpolation. * man/DiscountCurve.Rd: man page for DiscountCurve. * R/bermudan.R: new function that prices a Bermudan swaption using a choice of four models: G2 analytic, Hull-White analytic, Hull-White tree, and Black-Karasinski tree. * man/BermudanSwaption.Rd: man page for BermudanSwaption. * src/curves.cpp: utility code for curve construction. * src/discount.cpp: implements DiscountCurve. * src/bermudan.cpp: implements BermudanSwaption. * src/utils.cpp: added utility functions to simplify communication with R. * src/rquantlib.hpp: contains prototypes for utility functions and new definitions for Windows. * Changed: suffix .cc to .cpp, and .h to .hpp. 2005-09-16 Dirk Eddelbuettel * demo/OptionSurfaces.R: added demo with OpenGL visualizations of option analytics, requires rgl package [ Update: not released as rgl crashes on some platforms ] 2005-08-06 Dirk Eddelbuettel * Release 0.1.13 matching the new QuantLib 0.3.10 release * Implied volatilies are back! With gcc/g++ 4.0, the segmentation fault that I was seeing on implied volatility using gcc/g++ 3.3 (but which others did not see with gcc/g++ 3.2) has disappeared, so the corresponding code has been reactivated. * BinaryOptionImpliedVolatility() is also back * src/*.cc, R/*.R: Removed a lot of commented-out code 2005-04-26 Dirk Eddelbuettel * Release 0.1.12 matching the upcoming QuantLib 0.3.9 release * configure.in: Test for QuantLib >= 0.3.8 * src/*.cc: Several changes for QuantLib 0.3.9: - use Handle<...> instead of RelinkableHandle<...> - use YieldTermStructure instead of TermStructure - use today + alength instead of today.plusDays 2004-12-27 Dirk Eddelbuettel * Release 0.1.11 matching the new QuantLib 0.3.8 release * configure.in: Added tests for Boost headers, with thanks and a nod to QuantLib for the actual autoconf code * src/{barrier_binary.cc,implieds.cc,vanilla.cc}: Option type 'Straddle' now unsupported, hence commented out * man/*.Rd: Similarly removed reference to straddle from docs * src/{barrier_binary.cc,implieds.cc,utils.cc,vanilla.cc}: Renamed BlackScholesStochasticProcess to BlackScholesProcess * src/vanilla.cc: Changed Handle to boost::shared_ptr 2004-09-12 Dirk Eddelbuettel * Release 0.1.10 * Switched to using Boost library as per QuantLin 0.3.7 * AmericanOption now uses the Barone-Adesi-Whaley approximation * Implied volatility for both European and American options currently segfaults when called from R, though the code itself works as a standalone. The code also works from R when the implied calculation call is skipped. Something is corrupting memory somewhere. For now, we return NA for either function. 2004-08-06 Dirk Eddelbuettel * DESCRIPTION: Added SystemRequirements for QuantLib 2004-05-26 Dirk Eddelbuettel * Release 0.1.9 * man/EuropeanOption.Rd: Added corrections for the issues raised by Ajay Shah in the Debian bug report #249240 * man/{AmericanOption,BarrierOption,BinaryOption}.Rd: Idem 2004-04-05 Dirk Eddelbuettel * Release 0.1.8 * src/{barrier_binary,implieds,utils,vanilla}.cc: Updated to the new QuantLib 0.3.5 pricer framework. This currently implies that options priced using the binomial engines do not have Greeks; this should be addressed in a future QuantLib release. * man/{BarrierOption,AmericanOption}.Rd: Note that Greeks are currently unavailable with binary pricers 2003-11-28 Dirk Eddelbuettel * Release 0.1.7 * src/barrier_binary.cc: -- split off from RQuantLib.cc -- added three more greeks to Barrier Option -- reflected small change in QuantLib types for Barrier Options * src/implieds.cc -- split off from RQuantLib.cc -- rewritten functions for implied volatility on European and American options using new QuantLib framework * src/utils.cc -- split off from RQuantLib.cc * src/vanilla.cc -- rump of RQuantLib.cc, renamed 2003-07-31 Dirk Eddelbuettel * Release 0.1.6 * man/{EuropeanOption,ImpliedVolatility}: Two small corrections to argument call mismatches found by R CMD check 2003-05-31 Dirk Eddelbuettel * Release 0.1.5 * R/{option,implied}.R: generic/method consistency improved following heads-up, and subsequent help, from BDR. Thanks! 2003-03-25 Dirk Eddelbuettel * Release 0.1.4 * data/: Removed empty directory as suggested by Kurt * configure.in: Several additions: - test for g++ >= 3.0, kindly provided by Kurt - test for QuantLib >= 0.3, along the same lines - converted from autoconf 2.13 to 2.50 * cleanup: Remove temp dir created by autoconf 2003-02-05 Dirk Eddelbuettel * Release 0.1.3 * R/*.R: Added PACKAGE="RQuantLib" to .Call() as suggested by Kurt * DESCRIPTION: Removed QuantLib from Depends as requested by Kurt, and added explanation to Description 2002-11-13 Dirk Eddelbuettel * Release 0.1.2 * Minor correction to EuropeanOptionArrays manual page indexing 2002-11-11 Dirk Eddelbuettel * Release 0.1.1 * Added barrier option * Several small corrections and completions to documentation 2002-02-25 Dirk Eddelbuettel * Initial 0.1.0 release RQuantLib/DESCRIPTION0000644000175000017500000000304312271347225012544 0ustar00eddeddPackage: RQuantLib Title: R interface to the QuantLib library Version: 0.3.11 Date: 2014-01-26 Maintainer: Dirk Eddelbuettel Author: Dirk Eddelbuettel and Khanh Nguyen Description: The RQuantLib package makes parts of QuantLib visible to the R user. Currently a number option pricing functions are included, both vanilla and exotic, as well as a broad range of fixed-income functions. Also included are general calendaring and holiday utilities. Further software contributions are welcome. . The QuantLib project aims to provide a comprehensive software framework for quantitative finance. The goal is to provide a standard open source library for quantitative analysis, modeling, trading, and risk management of financial assets. . The Windows binary version is self-contained and does not require a QuantLib (or Boost) installation. . RQuantLib uses the Rcpp R/C++ interface class library. See the Rcpp package on CRAN (or R-Forge) for more information on Rcpp. . Note that while RQuantLib's code is licensed under the GPL (v2 or later), QuantLib itself is released under a somewhat less restrictive Open Source license (see QuantLib-License.txt). Depends: R (>= 2.10.0) Suggests: rgl, zoo, RUnit Imports: methods, Rcpp LinkingTo: Rcpp SystemRequirements: QuantLib library (>= 0.9.9) from http://quantlib.org, Boost library from http://www.boost.org License: GPL (>= 2) URL: http://quantlib.org http://dirk.eddelbuettel.com/code/rquantlib.html Packaged: 2014-01-27 03:12:21.548993 UTC; edd RQuantLib/NAMESPACE0000644000175000017500000000323612271333436012260 0ustar00eddedd import(Rcpp,methods) useDynLib(RQuantLib) exportPattern("*.default") export( ##--arrays.R "oldEuropeanOptionArrays", "EuropeanOptionArrays", "plotOptionSurface", ##--asian.R "AsianOption", ##--bermudan.R "BermudanSwaption", "summary.G2Analytic", "summary.HWAnalytic", "summary.HWTree", "summary.BKTree", ##--bond.R "ZeroCouponBond", "ZeroPriceByYield", "ZeroYield", "FixedRateBond", "FixedRateBondYield", "FixedRateBondPriceByYield", "FloatingRateBond", "ConvertibleZeroCouponBond", "ConvertibleFixedCouponBond", "ConvertibleFloatingCouponBond", "CallableBond", "FittedBondCurve", ##--calendars.R "isBusinessDay", "businessDay", "isHoliday", "isWeekend", "isEndOfMonth", "getEndOfMonth", "endOfMonth", "adjust", "advance", "businessDaysBetween", "getHolidayList", "holidayList", "setCalendarContext", ##--dayCounter.R "dayCount", "yearFraction", "setEvaluationDate", ##--discount.R "DiscountCurve", "plot.DiscountCurve", ##--implied.R "EuropeanOptionImpliedVolatility", "AmericanOptionImpliedVolatility", "BinaryOptionImpliedVolatility", ##--option.R "EuropeanOption", "AmericanOption", "AmericanOption.default", "BinaryOption", "BarrierOption" ) S3method("plot", "Option") S3method("print", "Option") S3method("summary", "Option") S3method("plot", "Bond") S3method("print", "Bond") S3method("summary", "Bond") RQuantLib/R/0000755000175000017500000000000012271341737011241 5ustar00eddeddRQuantLib/R/arrays.R0000644000175000017500000001450712271333436012671 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2010 Dirk Eddelbuettel ## ## $Id: arrays.R,v 1.2 2002/11/15 01:49:28 edd Exp $ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA oldEuropeanOptionArrays <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { n.underlying <- length(underlying) n.strike <- length(strike) n.dividendYield <- length(dividendYield) n.riskFreeRate <- length(riskFreeRate) n.maturity <- length(maturity) n.volatility <- length(volatility) res <- numeric(n.underlying * n.strike * n.dividendYield * n.riskFreeRate * n.maturity * n.volatility) dim(res) <- c(n.underlying, n.strike, n.dividendYield, n.riskFreeRate, n.maturity, n.volatility) dimnames(res) <- list(paste("s",underlying,sep="="), paste("k",strike,sep="="), paste("y",dividendYield,sep="="), paste("r",riskFreeRate,sep="="), paste("t",maturity,sep="="), paste("v",volatility,sep="=")) value <- delta <- gamma <- vega <- theta <- rho <- divRho <- res for (s in 1:n.underlying) for (k in 1:n.strike) for (y in 1:n.dividendYield) for (r in 1:n.riskFreeRate) for (t in 1:n.maturity) for (v in 1:n.volatility) { val <- .Call("EuropeanOption", list(type=as.character(type), underlying=as.double(underlying[s]), strike=as.double(strike[k]), dividendYield=as.double(dividendYield[y]), riskFreeRate=as.double(riskFreeRate[r]), maturity=as.double(maturity[t]), volatility=as.double(volatility[v])), PACKAGE="RQuantLib") value[s,k,y,r,t,v] <- val$value delta[s,k,y,r,t,v] <- val$delta gamma[s,k,y,r,t,v] <- val$gamma vega[s,k,y,r,t,v] <- val$vega theta[s,k,y,r,t,v] <- val$theta rho[s,k,y,r,t,v] <- val$rho divRho[s,k,y,r,t,v] <- val$divRho } value <- drop(value) delta <- drop(delta) gamma <- drop(gamma) vega <- drop(vega) theta <- drop(theta) rho <- drop(rho) divRho <- drop(divRho) invisible(list(value=value, delta=delta, gamma=gamma, vega=vega, theta=theta, rho=rho, divRho=divRho, parameters=list(type=type, underlying=underlying, strike=strike, dividendYield=dividendYield, riskFreeRate=riskFreeRate, maturity=maturity, volatility=volatility))) } EuropeanOptionArrays <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { ## check that we have two vectors lv <- c(length(underlying) > 1, length(strike) > 1, length(dividendYield) > 1, length(riskFreeRate) > 1, + length(maturity) > 1, + length(volatility) > 1) if (sum(lv) != 2) { warning("Need exactly two arguments as vectors") return(NULL) } type <- match.arg(type, c("call", "put")) ## expand parameters pars <- expand.grid(underlying, strike, dividendYield, riskFreeRate, maturity, volatility) nonconst <- which( apply(pars, 2, sd) != 0) colnames <- c("spot", "strike", "div", "rfrate", "mat", "vol") val <- .Call("EuropeanOptionArrays", type, as.matrix(pars), PACKAGE="RQuantLib") ## turn list of vectors in to list of matrices par1 <- unique(pars[, nonconst[1]]) par2 <- unique(pars[, nonconst[2]]) len1 <- length(par1) len2 <- length(par2) ml <- lapply(val, function(x) matrix(x, len1, len2, dimnames=list(par1,par2))) return(c(ml, parameters=list(type=type, underlying=underlying, strike=strike, dividendYield=dividendYield, riskFreeRate=riskFreeRate, maturity=maturity, volatility=volatility))) } plotOptionSurface <- function(EOres, ylabel="", xlabel="", zlabel="", fov=60) { stopifnot(require(rgl)) utils::globalVariables(c("clear3d", "bg3d", "ligh3d", "rgl.viewpoint", "rgl.surface", "tgl.texts")) axis.col <- "black" text.col <- axis.col ylab <- ylabel xlab <- xlabel zlab <- zlabel y <- EOres ## clear scene: rgl::clear3d() rgl::clear3d(type="bbox") rgl::clear3d(type="lights") ## setup env: rgl::bg3d(color="#DDDDDD") rgl::light3d() rgl::rgl.viewpoint(fov=fov) x <- 1:nrow(y) z <- 1:ncol(y) x <- (x-min(x))/(max(x)-min(x)) y <- (y-min(y))/(max(y)-min(y)) z <- (z-min(z))/(max(z)-min(z)) rgl::rgl.surface(x, z, y, alpha=0.6, lit=TRUE, color="blue") rgl::rgl.lines(c(0,1), c(0,0), c(0,0), col=axis.col) rgl::rgl.lines(c(0,0), c(0,1), c(0,0), col=axis.col) rgl::rgl.lines(c(0,0),c(0,0), c(0,1), col=axis.col) rgl::rgl.texts(1,0,0, xlab, adj=1, col=text.col) rgl::rgl.texts(0,1,0, ylab, adj=1, col=text.col) rgl::rgl.texts(0,0,1, zlab, adj=1, col=text.col) ## add grid (credit's to John Fox scatter3d) xgridind <- round(seq(1, nrow(y), length=25)) zgridind <- round(seq(1, ncol(y), length=25)) rgl::rgl.surface(x[xgridind], z[zgridind], y[xgridind,zgridind], color="darkgray", alpha=0.5, lit=TRUE, front="lines", back="lines") ## animate (credit to rgl.viewpoint() example) start <- proc.time()[3] while ((i <- 36*(proc.time()[3]-start)) < 360) { rgl::rgl.viewpoint(i,i/8); } } RQuantLib/R/asian.R0000644000175000017500000000566012271333436012463 0ustar00eddedd ## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2009 Dirk Eddelbuettel ## Copyright (C) 2009 Khanh Nguyen ## ## $Id$ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA AsianOption <- function(averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first, length, fixings) { UseMethod("AsianOption") } AsianOption.default <- function(averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first=0, length=0, fixings=0) { averageType <- match.arg(averageType, c("geometric", "arithmetic")) type <- match.arg(type, c("call", "put")) if (missing(maturity)) { if (averageType=="geometric") { warning("Geometric Asian Option requires maturity argument") return(NULL) } else { maturity <- 1.0 # actually unused for arithmetic option case } } val <- .Call("AsianOption", list(averageType=as.character(averageType), type=as.character(type), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility), first=as.double(first), length=as.double(length), fixings=as.double(fixings)), PACKAGE="RQuantLib") class(val) <- c("AsianOption","Option") val } plot.Option <- function(x, ...) { warning("No plotting available for class", class(x)[1],"\n") invisible(x) } print.Option <- function(x, digits=4, ...) { cat("Concise summary of valuation for", class(x)[1], "\n") print(round(unlist(x[1:7]), digits)) invisible(x) } summary.Option <- function(object, digits=4, ...) { cat("Detailed summary of valuation for", class(object)[1], "\n") print(round(unlist(object[1:7]), digits)) cat("with parameters\n") print(unlist(object[["parameters"]])) invisible(object) } RQuantLib/R/bermudan.R0000644000175000017500000001070612271333436013162 0ustar00eddedd## RQuantLib function DiscountCurve ## ## Copyright (C) 2005 Dominick Samperi ## ## $Id: bermudan.R,v 1.1 2005/10/12 03:42:03 edd Exp $ ## ## This program is part of the RQuantLib library for R (GNU S). ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version. ## ## 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 GNU General Public License for more ## details. BermudanSwaption <- function(params, tsQuotes, swaptionMaturities, swapTenors, volMatrix) { UseMethod("BermudanSwaption") } BermudanSwaption.default <- function(params, tsQuotes, swaptionMaturities, swapTenors, volMatrix) { # Check that params list names if(!is.list(params) || length(params) == 0) { stop("The params parameter must be a non-empty list"); } # Check that the term structure quotes are properly formatted. if(!is.list(tsQuotes) || length(tsQuotes) == 0) { stop("Term structure quotes must be a non-empty list"); } if(length(tsQuotes) != length(names(tsQuotes))) { stop("Term structure quotes must include labels"); } if(!is.numeric(unlist(tsQuotes))) { stop("Term structure quotes must have numeric values") } # Check for correct matrix/vector types if(!is.matrix(volMatrix) || !is.vector(swaptionMaturities) || !is.vector(swapTenors)) { stop("Swaption vol must be a matrix, maturities/tenors must be vectors") } # Check that matrix/vectors have compatible dimensions if(prod(dim(volMatrix)) != length(swaptionMaturities)*length(swapTenors)) { stop("Dimensions of swaption vol matrix not compatible with maturity/tenor vectors") } # Finally ready to make the call... # We could coerce types here and pass as.integer(round(swapTenors)), # temp <- as.double(volMatrix), dim(temp) < dim(a) [and pass temp instead # of volMatrix]. But this is taken care of in the C/C++ code. val <- .Call("BermudanSwaption", params, tsQuotes, swaptionMaturities, swapTenors, volMatrix, PACKAGE="RQuantLib") class(val) <- c(params$method, "BermudanSwaption") val } summary.G2Analytic <- function(object,...) { cat('\n\tSummary of pricing results for Bermudan Swaption\n') cat('\nPrice (in bp) of Bermudan swaption is ', object$price) cat('\nStike is ', format(object$params$strike,digits=6)) cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')') cat('\nModel used is: G2/Jamshidian using analytic formulas') cat('\nCalibrated model parameters are:') cat('\na = ', format(object$a,digits=4)) cat('\nb = ', format(object$b,digits=4)) cat('\nsigma = ', format(object$sigma,digits=4)) cat('\neta = ', format(object$eta,digits=4)) cat('\nrho = ', format(object$rho,digits=4)) cat('\n\n') } summary.HWAnalytic <- function(object,...) { cat('\n\tSummary of pricing results for Bermudan Swaption\n') cat('\nPrice (in bp) of Bermudan swaption is ', object$price) cat('\nStike is ', format(object$params$strike,digits=6)) cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')') cat('\nModel used is: Hull-White using analytic formulas') cat('\nCalibrated model parameters are:') cat('\na = ', format(object$a,digits=4)) cat('\nsigma = ', format(object$sigma,digits=4)) cat('\n\n') } summary.HWTree <- function(object,...) { cat('\n\tSummary of pricing results for Bermudan Swaption\n') cat('\nPrice (in bp) of Bermudan swaption is ', object$price) cat('\nStike is ', format(object$params$strike,digits=6)) cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')') cat('\nModel used is: Hull-White using a tree') cat('\nCalibrated model parameters are:') cat('\na = ', format(object$a,digits=4)) cat('\nsigma = ', format(object$sigma,digits=4)) cat('\n\n') } summary.BKTree <- function(object,...) { cat('\n\tSummary of pricing results for Bermudan Swaption\n') cat('\nPrice (in bp) of Bermudan swaption is ', object$price) cat('\nStike is ', format(object$params$strike,digits=6)) cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')') cat('\nModel used is: Black-Karasinski using a tree') cat('\nCalibrated model parameters are:') cat('\na = ', format(object$a,digits=4)) cat('\nsigma = ', format(object$sigma,digits=4)) cat('\n\n') } RQuantLib/R/bond.R0000644000175000017500000006604712271333436012320 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2009 Dirk Eddelbuettel ## Copyright (C) 2009 Khanh Nguyen ## Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Khanh Nguyen ## ## $Id$ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA ZeroCouponBond <- function(bond, discountCurve, dateparams ) { UseMethod("ZeroCouponBond") } ZeroCouponBond.default <- function(bond, discountCurve, dateparams=list( refDate=bond$issueDate, settlementDays=1, calendar='us', businessDayConvention='Following')) { val <- 0 if (is.null(bond$faceAmount)) {bond$faceAmount=100} if (is.null(bond$redemption)) {bond$redemption=100} if (is.null(dateparams$settlementDays)) {dateparams$settlementDays=1} if (is.null(dateparams$calendar)) {dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)) {dateparams$businessDayConvention='Following'} if (is.null(dateparams$refDate)) {dateparams$refDate=bond$issueDate} dateparams <- matchParams(dateparams) val <- .Call("ZeroBondWithRebuiltCurve", bond, c(discountCurve$table$date), discountCurve$table$zeroRates, dateparams, PACKAGE="RQuantLib") class(val) <- c("ZeroCouponBond", "Bond") val } ZeroPriceByYield <- function(yield, faceAmount, issueDate, maturityDate, dayCounter, frequency, compound, businessDayConvention){ UseMethod("ZeroPriceByYield") } ZeroPriceByYield.default <- function(yield, faceAmount=100, issueDate, maturityDate, dayCounter=2, frequency=2, compound=0, businessDayConvention=4){ val <- .Call("ZeroPriceByYield", list( yield=as.double(yield), faceAmount = as.double(faceAmount), dayCounter = as.double(dayCounter), compound = as.double(compound), businessDayConvention = as.double(businessDayConvention), frequency = as.double(frequency), maturityDate = maturityDate, issueDate = issueDate), PACKAGE="RQuantLib") class(val) <- c("ZeroPriceByYield") val } ZeroYield <- function(price, faceAmount, issueDate, maturityDate, dayCounter, frequency, compound, businessDayConvention){ UseMethod("ZeroYield") } ZeroYield.default <- function(price, faceAmount=100, issueDate, maturityDate, dayCounter=2, frequency=2, compound=0, businessDayConvention=4){ val <- .Call("ZeroYield", list( price=as.double(price), faceAmount = as.double(faceAmount), dayCounter = as.double(dayCounter), compound = as.double(compound), businessDayConvention = as.double(businessDayConvention), frequency = as.double(frequency), maturityDate = maturityDate, issueDate = issueDate), PACKAGE="RQuantLib") class(val) <- c("ZeroYield") val } FixedRateBond <- function(bond, rates, discountCurve, dateparams){ UseMethod("FixedRateBond") } FixedRateBond.default <- function(bond, rates, discountCurve, dateparams=list( settlementDays=1, calendar='us', businessDayConvention='Following', terminationDateConvention='Following', dayCounter='Thirty360', period='Semiannual', dateGeneration='Backward', endOfMonth=0, fixingDays=2 )){ val <- 0 if (is.null(bond$faceAmount)){bond$faceAmount=100} if (is.null(bond$redemption)){bond$redemption=100} if (is.null(bond$effectiveDate)){bond$effectiveDate=bond$issueDate} if (is.null(dateparams$settlementDays)){dateparams$settlementDays=1} if (is.null(dateparams$calendar)){dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)){ dateparams$businessDayConvention='Following' } if (is.null(dateparams$terminationDateConvention)){ dateparams$terminationDateConvention='Following' } if (is.null(dateparams$dayCounter)){dateparams$dayCounter='Thirty360'} if (is.null(dateparams$period)){dateparams$period='Semiannual'} if (is.null(dateparams$dateGeneration)){dateparams$dateGeneration='Backward'} if (is.null(dateparams$endOfMonth)){dateparams$endOfMonth=0} if (is.null(dateparams$fixingDays)){dateparams$fixingDays=2} dateparams <- matchParams(dateparams) val <- .Call("FixedRateWithRebuiltCurve", bond, rates, c(discountCurve$table$date), discountCurve$table$zeroRates, dateparams, PACKAGE="RQuantLib") class(val) <- c("FixedRateBond", "Bond") val } FixedRateBondYield <- function( settlementDays, price, faceAmount, effectiveDate, maturityDate, period, calendar, rates, dayCounter, businessDayConvention, compound, redemption, issueDate) { UseMethod("FixedRateBondYield") } FixedRateBondYield.default <- function(settlementDays = 1,price, faceAmount=100, effectiveDate, maturityDate, period, calendar = "us", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption = 100, issueDate) { val <- .Call("FixedRateBondYield", list( settlementDays=as.double(settlementDays), price = as.double(price), calendar=as.character(calendar), faceAmount = as.double(faceAmount), period = as.double(period), businessDayConvention=as.double(businessDayConvention), compound = as.double(compound), redemption= as.double(redemption), dayCounter = as.double(dayCounter), maturityDate = maturityDate, effectiveDate = effectiveDate, issueDate = issueDate ), rates, PACKAGE="RQuantLib") class(val) <- c("FixedRateBondYield") val } FixedRateBondPriceByYield <- function( settlementDays, yield, faceAmount, effectiveDate, maturityDate, period, calendar, rates, dayCounter, businessDayConvention, compound, redemption, issueDate) { UseMethod("FixedRateBondPriceByYield") } FixedRateBondPriceByYield.default <- function(settlementDays = 1, yield, faceAmount=100, effectiveDate=issueDate, maturityDate, period, calendar = "us", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption = 100, issueDate) { val <- .Call("FixedRateBondPriceByYield", list( settlementDays=as.double(settlementDays), yield = as.double(yield), calendar=as.character(calendar), faceAmount = as.double(faceAmount), period = as.double(period), businessDayConvention=as.double(businessDayConvention), compound = as.double(compound), redemption= as.double(redemption), dayCounter = as.double(dayCounter), maturityDate = maturityDate, effectiveDate = effectiveDate, issueDate = issueDate ), rates, PACKAGE="RQuantLib") class(val) <- c("FixedRateBondPriceByYield") val } FloatingRateBond <- function(bond, gearings, spreads, caps, floors, index, curve, dateparams){ UseMethod("FloatingRateBond") } FloatingRateBond.default <- function(bond, gearings=c(), spreads=c(), caps=c(), floors=c(), index, curve, dateparams=list(refDate=bond$issueDate-2, settlementDays=1, calendar='us', businessDayConvention='Following', terminationDateConvention='Following', dayCounter='Thirty360', period='Semiannual', dateGeneration='Backward', endOfMonth=0, fixingDays=2) ) { val <- 0 if (is.null(bond$faceAmount)){bond$faceAmount=100} if (is.null(bond$redemption)){bond$redemption=100} if (is.null(bond$effectiveDate)){bond$effectiveDate=bond$issueDate} if (is.null(dateparams$settlementDays)){dateparams$settlementDays=1} if (is.null(dateparams$calendar)){dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)){ dateparams$businessDayConvention='Following' } if (is.null(dateparams$terminationDateConvention)){ dateparams$terminationDateConvention='Following' } if (is.null(dateparams$dayCounter)){dateparams$dayCounter='Thirty360'} if (is.null(dateparams$period)){dateparams$period='Semiannual'} if (is.null(dateparams$dateGeneration)){dateparams$dateGeneration='Backward'} if (is.null(dateparams$endOfMonth)){dateparams$endOfMonth=0} if (is.null(dateparams$fixingDays)){dateparams$fixingDays=2} if (is.null(dateparams$refDate)) {dateparams$refDate=bond$issueDate-2} dateparams <- matchParams(dateparams) indexparams <- list(type=index$type, length=index$length, inTermOf=index$inTermOf) ibor <- index$term val <- .Call("FloatingWithRebuiltCurve", bond, gearings, spreads, caps, floors, indexparams, c(ibor$table$date), ibor$table$zeroRates, c(curve$table$date), curve$table$zeroRates, dateparams, PACKAGE="RQuantLib") class(val) <- c("FloatingRateBond", "Bond") val } ConvertibleZeroCouponBond <- function(bondparams, process, dateparams){ UseMethod("ConvertibleZeroCouponBond") } ConvertibleZeroCouponBond.default <- function(bondparams, process, dateparams=list( settlementDays=1, calendar='us', dayCounter='Thirty360', period='Semiannual', businessDayConvention='Following' ) ) { val <- 0 if (is.null(bondparams$exercise)){bondparams$exercise='am'} if (is.null(bondparams$faceAmount)){bondparams$faceAmount=100} if (is.null(bondparams$redemption)){bondparams$redemption=100} if (is.null(bondparams$divSch)){ bondparams$divSch = data.frame(Type=character(0), Amount=numeric(0), Rate = numeric(0), Date = as.Date(character(0))) } if (is.null(bondparams$callSch)){ bondparams$callSch = data.frame(Price=numeric(0), Type=character(0), Date=as.Date(character(0))) } if (is.null(dateparams$settlementDays)){dateparams$settlementDays=1} if (is.null(dateparams$calendar)){dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)){ dateparams$businessDayConvention='Following' } if (is.null(dateparams$dayCounter)){dateparams$dayCounter='Thirty360'} if (is.null(dateparams$period)){dateparams$period='Semiannual'} dateparams <- matchParams(dateparams) callabilitySchedule <- bondparams$callSch dividendSchedule <- bondparams$divSch dividendYield <- process$divYield riskFreeRate <- process$rff val <- .Call("ConvertibleZeroBond", bondparams, process, c(dividendYield$table$date), dividendYield$table$zeroRates, c(riskFreeRate$table$date), riskFreeRate$table$zeroRates, dividendSchedule, callabilitySchedule, dateparams, PACKAGE="RQuantLib") class(val) <- c("ConvertibleZeroCouponBond", "Bond") val } ConvertibleFixedCouponBond <- function(bondparams, coupon, process, dateparams){ UseMethod("ConvertibleFixedCouponBond") } ConvertibleFixedCouponBond.default <- function(bondparams, coupon, process, dateparams=list( settlementDays=1, calendar='us', dayCounter='Thirty360', period='Semiannual', businessDayConvention='Following' ) ){ val <- 0 if (is.null(bondparams$exercise)){bondparams$exercise='am'} if (is.null(bondparams$faceAmount)){bondparams$faceAmount=100} if (is.null(bondparams$redemption)){bondparams$redemption=100} if (is.null(bondparams$divSch)){ bondparams$divSch = data.frame(Type=character(0), Amount=numeric(0), Rate = numeric(0), Date = as.Date(character(0))) } if (is.null(bondparams$callSch)){ bondparams$callSch = data.frame(Price=numeric(0), Type=character(0), Date=as.Date(character(0))) } if (is.null(dateparams$settlementDays)){dateparams$settlementDays=1} if (is.null(dateparams$calendar)){dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)){ dateparams$businessDayConvention='Following' } if (is.null(dateparams$dayCounter)){dateparams$dayCounter='Thirty360'} if (is.null(dateparams$period)){dateparams$period='Semiannual'} dateparams <- matchParams(dateparams) callabilitySchedule <- bondparams$callSch dividendSchedule <- bondparams$divSch dividendYield <- process$divYield riskFreeRate <- process$rff val <- .Call("ConvertibleFixedBond", bondparams, coupon, process, c(dividendYield$table$date), dividendYield$table$zeroRates, c(riskFreeRate$table$date), riskFreeRate$table$zeroRates, dividendSchedule, callabilitySchedule, dateparams, PACKAGE="RQuantLib") class(val) <- c("ConvertibleFixedCouponBond", "Bond") val } ConvertibleFloatingCouponBond <- function(bondparams, iborindex,spread, process, dateparams){ UseMethod("ConvertibleFloatingCouponBond") } ConvertibleFloatingCouponBond.default <- function(bondparams, iborindex, spread, process, dateparams=list( settlementDays=1, calendar='us', dayCounter='Thirty360', period='Semiannual', businessDayConvention='Following' )){ val <- 0 if (is.null(bondparams$exercise)){bondparams$exercise='am'} if (is.null(bondparams$faceAmount)){bondparams$faceAmount=100} if (is.null(bondparams$redemption)){bondparams$redemption=100} if (is.null(bondparams$divSch)){ bondparams$divSch = data.frame(Type=character(0), Amount=numeric(0), Rate = numeric(0), Date = as.Date(character(0))) } if (is.null(bondparams$callSch)){ bondparams$callSch = data.frame(Price=numeric(0), Type=character(0), Date=as.Date(character(0))) } if (is.null(dateparams$settlementDays)){dateparams$settlementDays=1} if (is.null(dateparams$calendar)){dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)){ dateparams$businessDayConvention='Following' } if (is.null(dateparams$dayCounter)){dateparams$dayCounter='Thirty360'} if (is.null(dateparams$period)){dateparams$period='Semiannual'} dateparams <- matchParams(dateparams) callabilitySchedule <- bondparams$callSch dividendSchedule <- bondparams$divSch dividendYield <- process$divYield riskFreeRate <- process$rff indexparams <- list(type=iborindex$type, length=iborindex$length, inTermOf=iborindex$inTermOf) ibor <- iborindex$term val <- .Call("ConvertibleFloatingBond", bondparams, process, c(dividendYield$table$date), dividendYield$table$zeroRates, c(riskFreeRate$table$date), riskFreeRate$table$zeroRates, c(ibor$table$date), ibor$table$zeroRates, indexparams,spread, dividendSchedule, callabilitySchedule, dateparams, PACKAGE="RQuantLib") class(val) <- c("ConvertibleFloatingCouponBond", "Bond") val } CallableBond <- function(bondparams, hullWhite, coupon, dateparams){ UseMethod("CallableBond") } CallableBond.default <- function(bondparams, hullWhite, coupon, dateparams=list( settlementDays=1, calendar='us', dayCounter='Thirty360', period='Semiannual', businessDayConvention='Following', terminationDateConvention='Following' )){ val <- 0 if (is.null(bondparams$faceAmount)){bondparams$faceAmount=100} if (is.null(bondparams$redemption)){bondparams$redemption=100} if (is.null(bondparams$callSch)){ bondparams$callSch = data.frame(Price=numeric(0), Type=character(0), Date=as.Date(character(0))) } if (is.null(dateparams$settlementDays)){dateparams$settlementDays=1} if (is.null(dateparams$calendar)){dateparams$calendar='us'} if (is.null(dateparams$businessDayConvention)){ dateparams$businessDayConvention='Following' } if (is.null(dateparams$terminationDateConvention)){ dateparams$terminationDateConvention='Following' } if (is.null(dateparams$dayCounter)){dateparams$dayCounter='Thirty360'} if (is.null(dateparams$period)){dateparams$period='Semiannual'} dateparams <- matchParams(dateparams) callSch <- bondparams$callSch # hw.termStructure <- hullWhite$term val <- .Call("CallableBond", bondparams, hullWhite,coupon, # c(hw.termStructure$table$date), # hw.termStructure$table$zeroRates, callSch, dateparams, PACKAGE="RQuantLib") class(val) <- c("CallableBond", "Bond") val } FittedBondCurve <- function(curveparams, lengths, coupons, marketQuotes, dateparams){ UseMethod("FittedBondCurve") } FittedBondCurve.default <- function(curveparams, lengths, coupons, marketQuotes, dateparams){ val <- 0 dateparams <- matchParams(dateparams) val <- .Call("FittedBondCurve", curveparams, lengths, coupons, marketQuotes, dateparams, PACKAGE="RQuantLib") class(val) <- c("DiscountCurve") val } #CMSBond <- function(bondparams, swapIndex, cap, floor, gearings, spreads # pricer, iborIndex){ # UseMethod("CMSBond") #} #CMSBond.default <- function(bondparams, iborIndex, swapIndex, cap, floor, gearings, # spreads, pricer){ # val <- 0 # swaptionVol <- pricer$swaptionVol # atmOptionTenors <- swaptionVol$atmOptionTenors # atmSwapTenors <- swaptionVol$atmSwapTenors # volMatrix <- swaptionVol$volatilityMatrix # swapIndex <- matchParams(swapIndex) # ibor <- iborIndex$term # val <- .Call("CMSBond", bondparams, iborIndex, swapIndex, cap, floor, gearings, spreads, # swaptionVol, atmOptionTenors, atmSwapTenors, volMatrix, pricer # ibor$table$dates, ibor$table$zeroRates) #} # matching functions matchDayCounter <- function(daycounter = c("Actual360", "ActualFixed", "ActualActual", "Business252", "OneDayCounter", "SimpleDayCounter", "Thirty360")) { if (!is.numeric(daycounter)) { daycounter <- match.arg(daycounter) daycounter <- switch(daycounter, Actual360 = 0, ActualFixed = 1, ActualActual = 2, Business252 = 3, OneDayCounter = 4, SimpleDayCounter = 5, Thirty360 = 6) } daycounter } matchBDC <- function(bdc = c("Following", "ModifiedFollowing", "Preceding", "ModifiedPreceding", "Unadjusted")) { if (!is.numeric(bdc)){ bdc <- match.arg(bdc) bdc <- switch(bdc, Following = 0, ModifiedFollowing = 1, Preceding = 2, ModifiedPreceding = 3, Unadjusted = 4) } bdc } matchCompounding <- function(cp = c("Simple", "Compounded", "Continuous", "SimpleThenCompounded")) { if (!is.numeric(cp)){ cp <- match.arg(cp) cp <- switch(cp, Simple = 0, Compounded = 1, Continuous = 2, SimpleThenCompounded = 3) } cp } matchFrequency <- function(freq = c("NoFrequency","Once", "Annual", "Semiannual", "EveryFourthMonth", "Quarterly", "Bimonthly", "EveryFourthWeek", "Biweekly", "Weekly", "Daily")){ if (!is.numeric(freq)){ freq <- match.arg(freq) freq <- switch(freq, NoFrequency = -1, Once = 0, Annual = 1, Semiannual = 2, EveryFourthMonth = 3, Quarterly = 4, Bimonthly = 6, Monthly = 12, EveryFourthWeek = 13, Biweekly = 26, Weekly = 52, Daily = 365) } freq } matchDateGen <- function(dg = c("Backward", "Forward", "Zero", "ThirdWednesday", "Twentieth", "TwentiethIMM")){ if (!is.numeric(dg)){ dg <- match.arg(dg) dg <- switch(dg, Backward = 0, Forward = 1, Zero = 2, ThirdWednesday = 3, Twentieth = 4, TwentiethIMM = 5) } dg } matchParams <- function(params) { if (!is.null(params$dayCounter)) { params$dayCounter <- matchDayCounter(params$dayCounter) } if (!is.null(params$period)) { params$period <- matchFrequency(params$period) } if (!is.null(params$businessDayConvention)) { params$businessDayConvention <- matchBDC(params$businessDayConvention) } if (!is.null(params$terminationDateConvention)) { params$terminationDateConvention <- matchBDC(params$terminationDateConvention) } if (!is.null(params$dateGeneration)) { params$dateGeneration <- matchDateGen(params$dateGeneration) } if (!is.null(params$fixedLegConvention)) { params$fixedLegConvention <- matchBDC(params$fixedLegConvention) } if (!is.null(params$fixedLegDayCounter)) { params$fixedLegDayCounter <- matchDayCounter(params$fixedLegDayCounter) } params } # Generic methods plot.Bond <- function(x, ...) { warning("No plotting available for class", class(x)[1],"\n") invisible(x) } print.Bond <- function(x, digits=5, ...) { cat("Concise summary of valuation for", class(x)[1], "\n") cat(" Net present value : ", format(x$NPV), "\n") cat(" clean price : ", format(x$cleanPrice, digits=digits), "\n") cat(" dirty price : ", format(x$dirtyPrice, digits=digits), "\n") cat(" accrued coupon : ", format(x$accruedCoupon, digits=digits), "\n") cat(" yield : ", format(x$yield, digits=digits), "\n") cat(" cash flows : \n") print(x$cashFlow, row.names=FALSE, digits=digits) #print(round(unlist(x[1:5]), digits)) invisible(x) } summary.Bond <- function(object, digits=5, ...) { cat("Detailed summary of valuation for", class(object)[1], "\n") print(round(unlist(object[1:5]), digits)) cat("with parameters\n") print(unlist(object[["parameters"]])) invisible(object) } RQuantLib/R/calendars.R0000644000175000017500000001260012271333436013314 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2009 Dirk Eddelbuettel ## Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen ## ## $Id$ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA isBusinessDay <- function(calendar="TARGET", dates=Sys.Date()) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") val <- .Call("isBusinessDay", calendar, dates, PACKAGE="RQuantLib") val <- as.logical(val) names(val) <- dates val } businessDay <- function(calendar="TARGET", dates=Sys.Date()) { ## may get deprecated one day isBusinessDay(calendar, dates) } isHoliday <- function(calendar="TARGET", dates=Sys.Date()) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") val <- .Call("isHoliday", calendar, dates, PACKAGE="RQuantLib") val <- as.logical(val) names(val) <- dates val } isWeekend <- function(calendar="TARGET", dates=Sys.Date()) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") val <- .Call("isWeekend", calendar, dates, PACKAGE="RQuantLib") val <- as.logical(val) names(val) <- dates val } isEndOfMonth <- function(calendar="TARGET", dates=Sys.Date()) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") val <- .Call("isEndOfMonth", calendar, dates, PACKAGE="RQuantLib") val <- as.logical(val) names(val) <- dates val } getEndOfMonth <- function(calendar="TARGET", dates=Sys.Date()) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") val <- .Call("endOfMonth", calendar, dates, PACKAGE="RQuantLib") names(val) <- dates val } endOfMonth <- function(calendar="TARGET", dates=Sys.Date()) { getEndOfMonth(calendar, dates) } adjust <- function(calendar="TARGET", dates=Sys.Date(), bdc = 0 ) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") val <- .Call("adjust", calendar, as.double(bdc), dates, PACKAGE="RQuantLib") names(val) <- dates val } advance <- function(calendar="TARGET", dates=Sys.Date(), n, timeUnit, # call 1 period, # call 2 bdc = 0, emr = 0) { stopifnot(is.character(calendar)) stopifnot(class(dates)=="Date") call1 <- missing(period) & !missing(n) & !missing(timeUnit) ## or was it && ? call2 <- !missing(period) & missing(n) & missing(timeUnit) stopifnot(call1 | call2) val <- NULL if (call1) val <- .Call("advance1", calendar, list(amount = as.double(n), unit = as.double(timeUnit), bdc = as.double(bdc), emr = as.double(emr)), dates, PACKAGE="RQuantLib") if (call2) val <- .Call("advance2", calendar, list(period = as.double(period), bdc = as.double(bdc), emr = as.double(emr)), dates, PACKAGE="RQuantLib") stopifnot( !is.null(val) ) val } businessDaysBetween <- function(calendar="TARGET", from=Sys.Date(), to = Sys.Date() + 5, includeFirst = 1, includeLast = 0 ) { stopifnot(is.character(calendar)) stopifnot(class(from)=="Date") stopifnot(class(to)=="Date") val <- .Call("businessDaysBetween", calendar, list(includeFirst = as.double(includeFirst), includeLast = as.double(includeLast)), from, to, PACKAGE="RQuantLib") val <- val val } getHolidayList <- function(calendar="TARGET", from=Sys.Date(), to=Sys.Date() + 5, includeWeekends=0) { stopifnot(is.character(calendar)) stopifnot(class(from)=="Date") stopifnot(class(to)=="Date") val <- .Call("holidayList", calendar, list(includeWeekends=as.double(includeWeekends), from=from, to=to), PACKAGE="RQuantLib") val } holidayList <- function(calendar="TARGET", from=Sys.Date(), to=Sys.Date() + 5, includeWeekends=0) { getHolidayList(calendar, from, to, includeWeekends) } setCalendarContext <- function(calendar="TARGET", fixingDays = 2, settleDate = Sys.Date() + 2) { val <- .Call("setContext", list(calendar = calendar, fixingDays = fixingDays, settleDate = settleDate), PACKAGE="RQuantLib") } RQuantLib/R/dayCounter.R0000644000175000017500000000247112271333436013502 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Khanh Nguyen ## ## $Id: calendars.R 293 2010-08-07 15:56:13Z edd $ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA dayCount <- function(startDates, endDates, dayCounters) { val <- .Call('dayCount', startDates, endDates, dayCounters, PACKAGE="RQuantLib") invisible(val) } yearFraction <- function(startDates, endDates, dayCounters) { val <- .Call('yearFraction', startDates, endDates, dayCounters, PACKAGE="RQuantLib") invisible(val) } setEvaluationDate <- function(evalDate) { val <- .Call("setEvaluationDate", evalDate, PACKAGE="RQuantLib") invisible(val) } RQuantLib/R/discount.R0000644000175000017500000000670712271333436013223 0ustar00eddedd## RQuantLib function DiscountCurve ## ## Copyright (C) 2005 Dominick Samperi ## Copyright (C) 2007 - 2009 Dirk Eddelbuettel ## Copyright (C) 2009 - 2010 Dirk Eddelbuettel and Khanh Nguyen ## ## $Id: discount.R,v 1.3 2007/12/31 02:11:19 edd Exp $ ## ## This program is part of the RQuantLib library for R (GNU S). ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version. ## ## 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 GNU General Public License for more ## details. DiscountCurve <- function(params, tsQuotes, times=seq(0,10,.1)) { UseMethod("DiscountCurve") } DiscountCurve.default <- function(params, tsQuotes, times=seq(0,10,.1)) { ## Check that params is properly formatted. if(!is.list(params) || length(params) == 0) { stop("The params parameter must be a non-empty list"); } ## Check that the term structure quotes are properly formatted. if(!is.list(tsQuotes) || length(tsQuotes) == 0) { stop("Term structure quotes must be a non-empty list") } if(length(tsQuotes) != length(names(tsQuotes))) { stop("Term structure quotes must include labels") } if(!is.numeric(unlist(tsQuotes))) { stop("Term structure quotes must have numeric values") } ## Check the times vector if(!is.numeric(times) || length(times) == 0) { stop("The times parameter must be a non-emptry numeric vector") } ## Finally ready to make the call... val <- .Call("DiscountCurve", params, tsQuotes, times, PACKAGE="RQuantLib") val[["table"]] <- as.data.frame(val[["table"]]) ## Windows all of a sudden needs this class(val) <- c("DiscountCurve") val } plot.DiscountCurve <- function(x, setpar=TRUE, dolegend=TRUE,...) { if(setpar) { savepar <- par(mfrow=c(3,1)) } if (x$flatQuotes) { ## Don't want to plot noise when we look at a flat yield curve plot(c(x$times[1],x$times[length(x$times)]), c(0,.5),type='n', main='forwards', xlab='time',ylab='forward rate') lines(x$times, x$forwards, type='l') if(dolegend) { legend('center','center','flat',bty='n',text.col='red') } plot(c(x$times[1],x$times[length(x$times)]), c(0,.5),type='n', main='zero rates', xlab='time',ylab='zero rate') lines(x$times, x$zerorates, type='l') if(dolegend) { legend('center','center','flat',bty='n',text.col='red') } } else { plot(x$times, x$forwards, type='l', main='forwards',xlab='time',ylab='fwd rate') if(dolegend) { legend('center','center',paste(x$params$interpHow, 'discount'), bty='n', text.col='red') } plot(x$times, x$zerorates, type='l', main='zero rates',xlab='time',ylab='zero rate') if(dolegend) { legend('center','center',paste(x$params$interpHow, 'discount'),bty='n', text.col='red') } } plot(x$times, x$discounts, type='l', main='discounts',xlab='time',ylab='discount') if(dolegend) { if(x$flatQuotes) { legend('center','center','flat',bty='n',text.col='red') } else { legend('center','center',paste(x$params$interpHow, 'discount'),bty='n', text.col='red') } } if (setpar) { par(savepar) } } RQuantLib/R/hullWhiteCalibration.R0000644000175000017500000000342412271333436015501 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen ## ## $Id$ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA hullWhiteCalibrateUsingCap <- function(termStrc, capHelpers, index, evaluationDate) { capData <- capHelpers$data indexparams <- list(type=index$type); ibor <- index$term val <- .Call("HullWhiteCalibrationUsingCap", termStrc$table$date, termStrc$table$zeroRates, capData, ibor$table$date, ibor$table$zeroRates, indexparams, evaluationDate) } hullWhiteCalibrateUsingSwap <- function(termStrc, swapHelpers, index, evaluationDate){ swapData <- swapHelpers$data indexparams <- list(type=index$type); ibor <- index$term val <- .Call("HullWhiteCalibrationUsingSwap", termStrc$table$date, termStrc$table$zeroRates, swapData, ibor$table$date, ibor$table$zeroRates, indexparams, evaluationDate) } RQuantLib/R/implied.R0000644000175000017500000001053612271333436013011 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2009 Dirk Eddelbuettel ## ## $Id: implied.R,v 1.8 2005/10/12 03:20:39 edd Exp $ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA ## also dumps core (0.3.7) ## no longer under 0.3.9 and 0.3.10 with g++ 3.4/4.0 EuropeanOptionImpliedVolatility <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { UseMethod("EuropeanOptionImpliedVolatility") } EuropeanOptionImpliedVolatility.default <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { val <- .Call("EuropeanOptionImpliedVolatility", list(type=as.character(type), value=as.double(value), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility)), PACKAGE="RQuantLib") class(val) <- c("EuropeanOptionImpliedVolatility","ImpliedVolatility") val } # also dumps core (0.3.7) ## no longer under 0.3.9 and 0.3.10 with g++ 3.4/4.0 AmericanOptionImpliedVolatility <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=151) { UseMethod("AmericanOptionImpliedVolatility") } AmericanOptionImpliedVolatility.default <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=151) { val <- .Call("AmericanOptionImpliedVolatility", list(type=as.character(type), value=as.double(value), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility), timeSteps=as.integer(timeSteps), gridPoints=as.integer(gridPoints)), PACKAGE="RQuantLib") class(val) <- c("AmericanOptionImpliedVolatility","ImpliedVolatility") val } # dumps core :-/ BinaryOptionImpliedVolatility <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff=1) { UseMethod("BinaryOptionImpliedVolatility") } BinaryOptionImpliedVolatility.default <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff=1) { val <- .Call("BinaryOptionImpliedVolatility", list(type=as.character(type), value=as.double(value), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility), cashPayoff=as.double(cashPayoff)), PACKAGE="RQuantLib") class(val) <- c("BinaryOptionImpliedVolatility","ImpliedVolatility") val } print.ImpliedVolatility <- function(x, digits=3, ...) { impvol <- x[[1]] cat("Implied Volatility for", class(x)[1], "is", round(impvol, digits), "\n") invisible(x) } summary.ImpliedVolatility <- function(object, digits=3, ...) { impvol <- object[[1]] cat("Implied Volatility for", class(object)[1], "is", round(impvol, digits), "\n") cat("with parameters\n") print(unlist(object[[2]])) invisible(object) } RQuantLib/R/inline.R0000644000175000017500000000443412271341737012647 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2013 Dirk Eddelbuettel ## ## $Id$ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public License ## along with Rcpp. If not, see . .pkgglobalenv <- new.env(parent=emptyenv()) .onLoad <- function(libname, pkgname) { if (.Platform$OS.type=="windows") { ## by convention with CRAN, on Windows we expect these two ## variables to be set, and to be pointing to the respective ## helper installations qlroot <- Sys.getenv("QUANTLIB_ROOT") boostlib <- Sys.getenv("BOOSTLIB") rarch <- Sys.getenv("R_ARCH") qlcflags <- sprintf("-I%s -I. -I\"%s\"", qlroot, boostlib) qllibs <- sprintf("%s -L%s/lib%s -lQuantLib", Rcpp::LdFlags(), rarch) } else { qlcflags <- system( "quantlib-config --cflags", intern = TRUE) qllibs <- system( "quantlib-config --libs", intern = TRUE) } assign("ql_cflags", qlcflags, envir=.pkgglobalenv) assign("ql_libs", qllibs, envir=.pkgglobalenv) } LdFlags <- function(print = TRUE) { if (print) cat(.pkgglobalenv$ql_libs) else .pkgglobalenv$ql_libs } CFlags <- function(print = TRUE) { if (print) cat(.pkgglobalenv$ql_cflags) else .pkgglobalenv$ql_cflags } inlineCxxPlugin <- function(...) { ## this cannot be fixed til the next Rcpp is release as only it properly exports Rcpp.plugin.maker plugin <- Rcpp:::Rcpp.plugin.maker(include.before = "#include ", libs = sprintf("%s $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)", LdFlags(FALSE)), package = "RQuantLib", Makevars = NULL, Makevars.win = NULL) settings <- plugin() settings$env$PKG_CPPFLAGS <- CFlags(FALSE) settings } RQuantLib/R/mod.R0000644000175000017500000000007512271333436012142 0ustar00eddedd #loadModule("BondsMod", TRUE) #loadModule("BlackMod", TRUE) RQuantLib/R/option.R0000644000175000017500000001377612271333436012707 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2009 Dirk Eddelbuettel ## ## $Id: option.R,v 1.6 2007/12/31 01:53:06 edd Exp $ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA EuropeanOption <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { UseMethod("EuropeanOption") } EuropeanOption.default <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { type <- match.arg(type, c("call", "put")) val <- .Call("EuropeanOption", list(type=as.character(type), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility)), PACKAGE="RQuantLib") class(val) <- c("EuropeanOption", "Option") val } AmericanOption <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=149, engine="BaroneAdesiWhaley") { UseMethod("AmericanOption") } AmericanOption.default <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=149, engine="BaroneAdesiWhaley") { type <- match.arg(type, c("call", "put")) engine <- match.arg(engine, c("BaroneAdesiWhaley", "CrankNicolson")) val <- .Call("AmericanOption", list(type=as.character(type), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility), timeSteps=as.integer(timeSteps), gridPoints=as.integer(gridPoints), engine=as.character(engine)), PACKAGE="RQuantLib") class(val) <- c("AmericanOption","Option") val } BinaryOption <- function(binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) { UseMethod("BinaryOption") } BinaryOption.default <- function(binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) { type <- match.arg(type, c("call", "put")) binType <- match.arg(binType, c("cash", "asset", "gap")) excType <- match.arg(excType, c("american", "european")) val <- .Call("BinaryOption", list(binType=as.character(binType), type=as.character(type), excType=as.character(excType), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility), cashPayoff=as.double(cashPayoff)), PACKAGE="RQuantLib") class(val) <- c("BinaryOption", "Option") val } BarrierOption <- function(barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate=0.0) { UseMethod("BarrierOption") } BarrierOption.default <- function(barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate=0.0) { type <- match.arg(type, c("call", "put")) barrType <- match.arg(barrType, c("downin", "upin", "downout", "upout")) val <- .Call("BarrierOption", list(barrType=as.character(barrType), type=as.character(type), underlying=as.double(underlying), strike=as.double(strike), dividendYield=as.double(dividendYield), riskFreeRate=as.double(riskFreeRate), maturity=as.double(maturity), volatility=as.double(volatility), barrier=as.double(barrier), rebate=as.double(rebate)), PACKAGE="RQuantLib") class(val) <- c("BarrierOption", "Option") val } plot.Option <- function(x, ...) { warning("No plotting available for class", class(x)[1],"\n") invisible(x) } print.Option <- function(x, digits=4, ...) { cat("Concise summary of valuation for", class(x)[1], "\n") print(round(unlist(x[1:7]), digits)) invisible(x) } summary.Option <- function(object, digits=4, ...) { cat("Detailed summary of valuation for", class(object)[1], "\n") print(round(unlist(object[1:7]), digits)) cat("with parameters\n") print(unlist(object[["parameters"]])) invisible(object) } RQuantLib/R/zzz.R0000644000175000017500000000176512271333436012227 0ustar00eddedd## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2010 Dirk Eddelbuettel ## ## $Id: zzz.R,v 1.3 2005/10/05 03:03:54 edd Exp $ ## ## This file is part of the RQuantLib library for GNU R. ## It is made available under the terms of the GNU General Public ## License, version 2, or at your option, any later version, ## incorporated herein by reference. ## ## 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 GNU General Public License for more ## details. ## ## You should have received a copy of the GNU General Public ## License along with this program; if not, write to the Free ## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ## MA 02111-1307, USA #.First.lib <- function(lib, pkg) { # #cat("This is a pre-release. The interface might change...\n") # library.dynam("RQuantLib", pkg, lib ) #} RQuantLib/README.md0000644000175000017500000000127012271336022012306 0ustar00eddedd# RQuantLib The RQuantLib package makes parts of [QuantLib](https://github.com/lballabio/quantlib) visible to the R user. Currently a number option pricing functions are included, both vanilla and exotic, as well as a broad range of fixed-income functions. Also included are general calendaring and holiday utilities. Further software contributions are welcome. The QuantLib project aims to provide a comprehensive software framework for quantitative finance. The goal is to provide a standard open source library for quantitative analysis, modeling, trading, and risk management of financial assets. ## Authors Dirk Eddelbuettel and Khanh Nguyen (during 2009-2010) ## License GPL (>= 2) RQuantLib/cleanup0000755000175000017500000000041612271333436012413 0ustar00eddedd#!/bin/sh rm -f config.log config.status confdefs.h autom4te.cache \ src/Makevars src/libRQuantLib.a src/libRQuantLib.def src/*.o src/*.so src/symbols.rds \ RcppSrc/*.a RcppSrc/*.o RcppSrc/config.* inst/Rcpp-version.txt find . -name \*~ | xargs rm -f exit 0 RQuantLib/configure0000755000175000017500000035045312271333436012756 0ustar00eddedd#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.67 for RQuantlib 0.3.8. # # # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, # 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software # Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV export CONFIG_SHELL exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -p'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi if test -x / >/dev/null 2>&1; then as_test_x='test -x' else if ls -dL / >/dev/null 2>&1; then as_ls_L_option=L else as_ls_L_option= fi as_test_x=' eval sh -c '\'' if test -d "$1"; then test -d "$1/."; else case $1 in #( -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' fi as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='RQuantlib' PACKAGE_TARNAME='rquantlib' PACKAGE_VERSION='0.3.8' PACKAGE_STRING='RQuantlib 0.3.8' PACKAGE_BUGREPORT='' PACKAGE_URL='' ac_subst_vars='LTLIBOBJS LIBOBJS QUANTLIB RSCRIPT R CXXCPP OBJEXT EXEEXT ac_ct_CXX CPPFLAGS LDFLAGS CXXFLAGS CXX target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking with_boost_include with_boost_lib ' ac_precious_vars='build_alias host_alias target_alias CXX CXXFLAGS LDFLAGS LIBS CPPFLAGS CCC CXXCPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used" >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures RQuantlib 0.3.8 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/rquantlib] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of RQuantlib 0.3.8:";; esac cat <<\_ACEOF Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-boost-include=INCLUDE_PATH Supply the location of Boost header files --with-boost-lib=LIB_PATH Supply the location of Boost libraries Some influential environment variables: CXX C++ compiler command CXXFLAGS C++ compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CXXCPP C++ preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to the package provider. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF RQuantlib configure 0.3.8 generated by GNU Autoconf 2.67 Copyright (C) 2010 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_cxx_try_compile LINENO # ---------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} as_fn_set_status $ac_retval } # ac_fn_cxx_try_compile # ac_fn_cxx_try_cpp LINENO # ------------------------ # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} as_fn_set_status $ac_retval } # ac_fn_cxx_try_cpp cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by RQuantlib $as_me 0.3.8, which was generated by GNU Autoconf 2.67. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5 ; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # We are using C++ ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test -z "$CXX"; then if test -n "$CCC"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 $as_echo "$CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CXX" && break done fi if test -z "$CXX"; then ac_ct_CXX=$CXX for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CXX="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 $as_echo "$ac_ct_CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CXX" && break done if test "x$ac_ct_CXX" = x; then CXX="g++" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CXX=$ac_ct_CXX fi fi fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C++ compiler works" >&5 $as_echo_n "checking whether the C++ compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C++ compiler cannot create executables See \`config.log' for more details" "$LINENO" 5 ; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler default output file name" >&5 $as_echo_n "checking for C++ compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5 ; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C++ compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5 ; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if test "${ac_cv_objext+set}" = set; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5 ; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } if test "${ac_cv_cxx_compiler_gnu+set}" = set; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 $as_echo "$ac_cv_cxx_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GXX=yes else GXX= fi ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } if test "${ac_cv_prog_cxx_g+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes else CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cxx_werror_flag=$ac_save_cxx_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 $as_echo "$ac_cv_prog_cxx_g" >&6; } if test "$ac_test_CXXFLAGS" = set; then CXXFLAGS=$ac_save_CXXFLAGS elif test $ac_cv_prog_cxx_g = yes; then if test "$GXX" = yes; then CXXFLAGS="-g -O2" else CXXFLAGS="-g" fi else if test "$GXX" = yes; then CXXFLAGS="-O2" else CXXFLAGS= fi fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 $as_echo_n "checking how to run the C++ preprocessor... " >&6; } if test -z "$CXXCPP"; then if test "${ac_cv_prog_CXXCPP+set}" = set; then : $as_echo_n "(cached) " >&6 else # Double quotes because CXXCPP needs to be expanded for CXXCPP in "$CXX -E" "/lib/cpp" do ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CXXCPP=$CXXCPP fi CXXCPP=$ac_cv_prog_CXXCPP else ac_cv_prog_CXXCPP=$CXXCPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5 $as_echo "$CXXCPP" >&6; } ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5 ; } fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test -z "$CXX"; then if test -n "$CCC"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 $as_echo "$CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CXX" && break done fi if test -z "$CXX"; then ac_ct_CXX=$CXX for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_ac_ct_CXX="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 $as_echo "$ac_ct_CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CXX" && break done if test "x$ac_ct_CXX" = x; then CXX="g++" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CXX=$ac_ct_CXX fi fi fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } if test "${ac_cv_cxx_compiler_gnu+set}" = set; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 $as_echo "$ac_cv_cxx_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GXX=yes else GXX= fi ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } if test "${ac_cv_prog_cxx_g+set}" = set; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes else CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cxx_werror_flag=$ac_save_cxx_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 $as_echo "$ac_cv_prog_cxx_g" >&6; } if test "$ac_test_CXXFLAGS" = set; then CXXFLAGS=$ac_save_CXXFLAGS elif test $ac_cv_prog_cxx_g = yes; then if test "$GXX" = yes; then CXXFLAGS="-g -O2" else CXXFLAGS="-g" fi else if test "$GXX" = yes; then CXXFLAGS="-O2" else CXXFLAGS= fi fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test "${GXX}" = yes; then gxx_version=`${CXX} -v 2>&1 | grep "^.*g.. version" | \\ sed -e 's/^.*g.. version *//'` case ${gxx_version} in 1.*|2.*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Only g++ version 3.0 or greater can be used with RQuantib." >&5 $as_echo "$as_me: WARNING: Only g++ version 3.0 or greater can be used with RQuantib." >&2;} as_fn_error $? "Please use a different compiler." "$LINENO" 5 ;; 4.6.*|4.7.*|4.8.*) gxx_newer_than_45="-fpermissive" ;; esac fi # Extract the first word of "R", so it can be a program name with args. set dummy R; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_R+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$R"; then ac_cv_prog_R="$R" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_R="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi R=$ac_cv_prog_R if test -n "$R"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $R" >&5 $as_echo "$R" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi # Next segment by Kurt : ${R_HOME=`R RHOME`} if test -z "${R_HOME}"; then as_fn_error $? "Could not determine R_HOME." "$LINENO" 5 fi CXX=`${R_HOME}/bin/R CMD config CXX` CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS` ## look for Rscript, but use the one found via R_HOME to allow for multiple installations # Extract the first word of "Rscript", so it can be a program name with args. set dummy Rscript; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_RSCRIPT+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$RSCRIPT"; then ac_cv_prog_RSCRIPT="$RSCRIPT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_RSCRIPT="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RSCRIPT=$ac_cv_prog_RSCRIPT if test -n "$RSCRIPT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RSCRIPT" >&5 $as_echo "$RSCRIPT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi #AC_MSG_CHECKING([for Rscript]) if test x"${RSCRIPT}" == x"yes" ; then # AC_MSG_RESULT([yes]) ## Rcpp compile flag providing header directory containing Rcpp.h #rcpp_cxxflags=`${R_HOME}/bin/Rscript -e 'Rcpp:::CxxFlags()'` ## link flag providing libary as well as path to library, and optionally rpath rcpp_ldflags=`${R_HOME}/bin/Rscript -e 'Rcpp:::LdFlags()'` ## now use all these #AC_SUBST([CXXFLAGS],["${CXXFLAGS} $rcpp_cxxflags"]) LDFLAGS="${LDFLAGS} $rcpp_ldflags" else # AC_MSG_RESULT([no]) echo " Your installation does not appear to have Rscript installed. Please make sure that you have a working and complete R installation. " exit 1 fi # borrowed from a check for gnome in GNU gretl: define a check for quantlib-config # Extract the first word of "quantlib-config", so it can be a program name with args. set dummy quantlib-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if test "${ac_cv_prog_QUANTLIB+set}" = set; then : $as_echo_n "(cached) " >&6 else if test -n "$QUANTLIB"; then ac_cv_prog_QUANTLIB="$QUANTLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then ac_cv_prog_QUANTLIB="yes" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi QUANTLIB=$ac_cv_prog_QUANTLIB if test -n "$QUANTLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $QUANTLIB" >&5 $as_echo "$QUANTLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test x"${QUANTLIB}" == x"yes" ; then # use quantlib-config for QL settings pkg_cxxflags=`quantlib-config --cflags` pkg_libs=`quantlib-config --libs` pkg_version=`quantlib-config --version` # also test for quantlib version using result from quantlib-config --version case ${pkg_version} in 0.1.*|0.2.*|0.3.*|0.4.*|0.8.*|0.9.0|0.9.5|0.9.6|0.9.7) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: RQuantLib requires QuantLib (>= 0.9.9)." >&5 $as_echo "$as_me: WARNING: RQuantLib requires QuantLib (>= 0.9.9)." >&2;} as_fn_error $? "Please upgrade to a more recent version." "$LINENO" 5 ;; esac # now use all these CXXFLAGS="${CXXFLAGS} " CXXFLAGS="${CXXFLAGS} ${pkg_cxxflags} ${gxx_newer_than_45}" LDFLAGS="${LDFLAGS} $pkg_libs" else as_fn_error $? "Please install QuantLib before trying to build RQuantLib." "$LINENO" 5 fi ## check for boost, this segment as well as segment below are ## from QuantLib's configure.ac ## ## ## Help the compiler find external software # Check whether --with-boost-include was given. if test "${with_boost_include+set}" = set; then : withval=$with_boost_include; ql_boost_include_path=$withval else ql_boost_include_path="" fi if test -n "$ql_boost_include_path" ; then CXXFLAGS="${CXXFLAGS} -I${ql_boost_include_path}" fi # Check whether --with-boost-lib was given. if test "${with_boost_lib+set}" = set; then : withval=$with_boost_lib; ql_boost_lib_path=$withval else ql_boost_lib_path="" fi if test -n "$ql_boost_lib_path" ; then LDFLAGS="${LDFLAGS} -L${ql_boost_lib_path}" fi ## ## Check for Boost components # QL_CHECK_BOOST_DEVEL # -------------------- # Check whether the Boost headers are available # QL_CHECK_BOOST_VERSION # ---------------------- # Check whether the Boost installation is up to date # QL_CHECK_BOOST # ------------------------ # Boost-related tests { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Boost development files" >&5 $as_echo_n "checking for Boost development files... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } as_fn_error $? "Boost development files not found" "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: checking for minimal Boost version" >&5 $as_echo_n "checking for minimal Boost version... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #if BOOST_VERSION < 103400 #error too old #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } as_fn_error $? "outdated Boost installation" "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_config_files="$ac_config_files src/Makevars" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then test "x$cache_file" != "x/dev/null" && { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} cat confcache >$cache_file else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' # Transform confdefs.h into DEFS. # Protect against shell expansion while executing Makefile rules. # Protect against Makefile macro expansion. # # If the first sed substitution is executed (which looks for macros that # take arguments), then branch to the quote section. Otherwise, # look for a macro that doesn't take arguments. ac_script=' :mline /\\$/{ N s,\\\n,, b mline } t clear :clear s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g t quote s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g t quote b any :quote s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g s/\[/\\&/g s/\]/\\&/g s/\$/$$/g H :any ${ g s/^\n// s/\n/ /g p } ' DEFS=`sed -n "$ac_script" confdefs.h` ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : ${CONFIG_STATUS=./config.status} ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -p'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -p' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi if test -x / >/dev/null 2>&1; then as_test_x='test -x' else if ls -dL / >/dev/null 2>&1; then as_ls_L_option=L else as_ls_L_option= fi as_test_x=' eval sh -c '\'' if test -d "$1"; then test -d "$1/."; else case $1 in #( -*)set "./$1";; esac; case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( ???[sx]*):;;*)false;;esac;fi '\'' sh ' fi as_executable_p=$as_test_x # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by RQuantlib $as_me 0.3.8, which was generated by GNU Autoconf 2.67. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE Configuration files: $config_files Report bugs to the package provider." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ RQuantlib config.status 0.3.8 configured by $0, generated by GNU Autoconf 2.67, with options \\"\$ac_cs_config\\" Copyright (C) 2010 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --he | --h | --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "src/Makevars") CONFIG_FILES="$CONFIG_FILES src/Makevars" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= trap 'exit_status=$? { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" eval set X " :F $CONFIG_FILES " shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$tmp/stdin" case $ac_file in -) cat "$tmp/out" && rm -f "$tmp/out";; *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi echo "Completed configuration and ready to build." ### Local Variables: *** ### mode: autoconf *** ### autoconf-indentation: 4 *** ### End: *** RQuantLib/configure.in0000644000175000017500000001211712271333436013350 0ustar00eddedd# RQuantLib configure.in by Dirk Eddelbuettel # # Using pieces borrowed from RPgSQL, GNU Gretl, GNU R and QuantLib # Greatly simplified thanks to quantlib-config # Another contribution by Kurt Hornik gratefully acknowledged # # $Id$ # require at least autoconf 2.50 AC_PREREQ(2.50) # Process this file with autoconf to produce a configure script. AC_INIT(RQuantlib, 0.3.8) # We are using C++ AC_LANG(C++) AC_REQUIRE_CPP AC_PROG_CXX if test "${GXX}" = yes; then gxx_version=`${CXX} -v 2>&1 | grep "^.*g.. version" | \\ sed -e 's/^.*g.. version *//'` case ${gxx_version} in 1.*|2.*) AC_MSG_WARN([Only g++ version 3.0 or greater can be used with RQuantib.]) AC_MSG_ERROR([Please use a different compiler.]) ;; 4.6.*|4.7.*|4.8.*) gxx_newer_than_45="-fpermissive" ;; esac fi AC_DEFUN(AC_PROG_R, [AC_CHECK_PROG(R,R,yes)]) AC_PROG_R # Next segment by Kurt : ${R_HOME=`R RHOME`} if test -z "${R_HOME}"; then AC_MSG_ERROR([Could not determine R_HOME.]) fi CXX=`${R_HOME}/bin/R CMD config CXX` CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS` ## look for Rscript, but use the one found via R_HOME to allow for multiple installations AC_DEFUN(AC_PROG_RSCRIPT, [AC_CHECK_PROG(RSCRIPT,Rscript,yes)]) AC_PROG_RSCRIPT #AC_MSG_CHECKING([for Rscript]) if test x"${RSCRIPT}" == x"yes" ; then # AC_MSG_RESULT([yes]) ## Rcpp compile flag providing header directory containing Rcpp.h #rcpp_cxxflags=`${R_HOME}/bin/Rscript -e 'Rcpp:::CxxFlags()'` ## link flag providing libary as well as path to library, and optionally rpath rcpp_ldflags=`${R_HOME}/bin/Rscript -e 'Rcpp:::LdFlags()'` ## now use all these #AC_SUBST([CXXFLAGS],["${CXXFLAGS} $rcpp_cxxflags"]) AC_SUBST([LDFLAGS],["${LDFLAGS} $rcpp_ldflags"]) else # AC_MSG_RESULT([no]) echo " Your installation does not appear to have Rscript installed. Please make sure that you have a working and complete R installation. " exit 1 fi # borrowed from a check for gnome in GNU gretl: define a check for quantlib-config AC_DEFUN(AC_PROG_QUANTLIB, [AC_CHECK_PROG(QUANTLIB,quantlib-config,yes)]) AC_PROG_QUANTLIB if test x"${QUANTLIB}" == x"yes" ; then # use quantlib-config for QL settings pkg_cxxflags=`quantlib-config --cflags` pkg_libs=`quantlib-config --libs` pkg_version=`quantlib-config --version` # also test for quantlib version using result from quantlib-config --version case ${pkg_version} in 0.1.*|0.2.*|0.3.*|0.4.*|0.8.*|0.9.0|0.9.5|0.9.6|0.9.7) AC_MSG_WARN([RQuantLib requires QuantLib (>= 0.9.9).]) AC_MSG_ERROR([Please upgrade to a more recent version.]) ;; esac # now use all these AC_SUBST([CXXFLAGS],["${CXXFLAGS} "]) AC_SUBST([CXXFLAGS],["${CXXFLAGS} ${pkg_cxxflags} ${gxx_newer_than_45}"]) AC_SUBST([LDFLAGS],["${LDFLAGS} $pkg_libs"]) else AC_MSG_ERROR([Please install QuantLib before trying to build RQuantLib.]) fi ## check for boost, this segment as well as segment below are ## from QuantLib's configure.ac ## ## ## Help the compiler find external software AC_ARG_WITH([boost-include], AC_HELP_STRING([--with-boost-include=INCLUDE_PATH], [Supply the location of Boost header files]), [ql_boost_include_path=$withval], [ql_boost_include_path=""]) if test [ -n "$ql_boost_include_path" ] ; then AC_SUBST([CXXFLAGS],["${CXXFLAGS} -I${ql_boost_include_path}"]) fi AC_ARG_WITH([boost-lib], AC_HELP_STRING([--with-boost-lib=LIB_PATH], [Supply the location of Boost libraries]), [ql_boost_lib_path=$withval], [ql_boost_lib_path=""]) if test [ -n "$ql_boost_lib_path" ] ; then AC_SUBST([LDFLAGS],["${LDFLAGS} -L${ql_boost_lib_path}"]) fi ## ## Check for Boost components # QL_CHECK_BOOST_DEVEL # -------------------- # Check whether the Boost headers are available AC_DEFUN([QL_CHECK_BOOST_DEVEL], [AC_MSG_CHECKING([for Boost development files]) AC_TRY_COMPILE( [@%:@include @%:@include @%:@include @%:@include ], [], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]) AC_MSG_ERROR([Boost development files not found]) ]) ]) # QL_CHECK_BOOST_VERSION # ---------------------- # Check whether the Boost installation is up to date AC_DEFUN([QL_CHECK_BOOST_VERSION], [AC_MSG_CHECKING([for minimal Boost version]) AC_REQUIRE([QL_CHECK_BOOST_DEVEL]) AC_TRY_COMPILE( [@%:@include ], [@%:@if BOOST_VERSION < 103400 @%:@error too old @%:@endif], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no]) AC_MSG_ERROR([outdated Boost installation]) ]) ]) # QL_CHECK_BOOST # ------------------------ # Boost-related tests AC_DEFUN([QL_CHECK_BOOST], [AC_REQUIRE([QL_CHECK_BOOST_DEVEL]) AC_REQUIRE([QL_CHECK_BOOST_VERSION]) ]) QL_CHECK_BOOST AC_SUBST(CXXFLAGS) AC_SUBST(LDFLAGS) AC_OUTPUT(src/Makevars) echo "Completed configuration and ready to build." ### Local Variables: *** ### mode: autoconf *** ### autoconf-indentation: 4 *** ### End: *** RQuantLib/demo/0000755000175000017500000000000012271333436011761 5ustar00eddeddRQuantLib/demo/00Index0000644000175000017500000000006712271333436013116 0ustar00eddeddOptionSurfaces European Option surfaces (requires rgl) RQuantLib/demo/OptionSurfaces.R0000644000175000017500000000454512271333436015060 0ustar00eddedd ## RQuantLib Demo for (European) Option surfaces ## Dirk Eddelbuettel, September 2005 ## $Id: OptionSurfaces.R,v 1.1 2005/10/12 03:42:45 edd Exp $ OptionSurface <- function(EOres, label, fov=60) { axis.col <- "black" text.col <- axis.col ylab = label xlab = "Underlying" zlab = "Volatility" y <- EOres ## clear scene: clear3d() clear3d(type="bbox") clear3d(type="lights") ## setup env: ## bg3d(color="#887777") bg3d(color="#DDDDDD") light3d() rgl.viewpoint(fov=fov) ##rgl.bg(col="white", fogtype="exp2") ##rgl.bg(col="black", fogtype="exp2") ##rgl.bg(col="black", fogtype="exp") ##rgl.bg(col="white", fogtype="exp") x <- (1:nrow(y)) z <- (1:ncol(y)) x <- (x-min(x))/(max(x)-min(x)) y <- (y-min(y))/(max(y)-min(y)) z <- (z-min(z))/(max(z)-min(z)) rgl.surface(x, z, y, alpha=0.6, lit=TRUE, color="blue") rgl.lines(c(0,1), c(0,0), c(0,0), col=axis.col) rgl.lines(c(0,0), c(0,1), c(0,0), col=axis.col) rgl.lines(c(0,0),c(0,0), c(0,1), col=axis.col) rgl.texts(1,0,0, xlab, adj=1, col=text.col) rgl.texts(0,1,0, ylab, adj=1, col=text.col) rgl.texts(0,0,1, zlab, adj=1, col=text.col) ## add grid (credit's to John Fox scatter3d) xgridind <- round(seq(1, nrow(y), length=25)) zgridind <- round(seq(1, ncol(y), length=25)) rgl.surface(x[xgridind], z[zgridind], y[xgridind,zgridind], color="darkgray", alpha=0.5, lit=TRUE, front="lines", back="lines") ## animate (credit to rgl.viewpoint() example) start <- proc.time()[3] while ((i <- 36*(proc.time()[3]-start)) < 360) { rgl.viewpoint(i,i/8); } } RQuantLib.demo.OptionSurfaces <- function() { und.seq <- seq(10, 200, by = 2.5) vol.seq <- seq(0.05, 2, by = 0.025) cat("Calculating surface ...") EOarr <- EuropeanOptionArrays("call", underlying = und.seq, strike = 100, dividendYield = 0.01, riskFreeRate = 0.03, maturity = 1, volatility = vol.seq) cat(" done.\n") rgl.open() OptionSurface(EOarr$value, "Value") OptionSurface(EOarr$delta, "Delta") OptionSurface(EOarr$gamma, "Gamma") OptionSurface(EOarr$vega, "Vega") OptionSurface(EOarr$theta, "Theta") } require(rgl,quiet=TRUE) require(RQuantLib,quiet=TRUE) RQuantLib.demo.OptionSurfaces() RQuantLib/inst/0000755000175000017500000000000012271333436012012 5ustar00eddeddRQuantLib/inst/Boost-License.txt0000644000175000017500000000247312271333436015227 0ustar00eddeddBoost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. RQuantLib/inst/QuantLib-License.txt0000644000175000017500000001063212271333436015654 0ustar00eddeddQuantLib is Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2001, 2002, 2003 Nicolas Di Césaré Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb Copyright (C) 2002, 2003, 2004 Decillion Pty(Ltd) Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 Ferdinando Ametrano Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 StatPro Italia srl Copyright (C) 2003, 2004, 2007 Neil Firth Copyright (C) 2003, 2004 Roman Gitlin Copyright (C) 2003 Niels Elken Sønderby Copyright (C) 2003 Kawanishi Tomoya Copyright (C) 2004 FIMAT Group Copyright (C) 2004 M-Dimension Consulting Inc. Copyright (C) 2004 Mike Parker Copyright (C) 2004 Walter Penschke Copyright (C) 2004 Gianni Piolanti Copyright (C) 2004, 2005, 2006, 2007, 2008 Klaus Spanderen Copyright (C) 2004 Jeff Yu Copyright (C) 2005, 2006, 2008 Toyin Akin Copyright (C) 2005 Sercan Atalik Copyright (C) 2005, 2006 Theo Boafo Copyright (C) 2005, 2006, 2007 Piter Dias Copyright (C) 2005 Gary Kennedy Copyright (C) 2005, 2006, 2007 Joseph Wang Copyright (C) 2005 Charles Whitmore Copyright (C) 2006, 2007 Banca Profilo S.p.A. Copyright (C) 2006, 2007 Marco Bianchetti Copyright (C) 2006 Yiping Chen Copyright (C) 2006 Warren Chou Copyright (C) 2006, 2007 Cristina Duminuco Copyright (C) 2006, 2007 Giorgio Facchinetti Copyright (C) 2006, 2007 Chiara Fornarola Copyright (C) 2006 Silvia Frasson Copyright (C) 2006 Richard Gould Copyright (C) 2006, 2007, 2008 Mark Joshi Copyright (C) 2006, 2007, 2008 Allen Kuo Copyright (C) 2006, 2007, 2008 Roland Lichters Copyright (C) 2006, 2007 Katiuscia Manzoni Copyright (C) 2006, 2007 Mario Pucci Copyright (C) 2006, 2007 François du Vignaud Copyright (C) 2007 Affine Group Limited Copyright (C) 2007 Richard Gomes Copyright (C) 2007, 2008 Laurent Hoffmann Copyright (C) 2007, 2008 Chris Kenyon Copyright (C) 2007 Gang Liang Copyright (C) 2008 Jose Aparicio Copyright (C) 2008 Yee Man Chan Copyright (C) 2008 Charles Chongseok Hyun Copyright (C) 2008 Paul Farrington Copyright (C) 2008 Lorella Fatone Copyright (C) 2008 Andreas Gaida Copyright (C) 2008 Marek Glowacki Copyright (C) 2008 Florent Grenier Copyright (C) 2008 Frank Hövermann Copyright (C) 2008 Simon Ibbotson Copyright (C) 2008 John Maiden Copyright (C) 2008 Francesca Mariani Copyright (C) 2008 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis Copyright (C) 2008 Andrea Odetti Copyright (C) 2008 J. Erik Radmall Copyright (C) 2008 Maria Cristina Recchioni Copyright (C) 2008 Ralph Schreyer Copyright (C) 2008 Roland Stamm Copyright (C) 2008 Francesco Zirilli QuantLib includes code taken from Peter Jäckel's book "Monte Carlo Methods in Finance". QuantLib includes software developed by the University of Chicago, as Operator of Argonne National Laboratory. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the names of the copyright holders nor the names of the QuantLib Group and its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. RQuantLib/inst/include/0000755000175000017500000000000012271333436013435 5ustar00eddeddRQuantLib/inst/include/rquantlib.h0000644000175000017500000001610712271333436015614 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib function prototypes and macros // // Copyright 2002 - 2013 Dirk Eddelbuettel // Copyright 2005 - 2006 Dominick Samperi // // $Id$ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // 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 // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with RcppArmadillo. If not, see . #ifndef rquantlib_h #define rquantlib_h #include #include #include //using namespace QuantLib; #include //#define NULL_RateHelper (boost::shared_ptr)Null >() // Prototypes for convenience functions (some macros) //void insertListElement(SEXP &list, SEXP &names, // const int pos, const double value, // const char *label); //SEXP getListElement(SEXP list, char *str); // Used to maintain context while in an R function. class RQLContext : public QuantLib::Singleton { public: RQLContext() { fixingDays = 2; calendar = QuantLib::TARGET(); settleDate = QuantLib::Date::todaysDate()+2; } // The tradeDate (evaluation date) is maintained by Settings, // (which is a singleton structure provided by QuantLib) // and used to translate between dates and real-valued times. QuantLib::Date settleDate; QuantLib::Calendar calendar; QuantLib::Integer fixingDays; }; // Instrument types used to construct the yield curve. enum RQLObservableType { RQLDeposit, RQLSwap, RQLFuture, RQLFRA }; // Used to identify the specifics of a particular contract. class RQLObservable { public: RQLObservable(RQLObservableType type, int n1, int n2, QuantLib::TimeUnit units) : type_(type), n1_(n1), n2_(n2), units_(units) {} RQLObservableType getType() { return type_; } int getN1() { return n1_; } int getN2() { return n2_; } QuantLib::TimeUnit getUnits() { return units_; } private: RQLObservableType type_; int n1_, n2_; // n2 used for FRA's QuantLib::TimeUnit units_; // not used for futures and FRA's }; typedef std::map RQLMap; typedef std::map::const_iterator RQLMapIterator; // Database used to maintain curve construction instrument details. class ObservableDB : public QuantLib::Singleton { public: ObservableDB(); boost::shared_ptr getRateHelper(std::string& ticker, QuantLib::Rate r); private: RQLMap db_; }; boost::shared_ptr getTermStructure(std::string& interpWhat, std::string& interpHow, const QuantLib::Date& settleDate, const std::vector >& curveInput, QuantLib::DayCounter& dayCounter, QuantLib::Real tolerance); boost::shared_ptr makeFlatCurve(const QuantLib::Date& today, const boost::shared_ptr& forward, const QuantLib::DayCounter& dc); boost::shared_ptr flatRate(const QuantLib::Date& today, const boost::shared_ptr& forward, const QuantLib::DayCounter& dc); boost::shared_ptr makeFlatVolatility(const QuantLib::Date& today, const boost::shared_ptr& vol, QuantLib::DayCounter dc); boost::shared_ptr flatVol(const QuantLib::Date& today, const boost::shared_ptr& vol, const QuantLib::DayCounter& dc); enum EngineType {Analytic, JR, CRR, EQP, TGEO, TIAN, LR, JOSHI, FiniteDifferences, Integral, PseudoMonteCarlo, QuasiMonteCarlo }; boost::shared_ptr makeOption(const boost::shared_ptr& payoff, const boost::shared_ptr& exercise, const boost::shared_ptr& u, const boost::shared_ptr& q, const boost::shared_ptr& r, const boost::shared_ptr& vol, EngineType engineType = Analytic, QuantLib::Size binomialSteps=128, QuantLib::Size samples=100); boost::shared_ptr makeProcess(const boost::shared_ptr& u, const boost::shared_ptr& q, const boost::shared_ptr& r, const boost::shared_ptr& vol); // int dateFromR(const RcppDate &d); // using 'classic' API's RcppDate int dateFromR(const Rcpp::Date &d); // using 'new' API's Rcpp::Date //utility functions for parameters of fixed-income instrument function QuantLib::Frequency getFrequency(const double n); QuantLib::TimeUnit getTimeUnit(const double n); QuantLib::Compounding getCompounding(const double n); QuantLib::BusinessDayConvention getBusinessDayConvention(const double n); QuantLib::DayCounter getDayCounter(const double n); QuantLib::DateGeneration::Rule getDateGenerationRule(const double n); boost::shared_ptr buildTermStructure(SEXP params, SEXP tsQuotes, SEXP times); QuantLib::Schedule getSchedule(SEXP sch); boost::shared_ptr getIborIndex(SEXP index, const QuantLib::Date today); std::vector getDoubleVector(SEXP vector); boost::shared_ptr getFlatCurve(SEXP flatcurve); boost::shared_ptr rebuildCurveFromZeroRates(SEXP dateSexp, SEXP zeroSexp); boost::shared_ptr buildIborIndex(std::string type, const QuantLib::Handle& iborStrc); QuantLib::Calendar* getCalendar(SEXP calParameters); QuantLib::Period periodByTimeUnit(int length, std::string unit); // simple option type creator based on string QuantLib::Option::Type getOptionType(const std::string &t); // create a data.frame with dates and amounts Rcpp::DataFrame getCashFlowDataFrame(const QuantLib::Leg &bondCashFlow); // fill QL data structures based on data.frames QuantLib::DividendSchedule getDividendSchedule(SEXP dividendScheduleFrame); QuantLib::CallabilitySchedule getCallabilitySchedule(SEXP callabilityScheduleFrame); #endif RQuantLib/inst/unitTests/0000755000175000017500000000000012271333436014014 5ustar00eddeddRQuantLib/inst/unitTests/runTests.R0000644000175000017500000000262412271333436015772 0ustar00eddedd## borrowed from Rmetrics' unit testing framework ## removed test for interactive() ## ## Dirk Eddelbuettel, 29 Dec 2007 pkg <- "RQuantLib" if (require("RUnit", quietly = TRUE)) { library(package=pkg, character.only = TRUE) if(!(exists("path") && file.exists(path))) path <- system.file("unitTests", package = pkg) ## Define tests testSuite <- defineTestSuite(name = paste(pkg, "unit testing"), dirs = path) ## Run tests tests <- runTestSuite(testSuite) if(file.access(path, 02) != 0) { ## cannot write to path -> use writable one tdir <- tempfile(paste(pkg, "unitTests", sep="_")) dir.create(tdir) pathReport <- file.path(tdir, "report") cat("RUnit reports are written into ", tdir, "/report.(txt|html)", sep = "") } else { pathReport <- file.path(path, "report") } ## Print Results: printTextProtocol(tests) printTextProtocol(tests, fileName = paste(pathReport, ".txt", sep = "")) ## Print HTML Version to a File: printHTMLProtocol(tests, fileName = paste(pathReport, ".html", sep = "")) ## stop() if there are any failures i.e. FALSE to unit test. ## This will cause R CMD check to return error and stop if(getErrors(tests)$nFail > 0) { stop("one of the unit tests failed") } } else { cat("R package 'RUnit' cannot be loaded -- no unit tests run\n", "for package", pkg,"\n") } RQuantLib/inst/unitTests/runit.calendar.R0000755000175000017500000000057712271333436017064 0ustar00eddedd ## test for calendaring functions ## ## cf test-suite/calendars.cpp in the QL sources test.isHoliday <- function() { checkEquals(isHoliday("UnitedStates", as.Date("2004-05-01")), c("2004-05-01"=TRUE), msg="isHoliday.US") } test.isBusinessDay <- function() { checkEquals(isBusinessDay("UnitedStates", as.Date("2004-04-26")), c("2004-04-26"=TRUE), msg="isBusinessDay.US") } RQuantLib/inst/unitTests/runit.options.R0000644000175000017500000007471412271333436017007 0ustar00eddedd ## American option tests based on Haug's book test.american.Haug <- function() { ## see QuantLib's test-suite/americanoption.cpp #/* The data below are from # "Option pricing formulas", E.G. Haug, McGraw-Hill 1998 # pag 24 # # The following values were replicated only up to the second digit # by the VB code provided by Haug, which was used as base for the # C++ implementation # #*/ AO <- AmericanOption # shorthand checkEquals(AO(type="call", strike= 100.00, underl= 90.00, div= 0.10, riskF=0.10, mat=0.10, vol= 0.15)$value, 0.0206, tol=1.0e-2) checkEquals(AO(type="call", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.15)$value, 1.8771, tol=1.0e-4) checkEquals(AO(type="call", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.15)$value, 10.0089, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.25)$value, 0.3159, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.25)$value, 3.1280, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.25)$value, 10.3919, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.35)$value, 0.9495, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.35)$value, 4.3777, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.35)$value, 11.1679, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.15)$value, 0.8208, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.15)$value, 4.0842, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.15)$value, 10.8087, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.25)$value, 2.7437, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.25)$value, 6.8015, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.25)$value, 13.0170, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.35)$value, 5.0063, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.35)$value, 9.5106, tol=1.0e-3) checkEquals(AO(type="call", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.35)$value, 15.5689, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.15)$value, 10.0000, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.15)$value, 1.8770, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.15)$value, 0.0410, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.25)$value, 10.2533, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.25)$value, 3.1277, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.25)$value, 0.4562, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.35)$value, 10.8787, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.35)$value, 4.3777, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.10, vol= 0.35)$value, 1.2402, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.15)$value, 10.5595, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.15)$value, 4.0842, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.15)$value, 1.0822, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.25)$value, 12.4419, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.25)$value, 6.8014, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.25)$value, 3.3226, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 90.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.35)$value, 14.6945, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 100.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.35)$value, 9.5104, tol=1.0e-3) checkEquals(AO(type="put", strike= 100.00, underl= 110.00, div= 0.10, riskF= 0.10, mat= 0.50, vol= 0.35)$value, 5.8823, tol=1.0e-3) } ## Asian option tests test.asian <- function() { ## see QuantLib's test-suite/asianoptions.cpp AO <- AsianOption # shorthand checkEquals(AO(averageType="geometric", typ="put", strike=85, underl=80, div=-0.03, riskF=0.05, mat=0.25, vol=0.20)$value, 4.6922, tol=1.0e-4) ## data from "Asian Option", Levy, 1997 ## in "Exotic Options: The State of the Art", ## edited by Clewlow, Strickland checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=2, vol=0.13)$value, 1.3942835683, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=4, vol=0.13)$value, 1.5852442983, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=8, vol=0.13)$value, 1.66970673, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=12, vol=0.13)$value, 1.6980019214, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=26, vol=0.13)$value, 1.7255070456, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=52, vol=0.13)$value, 1.7401553533, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=100, vol=0.13)$value, 1.7478303712, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=250, vol=0.13)$value, 1.7490291943, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=500, vol=0.13)$value, 1.7515113291, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=0.0, length=11.0/12.0, fixings=1000, vol=0.13)$value, 1.7537344885, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=2, vol=0.13)$value, 1.8496053697, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=4, vol=0.13)$value, 2.0111495205, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=8, vol=0.13)$value, 2.0852138818, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=12, vol=0.13)$value, 2.1105094397, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=26, vol=0.13)$value, 2.1346526695, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=52, vol=0.13)$value, 2.147489651, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=100, vol=0.13)$value, 2.154728109, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=250, vol=0.13)$value, 2.1564276565, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=500, vol=0.13)$value, 2.1594238588, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=1.0/12.0, length=11.0/12.0, fixings=1000, vol=0.13)$value, 2.1595367326, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=2, vol=0.13)$value, 2.63315092584, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=4, vol=0.13)$value, 2.76723962361, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=8, vol=0.13)$value, 2.83124836881, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=12, vol=0.13)$value, 2.84290301412, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=26, vol=0.13)$value, 2.88179560417, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=52, vol=0.13)$value, 2.88447044543, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=100, vol=0.13)$value, 2.89985329603, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=250, vol=0.13)$value, 2.90047296063, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=500, vol=0.13)$value, 2.89813412160, tol=1.0e-2) checkEquals(AO("arithmetic", "put", underl=90.0, strike=87.0, div=0.06, riskF=0.025, first=3.0/12.0, length=11.0/12.0, fixings=1000, vol=0.13)$value, 2.8970336243, tol=1.0e-2) } ## Barrier Options test.barrier <- function() { checkEquals(BarrierOption(barrType="downin", type="call", underl=100, strike=100, div=0.02, riskF=0.03, mat=0.5, vol=0.4, barrier=90)$value, 3.738254414) checkEquals(BarrierOption("downout", barrier=95, rebate=3, type="call", strike=90, underlying=100, div=0.04, riskF=0.08, mat=0.5, vol=0.25)$value, 9.024567695) checkEquals(BarrierOption("downin", barrier=95, rebate=3, type="call", strike=90, underlying=100, div=0.04, riskF=0.08, mat=0.5, vol=0.25)$value, 7.76267021) } test.barrier.Haug <- function() { ## see QuantLib's test-suite/barrieroption.cpp # /* The data below are from # * "Option pricing formulas", E.G. Haug, McGraw-Hill 1998 pag. 72 # */ # BO <- BarrierOption # shorthand checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 9.0246, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 6.7924, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 4.8759, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.6789, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.3580, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.3453, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 7.7627, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 4.0109, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.0576, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 13.8333, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 7.8494, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.9795, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 14.1112, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 8.4482, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 4.5910, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 8.8334, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 7.0285, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 5.4137, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.6341, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.4389, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.4315, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 9.0093, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 5.1370, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.8517, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 14.8816, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 9.2045, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 5.3043, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="call", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 15.2098, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="call", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 9.7278, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="call", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 5.8350, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.2798, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.2947, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.6252, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.7760, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 5.4932, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 7.5187, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.9586, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 6.5677, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 11.9752, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 2.2845, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 5.9085, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 11.6465, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 1.4653, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 3.3721, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.25)$value, 7.0846, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.4170, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.4258, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=95.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.6246, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="downout", barrier=100.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.0000, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 4.2293, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 5.8032, tol=1.0e-4) checkEquals(BO(barrType="upout", barrier=105.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 7.5649, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.8769, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 7.7989, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=95.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 13.3078, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 3.3328, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 7.2636, tol=1.0e-4) checkEquals(BO(barrType="downin", barrier=100.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 12.9713, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="put", strike=90, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 2.0658, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="put", strike=100, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 4.4226, tol=1.0e-4) checkEquals(BO(barrType="upin", barrier=105.0, rebate=3.0, type="put", strike=110, underl=100.0, div=0.04, riskF=0.08, mat=0.50, vol=0.30)$value, 8.3686, tol=1.0e-4) } ## Binary Options aka Digitals test.binary <- function() { ## cash or nothing European rc <- BinaryOption(binType="cash", type="put", excType="european", strike=80, underl=100, div=0.06, r=0.06, mat=0.75, vol=0.35, cash=10) checkEquals(rc$value, 2.671045684) checkEquals(rc[1:7], list(value=2.671045, delta=-0.1060594, gamma=0.00310624, vega=8.153881, theta=-1.742309, rho=-9.9577, divRho=7.9544), tolerance=1.0e-5) return() } ## European option tests based on Haug's book test.european.Haug <- function() { ## see QuantLib's test-suite/europeanoption.cpp #/* The data below are from # "Option pricing formulas", E.G. Haug, McGraw-Hill 1998 #*/ # // pag 2-8, pg 24, p 27 # Lines <- "type strike spot q r t v value tol" EO <- EuropeanOption # shorthand checkEquals(EO(type="call", strike=65.00, underl=60.00, div= 0.00, riskF=0.08, mat=0.25, vol=0.30)$value, 2.1334, tol=1.0e-3) checkEquals(EO(type="put", strike=95.00, underl=100.00, div= 0.05, riskF=0.10, mat=0.50, vol=0.20)$value, 2.4648, tol=1.0e-3) checkEquals(EO(type="put", strike=19.00, underl=19.00, div= 0.10, riskF=0.10, mat=0.75, vol=0.28)$value, 1.7011, tol=1.0e-3) checkEquals(EO(type="call", strike=19.00, underl=19.00, div= 0.10, riskF=0.10, mat=0.75, vol=0.28)$value, 1.7011, tol=1.0e-3) checkEquals(EO(type="call", strike=1.60, underl=1.56, div= 0.08, riskF=0.06, mat=0.50, vol=0.12)$value, 0.0291, tol=1.0e-3) checkEquals(EO(type="put", strike=70.00, underl=75.00, div= 0.05, riskF=0.10, mat=0.50, vol=0.35)$value, 4.0870, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.15)$value, 0.0205, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.15)$value, 1.8734, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.15)$value, 9.9413, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.25)$value, 0.3150, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.25)$value, 3.1217, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.25)$value, 10.3556, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.35)$value, 0.9474, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.35)$value, 4.3693, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.35)$value, 11.1381, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.15)$value, 0.8069, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.15)$value, 4.0232, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.15)$value, 10.5769, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.25)$value, 2.7026, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.25)$value, 6.6997, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.25)$value, 12.7857, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.35)$value, 4.9329, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.35)$value, 9.3679, tol=1.0e-3) checkEquals(EO(type="call", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.35)$value, 15.3086, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.15)$value, 9.9210, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.15)$value, 1.8734, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.15)$value, 0.0408, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.25)$value, 10.2155, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.25)$value, 3.1217, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.25)$value, 0.4551, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.35)$value, 10.8479, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.35)$value, 4.3693, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.10, vol=0.35)$value, 1.2376, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.15)$value, 10.3192, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.15)$value, 4.0232, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.15)$value, 1.0646, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.25)$value, 12.2149, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.25)$value, 6.6997, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.25)$value, 3.2734, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=90.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.35)$value, 14.4452, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=100.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.35)$value, 9.3679, tol=1.0e-3) checkEquals(EO(type="put", strike=100.00, underl=110.00, div= 0.10, riskF=0.10, mat=0.50, vol=0.35)$value, 5.7963, tol=1.0e-3) checkEquals(EO(type="call", strike=40.00, underl=42.00, div= 0.08, riskF=0.04, mat=0.75, vol=0.35)$value, 5.0975, tol=1.0e-3) } RQuantLib/man/0000755000175000017500000000000012271333436011610 5ustar00eddeddRQuantLib/man/AmericanOption.Rd0000644000175000017500000000656012271333436015016 0ustar00eddedd% $Id: AmericanOption.Rd,v 1.6 2006/11/11 04:08:06 edd Exp $ \name{AmericanOption} \alias{AmericanOption} \alias{AmericanOption.default} \title{American Option evaluation using Finite Differences} \description{ This function evaluations an American-style option on a common stock using finite differences. The option value as well as the common first derivatives ("Greeks") are returned.} \usage{ \method{AmericanOption}{default}(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=149, engine="BaroneAdesiWhaley") } \arguments{ \item{type}{A string with one of the values \code{call} or \code{put}} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Volatility of the underlying stock} \item{timeSteps}{Time steps for the \dQuote{CrankNicolson} finite differences method engine, default value is 150} \item{gridPoints}{Grid points for the \dQuote{CrankNicolson} finite differences method, default value is 149} \item{engine}{String selecting pricing engine, currently supported are \dQuote{BaroneAdesiWhaley} and \dQuote{CrankNicolson}} } \value{ An object of class \code{AmericanOption} (which inherits from class \code{\link{Option}}) is returned. It contains a list with the following components: \item{value}{Value of option} \item{delta}{Sensitivity of the option value for a change in the underlying} \item{gamma}{Sensitivity of the option delta for a change in the underlying} \item{vega}{Sensitivity of the option value for a change in the underlying's volatility} \item{theta}{Sensitivity of the option value for a change in t, the remaining time to maturity} \item{rho}{Sensitivity of the option value for a change in the risk-free interest rate} \item{dividendRho}{Sensitivity of the option value for a change in the dividend yield} \item{parameters}{List with parameters with which object was created} Note that under the new pricing framework used in QuantLib, pricers do not provide analytics for all 'Greeks'. When \dQuote{CrankNicolson} is selected, then at least delta, gamma and vega are available. With the default pricing engine of \dQuote{BaroneAdesiWhaley}, no greeks are returned. } \details{ The Finite Differences method is used to value the American Option. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{EuropeanOption}}} \examples{ # simple call with unnamed parameters AmericanOption("call", 100, 100, 0.02, 0.03, 0.5, 0.4) # simple call with some explicit parameters AmericanOption("put", strike=100, volatility=0.4, 100, 0.02, 0.03, 0.5) # simple call with unnamed parameters, using Crank-Nicolons AmericanOption("put", strike=100, volatility=0.4, 100, 0.02, 0.03, 0.5, engine="CrankNicolson") } \keyword{misc} RQuantLib/man/AmericanOptionImpliedVolatility.Rd0000644000175000017500000000475212271333436020404 0ustar00eddedd% $Id: AmericanOptionImpliedVolatility.Rd,v 1.6 2006/11/11 04:08:41 edd Exp $ \name{AmericanOptionImpliedVolatility} \alias{AmericanOptionImpliedVolatility} \alias{AmericanOptionImpliedVolatility.default} \title{Implied Volatility calculation for American Option} \description{ The \code{AmericanOptionImpliedVolatility} function solves for the (unobservable) implied volatility, given an option price as well as the other required parameters to value an option.} \usage{ \method{AmericanOptionImpliedVolatility}{default}(type, value, underlying, strike,dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=151) } \arguments{ \item{type}{A string with one of the values \code{call} or \code{put}} \item{value}{Value of the option (used only for ImpliedVolatility calculation)} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Initial guess for the volatility of the underlying stock} \item{timeSteps}{Time steps for the Finite Differences method, default value is 150} \item{gridPoints}{Grid points for the Finite Differences method, default value is 151} } \value{ The \code{AmericanOptionImpliedVolatility} function returns an object of class \code{\link{ImpliedVolatility}}. It contains a list with the following elements: \item{impliedVol}{The volatility implied by the given market prices} \item{parameters}{List with the option parameters used} } \details{ The Finite Differences method is used to value the American Option. Implied volatilities are then calculated numerically. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{EuropeanOption}},\code{\link{AmericanOption}},\code{\link{BinaryOption}}} \examples{ AmericanOptionImpliedVolatility(type="call", value=11.10, underlying=100, strike=100, dividendYield=0.01, riskFreeRate=0.03, maturity=0.5, volatility=0.4) } \keyword{misc} RQuantLib/man/AsianOption.Rd0000644000175000017500000000561112271333436014326 0ustar00eddedd% $Id$ \name{AsianOption} \alias{AsianOption} \alias{AsianOption.default} \title{Asian Option evaluation using Closed-Form solution} \description{ The \code{AsianOption} function evaluates an Asian-style option on a common stock using an analytic solution for continuous geometric average price. The option value, the common first derivatives ("Greeks") as well as the calling parameters are returned. } \usage{ \method{AsianOption}{default}(averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first=0, length=0, fixings=0) } \arguments{ \item{averageType}{Specifiy averaging type, either "geometric" or "arithmetic" } \item{type}{A string with one of the values \code{call} or \code{put}} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Volatility of the underlying stock} \item{first}{to be written} \item{length}{to be written} \item{fixings}{to be written} } \value{ The \code{AsianOption} function returns an object of class \code{AsianOption} (which inherits from class \code{\link{Option}}). It contains a list with the following components: \item{value}{Value of option} \item{delta}{Sensitivity of the option value for a change in the underlying} \item{gamma}{Sensitivity of the option delta for a change in the underlying} \item{vega}{Sensitivity of the option value for a change in the underlying's volatility} \item{theta}{Sensitivity of the option value for a change in t, the remaining time to maturity} \item{rho}{Sensitivity of the option value for a change in the risk-free interest rate} \item{dividendRho}{Sensitivity of the option value for a change in the dividend yield} \item{parameters}{List with parameters with which object was created} } \details{ When "arithmetic" evaluation is used, only the NPV() is returned. The well-known closed-form solution derived by Black, Scholes and Merton is used for valuation. Implied volatilities are calculated numerically. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ # simple call with some explicit parameters, and slightly increased vol: AsianOption("geometric", "put", underlying=80, strike=85, div=-0.03, riskFree=0.05, maturity=0.25, vol=0.2) } \keyword{misc} RQuantLib/man/BarrierOption.Rd0000644000175000017500000000605712271333436014666 0ustar00eddedd% $Id: BarrierOption.Rd,v 1.7 2007/12/31 01:50:55 edd Exp $ \name{BarrierOption} \alias{BarrierOption} \alias{BarrierOption.default} \title{Barrier Option evaluation using Closed-Form solution} \description{ This function evaluations an Barrier option on a common stock using a closed-form solution. The option value as well as the common first derivatives ("Greeks") are returned.} \usage{ \method{BarrierOption}{default}(barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate=0.0) } \arguments{ \item{barrType}{A string with one of the values \code{downin}, \code{downout}, \code{upin} or \code{upout}} \item{type}{A string with one of the values \code{call} or \code{put}} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Volatility of the underlying stock} \item{barrier}{Option barrier value} \item{rebate}{Optional option rebate, defaults to 0.0} } \value{ An object of class \code{BarrierOption} (which inherits from class \code{\link{Option}}) is returned. It contains a list with the following components: \item{value}{Value of option} \item{delta}{Sensitivity of the option value for a change in the underlying} \item{gamma}{Sensitivity of the option delta for a change in the underlying} \item{vega}{Sensitivity of the option value for a change in the underlying's volatility} \item{theta}{Sensitivity of the option value for a change in t, the remaining time to maturity} \item{rho}{Sensitivity of the option value for a change in the risk-free interest rate} \item{dividendRho}{Sensitivity of the option value for a change in the dividend yield} \item{parameters}{List with parameters with which object was created}. Note that under the new pricing framework used in QuantLib, binary pricers do not provide analytics for 'Greeks'. This is expected to be addressed in future releases of QuantLib. } \details{ A closed-form solution is used to value the Barrier Option. In the case of Barrier options, the calculations are from Haug's "Option pricing formulas" book (McGraw-Hill). Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{AmericanOption}},\code{\link{EuropeanOption}}} \examples{ BarrierOption(barrType="downin", type="call", underlying=100, strike=100, dividendYield=0.02, riskFreeRate=0.03, maturity=0.5, volatility=0.4, barrier=90) } \keyword{misc} RQuantLib/man/BermudanSwaption.Rd0000644000175000017500000001445012271333436015365 0ustar00eddedd% $Id: BermudanSwaption.Rd,v 1.2 2006/07/20 02:42:44 dsamperi Exp $ \name{BermudanSwaption} \alias{BermudanSwaption} \alias{BermudanSwaption.default} \alias{summary.G2Analytic} \alias{summary.HWAnalytic} \alias{summary.HWTree} \alias{summary.BKTree} \title{Bermudan swaption valuation using several short-rate models} \description{ \code{BermudanSwaption} prices a Bermudan swaption with specified strike and maturity (in years), after calibrating the selected short-rate model to an input swaption volatility matrix. Swaption maturities are in years down the rows, and swap tenors are in years along the columns, in the usual fashion. It is assumed that the Bermudan swaption is exercisable on each reset date of the underlying swaps. } \usage{ BermudanSwaption(params, tsQuotes, swaptionMaturities, swapTenors, volMatrix) } \arguments{ \item{params}{A list specifying the \code{tradeDate} (month/day/year), \code{settlementDate}, \code{payFixed} flag, \code{strike}, pricing \code{method}, and curve construction options (see \emph{Examples} section below). Curve construction options are \code{interpWhat} (possible values are \code{discount}, \code{forward}, and \code{zero}) and \code{interpHow} (possible values are \code{linear}, \code{loglinear} , and \code{spline}). Both \code{interpWhat} and \code{interpHow} are ignored when a flat yield curve is requested, but they must be present nevertheless. The pricing method can be one of the following (all short-rate models): \tabular{ll}{ \code{G2Analytic} \tab G2 2-factor Gaussian model using analytic formulas.\cr \code{HWAnalytic} \tab Hull-White model using analytic formulas.\cr \code{HWTree} \tab Hull-White model using a tree.\cr \code{BKTree} \tab Black-Karasinski model using a tree. } } \item{tsQuotes}{Market observables needed to construct the spot term structure of interest rates. A list of name/value pairs. See the help page for \code{\link{DiscountCurve}} for details.} \item{swaptionMaturities}{A vector containing the swaption maturities associated with the rows of the swaption volatility matrix.} \item{swapTenors}{A vector containing the underlying swap tenors associated with the columns of the swaption volatility matrix.} \item{volMatrix}{The swaption volatility matrix. Must be a 2D matrix stored by rows. See the example below.} } \value{ \code{BermudanSwaption} returns a list containing calibrated model paramters (what parameters are returned depends on the model selected) along with: \item{price}{Price of swaption in basis points (actual price equals \code{price} times notional divided by 10,000)} \item{ATMStrike}{At-the-money strike} \item{params}{Input parameter list} } \details{ This function is based on \code{QuantLib} Version 0.3.10. It introduces support for fixed-income instruments in \code{RQuantLib}. At present only a small number of the many parameters that can be set in \code{QuantLib} are exposed by this function. Some of the hard-coded parameters that apply to the current version include: day-count conventions, fixing days (2), index (Euribor), fixed leg frequency (annual), and floating leg frequency (semi-annual). Also, it is assumed that the swaption volatility matrix corresponds to expiration dates and tenors that are measured in years (a 6-month expiration date is not currently supported, for example). Given the number of parameters that must be specified and the care with which they must be specified (with no defaults), it is not practical to use this function in the usual interactive fashion. The simplest approach is simply to save the example below to a file, edit as desired, and \code{source} the result. Alternatively, the input commands can be kept in a script file (under Windows) or an Emacs/ESS session (under Linux), and selected parts of the script can be executed in the usual way. Fortunately, the C++ exception mechanism seems to work well with the R interface, and \code{QuantLib} exceptions are propagated back to the R user, usually with a message that indicates what went wrong. (The first part of the message contains technical information about the precise location of the problem in the \code{QuantLib} code. Scroll to the end to find information that is meaningful to the R user.) } \references{ Brigo, D. and Mercurio, F. (2001) \emph{Interest Rate Models: Theory and Practice}, Springer-Verlag, New York. For information about \code{QuantLib} see \url{http://quantlib.org}. For information about \code{RQuantLib} see \url{http://dirk.eddelbuettel.com/code/rquantlib.html}. } \author{Dominick Samperi} \seealso{\code{\link{DiscountCurve}}} \examples{ # This data is taken from sample code shipped with QuantLib 0.3.10. params <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-19'), payFixed=TRUE, strike=.06, method="G2Analytic", interpWhat="discount", interpHow="loglinear") # Market data used to construct the term structure of interest rates tsQuotes <- list(d1w =0.0382, d1m =0.0372, fut1=96.2875, fut2=96.7875, fut3=96.9875, fut4=96.6875, fut5=96.4875, fut6=96.3875, fut7=96.2875, fut8=96.0875, s3y =0.0398, s5y =0.0443, s10y =0.05165, s15y =0.055175) # Use this to compare with the Bermudan swaption example from QuantLib #tsQuotes <- list(flat=0.04875825) # Swaption volatility matrix with corresponding maturities and tenors swaptionMaturities <- c(1,2,3,4,5) swapTenors <- c(1,2,3,4,5) volMatrix <- matrix( c(0.1490, 0.1340, 0.1228, 0.1189, 0.1148, 0.1290, 0.1201, 0.1146, 0.1108, 0.1040, 0.1149, 0.1112, 0.1070, 0.1010, 0.0957, 0.1047, 0.1021, 0.0980, 0.0951, 0.1270, 0.1000, 0.0950, 0.0900, 0.1230, 0.1160), ncol=5, byrow=TRUE) # Price the Bermudan swaption pricing <- BermudanSwaption(params, tsQuotes, swaptionMaturities, swapTenors, volMatrix) summary(pricing) } \keyword{models} RQuantLib/man/BinaryOption.Rd0000644000175000017500000000552212271333436014520 0ustar00eddedd% $Id: BinaryOption.Rd,v 1.7 2007/12/31 01:51:47 edd Exp $ \name{BinaryOption} \alias{BinaryOption} \alias{BinaryOption.default} \title{Binary Option evaluation using Closed-Form solution} \description{ This function evaluations an Binary option on a common stock using a closed-form solution. The option value as well as the common first derivatives ("Greeks") are returned.} \usage{ \method{BinaryOption}{default}(binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) } \arguments{ \item{binType}{A string with one of the values \code{cash}, \code{asset} or \code{gap} to select CashOrNothing, AssetOrNothing or Gap payoff profiles} \item{type}{A string with one of the values \code{call} or \code{put}} \item{excType}{A string with one of the values \code{european} or \code{american} to denote the exercise type} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Volatility of the underlying stock} \item{cashPayoff}{Payout amount} } \value{ An object of class \code{BinaryOption} (which inherits from class \code{\link{Option}}) is returned. It contains a list with the following components: \item{value}{Value of option} \item{delta}{Sensitivity of the option value for a change in the underlying} \item{gamma}{Sensitivity of the option delta for a change in the underlying} \item{vega}{Sensitivity of the option value for a change in the underlying's volatility} \item{theta}{Sensitivity of the option value for a change in t, the remaining time to maturity} \item{rho}{Sensitivity of the option value for a change in the risk-free interest rate} \item{dividendRho}{Sensitivity of the option value for a change in the dividend yield} \item{parameters}{List with parameters with which object was created} } \details{ A closed-form solution is used to value the Binary Option. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{AmericanOption}},\code{\link{EuropeanOption}}} \examples{ BinaryOption(binType="asset", type="call", excType="european", underlying=100, strike=100, dividendYield=0.02, riskFreeRate=0.03, maturity=0.5, volatility=0.4, cashPayoff=10) } \keyword{misc} RQuantLib/man/BinaryOptionImpliedVolatility.Rd0000644000175000017500000000444612271333436020111 0ustar00eddedd% $Id: BinaryOptionImpliedVolatility.Rd,v 1.2 2006/11/11 04:12:02 edd Exp $ \name{BinaryOptionImpliedVolatility} \alias{BinaryOptionImpliedVolatility} \alias{BinaryOptionImpliedVolatility.default} \title{Implied Volatility calculation for Binary Option} \description{ The \code{BinaryOptionImpliedVolatility} function solves for the (unobservable) implied volatility, given an option price as well as the other required parameters to value an option.} \usage{ \method{BinaryOptionImpliedVolatility}{default}(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff=1) } \arguments{ \item{type}{A string with one of the values \code{call}, \code{put} or \code{straddle}} \item{value}{Value of the option (used only for ImpliedVolatility calculation)} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Initial guess for the volatility of the underlying stock} \item{cashPayoff}{Binary payout if options is exercised, default is 1} } \value{ The \code{BinaryOptionImpliedVolatility} function returns an object of class \code{\link{ImpliedVolatility}}. It contains a list with the following elements: \item{impliedVol}{The volatility implied by the given market prices} \item{parameters}{List with the option parameters used} } \details{ The Finite Differences method is used to value the Binary Option. Implied volatilities are then calculated numerically. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{EuropeanOption}},\code{\link{AmericanOption}},\code{\link{BinaryOption}}} \examples{ BinaryOptionImpliedVolatility("call", value=4.50, strike=100, 100, 0.02, 0.03, 0.5, 0.4, 10) } \keyword{misc} RQuantLib/man/Bond.Rd0000644000175000017500000000747012271333436012771 0ustar00eddedd% $Id$ \name{Bond} \alias{Bond} \alias{plot.Bond} \alias{print.Bond} \alias{summary.Bond} \title{Base class for Bond price evalution} \description{ This class forms the basis from which the more specific classes are derived. } \usage{ \method{print}{Bond}(x, digits=5, ...) \method{plot}{Bond}(x, ...) \method{summary}{Bond}(object, digits=5, ...) } \arguments{ \item{x}{Any Bond object derived from this base class} \item{object}{Any Bond object derived from this base class} \item{digits}{Number of digits of precision shown} \item{...}{Further arguments} } \value{ None, but side effects of displaying content. } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umb.edu}; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ ## This data is taken from sample code shipped with QuantLib 0.9.7 ## from the file Examples/Swap/swapvaluation params <- list(tradeDate=as.Date('2004-09-20'), settleDate=as.Date('2004-09-22'), dt=.25, interpWhat="discount", interpHow="loglinear") setEvaluationDate(as.Date("2004-11-22")) ## We got numerical issues for the spline interpolation if we add ## any on of these three extra futures, at least with QuantLib 0.9.7 ## The curve data comes from QuantLib's Examples/Swap/swapvaluation.cpp tsQuotes <- list(d1w = 0.0382, d1m = 0.0372, fut1=96.2875, fut2=96.7875, fut3=96.9875, fut4=96.6875, fut5=96.4875, fut6=96.3875, fut7=96.2875, fut8=96.0875, s2y = 0.037125, s3y = 0.0398, s5y = 0.0443, s10y = 0.05165, s15y = 0.055175) tsQuotes <- list("flat" = 0.02) ## While discount curve code is buggy times <- seq(0,10,.1) discountCurve <- DiscountCurve(params, tsQuotes, times) # price a zero coupon bond bondparams <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100 ) dateparams <-list(settlementDays=1, calendar="us", businessDayConvention=4) ZeroCouponBond(bondparams, discountCurve, dateparams) # price a fixed rate coupon bond bondparams <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100, effectiveDate=as.Date("2004-11-30")) dateparams <- list(settlementDays=1, calendar="us", dayCounter = 1, period=3, businessDayConvention = 4, terminationDateConvention=4, dateGeneration=1, endOfMonth=1) rates <- c(0.02875) FixedRateBond(bondparams, rates, discountCurve, dateparams) # price a floating rate bond bondparams <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100, effectiveDate=as.Date("2004-12-01")) dateparams <- list(settlementDays=1, calendar="us", dayCounter = 1, period=3, businessDayConvention = 1, terminationDateConvention=1, dateGeneration=0, endOfMonth=0, fixingDays = 1) gearings <- c() spreads <- c() caps <- c() floors <- c() iborCurve <- DiscountCurve(params,list(flat=0.05), times) ibor <- list(type="USDLibor", length=6, inTermOf="Month", term=iborCurve) FloatingRateBond(bondparams, gearings, spreads, caps, floors, ibor, discountCurve, dateparams) } \keyword{misc} RQuantLib/man/BondUtilities.Rd0000644000175000017500000000445512271333436014665 0ustar00eddedd% $Id$ \name{BondUtilities} \alias{matchBDC} \alias{matchCompounding} \alias{matchDateGen} \alias{matchDayCounter} \alias{matchFrequency} \alias{matchParams} \title{Bond parameter conversion utilities} \description{ These functions are using internally to convert from the characters at the R level to the \code{enum} types used at the C++ level. They are documented here mostly to provide a means to look up some of the possible values---the user is not expected to call these functions directly..} \usage{ matchBDC(bdc = c("Following", "ModifiedFollowing", "Preceding", "ModifiedPreceding", "Unadjusted")) matchCompounding(cp = c("Simple", "Compounded", "Continuous", "SimpleThenCompounded")) matchDayCounter(daycounter = c("Actual360", "ActualFixed", "ActualActual", "Business252", "OneDayCounter", "SimpleDayCounter", "Thirty360")) matchDateGen(dg = c("Backward", "Forward", "Zero", "ThirdWednesday", "Twentieth", "TwentiethIMM")) matchFrequency(freq = c("NoFrequency","Once", "Annual", "Semiannual", "EveryFourthMonth", "Quarterly", "Bimonthly", "EveryFourthWeek", "Biweekly", "Weekly", "Daily")) matchParams(params) } \arguments{ \item{bdc}{A string identifying one of the possible business day convention values.} \item{cp}{A string identifying one of the possible compounding frequency values.} \item{daycounter}{A string identifying one of the possible day counter scheme values.} \item{dg}{A string identifying one of the possible date generation scheme values.} \item{freq}{A string identifying one of the possible (dividend) frequency values.} \item{params}{A named vector containing the other parameters as components.} } \value{ Each function converts the given character value into a corresponding numeric entry. For \code{matchParams}, an named vector of strings is converted into a named vector of numerics.. } \details{ The QuantLib documentation should be consulted for details. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umb.edu} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} %\examples{} \keyword{misc} RQuantLib/man/Calendars.Rd0000644000175000017500000002212612271333436013776 0ustar00eddedd% $Id$ \name{Calendars} \alias{isBusinessDay} \alias{businessDay} \alias{isHoliday} \alias{isWeekend} \alias{isEndOfMonth} \alias{getEndOfMonth} \alias{endOfMonth} \alias{getHolidayList} \alias{holidayList} \alias{setCalendarContext} \alias{adjust} \alias{advance} \alias{businessDaysBetween} \alias{dayCount} \alias{yearFraction} \alias{setEvaluationDate} \title{Calendar functions from QuantLib} \description{ The \code{isBusinessDay} function evaluates the given dates in the context of the given calendar, and returns a vector of booleans indicating business day status. \code{BusinessDay} is also recognised (but may be deprecated one day). The \code{isHoliday} function evaluates the given dates in the context of the given calendar, and returns a vector of booleans indicating holiday day status. The \code{isWeekend} function evaluates the given dates in the context of the given calendar, and returns a vector of booleans indicating weekend status. The \code{isEndOfMonth} function evaluates the given dates in the context of the given calendar, and returns a vector of booleans indicating end of month status. The \code{getEndOfMonth} function evaluates the given dates in the context of the given calendar, and returns a vector that corresponds to the end of month. \code{endOfMonth} is a deprecated form for this function. The \code{getHolidayList} function returns the holidays between the given dates, with an option to exclude weekends. \code{holidayList} is a deprecated form for this function. The \code{adjust} function evaluates the given dates in the context of the given calendar, and returns a vector that adjusts each input dates to the appropriate near business day with respect to the given convention. The \code{advance} function evaluates the given dates in the context of the given calendar, and returns a vector that advances the given dates of the given number of business days and returns the result. This functions gets called either with both argument \code{n} and \code{timeUnit}, or with argument \code{period}. The \code{businessDaysBetween} function evaluates two given dates in the context of the given calendar, and returns a vector that gives the number of business day between. The \code{dayCount} function returns the number of day between two dates given a day counter, see \link{Enum}. The \code{yearFraction} function returns year fraction between two dates given a day counter, see \link{Enum}. The \code{setCalendarContext} function sets three values to a singleton instance at the C++ layer. The \code{setEvaluationDate} function sets the evaluation date used by the QuantLib pricing engines. } \usage{ isBusinessDay(calendar="TARGET", dates=Sys.Date()) businessDay(calendar="TARGET", dates=Sys.Date()) # deprecated form isHoliday(calendar="TARGET", dates=Sys.Date()) isWeekend(calendar="TARGET", dates=Sys.Date()) isEndOfMonth(calendar="TARGET", dates=Sys.Date()) getEndOfMonth(calendar="TARGET", dates=Sys.Date()) endOfMonth(calendar="TARGET", dates=Sys.Date()) getHolidayList(calendar="TARGET", from=Sys.Date(), to = Sys.Date() + 5, includeWeekends = 0) holidayList(calendar="TARGET", from=Sys.Date(), to = Sys.Date() + 5, includeWeekends = 0) adjust(calendar="TARGET", dates=Sys.Date(), bdc = 0) advance(calendar="TARGET", dates=Sys.Date(), n, timeUnit, period, bdc = 0, emr =0) %advance(calendar="TARGET", dates=Sys.Date(), period, bdc = 0, emr =0) businessDaysBetween(calendar="TARGET", from=Sys.Date(), to = Sys.Date() + 5, includeFirst = 1, includeLast = 0) dayCount(startDates, endDates, dayCounters) yearFraction(startDates, endDates, dayCounters) setCalendarContext(calendar, fixingDays, settleDate) setEvaluationDate(evalDate) } \arguments{ \item{calendar}{A string identifying one of the supported QuantLib calendars, see Details for more} \item{dates}{A vector (or scalar) of \code{Date} types.} \item{from}{A vector (or scalar) of \code{Date} types.} \item{to}{A vector (or scalar) of \code{Date} types.} \item{includeWeekends}{boolean that indicates whether the calculation should include the weekends. Default = false} \item{fixingDays}{An integer for the fixing day period, defaults to 2.} \item{settleDate}{A date on which trades settles, defaults to two days after the current day.} \item{n}{an integer number} \item{timeUnit}{A value of 0,1,2,3 that corresponds to Days, Weeks, Months, and Year; for more detail, see the QuantLib documentation at \url{http://quantlib.org/reference/group__datetime.html}} \item{period}{See \link{Enum}} \item{bdc}{Business day convention. By default, this value is 0 and correspond to Following convention} \item{emr}{End Of Month rule, default is false} \item{includeFirst}{boolean that indicates whether the calculation should include the first day. Default = true} \item{includeLast}{Default = false} \item{startDates}{A vector of \code{Date} type.} \item{endDates}{A vector of \code{Date} type.} \item{dayCounters}{A vector of numeric type. See \link{Enum}} \item{evalDate}{A single date used for the pricing valuations.} } \value{ A named vector of booleans each of which is true if the corresponding date is a business day (or holiday or weekend) in the given calendar. The element names are the dates (formatted as text in yyyy-mm-dd format). For \code{setCalendarContext}, a boolean or NULL in case of error. } \details{ The calendars are coming from QuantLib, and the QuantLib documentation should be consulted for details. Currently, the following strings are recognised: TARGET (a default calendar), Canada and Canada/Settlement, Canada/TSX, Germany and Germany/FrankfurtStockExchange, Germany/Settlement, Germany/Xetra, Germany/Eurex, Italy and Italy/Settlement, Italy/Exchange, Japan, UnitedKingdom and UnitedKingdom/Settlement, UnitedKingdom/Exchange, UnitedKingdom/Metals, UnitedStates and UnitedStates/Settlement, UnitedStates/NYSE, UnitedStates/GovernmentBond, UnitedStates/NERC. (In case of multiples entries per country, the country default is listed right after the country itself. Using the shorter form is equivalent.) } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ dates <- seq(from=as.Date("2009-04-07"), to=as.Date("2009-04-14"), by=1) isBusinessDay("UnitedStates", dates) isBusinessDay("UnitedStates/Settlement", dates) ## same as previous isBusinessDay("UnitedStates/NYSE", dates) ## stocks isBusinessDay("UnitedStates/GovernmentBond", dates) ## bonds isBusinessDay("UnitedStates/NERC", dates) ## energy isHoliday("UnitedStates", dates) isHoliday("UnitedStates/Settlement", dates) ## same as previous isHoliday("UnitedStates/NYSE", dates) ## stocks isHoliday("UnitedStates/GovernmentBond", dates) ## bonds isHoliday("UnitedStates/NERC", dates) ## energy isWeekend("UnitedStates", dates) isWeekend("UnitedStates/Settlement", dates) ## same as previous isWeekend("UnitedStates/NYSE", dates) ## stocks isWeekend("UnitedStates/GovernmentBond", dates) ## bonds isWeekend("UnitedStates/NERC", dates) ## energy isEndOfMonth("UnitedStates", dates) isEndOfMonth("UnitedStates/Settlement", dates) ## same as previous isEndOfMonth("UnitedStates/NYSE", dates) ## stocks isEndOfMonth("UnitedStates/GovernmentBond", dates) ## bonds isEndOfMonth("UnitedStates/NERC", dates) ## energy getEndOfMonth("UnitedStates", dates) getEndOfMonth("UnitedStates/Settlement", dates) ## same as previous getEndOfMonth("UnitedStates/NYSE", dates) ## stocks getEndOfMonth("UnitedStates/GovernmentBond", dates) ## bonds getEndOfMonth("UnitedStates/NERC", dates) ## energy from <- as.Date("2009-04-07") to<-as.Date("2009-04-14") getHolidayList("UnitedStates", from, to) to <- as.Date("2009-10-7") getHolidayList("UnitedStates", from, to) dates <- seq(from=as.Date("2009-04-07"), to=as.Date("2009-04-14"), by=1) adjust("UnitedStates", dates) adjust("UnitedStates/Settlement", dates) ## same as previous adjust("UnitedStates/NYSE", dates) ## stocks adjust("UnitedStates/GovernmentBond", dates) ## bonds adjust("UnitedStates/NERC", dates) ## energy advance("UnitedStates", dates, 10, 0) advance("UnitedStates/Settlement", dates, 10, 1) ## same as previous advance("UnitedStates/NYSE", dates, 10, 2) ## stocks advance("UnitedStates/GovernmentBond", dates, 10, 3) ## bonds advance("UnitedStates/NERC", dates, period = 3) ## energy from <- as.Date("2009-04-07") to<-as.Date("2009-04-14") businessDaysBetween("UnitedStates", from, to) startDates <- seq(from=as.Date("2009-04-07"), to=as.Date("2009-04-14"),by=1) endDates <- seq(from=as.Date("2009-11-07"), to=as.Date("2009-11-14"), by=1) dayCounters <- c(0,1,2,3,4,5,6,1) dayCount(startDates, endDates, dayCounters) yearFraction(startDates, endDates, dayCounters) } \keyword{misc} RQuantLib/man/CallableBond.Rd0000644000175000017500000001323212271333436014402 0ustar00eddedd% $Id: CallableBond.Rd 87 2009-06-09 16:48:13Z knguyen $ \name{CallableBond} \alias{CallableBond} \alias{CallableBond.default} \title{CallableBond evaluation} \description{ The \code{CallableBond} function sets up and evaluates a callable fixed rate bond using Hull-White model and a TreeCallableFixedBondEngine pricing engine. For more detail, see the source codes in quantlib's example folder, Examples/CallableBond/CallableBond.cpp } \usage{ \method{CallableBond}{default}(bondparams, hullWhite, coupon, dateparams) } \arguments{ \item{bondparams}{a named list whose elements are: \tabular{ll}{ \code{issueDate} \tab a Date, the bond's issue date \cr \code{maturityDate} \tab a Date, the bond's maturity date \cr \code{faceAmount} \tab (Optional) a double, face amount of the bond. \cr \code{} \tab Default value is 100.\cr \code{redemption} \tab (Optional) a double, percentage of the initial face \cr \code{} \tab amount that will be returned at maturity date. \cr \code{} \tab Default value is 100. \cr \code{callSch} \tab (Optional) a data frame whose columns are "Price",\cr \code{} \tab "Type" and "Date" corresponding to QuantLib's \cr \code{} \tab CallabilitySchedule. Defaule is an empty frame, or no callability.\cr } } \item{hullWhite}{a named list whose elements are parameters needed to set up a HullWhite pricing engine in QuantLib: \tabular{ll}{ \code{term} \tab a double, to set up a flat rate yield term structure \cr \code{alpha} \tab a double, Hull-White model's alpha value \cr \code{sigma} \tab a double, Hull-White model's sigma value \cr \code{gridIntervals}. \tab a double, time intervals parameter to \cr \code{} \tab set up the TreeCallableFixedBondEngine \cr } Currently, the codes only support a flat rate yield term structure. For more detail, see QuantLib's doc on HullWhite and TreeCallableFixedBondEngine. } \item{coupon}{a numeric vector of coupon rates} \item{dateparams}{(Optional) a named list, QuantLib's date parameters of the bond. \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{calendar} \tab (Optional) a string, either 'us' or 'uk' \cr \code{} \tab corresponding to US Goverment Bond \cr \code{} \tab calendar and UK Exchange calendar.\cr \code{} \tab Default value is 'us'.\cr \code{dayCounter} \tab (Optional) a number or string, \cr \code{} \tab day counter convention.\cr \code{} \tab See \link{Enum}. Default value is 'Thirty360' \cr \code{period} \tab (Optional) a number or string, \cr \code{} \tab interest compounding interval. See \link{Enum}. \cr \code{} \tab Default value is 'Semiannual'.\cr \code{businessDayConvention} \tab (Optional) a number or string, \cr \code{} \tab business day convention. \cr \code{} \tab See \link{Enum}. Default value is 'Following'. \cr \code{terminationDateConvention} \tab (Optional) a number or string \cr \code{} \tab termination day convention.\cr \code{} \tab See \link{Enum}. Default value is'Following'.\cr } See example below. } } \value{ The \code{CallableBond} function returns an object of class \code{CallableBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{price price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umb.edu} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ #set-up a HullWhite according to example from QuantLib HullWhite <- list(term = 0.055, alpha = 0.03, sigma = 0.01, gridIntervals = 40) #callability schedule dataframe Price <- rep(as.double(100),24) Type <- rep(as.character("C"), 24) Date <- seq(as.Date("2006-09-15"), by = '3 months', length = 24) callSch <- data.frame(Price, Type, Date) callSch$Type <- as.character(callSch$Type) bondparams <- list(faceAmount=100, issueDate = as.Date("2004-09-16"), maturityDate=as.Date("2012-09-16"), redemption=100, callSch = callSch) dateparams <- list(settlementDays=3, calendar="us", dayCounter = "ActualActual", period="Quarterly", businessDayConvention = "Unadjusted", terminationDateConvention= "Unadjusted") coupon <- c(0.0465) CallableBond(bondparams, HullWhite, coupon, dateparams) #examples using default values CallableBond(bondparams, HullWhite, coupon) dateparams <- list( period="Quarterly", businessDayConvention = "Unadjusted", terminationDateConvention= "Unadjusted") CallableBond(bondparams, HullWhite, coupon, dateparams) bondparams <- list(issueDate = as.Date("2004-09-16"), maturityDate=as.Date("2012-09-16") ) CallableBond(bondparams, HullWhite, coupon, dateparams) } \keyword{misc} RQuantLib/man/ConvertibleBond.Rd0000644000175000017500000003314312271333436015162 0ustar00eddedd% $Id: ConvertibleFloatingCouponBond 84 2009-06-19 knguyen $ \name{ConvertibleBond} \alias{ConvertibleFixedCouponBond} \alias{ConvertibleFixedCouponBond.default} \alias{ConvertibleFloatingCouponBond} \alias{ConvertibleFloatingCouponBond.default} \alias{ConvertibleZeroCouponBond} \alias{ConvertibleZeroCouponBond.default} \title{Convertible Bond evaluation for Fixed, Floating and Zero Coupon} \description{ The \code{ConvertibleFixedCouponBond} function setups and evaluates a ConvertibleFixedCouponBond using QuantLib's BinomialConvertibleEngine %\url{http://quantlib.org/reference/class_quant_lib_1_1_binomial_convertible_engine.html} and BlackScholesMertonProcess %\url{http://quantlib.org/reference/class_quant_lib_1_1_black_scholes_merton_process.html}. The NPV, clean price, dirty price, accrued interest, yield and cash flows of the bond is returned. For detail, see test-suite/convertiblebond.cpp The \code{ConvertibleFloatingCouponBond} function setups and evaluates a ConvertibleFixedCouponBond using QuantLib's BinomialConvertibleEngine % \url{http://quantlib.org/reference/class_quant_lib_1_1_binomial_convertible_engine.html} and BlackScholesMertonProcess % \url{http://quantlib.org/reference/class_quant_lib_1_1_black_scholes_merton_process.html}. The NPV, clean price, dirty price, accrued interest, yield and cash flows of the bond is returned. For detail, see test-suite/convertiblebond.cpp The \code{ConvertibleZeroCouponBond} function setups and evaluates a ConvertibleFixedCouponBond using QuantLib's BinomialConvertibleEngine % \url{http://quantlib.org/reference/class_quant_lib_1_1_binomial_convertible_engine.html} and BlackScholesMertonProcess % \url{http://quantlib.org/reference/class_quant_lib_1_1_black_scholes_merton_process.html}. The NPV, clean price, dirty price, accrued interest, yield and cash flows of the bond is returned. For detail, see \code{test-suite/convertiblebond.cpp}. } \usage{ \method{ConvertibleFloatingCouponBond}{default}(bondparams, iborindex, spread, process, dateparams) \method{ConvertibleFixedCouponBond}{default}(bondparams, coupon, process, dateparams) \method{ConvertibleZeroCouponBond}{default}(bondparams, process, dateparams) } \arguments{ \item{bondparams}{bond parameters, a named list whose elements are: \tabular{ll}{ \code{issueDate} \tab a Date, the bond's issue date\cr \code{maturityDate} \tab a Date, the bond's maturity date\cr \code{creditSpread} \tab a double, credit spread parameter \cr \code{} \tab in the constructor of the bond. \cr \code{conversitionRatio} \tab a double, conversition ratio \cr \code{} \tab parameter in the constructor of the bond. \cr \code{exercise} \tab (Optional) a string, either "eu" for European \cr \code{} \tab option, or "am" for American option. \cr \code{} \tab Default value is 'am'.\cr \code{faceAmount} \tab (Optional) a double, face amount of the bond.\cr \code{} \tab Default value is 100. \cr \code{redemption} \tab (Optional) a double, percentage of the initial \cr \code{} \tab face amount that will be returned at maturity \cr \code{} \tab date. Default value is 100.\cr \code{divSch} \tab (Optional) a data frame whose columns are \cr \code{} \tab "Type", "Amount", "Rate", and "Date" \cr \code{} \tab corresponding to QuantLib's DividendSchedule. \cr \code{} \tab Default value is an empty frame, or no dividend. \cr \code{callSch} \tab (Optional) a data frame whose columns are "Price",\cr \code{} \tab "Type" and "Date" corresponding to QuantLib's \cr \code{} \tab CallabilitySchedule. Defaule is an empty frame, \cr \code{} \tab or no callability.\cr } } \item{iborindex}{a DiscountCurve object, represents an IborIndex} \item{spread}{ a double vector, represents paramter 'spreads' in ConvertibleFloatingBond's constructor. } \item{coupon}{a double vector of coupon rate} \item{process}{arguments to construct a BlackScholes process and set up the binomial pricing engine for this bond. \tabular{ll}{ \code{underlying} \tab a double, flat underlying term structure \cr \code{volatility} \tab a double, flat volatility term structure \cr \code{dividendYield} \tab a DiscountCurve object \cr \code{riskFreeRate} \tab a DiscountCurve object \cr } } \item{dateparams}{(Optional) a named list, QuantLib's date parameters of the bond. \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{calendar} \tab (Optional) a string, either 'us' or 'uk' \cr \code{} \tab corresponding to US Goverment Bond \cr \code{} \tab calendar and UK Exchange calendar.\cr \code{} \tab Default value is 'us'.\cr \code{dayCounter} \tab (Optional) a number or string, \cr \code{} \tab day counter convention.\cr \code{} \tab See \link{Enum}. Default value is 'Thirty360' \cr \code{period} \tab (Optional) a number or string, \cr \code{} \tab interest compounding interval. See \link{Enum}. \cr \code{} \tab Default value is 'Semiannual'.\cr \code{businessDayConvention} \tab (Optional) a number or string, \cr \code{} \tab business day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr } See the examples below. } } \value{ The \code{ConvertibleFloatingCouponBond} function returns an object of class \code{ConvertibleFloatingCouponBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{price price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} The \code{ConvertibleFixedCouponBond} function returns an object of class \code{ConvertibleFixedCouponBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{price price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} The \code{ConvertibleZeroCouponBond} function returns an object of class \code{ConvertibleZeroCouponBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{price price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{ \url{http://quantlib.org/} for details on \code{QuantLib}. } \author{Khanh Nguyen \email{knguyen@cs.umb.edu} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib} } \examples{ #this follow an example in test-suite/convertiblebond.cpp params <- list(tradeDate=Sys.Date()-2, settleDate=Sys.Date(), dt=.25, interpWhat="discount", interpHow="loglinear") dividendYield <- DiscountCurve(params, list(flat=0.02)) riskFreeRate <- DiscountCurve(params, list(flat=0.05)) dividendSchedule <- data.frame(Type=character(0), Amount=numeric(0), Rate = numeric(0), Date = as.Date(character(0))) callabilitySchedule <- data.frame(Price = numeric(0), Type=character(0), Date = as.Date(character(0))) process <- list(underlying=50, divYield = dividendYield, rff = riskFreeRate, volatility=0.15) today <- Sys.Date() bondparams <- list(exercise="am", faceAmount=100, divSch = dividendSchedule, callSch = callabilitySchedule, redemption=100, creditSpread=0.005, conversionRatio = 0.0000000001, issueDate=as.Date(today+2), maturityDate=as.Date(today+3650)) dateparams <- list(settlementDays=3, dayCounter="ActualActual", period = "Semiannual", calendar = "us", businessDayConvention="Following") lengths <- c(2,4,6,8,10,12,14,16,18,20,22,24,26,28,30) coupons <- c( 0.0200, 0.0225, 0.0250, 0.0275, 0.0300, 0.0325, 0.0350, 0.0375, 0.0400, 0.0425, 0.0450, 0.0475, 0.0500, 0.0525, 0.0550 ) marketQuotes <- rep(100, length(lengths)) curvedateparams <- list(settlementDays=0, period="Annual", dayCounter="ActualActual", businessDayConvention ="Unadjusted") curveparams <- list(method="ExponentialSplinesFitting", origDate = Sys.Date()) curve <- FittedBondCurve(curveparams, lengths, coupons, marketQuotes, curvedateparams) iborindex <- list(type="USDLibor", length=6, inTermOf="Month", term=curve) spreads <- c() #ConvertibleFloatingCouponBond(bondparams, iborindex, spreads, process, dateparams) #example using default values #ConvertibleFloatingCouponBond(bondparams, iborindex,spreads, process) dateparams <- list(settlementDays=3, period = "Semiannual", businessDayConvention="Unadjusted") bondparams <- list( creditSpread=0.005, conversionRatio = 0.0000000001, issueDate=as.Date(today+2), maturityDate=as.Date(today+3650)) #ConvertibleFloatingCouponBond(bondparams, iborindex, #spreads, process, dateparams) #this follow an example in test-suite/convertiblebond.cpp #for ConvertibleFixedCouponBond #set up arguments to build a pricing engine. params <- list(tradeDate=Sys.Date()-2, settleDate=Sys.Date(), dt=.25, interpWhat="discount", interpHow="loglinear") times <- seq(0,10,.1) dividendYield <- DiscountCurve(params, list(flat=0.02), times) riskFreeRate <- DiscountCurve(params, list(flat=0.05), times) dividendSchedule <- data.frame(Type=character(0), Amount=numeric(0), Rate = numeric(0), Date = as.Date(character(0))) callabilitySchedule <- data.frame(Price = numeric(0), Type=character(0), Date = as.Date(character(0))) process <- list(underlying=50, divYield = dividendYield, rff = riskFreeRate, volatility=0.15) today <- Sys.Date() bondparams <- list(exercise="am", faceAmount=100, divSch = dividendSchedule, callSch = callabilitySchedule, redemption=100, creditSpread=0.005, conversionRatio = 0.0000000001, issueDate=as.Date(today+2), maturityDate=as.Date(today+3650)) dateparams <- list(settlementDays=3, dayCounter="Actual360", period = "Once", calendar = "us", businessDayConvention="Following" ) coupon <- c(0.05) ConvertibleFixedCouponBond(bondparams, coupon, process, dateparams) #example with default value ConvertibleFixedCouponBond(bondparams, coupon, process) dateparams <- list(settlementDays=3, dayCounter="Actual360") ConvertibleFixedCouponBond(bondparams, coupon, process, dateparams) bondparams <- list(creditSpread=0.005, conversionRatio = 0.0000000001, issueDate=as.Date(today+2), maturityDate=as.Date(today+3650)) ConvertibleFixedCouponBond(bondparams, coupon, process, dateparams) #this follow an example in test-suite/convertiblebond.cpp params <- list(tradeDate=Sys.Date()-2, settleDate=Sys.Date(), dt=.25, interpWhat="discount", interpHow="loglinear") times <- seq(0,10,.1) dividendYield <- DiscountCurve(params, list(flat=0.02), times) riskFreeRate <- DiscountCurve(params, list(flat=0.05), times) dividendSchedule <- data.frame(Type=character(0), Amount=numeric(0), Rate = numeric(0), Date = as.Date(character(0))) callabilitySchedule <- data.frame(Price = numeric(0), Type=character(0), Date = as.Date(character(0))) process <- list(underlying=50, divYield = dividendYield, rff = riskFreeRate, volatility=0.15) today <- Sys.Date() bondparams <- list(exercise="am", faceAmount=100, divSch = dividendSchedule, callSch = callabilitySchedule, redemption=100, creditSpread=0.005, conversionRatio = 0.0000000001, issueDate=as.Date(today+2), maturityDate=as.Date(today+3650)) dateparams <- list(settlementDays=3, dayCounter="Actual360", period = "Once", calendar = "us", businessDayConvention="Following" ) ConvertibleZeroCouponBond(bondparams, process, dateparams) #example with default values ConvertibleZeroCouponBond(bondparams, process) bondparams <- list(creditSpread=0.005, conversionRatio=0.0000000001, issueDate=as.Date(today+2), maturityDate=as.Date(today+3650)) dateparams <- list(settlementDays=3, dayCounter='Actual360') ConvertibleZeroCouponBond(bondparams, process, dateparams) ConvertibleZeroCouponBond(bondparams, process) } RQuantLib/man/DiscountCurve.Rd0000644000175000017500000001461612271333436014704 0ustar00eddedd% $Id: DiscountCurve.Rd,v 1.5 2007/12/31 02:12:27 edd Exp $ \name{DiscountCurve} \alias{DiscountCurve} \alias{DiscountCurve.default} \alias{plot.DiscountCurve} \title{Returns the discount curve (with zero rates and forwards) given times} \description{ \code{DiscountCurve} constructs the spot term structure of interest rates based on input market data including the settlement date, deposit rates, futures prices, FRA rates, or swap rates, in various combinations. It returns the corresponding discount factors, zero rates, and forward rates for a vector of times that is specified as input. } \usage{ DiscountCurve(params, tsQuotes, times) } \arguments{ \item{params}{A list specifying the \code{tradeDate} (month/day/year), \code{settleDate}, forward rate time span \code{dt}, and two curve construction options: \code{interpWhat} (with possible values \code{discount}, \code{forward}, and \code{zero}) and \code{interpHow} (with possible values \code{linear}, \code{loglinear}, and \code{spline}). \code{spline} here means cubic spline interpolation of the \code{interpWhat} value. } \item{tsQuotes}{Market quotes used to construct the spot term structure of interest rates. Must be a list of name/value pairs, where the currently recognized names are: \tabular{ll}{ \code{flat} \tab rate for a flat yield curve\cr \code{d1w} \tab 1-week deposit rate\cr \code{d1m} \tab 1-month deposit rate\cr \code{d3m} \tab 3-month deposit rate\cr \code{d6m} \tab 6-month deposit rate\cr \code{d9m} \tab 9-month deposit rate\cr \code{d1y} \tab 1-year deposit rate\cr \code{s2y} \tab 2-year swap rate\cr \code{s3y} \tab 3-year swap rate\cr \code{s5y} \tab 5-year swap rate\cr \code{s10y} \tab 10-year swap rate\cr \code{s15y} \tab 15-year swap rate\cr \code{s20y} \tab 20-year swap rate\cr \code{s30y} \tab 30-year swap rate\cr \code{fut1}--\code{fut8} \tab 3-month futures contracts\cr \code{fra3x6} \tab 3x6 FRA\cr \code{fra6x9} \tab 6x9 FRA\cr \code{fra6x12}\tab 6x12 FRA } Here rates are expected as fractions (so 5\% means .05). If \code{flat} is specified it must be the first and only item in the list. The eight futures correspond to the first eight IMM dates. The maturity dates of the instruments specified need not be ordered, but they must be distinct. } \item{times}{A vector of times at which to return the discount factors, forward rates, and zero rates. Times must be specified such that the largest time plus \code{dt} does not exceed the longest maturity of the instruments used for calibration (no extrapolation). } } \value{ \code{DiscountCurve} returns a list containing: \item{times}{Vector of input times} \item{discounts}{Corresponding discount factors} \item{forwards}{Corresponding forward rates with time span \code{dt}} \item{zerorates}{Corresponding zero coupon rates} \item{flatQuotes}{True if a flat quote was used, False otherwise} \item{params}{The input parameter list} } \details{ This function is based on \code{QuantLib} Version 0.3.10. It introduces support for fixed-income instruments in \code{RQuantLib}. Forward rates and zero rates are computed assuming continuous compounding, so the forward rate \eqn{f} over the period from \eqn{t_1}{t1} to \eqn{t_2}{t2} is determined by the relation \deqn{d_1/d_2 = e^{f (t_2 - t_1)},}{d1/d2 = exp(f(t2 - t1)),} where \eqn{d_1}{d1} and \eqn{d_2}{d2} are discount factors corresponding to the two times. In the case of the zero rate \eqn{t_1}{t1} is the current time (the spot date). Curve construction can be a delicate problem and the algorithms may fail for some input data sets and/or some combinations of the values for \code{interpWhat} and \code{interpHow}. Fortunately, the C++ exception mechanism seems to work well with the R interface, and \code{QuantLib} exceptions are propagated back to the R user, usually with a message that indicates what went wrong. (The first part of the message contains technical information about the precise location of the problem in the \code{QuantLib} code. Scroll to the end to find information that is meaningful to the R user.) } \references{ Brigo, D. and Mercurio, F. (2001) \emph{Interest Rate Models: Theory and Practice}, Springer-Verlag, New York. For information about \code{QuantLib} see \url{http://quantlib.org}. For information about \code{RQuantLib} see \url{http://dirk.eddelbuettel.com/code/rquantlib.html}. } \author{Dominick Samperi} \seealso{\code{\link{BermudanSwaption}}} \examples{ savepar <- par(mfrow=c(3,3), mar=c(4,4,2,0.5)) ## This data is taken from sample code shipped with QuantLib 0.9.7 ## from the file Examples/Swap/swapvaluation params <- list(tradeDate=as.Date('2004-09-20'), settleDate=as.Date('2004-09-22'), dt=.25, interpWhat="discount", interpHow="loglinear") setEvaluationDate(as.Date("2004-11-22")) ## We get numerical issue for the spline interpolation if we add ## any on of these three extra futures -- the original example ## creates different curves based on different deposit, fra, futures ## and swap data tsQuotes <- list(d1w = 0.0382, d1m = 0.0372, d3m = 0.0363, d6m = 0.0353, d9m = 0.0348, d1y = 0.0345, # fut1=96.2875, # fut2=96.7875, # fut3=96.9875, # fut4=96.6875, # fut5=96.4875, # fut6=96.3875, # fut7=96.2875, # fut8=96.0875, s2y = 0.037125, s3y = 0.0398, s5y = 0.0443, s10y = 0.05165, s15y = 0.055175) tsQuotes <- list("flat" = 0.02) ## While discount curve code is buggy times <- seq(0,10,.1) # Loglinear interpolation of discount factors curves <- DiscountCurve(params, tsQuotes, times) plot(curves,setpar=FALSE) # Linear interpolation of discount factors params$interpHow="linear" curves <- DiscountCurve(params, tsQuotes, times) plot(curves,setpar=FALSE) # Spline interpolation of discount factors params$interpHow="spline" ## NB Commented out for numerical issues under current parameterisation #curves <- DiscountCurve(params, tsQuotes, times) plot(curves,setpar=FALSE) par(savepar) } \keyword{models} RQuantLib/man/Enum.Rd0000644000175000017500000000433512271333436013010 0ustar00eddedd% $Id: Enum.Rd 78 2009-05-30 18:31:48Z edd $ \name{Enum} \alias{Enum} \title{Documentation for parameters} \description{ Reference for parameters when constructing a bond } %\usage{} \arguments{ \item{DayCounter}{an int value \tabular{ll}{ \code{0} \tab Actual360 \cr \code{1} \tab Actual360FixEd \cr \code{2} \tab ActualActual \cr \code{3} \tab ActualBusiness252 \cr \code{4} \tab OneDayCounter \cr \code{5} \tab SimpleDayCounter \cr \code{anything else} \tab Thirty360 } } \item{businessDayConvention}{an int value \tabular{ll}{ \code{0} \tab Following \cr \code{1} \tab ModifiedFollowing \cr \code{2} \tab Preceding \cr \code{3} \tab ModifiedPreceding \cr \code{anything else} \tab UNadjusted } } \item{compounding}{an int value \tabular{ll}{ \code{0} \tab Simple \cr \code{1} \tab Compounded \cr \code{2} \tab Continuous \cr \code{3} \tab SimpleThenCompounded } } \item{period or frequency}{an int value \tabular{ll}{ \code{-1} \tab NoFrequency \cr \code{0} \tab Once \cr \code{1} \tab Annual \cr \code{2} \tab Semiannual \cr \code{3} \tab EveryFourthMonth \cr \code{4} \tab Quarterly \cr \code{6} \tab BiMonthtly \cr \code{12} \tab Monthly \cr \code{13} \tab EveryFourthWeek \cr \code{26} \tab BiWeekly \cr \code{52} \tab Weekly \cr \code{365} \tab Daily \cr \code{anything else} \tab OtherFrequency } } \item{date generation}{an int value to specify date generation rule \tabular{ll}{ \code{0} \tab Backward \cr \code{1} \tab Forward \cr \code{2} \tab Zero \cr \code{3} \tab ThirdWednesday \cr \code{4} \tab Twentieth \cr \code{anything else} \tab TwentiethIMM } } } \value{ None } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation, particularly the datetime classes. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umb.edu}} \keyword{misc} RQuantLib/man/EuropeanOption.Rd0000644000175000017500000000556512271333436015061 0ustar00eddedd% $Id: EuropeanOption.Rd,v 1.5 2006/11/11 04:12:45 edd Exp $ \name{EuropeanOption} \alias{EuropeanOption} \alias{EuropeanOption.default} \title{European Option evaluation using Closed-Form solution} \description{ The \code{EuropeanOption} function evaluations an European-style option on a common stock using the Black-Scholes-Merton solution. The option value, the common first derivatives ("Greeks") as well as the calling parameters are returned. } \usage{ \method{EuropeanOption}{default}(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) } \arguments{ \item{type}{A string with one of the values \code{call} or \code{put}} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Volatility of the underlying stock} } \value{ The \code{EuropeanOption} function returns an object of class \code{EuropeanOption} (which inherits from class \code{\link{Option}}). It contains a list with the following components: \item{value}{Value of option} \item{delta}{Sensitivity of the option value for a change in the underlying} \item{gamma}{Sensitivity of the option delta for a change in the underlying} \item{vega}{Sensitivity of the option value for a change in the underlying's volatility} \item{theta}{Sensitivity of the option value for a change in t, the remaining time to maturity} \item{rho}{Sensitivity of the option value for a change in the risk-free interest rate} \item{dividendRho}{Sensitivity of the option value for a change in the dividend yield} \item{parameters}{List with parameters with which object was created} } \details{ The well-known closed-form solution derived by Black, Scholes and Merton is used for valuation. Implied volatilities are calculated numerically. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{EuropeanOptionImpliedVolatility}}, \code{\link{EuropeanOptionArrays}}, \code{\link{AmericanOption}},\code{\link{BinaryOption}}} \examples{ # simple call with unnamed parameters EuropeanOption("call", 100, 100, 0.01, 0.03, 0.5, 0.4) # simple call with some explicit parameters, and slightly increased vol: EuropeanOption(type="call", underlying=100, strike=100, dividendYield=0.01, riskFreeRate=0.03, maturity=0.5, volatility=0.5) } \keyword{misc} RQuantLib/man/EuropeanOptionArrays.Rd0000644000175000017500000001163112271333436016232 0ustar00eddedd% $Id: EuropeanOptionArrays.Rd,v 1.4 2004/12/28 03:20:07 edd Exp $ \name{EuropeanOptionArrays} \alias{EuropeanOptionArrays} \alias{oldEuropeanOptionArrays} \alias{plotOptionSurface} \title{European Option evaluation using Closed-Form solution} \description{ The \code{EuropeanOptionArrays} function allows any two of the numerical input parameters to be a vector, and a list of matrices is returned for the option value as well as each of the 'greeks'. For each of the returned matrices, each element corresponds to an evaluation under the given set of parameters. } \usage{ EuropeanOptionArrays(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) oldEuropeanOptionArrays(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) plotOptionSurface(EOres, ylabel="", xlabel="", zlabel="", fov=60) } \arguments{ \item{type}{A string with one of the values \code{call} or \code{put}} \item{underlying}{(Scalar or list) current price(s) of the underlying stock} \item{strike}{(Scalar or list) strike price(s) of the option} \item{dividendYield}{(Scalar or list) continuous dividend yield(s) (as a fraction) of the stock} \item{riskFreeRate}{(Scalar or list) risk-free rate(s)} \item{maturity}{(Scalar or list) time(s) to maturity (in fractional years)} \item{volatility}{(Scalar or list) volatilit(y|ies) of the underlying stock} \item{EOres}{result matrix produced by \code{EuropeanOptionArrays}} \item{ylabel}{label for y-axsis} \item{xlabel}{label for x-axsis} \item{zlabel}{label for z-axsis} \item{fov}{viewpoint for 3d rendering} } \value{ The \code{EuropeanOptionArrays} function allows any two of the numerical input parameters to be a vector or sequence. A list of two-dimensional matrices is returned. Each cell corresponds to an evaluation under the given set of parameters. For these functions, the following components are returned: \item{value}{(matrix) value of option} \item{delta}{(matrix) change in value for a change in the underlying} \item{gamma}{(matrix) change in value for a change in delta} \item{vega}{(matrix) change in value for a change in the underlying's volatility} \item{theta}{(matrix) change in value for a change in delta} \item{rho}{(matrix) change in value for a change in time to maturity} \item{dividendRho}{(matrix) change in value for a change in delta} \item{parameters}{List with parameters with which object was created} The \code{oldEuropeanOptionArrays} function is an older implementation which vectorises this at the R level instead but allows more general multidimensional arrays. } \details{ The well-known closed-form solution derived by Black, Scholes and Merton is used for valuation. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{AmericanOption}},\code{\link{BinaryOption}}} \examples{ # define two vectos for the underlying and the volatility und.seq <- seq(10,180,by=2) vol.seq <- seq(0.1,0.9,by=0.1) # evaluate them along with three scalar parameters EOarr <- EuropeanOptionArrays("call", underlying=und.seq, strike=100, dividendYield=0.01, riskFreeRate=0.03, maturity=1, volatility=vol.seq) # and look at four of the result arrays: value, delta, gamma, vega old.par <- par(no.readonly = TRUE) par(mfrow=c(2,2),oma=c(5,0,0,0),mar=c(2,2,2,1)) plot(EOarr$parameters.underlying, EOarr$value[,1], type='n', main="option value", xlab="", ylab="") topocol <- topo.colors(length(vol.seq)) for (i in 1:length(vol.seq)) lines(EOarr$parameters.underlying, EOarr$value[,i], col=topocol[i]) plot(EOarr$parameters.underlying, EOarr$delta[,1],type='n', main="option delta", xlab="", ylab="") for (i in 1:length(vol.seq)) lines(EOarr$parameters.underlying, EOarr$delta[,i], col=topocol[i]) plot(EOarr$parameters.underlying, EOarr$gamma[,1],type='n', main="option gamma", xlab="", ylab="") for (i in 1:length(vol.seq)) lines(EOarr$parameters.underlying, EOarr$gamma[,i], col=topocol[i]) plot(EOarr$parameters.underlying, EOarr$vega[,1],type='n', main="option vega", xlab="", ylab="") for (i in 1:length(vol.seq)) lines(EOarr$parameters.underlying, EOarr$vega[,i], col=topocol[i]) mtext(text=paste("Strike is 100, maturity 1 year, riskless rate 0.03", "\nUnderlying price from", und.seq[1],"to", und.seq[length(und.seq)], "\nVolatility from",vol.seq[1], "to",vol.seq[length(vol.seq)]), side=1,font=1,outer=TRUE,line=3) par(old.par) } \keyword{misc} RQuantLib/man/EuropeanOptionImpliedVolatility.Rd0000644000175000017500000000444312271333436020440 0ustar00eddedd% $Id: EuropeanOptionImpliedVolatility.Rd,v 1.6 2006/11/11 04:13:25 edd Exp $ \name{EuropeanOptionImpliedVolatility} \alias{EuropeanOptionImpliedVolatility} \alias{EuropeanOptionImpliedVolatility.default} \title{Implied Volatility calculation for European Option} \description{ The \code{EuropeanOptionImpliedVolatility} function solves for the (unobservable) implied volatility, given an option price as well as the other required parameters to value an option.} \usage{ \method{EuropeanOptionImpliedVolatility}{default}(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) } \arguments{ \item{type}{A string with one of the values \code{call} or \code{put}} \item{value}{Value of the option (used only for ImpliedVolatility calculation)} \item{underlying}{Current price of the underlying stock} \item{strike}{Strike price of the option} \item{dividendYield}{Continuous dividend yield (as a fraction) of the stock} \item{riskFreeRate}{Risk-free rate} \item{maturity}{Time to maturity (in fractional years)} \item{volatility}{Initial guess for the volatility of the underlying stock} } \value{ The \code{EuropeanOptionImpliedVolatility} function returns an object of class \code{\link{ImpliedVolatility}}. It contains a list with the following elements: \item{impliedVol}{The volatility implied by the given market prices} \item{parameters}{List with the option parameters used} } \details{ The well-known closed-form solution derived by Black, Scholes and Merton is used for valuation. Implied volatilities are then calculated numerically. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{EuropeanOption}},\code{\link{AmericanOption}},\code{\link{BinaryOption}}} \examples{ EuropeanOptionImpliedVolatility(type="call", value=11.10, underlying=100, strike=100, dividendYield=0.01, riskFreeRate=0.03, maturity=0.5, volatility=0.4) } \keyword{misc} RQuantLib/man/FittedBondCurve.Rd0000644000175000017500000000563712271333436015141 0ustar00eddedd\name{FittedBondCurve} \alias{FittedBondCurve} \alias{FittedBondCurve.default} \alias{plot.FittedBondCurve} \title{Returns the discount curve (with zero rates and forwards) given set of bonds} \description{ \code{FittedBondCurve} fits a term structure to a set of bonds using three different fitting methodologies. For more detail, see QuantLib/Example/FittedBondCurve. } \usage{ FittedBondCurve(curveparams, lengths, coupons, marketQuotes, dateparams) } \arguments{ \item{curveparams}{curve parameters \tabular{ll}{ \code{method} \tab a string, fitting methods: "ExponentialSplinesFitting", \cr \code{} \tab "SimplePolynomialFitting", "NelsonSiegelFitting"\cr \code{origDate} \tab a Date, starting date of the curve \cr } } \item{lengths}{an numeric vector, length of the bonds in year} \item{coupons}{a numeric vector, coupon rate of the bonds} \item{marketQuotes}{a numeric vector, market price of the bonds} \item{dateparams}{(Optional) a named list, QuantLib's date parameters of the bond. \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{dayCounter} \tab (Optional) a number or string, \cr \code{} \tab day counter convention.\cr \code{} \tab See \link{Enum}. Default value is 'Thirty360' \cr \code{period} \tab (Optional) a number or string, \cr \code{} \tab interest compounding interval. See \link{Enum}. \cr \code{} \tab Default value is 'Semiannual'.\cr \code{businessDayConvention} \tab (Optional) a number or string, \cr \code{} \tab business day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr } See example below. } } \value{ \code{table}, a three columns "date - zeroRate - discount" data frame } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{ \url{http://quantlib.org/} for details on \code{QuantLib}. } \author{Khanh Nguyen \email{knguyen@cs.umb.edu} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib} } \examples{ lengths <- c(2,4,6,8,10,12,14,16,18,20,22,24,26,28,30) coupons <- c( 0.0200, 0.0225, 0.0250, 0.0275, 0.0300, 0.0325, 0.0350, 0.0375, 0.0400, 0.0425, 0.0450, 0.0475, 0.0500, 0.0525, 0.0550 ) marketQuotes <- rep(100, length(lengths)) dateparams <- list(settlementDays=0, period="Annual", dayCounter="ActualActual", businessDayConvention ="Unadjusted") curveparams <- list(method="ExponentialSplinesFitting", origDate = Sys.Date()) curve <- FittedBondCurve(curveparams, lengths, coupons, marketQuotes, dateparams) library(zoo) z <- zoo(curve$table$zeroRates, order.by=curve$table$date) plot(z) } RQuantLib/man/FixedRateBond.Rd0000644000175000017500000002322412271333436014560 0ustar00eddedd% $Id$ \name{FixedRateBond} \alias{FixedRateBond} \alias{FixedRateBond.default} \alias{FixedRateBondPriceByYield} \alias{FixedRateBondPriceByYield.default} \alias{FixedRateBondYield} \alias{FixedRateBondYield.default} \title{Fixed-Rate bond pricing} \description{ The \code{FixedRateBond} function evaluates a fixed rate bond using discount curve. More specificly, the calculation is done by DiscountingBondEngine from QuantLib. The NPV, clean price, dirty price, accrued interest, yield and cash flows of the bond is returned. For more detail, see the source codes in QuantLib's file \code{test-suite/bond.cpp}. The \code{FixedRateBondPriceByYield} function calculates the theoretical price of a fixed rate bond from its yield. The \code{FixedRateBondYield} function calculates the theoretical yield of a fixed rate bond from its price. } \usage{ \method{FixedRateBond}{default}(bond, rates, discountCurve, dateparams ) \method{FixedRateBondPriceByYield}{default}( settlementDays=1, yield, faceAmount, effectiveDate, maturityDate, period, calendar="us", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption=100, issueDate) \method{FixedRateBondYield}{default}( settlementDays=1, price, faceAmount, effectiveDate, maturityDate, period, calendar="us", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption=100, issueDate) } \arguments{ \item{bond}{bond parameters, a named list whose elements are: \tabular{ll}{ \code{issueDate} \tab a Date, the bond's issue date\cr \code{maturityDate} \tab a Date, the bond's maturity date\cr \code{faceAmount} \tab (Optional) a double, face amount of the bond.\cr \code{} \tab Default value is 100. \cr \code{redemption} \tab (Optional) a double, percentage of the initial \cr \code{} \tab face amount that will be returned at maturity \cr \code{} \tab date. Default value is 100.\cr \code{effectiveDate} \tab (Optinal) a Date, the bond's effective date. Default value is issueDate\cr } } \item{rates}{a numeric vector, bond's coupon rates} \item{discountCurve}{Can be one of the following: \tabular{ll}{ \code{a DiscountCurve} \tab a object of DiscountCurve class \cr \code{} \tab For more detail, see example or \cr \code{} \tab the discountCurve function \cr \code{A 2 items list} \tab specifies a flat curve in two \cr \code{} \tab values "todayDate" and "rate" \cr \code{A 3 items list} \tab specifies three values to construct a \cr \code{} \tab DiscountCurve object, "params" , \cr \code{} \tab "tsQuotes", "times". \cr \code{} \tab For more detail, see example or \cr \code{} \tab the discountCurve function \cr } } \item{dateparams}{(Optional) a named list, QuantLib's date parameters of the bond. \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{calendar} \tab (Optional) a string, either 'us' or 'uk' \cr \code{} \tab corresponding to US Goverment Bond \cr \code{} \tab calendar and UK Exchange calendar.\cr \code{} \tab Default value is 'us'.\cr \code{dayCounter} \tab (Optional) a number or string, \cr \code{} \tab day counter convention.\cr \code{} \tab See \link{Enum}. Default value is 'Thirty360' \cr \code{period} \tab (Optional) a number or string, \cr \code{} \tab interest compounding interval. See \link{Enum}. \cr \code{} \tab Default value is 'Semiannual'.\cr \code{businessDayConvention} \tab (Optional) a number or string, \cr \code{} \tab business day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr \code{terminationDateConvention} \tab (Optional) a number or string, \cr \code{} \tab termination day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr \code{endOfMonth} \tab (Optional) a numeric with value 1 or 0. \cr \code{} \tab End of Month rule. Default value is 0.\cr \code{dateGeneration} \tab (Optional) a numeric, date generation method. \cr \code{} \tab See \link{Enum}. Default value is 'Backward' \cr } See example below. } \item{settlementDays}{an integer, 1 for T+1, 2 for T+2, etc...} \item{yield}{yield of the bond} \item{price}{price of the bond} \item{effectiveDate}{bond's effective date} \item{maturityDate}{bond's maturity date} \item{period}{frequency of events,0=NoFrequency, 1=Once, 2=Annual, 3=Semiannual, 4=EveryFourthMonth, 5=Quarterly, 6=Bimonthly ,7=Monthly ,8=EveryFourthWeely,9=Biweekly, 10=Weekly, 11=Daily. For more information, see QuantLib's Frequency class } \item{calendar}{Business Calendar. Either \code{us} or \code{uk}} \item{faceAmount}{face amount of the bond} \item{businessDayConvention}{convention used to adjust a date in case it is not a valid business day. See quantlib for more detail. 0 = Following, 1 = ModifiedFollowing, 2 = Preceding, 3 = ModifiedPreceding, other = Unadjusted} \item{dayCounter}{day count convention. 0 = Actual360(), 1 = Actual365Fixed(), 2 = ActualActual(), 3 = Business252(), 4 = OneDayCounter(), 5 = SimpleDayCounter(), all other = Thirty360(). For more information, see QuantLib's DayCounter class} \item{compound}{compounding type. 0=Simple, 1=Compounded, 2=Continuous, all other=SimpleThenCompounded. See QuantLib's Compound class} \item{redemption}{redemption when the bond expires} \item{issueDate}{date the bond is issued} } \value{ The \code{FixedRateBond} function returns an object of class \code{FixedRateBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{clean price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} The \code{FixedRateBondPriceByYield} function returns an object of class \code{FixedRateBondPriceByYield} (which inherits from class \code{Bond}). It contains a list with the following components: \item{price}{price of the bond} The \code{FixedRateBondYield} function returns an object of class \code{FixedRateBondYield} (which inherits from class \code{Bond}). It contains a list with the following components: \item{yield}{yield of the bond} } \details{ A discount curve is built to calculate the bond value. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umb.edu} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ #Simple call with a flat curve bond <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100, effectiveDate=as.Date("2004-11-30")) dateparams <- list(settlementDays=1, calendar="us", dayCounter = 'Thirty360', period=2, businessDayConvention = 4, terminationDateConvention=4, dateGeneration=1, endOfMonth=1) coupon.rate <- c(0.02875) params <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-19'), dt=.25, interpWhat="discount", interpHow="loglinear") setEvaluationDate(as.Date("2004-11-22")) discountCurve.flat <- DiscountCurve(params, list(flat=0.05)) FixedRateBond(bond, coupon.rate, discountCurve.flat, dateparams) #Same bond with a discount curve constructed from market quotes tsQuotes <- list(d1w =0.0382, d1m =0.0372, fut1=96.2875, fut2=96.7875, fut3=96.9875, fut4=96.6875, fut5=96.4875, fut6=96.3875, fut7=96.2875, fut8=96.0875, s3y =0.0398, s5y =0.0443, s10y =0.05165, s15y =0.055175) tsQuotes <- list("flat" = 0.02) ## While discount curve code is buggy discountCurve <- DiscountCurve(params, tsQuotes) FixedRateBond(bond, coupon.rate, discountCurve, dateparams) #example with default dateparams FixedRateBond(bond, coupon.rate, discountCurve) ##exampe with defaul bond parameter and dateparams bond <- list(issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30")) dateparams <- list(calendar="us", dayCounter = "ActualActual", period="Annual") FixedRateBond(bond, coupon.rate, discountCurve, dateparams) FixedRateBondPriceByYield(,0.0307, 100000, as.Date("2004-11-30"), as.Date("2008-11-30"), 3, , c(0.02875), , , , ,as.Date("2004-11-30")) FixedRateBondYield(,90, 100000, as.Date("2004-11-30"), as.Date("2008-11-30"), 3, , c(0.02875), , , , ,as.Date("2004-11-30")) } \keyword{misc} RQuantLib/man/FloatingRateBond.Rd0000644000175000017500000001747212271333436015274 0ustar00eddedd% $Id: FloatingRateBond.Rd 87 2009-06-09 16:48:13Z knguyen $ \name{FloatingRateBond} \alias{FloatingRateBond} \alias{FloatingRateBond.default} \title{Floating rate bond pricing} \description{ The \code{FloatingRateBond} function evaluates a floating rate bond using discount curve. More specificly, the calculation is done by DiscountingBondEngine from QuantLib. The NPV, clean price, dirty price, accrued interest, yield and cash flows of the bond is returned. For more detail, see the source codes in quantlib's test-suite. test-suite/bond.cpp } \usage{ \method{FloatingRateBond}{default}(bond, gearings, spreads, caps, floors, index, curve, dateparams ) } \arguments{ \item{bond}{bond parameters, a named list whose elements are: \tabular{ll}{ \code{issueDate} \tab a Date, the bond's issue date\cr \code{maturityDate} \tab a Date, the bond's maturity date\cr \code{faceAmount} \tab (Optional) a double, face amount of the bond.\cr \code{} \tab Default value is 100. \cr \code{redemption} \tab (Optional) a double, percentage of the initial \cr \code{} \tab face amount that will be returned at maturity \cr \code{} \tab date. Default value is 100.\cr \code{effectiveDate} \tab (Optinal) a Date, the bond's effective date. Default value is issueDate\cr } } \item{gearings}{(Optional) a numeric vector, bond's gearings. See quantlib's doc on FloatingRateBond for more detail. Default value is an empty vector c(). } \item{spreads}{(Optional) a numeric vector, bond's spreads. See quantlib's doc on FloatingRateBond for more detail.Default value is an empty vector c() } \item{caps}{(Optional) a numeric vector, bond's caps. See quantlib's doc on FloatingRateBond for more detail. Default value is an empty vector c() } \item{floors}{(Optional) a numeric vector, bond's floors. See quantlib's doc on FloatingRateBond for more detail. Default value is an empty vector c() } \item{curve}{Can be one of the following: \tabular{ll}{ \code{a DiscountCurve} \tab a object of DiscountCurve class \cr \code{} \tab For more detail, see example or \cr \code{} \tab the discountCurve function \cr \code{A 2 items list} \tab specifies a flat curve in two \cr \code{} \tab values "todayDate" and "rate" \cr \code{A 3 items list} \tab specifies three values to construct a \cr \code{} \tab DiscountCurve object, "params" , \cr \code{} \tab "tsQuotes", "times". \cr \code{} \tab For more detail, see example or \cr \code{} \tab the discountCurve function \cr } } \item{index}{a named list whose elements are parameters of an IborIndex term structure. \tabular{ll}{ \code{type} \tab a string, currently support only "USDLibor" \cr \code{length} \tab an integer, length of the index \cr \code{inTermOf} \tab a string, period unit, currently support only 'Month' \cr \code{term} \tab a DiscountCurve object, the term structure of the index\cr } } \item{dateparams}{(Optional) a named list, QuantLib's date parameters of the bond. \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{calendar} \tab (Optional) a string, either 'us' or 'uk' \cr \code{} \tab corresponding to US Goverment Bond \cr \code{} \tab calendar and UK Exchange calendar.\cr \code{} \tab Default value is 'us'.\cr \code{dayCounter} \tab (Optional) a number or string, \cr \code{} \tab day counter convention.\cr \code{} \tab See \link{Enum}. Default value is 'Thirty360' \cr \code{period} \tab (Optional) a number or string, \cr \code{} \tab interest compounding interval. See \link{Enum}. \cr \code{} \tab Default value is 'Semiannual'.\cr \code{businessDayConvention} \tab (Optional) a number or string, \cr \code{} \tab business day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr \code{terminationDateConvention} \tab (Optional) a number or string, \cr \code{} \tab termination day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr \code{endOfMonth} \tab (Optional) a numeric with value 1 or 0. \cr \code{} \tab End of Month rule. Default value is 0.\cr \code{dateGeneration} \tab (Optional) a numeric, date generation method. \cr \code{} \tab See \link{Enum}. Default value is 'Backward' \cr } See example below. } } \value{ The \code{FloatingRateBond} function returns an object of class \code{FloatingRateBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{clean price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} } \details{ A discount curve is built to calculate the bond value. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umbno.edu} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ bond <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100, effectiveDate=as.Date("2004-11-30")) dateparams <- list(settlementDays=1, calendar="us", dayCounter = 'ActualActual', period=2, businessDayConvention = 1, terminationDateConvention=1, dateGeneration=0, endOfMonth=0, fixingDays = 1) gearings <- c() spreads <- c() caps <- c() floors <- c() params <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-19'), dt=.25, interpWhat="discount", interpHow="loglinear") setEvaluationDate(as.Date("2004-11-22")) tsQuotes <- list(d1w =0.0382, d1m =0.0372, fut1=96.2875, fut2=96.7875, fut3=96.9875, fut4=96.6875, fut5=96.4875, fut6=96.3875, fut7=96.2875, fut8=96.0875, s3y =0.0398, s5y =0.0443, s10y =0.05165, s15y =0.055175) tsQuotes <- list("flat" = 0.02) ## While discount curve code is buggy ## when both discount and libor curves are flat. discountCurve.flat <- DiscountCurve(params, list(flat=0.05)) termstructure <- DiscountCurve(params, list(flat=0.03)) iborIndex.params <- list(type="USDLibor", length=6, inTermOf="Month", term=termstructure) FloatingRateBond(bond, gearings, spreads, caps, floors, iborIndex.params, discountCurve.flat, dateparams) ## discount curve is constructed from market quotes ## and a flat libor curve discountCurve <- DiscountCurve(params, tsQuotes) termstructure <- DiscountCurve(params, list(flat=0.03)) iborIndex.params <- list(type="USDLibor", length=6, inTermOf="Month", term = termstructure) FloatingRateBond(bond, gearings, spreads, caps, floors, iborIndex.params, discountCurve, dateparams) #example using default values FloatingRateBond(bond=bond, index=iborIndex.params, curve=discountCurve) } \keyword{misc} RQuantLib/man/ImpliedVolatility.Rd0000644000175000017500000000320312271333436015541 0ustar00eddedd% $Id: ImpliedVolatility.Rd,v 1.2 2003/08/01 01:23:48 edd Exp $ \name{ImpliedVolatility} \alias{ImpliedVolatility} \alias{print.ImpliedVolatility} \alias{summary.ImpliedVolatility} \title{Base class for option-price implied volatility evalution} \description{ This class forms the basis from which the more specific classes are derived. } \usage{ \method{print}{ImpliedVolatility}(x, digits=3, ...) \method{summary}{ImpliedVolatility}(object, digits=3, ...) } \arguments{ \item{x}{Any option-price implied volatility object derived from this base class} \item{object}{Any option-price implied volatility object derived from this base class} \item{digits}{Number of digits of precision shown} \item{...}{Further arguments} } \value{ None, but side effects of displaying content. } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{AmericanOptionImpliedVolatility}}, \code{\link{EuropeanOptionImpliedVolatility}}, \code{\link{AmericanOption}},\code{\link{EuropeanOption}}, \code{\link{BinaryOption}}} \examples{ impVol<-EuropeanOptionImpliedVolatility("call", value=11.10, strike=100, volatility=0.4, 100, 0.01, 0.03, 0.5) print(impVol) summary(impVol) } \keyword{misc} RQuantLib/man/Option.Rd0000644000175000017500000000254412271333436013354 0ustar00eddedd% $Id: Option.Rd,v 1.1 2002/02/26 03:49:27 edd Exp $ \name{Option} \alias{Option} \alias{plot.Option} \alias{print.Option} \alias{summary.Option} \title{Base class for option price evalution} \description{ This class forms the basis from which the more specific classes are derived. } \usage{ \method{print}{Option}(x, digits=4, ...) \method{plot}{Option}(x, ...) \method{summary}{Option}(object, digits=4, ...) } \arguments{ \item{x}{Any option object derived from this base class} \item{object}{Any option object derived from this base class} \item{digits}{Number of digits of precision shown} \item{...}{Further arguments} } \value{ None, but side effects of displaying content. } \details{ Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \seealso{\code{\link{AmericanOption}},\code{\link{EuropeanOption}}, \code{\link{BinaryOption}}} \examples{ EO<-EuropeanOption("call", strike=100, volatility=0.4, 100, 0.01, 0.03, 0.5) print(EO) summary(EO) } \keyword{misc} RQuantLib/man/ZeroCouponBond.Rd0000644000175000017500000001671612271333436015020 0ustar00eddedd% $Id$ \name{ZeroCouponBond} \alias{ZeroCouponBond} \alias{ZeroCouponBond.default} \alias{ZeroPriceByYield} \alias{ZeroPriceByYield.default} \alias{ZeroYield} \alias{ZeroYield.default} \title{Zero-Coupon bond pricing} \description{ The \code{ZeroCouponBond} function evaluates a zero-coupon plainly using discount curve. More specificly, the calculation is done by DiscountingBondEngine from QuantLib. The NPV, clean price, dirty price, accrued interest, yield and cash flows of the bond is returned. For more detail, see the source code in the QuantLib file \code{test-suite/bond.cpp}. The \code{ZeroPriceYield} function evaluates a zero-coupon clean price based on its yield. The \code{ZeroYield} function evaluations a zero-coupon yield based. See also http://www.mathworks.com/access/helpdesk/help/toolbox/finfixed/zeroyield.html } \usage{ \method{ZeroCouponBond}{default}(bond, discountCurve, dateparams) \method{ZeroPriceByYield}{default}(yield, faceAmount, issueDate, maturityDate, dayCounter=2, frequency=2, compound=0, businessDayConvention=4) \method{ZeroYield}{default}(price, faceAmount, issueDate, maturityDate, dayCounter=2, frequency=2, compound=0, businessDayConvention=4) } \arguments{ \item{bond}{bond parameters, a named list whose elements are: \tabular{ll}{ \code{issueDate} \tab a Date, the bond's issue date\cr \code{maturityDate} \tab a Date, the bond's maturity date\cr \code{faceAmount} \tab (Optional) a double, face amount of the bond.\cr \code{} \tab Default value is 100. \cr \code{redemption} \tab (Optional) a double, percentage of the initial \cr \code{} \tab face amount that will be returned at maturity \cr \code{} \tab date. Default value is 100.\cr } } \item{discountCurve}{Can be one of the following: \tabular{ll}{ \code{a DiscountCurve} \tab a object of DiscountCurve class \cr \code{} \tab For more detail, see example or \cr \code{} \tab the discountCurve function \cr \code{A 2 items list} \tab specifies a flat curve in two \cr \code{} \tab values "todayDate" and "rate" \cr \code{A 3 items list} \tab specifies three values to construct a \cr \code{} \tab DiscountCurve object, "params" , \cr \code{} \tab "tsQuotes", "times". \cr \code{} \tab For more detail, see example or \cr \code{} \tab the discountCurve function \cr } } \item{dateparams}{(Optional) a named list, QuantLib's date parameters of the bond. \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{calendar} \tab (Optional) a string, either 'us' or 'uk' \cr \code{} \tab corresponding to US Goverment Bond \cr \code{} \tab calendar and UK Exchange calendar.\cr \code{} \tab Default value is 'us'.\cr \code{businessDayConvention} \tab (Optional) a number or string, \cr \code{} \tab business day convention. \cr \tab See \link{Enum}. Default value is 'Following'. \cr } See example below. } \item{yield}{yield of the bond} \item{price}{price of the bond} \item{faceAmount}{face amount of the bond} \item{issueDate}{date the bond is issued} \item{maturityDate}{maturity date, an R's date type} \item{dayCounter}{day count convention. 0 = Actual360(), 1 = Actual365Fixed(), 2 = ActualActual(), 3 = Business252(), 4 = OneDayCounter(), 5 = SimpleDayCounter(), all other = Thirty360(). For more information, see QuantLib's DayCounter class} \item{frequency}{frequency of events,0=NoFrequency, 1=Once, 2=Annual, 3=Semiannual, 4=EveryFourthMonth, 5=Quarterly, 6=Bimonthly ,7=Monthly ,8=EveryFourthWeely,9=Biweekly, 10=Weekly, 11=Daily. For more information, see QuantLib's Frequency class } \item{compound}{compounding type. 0=Simple, 1=Compounded, 2=Continuous, all other=SimpleThenCompounded. See QuantLib's Compound class} \item{businessDayConvention}{convention used to adjust a date in case it is not a valid business day. See quantlib for more detail. 0 = Following, 1 = ModifiedFollowing, 2 = Preceding, 3 = ModifiedPreceding, other = Unadjusted} } \value{ The \code{ZeroCouponBond} function returns an object of class \code{ZeroCouponBond} (which inherits from class \code{Bond}). It contains a list with the following components: \item{NPV}{net present value of the bond} \item{cleanPrice}{clean price of the bond} \item{dirtyPrice}{dirty price of the bond} \item{accruedAmount}{accrued amount of the bond} \item{yield}{yield of the bond} \item{cashFlows}{cash flows of the bond} The \code{ZeroPriceByYield} function returns an object of class \code{ZeroPriceByYield} (which inherits from class \code{Bond}). It contains a list with the following components: \item{price}{price of the bond} The \code{ZeroYield} function returns an object of class \code{ZeroYield} (which inherits from class \code{Bond}). It contains a list with the following components: \item{yield}{yield of the bond} } \details{ A discount curve is built to calculate the bond value. Please see any decent Finance textbook for background reading, and the \code{QuantLib} documentation for details on the \code{QuantLib} implementation. } \references{\url{http://quantlib.org} for details on \code{QuantLib}.} \author{Khanh Nguyen \email{knguyen@cs.umb.edu} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib}} \note{The interface might change in future release as \code{QuantLib} stabilises its own API.} \examples{ # Simple call with all parameter and a flat curve bond <- list(faceAmount=100,issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100 ) dateparams <-list(settlementDays=1, calendar="us", businessDayConvention='Unadjusted') discountCurve.param <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-15'), dt=0.25, interpWhat='discount', interpHow='loglinear') discountCurve.flat <- DiscountCurve(discountCurve.param, list(flat=0.05)) ZeroCouponBond(bond, discountCurve.flat, dateparams) # The same bond with a discount curve constructed from market quotes tsQuotes <- list(d1w =0.0382, d1m =0.0372, fut1=96.2875, fut2=96.7875, fut3=96.9875, fut4=96.6875, fut5=96.4875, fut6=96.3875, fut7=96.2875, fut8=96.0875, s3y =0.0398, s5y =0.0443, s10y =0.05165, s15y =0.055175) tsQuotes <- list("flat" = 0.02) ## While discount curve code is buggy discountCurve <- DiscountCurve(discountCurve.param, tsQuotes) ZeroCouponBond(bond, discountCurve, dateparams) #examples with default arguments ZeroCouponBond(bond, discountCurve) bond <- list(issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30")) dateparams <-list(settlementDays=1) ZeroCouponBond(bond, discountCurve, dateparams) ZeroPriceByYield(0.1478, 100, as.Date("1993-6-24"), as.Date("1993-11-1")) ZeroYield(90, 100, as.Date("1993-6-24"), as.Date("1993-11-1")) } \keyword{misc} RQuantLib/src/0000755000175000017500000000000012271333436011624 5ustar00eddeddRQuantLib/src/Makevars.in0000644000175000017500000000010212271333436013716 0ustar00eddeddPKG_CXXFLAGS=@CXXFLAGS@ -I../inst/include -I. PKG_LIBS=@LDFLAGS@ RQuantLib/src/Makevars.win0000644000175000017500000000141612271333436014116 0ustar00eddedd# -*- mode: Makefile -*- # # Copyright 2005 - 2006 Dominick Samperi # Copyright 2005 Uwe Ligges # Copyright 2008 - 2013 Dirk Eddelbuettel # Copyright 2011 Uwe Ligges, Brian Ripley, and Josh Ulrich ## This assumes that we can call Rscript to ask Rcpp about its locations ## Use the R_HOME indirection to support installations of multiple R version RCPP_LDFLAGS = $(shell "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" -e "Rcpp:::LdFlags()") ## The environment variable QUANTLIB_ROOT has to point to an existing build of QuantLib ## With R 2.12.0 and later, we also support 32 and 64 bit builds and need to differentiate PKG_CXXFLAGS=-I$(QUANTLIB_ROOT) -I../inst/include -I. -I"$(BOOSTLIB)" PKG_LIBS=$(RCPP_LDFLAGS) -L$(QUANTLIB_ROOT)/lib${R_ARCH} -lQuantLib RQuantLib/src/asian.cpp0000644000175000017500000001664412271347225013437 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2009 Dirk Eddelbuettel // Copyright (C) 2009 - 2010 Dirk Eddelbuettel and Khanh Nguyen // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include RcppExport SEXP AsianOption(SEXP optionParameters){ try{ Rcpp::List rparam(optionParameters); std::string avgType = Rcpp::as(rparam["averageType"]); std::string type = Rcpp::as(rparam["type"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); // int length = int(maturity*360 + 0.5); // FIXME: this could be better double volatility = Rcpp::as(rparam["volatility"]); QuantLib::Option::Type optionType = getOptionType(type); //from test-suite/asionoptions.cpp QuantLib::DayCounter dc = QuantLib::Actual360(); QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today, qRate, dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today, rRate, dc); boost::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType,strike)); QuantLib::Average::Type averageType = QuantLib::Average::Geometric; Rcpp::List rl = R_NilValue; if (avgType=="geometric"){ averageType = QuantLib::Average::Geometric; boost::shared_ptr engine(new QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(stochProcess)); QuantLib::Date exDate = today + int(maturity * 360 + 0.5); boost::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ContinuousAveragingAsianOption option(averageType, payoff, exercise); option.setPricingEngine(engine); rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(), Rcpp::Named("delta") = option.delta(), Rcpp::Named("gamma") = option.gamma(), Rcpp::Named("vega") = option.vega(), Rcpp::Named("theta") = option.theta(), Rcpp::Named("rho") = option.rho(), Rcpp::Named("divRho") = option.dividendRho(), Rcpp::Named("parameters") = optionParameters); } else if (avgType=="arithmetic"){ averageType = QuantLib::Average::Arithmetic; boost::shared_ptr engine = QuantLib::MakeMCDiscreteArithmeticAPEngine(stochProcess) .withSamples(2047) .withControlVariate(); //boost::shared_ptr engine = // MakeMCDiscreteArithmeticASEngine(stochProcess) // .withSeed(3456789) // .withSamples(1023); QuantLib::Size fixings = Rcpp::as(rparam["fixings"]); QuantLib::Time length = Rcpp::as(rparam["length"]); QuantLib::Time first = Rcpp::as(rparam["first"]); QuantLib::Time dt = length / (fixings - 1); std::vector timeIncrements(fixings); std::vector fixingDates(fixings); timeIncrements[0] = first; fixingDates[0] = today + QuantLib::Integer(timeIncrements[0] * 360 + 0.5); for (QuantLib::Size i=1; i exercise(new QuantLib::EuropeanExercise(fixingDates[fixings-1])); QuantLib::DiscreteAveragingAsianOption option(QuantLib::Average::Arithmetic, runningSum, pastFixing, fixingDates, payoff, exercise); option.setPricingEngine(engine); rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(), Rcpp::Named("delta") = R_NaN, Rcpp::Named("gamma") = R_NaN, Rcpp::Named("vega") = R_NaN, Rcpp::Named("theta") = R_NaN, Rcpp::Named("rho") = R_NaN, Rcpp::Named("divRho") = R_NaN, Rcpp::Named("parameters") = optionParameters); } else { throw std::range_error("Unknown average type " + type); } return rl; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/barrier_binary.cpp0000644000175000017500000003413512271347225015331 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2010 Dirk Eddelbuettel // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include "rquantlib.h" RcppExport SEXP BinaryOption(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); std::string binType = Rcpp::as(rparam["binType"]); std::string type = Rcpp::as(rparam["type"]); std::string excType = Rcpp::as(rparam["excType"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better, but same rounding in QL double volatility = Rcpp::as(rparam["volatility"]); double cashPayoff = Rcpp::as(rparam["cashPayoff"]); QuantLib::Option::Type optionType = getOptionType(type); // new QuantLib 0.3.5 framework: digitals, updated for 0.3.7 // updated again for QuantLib 0.9.0, // cf QuantLib-0.9.0/test-suite/digitaloption.cpp QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today,qRate,dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today,rRate,dc); boost::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr payoff; if (binType=="cash") { boost::shared_ptr con(new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff)); payoff = con; } else if (binType=="asset") { boost::shared_ptr aon(new QuantLib::AssetOrNothingPayoff(optionType, strike)); payoff = aon; } else if (binType=="gap") { boost::shared_ptr gap(new QuantLib::GapPayoff(optionType, strike, cashPayoff)); payoff = gap; } else { throw std::range_error("Unknown binary option type " + binType); } QuantLib::Date exDate = today + length; boost::shared_ptr exercise; if (excType=="american") { boost::shared_ptr amEx(new QuantLib::AmericanExercise(today, exDate)); exercise = amEx; } else if (excType=="european") { boost::shared_ptr euEx(new QuantLib::EuropeanExercise(exDate)); exercise = euEx; } else { throw std::range_error("Unknown binary exercise type " + excType); } boost::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); boost::shared_ptr engine; if (excType=="american") { boost::shared_ptr amEng(new QuantLib::AnalyticDigitalAmericanEngine(stochProcess)); engine = amEng; } else if (excType=="european") { boost::shared_ptr euEng(new QuantLib::AnalyticEuropeanEngine(stochProcess)); engine = euEng; } else { throw std::range_error("Unknown binary exercise type " + excType); } QuantLib::VanillaOption opt(payoff, exercise); opt.setPricingEngine(engine); Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = opt.NPV(), Rcpp::Named("delta") = opt.delta(), Rcpp::Named("gamma") = opt.gamma(), Rcpp::Named("vega") = (excType=="european") ? opt.vega() : R_NaN, Rcpp::Named("theta") = (excType=="european") ? opt.theta() : R_NaN, Rcpp::Named("rho") = (excType=="european") ? opt.rho() : R_NaN, Rcpp::Named("divRho") = (excType=="european") ? opt.dividendRho() : R_NaN, Rcpp::Named("parameters") = optionParameters); return rl; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } // dumped core when we tried last // no longer under 0.3.10 and g++ 4.0.1 (Aug 2005) RcppExport SEXP BinaryOptionImpliedVolatility(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); std::string type = Rcpp::as(rparam["type"]); double value = Rcpp::as(rparam["value"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better double volatility = Rcpp::as(rparam["volatility"]); double cashPayoff = Rcpp::as(rparam["cashPayoff"]); QuantLib::Option::Type optionType = getOptionType(type); // updated again for QuantLib 0.9.0, // cf QuantLib-0.9.0/test-suite/digitaloption.cpp QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today, qRate, dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today, rRate, dc); boost::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr payoff(new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff)); QuantLib::Date exDate = today + length; boost::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); boost::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); //boost::shared_ptr engine(new AnalyticEuropeanEngine(stochProcess)); boost::shared_ptr engine(new QuantLib::AnalyticBarrierEngine(stochProcess)); QuantLib::VanillaOption opt(payoff, exercise); opt.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("impliedVol") = opt.impliedVolatility(value, stochProcess), Rcpp::Named("parameters") = optionParameters); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP BarrierOption(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); std::string barrType = Rcpp::as(rparam["barrType"]); std::string type = Rcpp::as(rparam["type"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better double volatility = Rcpp::as(rparam["volatility"]); double barrier = Rcpp::as(rparam["barrier"]); double rebate = Rcpp::as(rparam["rebate"]); QuantLib::Barrier::Type barrierType = QuantLib::Barrier::DownIn; if (barrType=="downin") { barrierType = QuantLib::Barrier::DownIn; } else if (barrType=="upin") { barrierType = QuantLib::Barrier::UpIn; } else if (barrType=="downout") { barrierType = QuantLib::Barrier::DownOut; } else if (barrType=="upout") { barrierType = QuantLib::Barrier::UpOut; } else { throw std::range_error("Unknown barrier type " + type); } QuantLib::Option::Type optionType = getOptionType(type); // new QuantLib 0.3.5 framework, updated for 0.3.7 // updated again for QuantLib 0.9.0, // cf QuantLib-0.9.0/test-suite/barrieroption.cpp QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today, qRate, dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today,rRate,dc); boost::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); boost::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::Date exDate = today + length; boost::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); boost::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess( QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); // Size timeSteps = 1; // bool antitheticVariate = false; // bool controlVariate = false; // Size requiredSamples = 10000; // double requiredTolerance = 0.02; // Size maxSamples = 1000000; // bool isBiased = false; boost::shared_ptr engine(new QuantLib::AnalyticBarrierEngine(stochProcess)); // need to explicitly reference BarrierOption from QuantLib here QuantLib::BarrierOption barrierOption(barrierType, barrier, rebate, payoff, exercise); barrierOption.setPricingEngine(engine); Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = barrierOption.NPV(), Rcpp::Named("delta") = R_NaN, Rcpp::Named("gamma") = R_NaN, Rcpp::Named("vega") = R_NaN, Rcpp::Named("theta") = R_NaN, Rcpp::Named("rho") = R_NaN, Rcpp::Named("divRho") = R_NaN, Rcpp::Named("parameters") = optionParameters); return rl; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/bermudan.cpp0000644000175000017500000004243012271347225014131 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib function BermudanSwaption // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2011 Dirk Eddelbuettel // // $Id$ // // This program is part of the RQuantLib library for R (GNU S). // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version. // // 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 GNU General Public License for more // details. #include "rquantlib.h" // Calibrates underlying swaptions to the input volatility matrix. void calibrateModel(const boost::shared_ptr& model, const std::vector > &helpers, QuantLib::Real lambda, Rcpp::NumericVector &swaptionMat, Rcpp::NumericVector &swapLengths, Rcpp::NumericMatrix &swaptionVols) { QuantLib::Size numRows = swaptionVols.nrow(); QuantLib::Size numCols = swaptionVols.ncol(); QuantLib::LevenbergMarquardt om; model->calibrate(helpers, om,QuantLib:: EndCriteria(400,100,1.0e-8, 1.0e-8, 1.0e-8)); // Output the implied Black volatilities for (QuantLib::Size i=0; imodelValue(); QuantLib::Volatility implied = helpers[i]->impliedVolatility(npv, 1e-4, 1000, 0.05, 0.50); QuantLib::Volatility diff = implied - swaptionVols(i, numCols-i-1); Rprintf((char*) "%dx%d: model %lf, market %lf, diff %lf\n", swaptionMat[i], swapLengths[numCols-i-1], implied, swaptionVols(i, numCols-i-1), diff); } } RcppExport SEXP BermudanSwaption(SEXP params, SEXP tsQuotes, SEXP maturities, SEXP tenors, SEXP vols) { try { Rcpp::List rparam(params); Rcpp::List tslist(tsQuotes); std::vector tsnames = tslist.names(); QuantLib::Size i; //int *swaptionMat=0, *swapLengths=0; //double **swaptionVols=0; double notional = 10000; // prices in basis points QuantLib::Date todaysDate(dateFromR(Rcpp::as(rparam["tradeDate"]))); QuantLib::Date settlementDate(dateFromR(Rcpp::as(rparam["settleDate"]))); //cout << "TradeDate: " << todaysDate << endl << "Settle: " << settlementDate << endl; RQLContext::instance().settleDate = settlementDate; QuantLib::Settings::instance().evaluationDate() = todaysDate; double strike = Rcpp::as(rparam["strike"]); std::string method = Rcpp::as(rparam["method"]); std::string firstQuoteName = tsnames[0]; //tslist.getName(0); std::string interpWhat, interpHow; if(firstQuoteName.compare("flat") != 0) { // Get interpolation method (not needed for "flat" case) interpWhat = Rcpp::as(rparam["interpWhat"]); interpHow = Rcpp::as(rparam["interpHow"]); } // initialise from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; //Integer fixingDays = RQLContext::instance().fixingDays; // Any DayCounter would be fine. // ActualActual::ISDA ensures that 30 years is 30.0 QuantLib::DayCounter termStructureDayCounter = QuantLib::ActualActual(QuantLib::ActualActual::ISDA); double tolerance = 1.0e-15; boost::shared_ptr curve; if(firstQuoteName.compare("flat") == 0) { // Get flat yield curve double rateQuote = Rcpp::as(tslist[0]); //tslist.getValue(0); boost::shared_ptr flatRate(new QuantLib::SimpleQuote(rateQuote)); boost::shared_ptr ts(new QuantLib::FlatForward(settlementDate, QuantLib::Handle(flatRate), QuantLib::Actual365Fixed())); curve = ts; } else { // Get yield curve based on a set of market rates and/or prices. std::vector > curveInput; for(i = 0; i < (QuantLib::Size)tslist.size(); i++) { std::string name = tsnames[i]; //tslist.getName(i); double val = Rcpp::as(tslist[i]); //tslist.getValue(i); boost::shared_ptr rh = ObservableDB::instance().getRateHelper(name, val); // edd 2009-11-01 FIXME NULL_RateHelper no longer builds under 0.9.9 // if(rh == NULL_RateHelper) if (rh.get() == NULL) throw std::range_error("Unknown rate in getRateHelper"); curveInput.push_back(rh); } boost::shared_ptr ts = getTermStructure(interpWhat, interpHow, settlementDate, curveInput, termStructureDayCounter, tolerance); curve = ts; } //Handle rhTermStructure; //rhTermStructure.linkTo(curve); boost::shared_ptr flatRate(new QuantLib::SimpleQuote(0.04875825)); // FIXME: hardcoded? QuantLib::Handle rhTermStructure(boost::shared_ptr(new QuantLib::FlatForward(settlementDate, QuantLib::Handle(flatRate), QuantLib::Actual365Fixed()))); // Get swaption vol matrix. Rcpp::NumericMatrix swaptionVols(vols); int dim1 = swaptionVols.nrow(); int dim2 = swaptionVols.ncol(); // Get swaption maturities Rcpp::NumericVector swaptionMat(maturities); int numRows = swaptionMat.size(); // Get swap tenors Rcpp::NumericVector swapLengths(tenors); int numCols = swapLengths.size(); if (numRows*numCols != dim1*dim2) { std::ostringstream oss; oss << "Swaption vol matrix size (" << dim1 << " x " << dim2 << ") " << "incompatible\nwith size of swaption maturity vector (" << numRows << ") and swap tenor vector (" << numCols << ")"; throw std::range_error(oss.str()); } // Create dummy swap to get schedules. QuantLib::Frequency fixedLegFrequency = QuantLib::Annual; QuantLib::BusinessDayConvention fixedLegConvention = QuantLib::Unadjusted; QuantLib::BusinessDayConvention floatingLegConvention = QuantLib::ModifiedFollowing; QuantLib::DayCounter fixedLegDayCounter = QuantLib::Thirty360(QuantLib::Thirty360::European); QuantLib::Frequency floatingLegFrequency = QuantLib::Semiannual; QuantLib::Rate dummyFixedRate = 0.03; boost::shared_ptr indexSixMonths(new QuantLib::Euribor6M(rhTermStructure)); QuantLib::Date startDate = calendar.advance(settlementDate, 1, QuantLib::Years, floatingLegConvention); QuantLib::Date maturity = calendar.advance(startDate, 5, QuantLib::Years, floatingLegConvention); QuantLib::Schedule fixedSchedule(startDate,maturity, QuantLib::Period(fixedLegFrequency),calendar, fixedLegConvention,fixedLegConvention, QuantLib::DateGeneration::Forward,false); QuantLib::Schedule floatSchedule(startDate,maturity,QuantLib::Period(floatingLegFrequency), calendar, floatingLegConvention,floatingLegConvention, QuantLib::DateGeneration::Forward,false); QuantLib::VanillaSwap::Type type = QuantLib::VanillaSwap::Payer; boost::shared_ptr swap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, dummyFixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths->dayCounter())); swap->setPricingEngine(boost::shared_ptr(new QuantLib::DiscountingSwapEngine(rhTermStructure))); // Find the ATM or break-even rate QuantLib::Rate fixedATMRate = swap->fairRate(); QuantLib::Rate fixedRate; if(strike < 0) // factor instead of real strike fixedRate = fixedATMRate * (-strike); else fixedRate = strike; // The swap underlying the Bermudan swaption. boost::shared_ptr mySwap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths->dayCounter())); swap->setPricingEngine(boost::shared_ptr(new QuantLib::DiscountingSwapEngine(rhTermStructure))); // Build swaptions that will be used to calibrate model to // the volatility matrix. std::vector swaptionMaturities; for(i = 0; i < (QuantLib::Size)numRows; i++) swaptionMaturities.push_back(QuantLib::Period(swaptionMat[i], QuantLib::Years)); // Swaptions used for calibration std::vector > swaptions; // List of times that have to be included in the timegrid std::list times; for (i=0; i<(QuantLib::Size)numRows; i++) { //boost::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols[i][numCols-i-1])); boost::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols(i, numCols-i-1))); swaptions.push_back(boost::shared_ptr(new QuantLib::SwaptionHelper(swaptionMaturities[i], QuantLib::Period(swapLengths[numCols-i-1], QuantLib::Years), QuantLib::Handle(vol), indexSixMonths, indexSixMonths->tenor(), indexSixMonths->dayCounter(), indexSixMonths->dayCounter(), rhTermStructure))); swaptions.back()->addTimesTo(times); } // Building time-grid QuantLib::TimeGrid grid(times.begin(), times.end(), 30); // Get Bermudan swaption exercise dates. std::vector bermudanDates; const std::vector >& leg = swap->fixedLeg(); for (i=0; i coupon = boost::dynamic_pointer_cast(leg[i]); bermudanDates.push_back(coupon->accrualStartDate()); } boost::shared_ptr bermudaExercise(new QuantLib::BermudanExercise(bermudanDates)); // Price based on method selected. if (method.compare("G2Analytic") == 0) { boost::shared_ptr modelG2(new QuantLib::G2(rhTermStructure)); Rprintf((char*)"G2/Jamshidian (analytic) calibration\n"); for(i = 0; i < swaptions.size(); i++) swaptions[i]->setPricingEngine(boost::shared_ptr(new QuantLib::G2SwaptionEngine(modelG2, 6.0, 16))); calibrateModel(modelG2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); boost::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelG2, 50)); QuantLib::Swaption bermudanSwaption(mySwap, bermudaExercise); bermudanSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelG2->params()[0], Rcpp::Named("sigma") = modelG2->params()[1], Rcpp::Named("b") = modelG2->params()[2], Rcpp::Named("eta") = modelG2->params()[3], Rcpp::Named("rho") = modelG2->params()[4], Rcpp::Named("price") = bermudanSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate, Rcpp::Named("params") = params); } else if (method.compare("HWAnalytic") == 0) { boost::shared_ptr modelHW(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (analytic) calibration\n"); for (i=0; isetPricingEngine(boost::shared_ptr(new QuantLib::JamshidianSwaptionEngine(modelHW))); calibrateModel(modelHW, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); boost::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelHW, 50)); QuantLib::Swaption bermudanSwaption(mySwap, bermudaExercise); bermudanSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelHW->params()[0], Rcpp::Named("sigma") = modelHW->params()[1], Rcpp::Named("price") = bermudanSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate, Rcpp::Named("params") = params); } else if (method.compare("HWTree") == 0) { boost::shared_ptr modelHW2(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (tree) calibration\n"); for (i=0; isetPricingEngine(boost::shared_ptr(new QuantLib::TreeSwaptionEngine(modelHW2,grid))); calibrateModel(modelHW2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); boost::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelHW2, 50)); QuantLib::Swaption bermudanSwaption(mySwap, bermudaExercise); bermudanSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelHW2->params()[0], Rcpp::Named("sigma") = modelHW2->params()[1], Rcpp::Named("price") = bermudanSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate, Rcpp::Named("params") = params); } else if (method.compare("BKTree") == 0) { boost::shared_ptr modelBK(new QuantLib::BlackKarasinski(rhTermStructure)); Rprintf((char*)"Black-Karasinski (tree) calibration\n"); for (i=0; isetPricingEngine(boost::shared_ptr(new QuantLib::TreeSwaptionEngine(modelBK,grid))); calibrateModel(modelBK, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); boost::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelBK, 50)); QuantLib::Swaption bermudanSwaption(mySwap, bermudaExercise); bermudanSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelBK->params()[0], Rcpp::Named("sigma") = modelBK->params()[1], Rcpp::Named("price") = bermudanSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate, Rcpp::Named("params") = params); } else { throw std::range_error("Unknown method in BermudanSwaption\n"); } } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/bonds.cpp0000644000175000017500000017664312271347225013457 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2012 Dirk Eddelbuettel // Copyright (C) 2009 - 2012 Khanh Nguyen and Dirk Eddelbuettel // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include RcppExport SEXP ZeroPriceByYield(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); double yield = Rcpp::as(rparam["yield"]); double faceAmount = Rcpp::as(rparam["faceAmount"]); double dayCounter = Rcpp::as(rparam["dayCounter"]); double frequency = Rcpp::as(rparam["frequency"]); double businessDayConvention = Rcpp::as(rparam["businessDayConvention"]); double compound = Rcpp::as(rparam["compound"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); //setup bond QuantLib::Integer fixingDays = 2; QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); QuantLib::Date todaysDate = calendar.advance(issueDate, -fixingDays, QuantLib::Days); QuantLib::Settings::instance().evaluationDate() = todaysDate; QuantLib::Natural settlementDays = 1; QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); double redemption = 100; QuantLib::ZeroCouponBond zbond(settlementDays, calendar, faceAmount, maturityDate, bdc, redemption, issueDate); //return cleanPrice QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Compounding cp = getCompounding(compound); QuantLib::Frequency freq = getFrequency(frequency); return Rcpp::wrap(zbond.cleanPrice(yield, dc, cp, freq)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP ZeroYield(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); double price = Rcpp::as(rparam["price"]); double faceAmount = Rcpp::as(rparam["faceAmount"]); double dayCounter = Rcpp::as(rparam["dayCounter"]); double frequency = Rcpp::as(rparam["frequency"]); double businessDayConvention = Rcpp::as(rparam["businessDayConvention"]); double compound = Rcpp::as(rparam["compound"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); //setup bond QuantLib::Integer fixingDays = 2; QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); QuantLib::Date todaysDate = calendar.advance(issueDate, -fixingDays, QuantLib::Days); QuantLib::Settings::instance().evaluationDate() = todaysDate; QuantLib::Natural settlementDays = 1; QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); double redemption = 100; QuantLib::ZeroCouponBond zbond(settlementDays, calendar, faceAmount, maturityDate, bdc, redemption, issueDate); //return yield QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Compounding cp = getCompounding(compound); QuantLib::Frequency freq = getFrequency(frequency); return Rcpp::wrap(zbond.yield(price, dc, cp, freq)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP ZeroBond(SEXP bondparam, QuantLib::Handle &discountCurve, SEXP dateparams) { try { Rcpp::List rparam(bondparam); double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); double redemption = Rcpp::as(rparam["redemption"]); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); QuantLib::Date refDate(dateFromR(Rcpp::as(misc["refDate"]))); QuantLib::Settings::instance().evaluationDate() = refDate; /* test-suite/bonds.cpp */ //set up QuantLib::BusinessDayConvetion QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); // set up calendar -- FIXME: use utils function getCalendar instead QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::ZeroCouponBond bond(settlementDays, calendar, faceAmount, maturityDate, bdc, redemption, issueDate); boost::shared_ptr bondEngine(new QuantLib::DiscountingBondEngine(discountCurve)); bond.setPricingEngine(bondEngine); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(QuantLib::Actual360(), QuantLib::Compounded, QuantLib::Annual), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FixedBond(SEXP bondparam, SEXP ratesVec, QuantLib::Handle &discountCurve, SEXP dateparams){ try { Rcpp::List rparam(bondparam); double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); QuantLib::Date effectiveDate(dateFromR(Rcpp::as(rparam["effectiveDate"]))); double redemption = Rcpp::as(rparam["redemption"]); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); double terminationDateConvention = Rcpp::as(misc["terminationDateConvention"]); double dateGeneration = Rcpp::as(misc["dateGeneration"]); double endOfMonthRule = Rcpp::as(misc["endOfMonth"]); //extract coupon rates vector Rcpp::NumericVector rates(ratesVec); //set up BusinessDayConvetion QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::BusinessDayConvention tbdc = getBusinessDayConvention(terminationDateConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::DateGeneration::Rule rule = getDateGenerationRule(dateGeneration); bool endOfMonth = (endOfMonthRule==1) ? true : false; //set up calendar QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us") { calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } //build the bond QuantLib::Schedule sch(effectiveDate, maturityDate, QuantLib::Period(freq), calendar, bdc, tbdc, rule, endOfMonth); QuantLib::FixedRateBond bond(settlementDays, faceAmount, sch, Rcpp::as >(rates), dc, bdc, redemption, issueDate); //bond price boost::shared_ptr bondEngine(new QuantLib::DiscountingBondEngine(discountCurve)); bond.setPricingEngine(bondEngine); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(QuantLib::Actual360(), QuantLib::Compounded, QuantLib::Annual), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FixedRateBondYield(SEXP optionParameters, SEXP ratesVec) { try { Rcpp::List rparam(optionParameters); double settlementDays = Rcpp::as(rparam["settlementDays"]); std::string cal = Rcpp::as(rparam["calendar"]); double price = Rcpp::as(rparam["price"]); double faceAmount = Rcpp::as(rparam["faceAmount"]); double businessDayConvention = Rcpp::as(rparam["businessDayConvention"]); double compound = Rcpp::as(rparam["compound"]); double redemption = Rcpp::as(rparam["redemption"]); double dayCounter = Rcpp::as(rparam["dayCounter"]); double frequency = Rcpp::as(rparam["period"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); QuantLib::Date effectiveDate(dateFromR(Rcpp::as(rparam["effectiveDate"]))); //extract coupon rates vector Rcpp::NumericVector rates(ratesVec); //set up BusinessDayConvetion QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::Compounding cp = getCompounding(compound); //set up calendar QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } //build the bond QuantLib::Schedule sch(effectiveDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::FixedRateBond bond(settlementDays, faceAmount, sch, Rcpp::as >(rates), dc, bdc, redemption, issueDate); return Rcpp::wrap(bond.yield(price, dc, cp, freq)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FixedRateBondPriceByYield(SEXP optionParameters, SEXP ratesVec) { try { Rcpp::List rparam(optionParameters); double settlementDays = Rcpp::as(rparam["settlementDays"]); std::string cal = Rcpp::as(rparam["calendar"]); double yield = Rcpp::as(rparam["yield"]); double faceAmount = Rcpp::as(rparam["faceAmount"]); double businessDayConvention = Rcpp::as(rparam["businessDayConvention"]); double compound = Rcpp::as(rparam["compound"]); double redemption = Rcpp::as(rparam["redemption"]); double dayCounter = Rcpp::as(rparam["dayCounter"]); double frequency = Rcpp::as(rparam["period"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); QuantLib::Date effectiveDate(dateFromR(Rcpp::as(rparam["effectiveDate"]))); //extract coupon rates vector Rcpp::NumericVector rates(ratesVec); //set up BusinessDayConvetion QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::Compounding cp = getCompounding(compound); //set up calendar QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } //build the bond QuantLib::Schedule sch(effectiveDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::FixedRateBond bond(settlementDays, faceAmount, sch, Rcpp::as >(rates), dc, bdc, redemption, issueDate); return Rcpp::wrap(bond.cleanPrice(yield, dc, cp, freq)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } SEXP FloatingBond(SEXP bondparam, SEXP gearingsVec, SEXP spreadsVec, SEXP capsVec, SEXP floorsVec, QuantLib::Handle &index, SEXP indexparams, QuantLib::Handle &discountCurve, SEXP dateparams) { try { Rcpp::List rparam(bondparam); double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); QuantLib::Date effectiveDate(dateFromR(Rcpp::as(rparam["effectiveDate"]))); double redemption = Rcpp::as(rparam["redemption"]); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); double terminationDateConvention = Rcpp::as(misc["terminationDateConvention"]); double dateGeneration = Rcpp::as(misc["dateGeneration"]); double endOfMonthRule = Rcpp::as(misc["endOfMonth"]); double fixingDays = Rcpp::as(misc["fixingDays"]); //build schedule QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::BusinessDayConvention tbdc = getBusinessDayConvention(terminationDateConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::DateGeneration::Rule rule = getDateGenerationRule(dateGeneration); bool endOfMonth = (endOfMonthRule==1) ? true : false; //set up calendar QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us") { calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::Schedule sch(effectiveDate, maturityDate, QuantLib::Period(freq), calendar, bdc, tbdc, rule, endOfMonth); //extract gearings, spreads, caps, and floors std::vector gearings = getDoubleVector(gearingsVec); std::vector spreads = getDoubleVector(spreadsVec); std::vector caps = getDoubleVector(capsVec); std::vector floors = getDoubleVector(floorsVec); Rcpp::List iborparams(indexparams); std::string type = Rcpp::as(iborparams["type"]); double length = Rcpp::as(iborparams["length"]); std::string inTermOf = Rcpp::as(iborparams["inTermOf"]); boost::shared_ptr iborindex(new QuantLib::USDLibor(6 * QuantLib::Months, index)); if (type=="USDLibor") { if (inTermOf=="Months") { boost::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Months, index)); iborindex = temp; } else if (inTermOf=="Years") { boost::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Years, index)); iborindex = temp; } } //build the bond QuantLib::FloatingRateBond bond(settlementDays, faceAmount, sch, iborindex, dc, bdc, fixingDays, gearings, spreads, caps, floors, false, redemption, issueDate); //bond price boost::shared_ptr bondEngine(new QuantLib::DiscountingBondEngine(discountCurve)); bond.setPricingEngine(bondEngine); //cashflow boost::shared_ptr pricer(new QuantLib::BlackIborCouponPricer(QuantLib::Handle())); setCouponPricer(bond.cashflows(),pricer); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(QuantLib::Actual360(), QuantLib::Compounded, QuantLib::Annual), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FloatBond1(SEXP bond, SEXP gearings, SEXP caps, SEXP spreads, SEXP floors, SEXP indexparams, SEXP index, SEXP discountCurve, SEXP dateparams) { try{ QuantLib::Handle discount_curve(getFlatCurve(discountCurve)); QuantLib::Handle ibor_curve(getFlatCurve(index)); return Rcpp::wrap(FloatingBond(bond, gearings, caps, spreads, floors, ibor_curve, indexparams, discount_curve, dateparams)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FloatBond2(SEXP bond, SEXP gearings, SEXP caps, SEXP spreads, SEXP floors, SEXP indexparams, SEXP index_params, SEXP index_tsQuotes, SEXP index_times, SEXP discountCurve, SEXP dateparams) { try{ QuantLib::Handle discount_curve(getFlatCurve(discountCurve)); QuantLib::Handle ibor_curve(buildTermStructure(index_params, index_tsQuotes, index_times)); return Rcpp::wrap(FloatingBond(bond, gearings, caps, spreads, floors, ibor_curve, indexparams, discount_curve, dateparams)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FloatBond3(SEXP bond, SEXP gearings, SEXP caps, SEXP spreads, SEXP floors, SEXP indexparams, SEXP index, SEXP discount_params, SEXP discount_tsQuotes, SEXP discount_times, SEXP dateparams) { try { QuantLib::Handle ibor_curve(getFlatCurve(index)); QuantLib::Handle discount_curve(buildTermStructure(discount_params, discount_tsQuotes, discount_times)); return Rcpp::wrap(FloatingBond(bond, gearings, caps, spreads, floors, ibor_curve, indexparams, discount_curve, dateparams)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FloatBond4(SEXP bond, SEXP gearings, SEXP caps, SEXP spreads, SEXP floors, SEXP indexparams, SEXP index_params, SEXP index_tsQuotes, SEXP index_times, SEXP discount_params, SEXP discount_tsQuotes, SEXP discount_times, SEXP dateparams) { try { QuantLib::Handle ibor_curve(buildTermStructure(index_params, index_tsQuotes, index_times)); QuantLib::Handle discount_curve(buildTermStructure(discount_params, discount_tsQuotes, discount_times)); return Rcpp::wrap(FloatingBond(bond, gearings, caps, spreads, floors, ibor_curve, indexparams, discount_curve, dateparams)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FloatingWithRebuiltCurve(SEXP bondparams, SEXP gearings, SEXP spreads, SEXP caps, SEXP floors, SEXP indexparams, SEXP iborDateSexp, SEXP iborzeroSexp, SEXP dateSexp, SEXP zeroSexp, SEXP dateparams) { try { QuantLib::Handle ibor_curve(rebuildCurveFromZeroRates(iborDateSexp, iborzeroSexp)); QuantLib::Handle curve(rebuildCurveFromZeroRates(dateSexp, zeroSexp)); SEXP flrtbond = FloatingBond(bondparams, gearings, caps, spreads, floors, ibor_curve, indexparams, curve, dateparams); return flrtbond; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP FixedRateWithRebuiltCurve(SEXP bondparam, SEXP ratesVec, SEXP dateSexp, SEXP zeroSexp, SEXP dateparams){ try { QuantLib::Handle curve(rebuildCurveFromZeroRates(dateSexp, zeroSexp)); return Rcpp::wrap(FixedBond(bondparam, ratesVec, curve, dateparams)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP ZeroBondWithRebuiltCurve(SEXP bond, SEXP dateSexp, SEXP zeroSexp, SEXP dateparams){ try { QuantLib::Handle curve(rebuildCurveFromZeroRates(dateSexp, zeroSexp)); return Rcpp::wrap(ZeroBond(bond, curve, dateparams)); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP ConvertibleZeroBond(SEXP bondparams, SEXP process, SEXP dividendYieldDateSexp, SEXP dividendYieldZeroSexp, SEXP rffDateSexp, SEXP rffZeroSexp, SEXP dividendScheduleFrame, SEXP callabilityScheduleFrame, SEXP dateparams) { try { QuantLib::DividendSchedule dividendSchedule = getDividendSchedule(dividendScheduleFrame); QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); Rcpp::List rparam(bondparams); //double faceAmount = Rcpp::as(rparam["faceAmount"); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); double redemption = Rcpp::as(rparam["redemption"]); std::string exercise = Rcpp::as(rparam["exercise"]); double creditSpreadQuote = Rcpp::as(rparam["creditSpread"]); double conversionRatio = Rcpp::as(rparam["conversionRatio"]); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); QuantLib::Date todayDate = issueDate; QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us") { calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::RelinkableHandle underlying; QuantLib::RelinkableHandle volatility; boost::shared_ptr blackProcess; QuantLib::Handle dividendYield(rebuildCurveFromZeroRates(dividendYieldDateSexp, dividendYieldZeroSexp)); QuantLib::Handle rff(rebuildCurveFromZeroRates(rffDateSexp, rffZeroSexp)); Rcpp::List processParam(process); double underlyingQuote = Rcpp::as(processParam["underlying"]); double volatilityQuote = Rcpp::as(processParam["volatility"]); underlying.linkTo(boost::shared_ptr(new QuantLib::SimpleQuote(underlyingQuote))); boost::shared_ptr vol(new QuantLib::SimpleQuote( volatilityQuote )); volatility.linkTo(flatVol(todayDate, vol, dc)); blackProcess = boost::shared_ptr(new QuantLib::BlackScholesMertonProcess(underlying, dividendYield, rff, volatility)); QuantLib::RelinkableHandle creditSpread; creditSpread.linkTo(boost::shared_ptr(new QuantLib::SimpleQuote(creditSpreadQuote))); boost::shared_ptr euExercise(new QuantLib::EuropeanExercise(maturityDate)); boost::shared_ptr amExercise(new QuantLib::AmericanExercise(issueDate, maturityDate)); boost::shared_ptr ex = (exercise == "eu") ? euExercise : amExercise; QuantLib::Size timeSteps = 1001; boost::shared_ptr engine(new QuantLib::BinomialConvertibleEngine(blackProcess, timeSteps)); QuantLib::Handle discountCurve(boost::shared_ptr(new QuantLib::ForwardSpreadedTermStructure(rff, creditSpread))); QuantLib::Schedule sch(issueDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::ConvertibleZeroCouponBond bond(ex, conversionRatio, dividendSchedule, callabilitySchedule, creditSpread, issueDate, settlementDays, dc, sch, redemption); bond.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(QuantLib::Actual360(), QuantLib::Compounded, QuantLib::Annual), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP ConvertibleFixedBond(SEXP bondparams, SEXP coupon, SEXP process, SEXP dividendYieldDateSexp, SEXP dividendYieldZeroSexp, SEXP rffDateSexp, SEXP rffZeroSexp, SEXP dividendScheduleFrame, SEXP callabilityScheduleFrame, SEXP dateparams) { try { QuantLib::DividendSchedule dividendSchedule = getDividendSchedule(dividendScheduleFrame); QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); Rcpp::List rparam(bondparams); //double faceAmount = Rcpp::as(rparam["faceAmount"); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); double redemption = Rcpp::as(rparam["redemption"]); std::string exercise = Rcpp::as(rparam["exercise"]); double creditSpreadQuote = Rcpp::as(rparam["creditSpread"]); double conversionRatio = Rcpp::as(rparam["conversionRatio"]); //extract coupon rates vector Rcpp::NumericVector rates(coupon); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); QuantLib::Date todayDate = issueDate; QuantLib::Settings::instance().evaluationDate() = todayDate; QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::RelinkableHandle underlying; QuantLib::RelinkableHandle volatility; QuantLib::Handle dividendYield(rebuildCurveFromZeroRates(dividendYieldDateSexp, dividendYieldZeroSexp)); QuantLib::Handle rff(rebuildCurveFromZeroRates(rffDateSexp, rffZeroSexp)); Rcpp::List processParam(process); double underlyingQuote = Rcpp::as(processParam["underlying"]); double volatilityQuote = Rcpp::as(processParam["volatility"]); underlying.linkTo(boost::shared_ptr(new QuantLib::SimpleQuote(underlyingQuote))); boost::shared_ptr vol(new QuantLib::SimpleQuote( volatilityQuote )); volatility.linkTo(flatVol(todayDate, vol, dc)); boost::shared_ptr blackProcess; blackProcess = boost::shared_ptr(new QuantLib::BlackScholesMertonProcess(underlying, dividendYield, rff, volatility)); // boost::shared_ptr blackProcess; //ackProcess = boost::shared_ptr( // new QuantLib::BlackScholesProcess(underlying, // rff, volatility)); QuantLib::RelinkableHandle creditSpread; creditSpread.linkTo(boost::shared_ptr(new QuantLib::SimpleQuote(creditSpreadQuote))); boost::shared_ptr euExercise(new QuantLib::EuropeanExercise(maturityDate)); boost::shared_ptr amExercise(new QuantLib::AmericanExercise(issueDate, maturityDate)); boost::shared_ptr ex = (exercise == "eu") ? euExercise : amExercise; QuantLib::Size timeSteps = 1001; boost::shared_ptr engine(new QuantLib::BinomialConvertibleEngine(blackProcess, timeSteps)); QuantLib::Handle discountCurve(boost::shared_ptr(new QuantLib::ForwardSpreadedTermStructure(rff, creditSpread))); QuantLib::Schedule sch(issueDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::ConvertibleFixedCouponBond bond(ex, conversionRatio, dividendSchedule, callabilitySchedule, creditSpread,issueDate, settlementDays, Rcpp::as >(rates), dc, sch, redemption); bond.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(QuantLib::Actual360(), QuantLib::Compounded, QuantLib::Annual), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP ConvertibleFloatingBond(SEXP bondparams, SEXP process, SEXP dividendYieldDateSexp, SEXP dividendYieldZeroSexp, SEXP rffDateSexp, SEXP rffZeroSexp, SEXP iborIndexDateSexp, SEXP iborIndexZeroSexp, SEXP indexparams, SEXP spreadVec, SEXP dividendScheduleFrame, SEXP callabilityScheduleFrame, SEXP dateparams) { try { QuantLib::DividendSchedule dividendSchedule = getDividendSchedule(dividendScheduleFrame); QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); Rcpp::List rparam(bondparams); //double faceAmount = Rcpp::as(rparam["faceAmount"); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); double redemption = Rcpp::as(rparam["redemption"]); std::string exercise = Rcpp::as(rparam["exercise"]); double creditSpreadQuote = Rcpp::as(rparam["creditSpread"]); double conversionRatio = Rcpp::as(rparam["conversionRatio"]); std::vector spreads = getDoubleVector(spreadVec); //extract iborindex curve QuantLib::Handle index(rebuildCurveFromZeroRates(iborIndexDateSexp, iborIndexZeroSexp)); Rcpp::List iborparams(indexparams); std::string type = Rcpp::as(iborparams["type"]); double length = Rcpp::as(iborparams["length"]); std::string inTermOf = Rcpp::as(iborparams["inTermOf"]); boost::shared_ptr iborindex(new QuantLib::USDLibor(6 * QuantLib::Months, index)); if (type=="USDLibor"){ if (inTermOf=="Months"){ boost::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Months, index)); iborindex = temp; } else if (inTermOf=="Years") { boost::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Years, index)); iborindex = temp; } } Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); QuantLib::Date todayDate = issueDate; QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::RelinkableHandle underlying; QuantLib::RelinkableHandle volatility; boost::shared_ptr blackProcess; QuantLib::Handle dividendYield(rebuildCurveFromZeroRates(dividendYieldDateSexp, dividendYieldZeroSexp)); QuantLib::Handle rff(rebuildCurveFromZeroRates(rffDateSexp, rffZeroSexp)); Rcpp::List processParam(process); double underlyingQuote = Rcpp::as(processParam["underlying"]); double volatilityQuote = Rcpp::as(processParam["volatility"]); underlying.linkTo(boost::shared_ptr(new QuantLib::SimpleQuote(underlyingQuote))); boost::shared_ptr vol(new QuantLib::SimpleQuote( volatilityQuote )); volatility.linkTo(flatVol(todayDate, vol, dc)); blackProcess = boost::shared_ptr(new QuantLib::BlackScholesMertonProcess(underlying, dividendYield, rff, volatility)); QuantLib::RelinkableHandle creditSpread; creditSpread.linkTo(boost::shared_ptr(new QuantLib::SimpleQuote(creditSpreadQuote))); boost::shared_ptr euExercise(new QuantLib::EuropeanExercise(maturityDate)); boost::shared_ptr amExercise(new QuantLib::AmericanExercise(issueDate, maturityDate)); boost::shared_ptr ex = (exercise == "eu") ? euExercise : amExercise; QuantLib::Size timeSteps = 1001; boost::shared_ptr engine(new QuantLib::BinomialConvertibleEngine(blackProcess, timeSteps)); QuantLib::Handle discountCurve(boost::shared_ptr(new QuantLib::ForwardSpreadedTermStructure(rff, creditSpread))); QuantLib::Natural fixingDays = 2; QuantLib::Schedule sch(issueDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::ConvertibleFloatingRateBond bond(ex, conversionRatio, dividendSchedule, callabilitySchedule, creditSpread,issueDate, settlementDays,iborindex,fixingDays, spreads, dc, sch, redemption); bond.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(QuantLib::Actual360(), QuantLib::Compounded, QuantLib::Annual), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP CallableBond(SEXP bondparams, SEXP hw, SEXP coupon, SEXP callabilityScheduleFrame, SEXP dateparams) { try { QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); Rcpp::List rparam(bondparams); double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(dateFromR(Rcpp::as(rparam["maturityDate"]))); QuantLib::Date issueDate(dateFromR(Rcpp::as(rparam["issueDate"]))); double redemption = Rcpp::as(rparam["redemption"]); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); std::string cal = Rcpp::as(misc["calendar"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); //extract coupon rates vector Rcpp::NumericVector rates(coupon); Rcpp::List hwparam(hw); double alpha = Rcpp::as(hwparam["alpha"]); double sigma = Rcpp::as(hwparam["sigma"]); double gridIntervals = Rcpp::as(hwparam["gridIntervals"]); double rate = Rcpp::as(hwparam["term"]); boost::shared_ptr rRate(new QuantLib::SimpleQuote(rate)); QuantLib::Handle termStructure(flatRate(issueDate,rRate,QuantLib::Actual360())); //QuantLib::Handle termStructure(rebuildCurveFromZeroRates( // hwTermDateSexp, // hwTermZeroSexp)); boost::shared_ptr hw0(new QuantLib::HullWhite(termStructure,alpha,sigma)); boost::shared_ptr engine0(new QuantLib::TreeCallableFixedRateBondEngine(hw0,gridIntervals)); QuantLib::Schedule sch(issueDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); //std::cout << "RQL SettleDate : " << RQLContext::instance().settleDate << std::endl; //std::cout << "RQL calendar : " << RQLContext::instance().calendar << std::endl; //std::cout << "RQL fixingDays : " << RQLContext::instance().fixingDays << std::endl; QuantLib::CallableFixedRateBond bond(settlementDays, faceAmount, sch, Rcpp::as >(rates), dc, bdc, redemption, issueDate, callabilitySchedule); bond.setPricingEngine(engine0); return Rcpp::List::create(Rcpp::Named("NPV") = bond.NPV(), Rcpp::Named("cleanPrice") = bond.cleanPrice(), Rcpp::Named("dirtyPrice") = bond.dirtyPrice(), Rcpp::Named("accruedCoupon") = bond.accruedAmount(), Rcpp::Named("yield") = bond.yield(dc, QuantLib::Compounded, freq), Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond.cashflows())); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } // RcppExport SEXP CMSBond(SEXP bondparams, SEXP iborIndex, SEXP swapIndexParam, // SEXP capsVec, SEXP floorsVec, SEXP gearingsVec, // SEXP spreadsVec, SEXP swaptionVolSEXP, SEXP atmOptionTenorsSEXP, // SEXP atmSwapTenorsSEXP, SEXP volMatrixSEXP, SEXP pricer, // SEXP iborIndexDate, SEXP iborIndexRates) // { // SEXP rl=R_NilValue; // char* exceptionMesg=NULL; // try { // std::vector gearings = getDoubleVector(gearingsVec); // std::vector spreads = getDoubleVector(spreadsVec); // std::vector caps = getDoubleVector(capsVec); // std::vector floors = getDoubleVector(floorsVec); // RcppStringVector strVec(atmOptionTenorsSEXP); // std::vector atmOptionTenors(strVec.stlVector()); // RcppStringVector strVec2(atmSwapTenorsSEXP); // std::vector atmSwapTenors(strVec2.stlVector()); // RcppMatrix m(volMatrixSEXP); // QuantLib::Handle termStructure(rebuildCurveFromZeroRates( // iborIndexDate,iborIndexRates)); // Rcppparams iborparams(iborIndex); // std::string ibortype = iborparams.getStringValue("type"); // std::string iborlength = iborparams.getStringValue("length"); // boost::shared_ptr ibor = getIborIndex(termStructure, ibortype, // iborlength); // //fix tenor to make sure it is converted by matchparam // Rcppparams swapparams(swapIndexParam); // std::string familyName = swapparams.getStringValue("familyName"); // std::double tenor = swapparams.getDoubleValue("tenor"); // std::double settlementDays = swapparams.getDoubleValue("settlementDays"); // std::string currency = swapparams.getStringValue("currency"); // std::string fixedLegTenor = swapparams.getDoubleValue("fixedLegTenor"); // std::string fixedLegConvention = swapparams.getDoubleValue("fixedLegConvention"); // std::string fixedLegDayCounter = swapparams.getDoubleValue("fixedLegDayCounter"); // std::string cal = swapparams.getStringValue("calendar"); // QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); // if (cal == "us"){ // calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); // } // else if (cal == "uk"){ // calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); // } // QuantLib::BusinessDayConvention fixedLegBDC = getBusinessDayConvention(fixedLegConvention); // QuantLib::DayCounter fixedLedDC = getDayCounter(fixedLegDayCounter); // boost::shared_ptr swapIndex(new QuantLib::SwapIndex(familiName, // getPeriodFromString(fixedLegTenor), // settlemenDays, // currency, // calendar, // getPeriodFromString(fixedLegTenor), // fixedLegBDC, // fixedLegDC, // ibor)); // Rcppparams pricerparams(pricer); // std::string pricerType = pricerparams.getStringValue("type"); // std::double zeroMeanRev = pricerparams.getDoubleValue("zeroMeanRev"); // Rcppparams swaptionVolParams(swaptionVolSEXP); // std::string swaptionCal = swaptionVolParams.getStringValue("calendar"); // std::double swaptionBDC = swaptionVolParams.getDoubleValue("businessDayConvention"); // std::double swaptionDC = swaptionVolParams.getDoubleValue("dayCounter"); // QuantLib::Handle atmVol; // atmVol = QuantLib::Handle( // boost::shared_ptr // new QuantLib::SwaptionVolatilityMatrix(swapCal, // swaptionBDC, // atmOptionTenors, // atmSwapTenors, // m, // swaptionDC)); // boost::shared_ptr pricer(new QuantLib::NumericHaganPricer(atmVol, yieldCurveModel, // zeroMeanRev)); // Rcppparams rparams(bondparams); // Rcpp::Date mDate = Rcpp::Date(Rcpp::as(rparam["maturityDate"])); // Rcpp::Date iDate = Rcpp::Date(Rcpp::as(rparam["issueDate"])); // Rcpp::Date pDate = Rcpp::Date(Rcpp::as(rparam["paymentDate"])); // QuantLib::Date maturityDate(dateFromR(mDate)); // QuantLib::Date issueDate(dateFromR(iDate)); // QuantLib::Date paymentDate(dateFromR(pDate)); // std::double nomial = rparams.getDoubleValue("nomial"); // CappedFlooredCmsCoupon coupon(paymentDate, nomial, // issueDate, maturityDate, // settlementDays, swapIndex, // gearings, spreads, // caps, floors, // issueDate, maturityDate, // dayCounter); // pricer->setSwaptionVolatility(atmVol); // coupon.setPricer(pricer); // } catch(std::exception& ex) { // exceptionMesg = copyMessageToR(ex.what()); // } catch(...) { // exceptionMesg = copyMessageToR("unknown reason"); // } // if(exceptionMesg != NULL) // Rf_error(exceptionMesg); // return rl; // } RcppExport SEXP FittedBondCurve(SEXP curveparams, SEXP lengthVec, SEXP couponVec,SEXP marketVec, SEXP dateparams){ try { //extract length, coupon and market prices vector Rcpp::NumericVector length(lengthVec); Rcpp::NumericVector coupons(couponVec); Rcpp::NumericVector marketQuotes(marketVec); Rcpp::List misc(dateparams); double settlementDays = Rcpp::as(misc["settlementDays"]); double dayCounter = Rcpp::as(misc["dayCounter"]); double frequency = Rcpp::as(misc["period"]); double businessDayConvention = Rcpp::as(misc["businessDayConvention"]); Rcpp::List curvepam(curveparams); std::string method = Rcpp::as(curvepam["method"]); Rcpp::Date oDate = Rcpp::as(curvepam["origDate"]); QuantLib::Date origDate(dateFromR(oDate)); QuantLib::Settings::instance().evaluationDate() = origDate; const QuantLib::Size numberOfBonds = length.size(); std::vector< boost::shared_ptr > quote; for (QuantLib::Size i=0; i cp(new QuantLib::SimpleQuote(marketQuotes[i])); quote.push_back(cp); } std::vector< QuantLib::RelinkableHandle > quoteHandle(numberOfBonds); for (QuantLib::Size i=0; i > instrumentsA; for (QuantLib::Size j=0; j < static_cast(length.size()); j++) { QuantLib::Date dated = origDate; QuantLib::Date issue = origDate; QuantLib::Date maturity = calendar.advance(issue, length[j], QuantLib::Years); QuantLib::Schedule schedule(dated, maturity, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); boost::shared_ptr helperA( new QuantLib::FixedRateBondHelper(quoteHandle[j], settlementDays, 100.0, schedule, std::vector(1,coupons[j]), dc, bdc, redemption, issue)); instrumentsA.push_back(helperA); } bool constrainAtZero = true; QuantLib::Real tolerance = 1.0e-10; QuantLib::Size max = 5000; boost::shared_ptr curve; if (method=="ExponentialSplinesFitting") { QuantLib::ExponentialSplinesFitting exponentialSplines(constrainAtZero); boost::shared_ptr ts1 (new QuantLib::FittedBondDiscountCurve(settlementDays, calendar, instrumentsA, dc, exponentialSplines, tolerance, max)); curve = ts1; } else if (method == "SimplePolynomialFitting"){ double degree = Rcpp::as(curvepam["degree"]); QuantLib::SimplePolynomialFitting simplePolynomial(degree, constrainAtZero); boost::shared_ptr ts2 (new QuantLib::FittedBondDiscountCurve(settlementDays, calendar, instrumentsA, dc, simplePolynomial, tolerance, max)); curve = ts2; } else if (method == "NelsonSiegelFitting"){ QuantLib::NelsonSiegelFitting nelsonSiegel; boost::shared_ptr ts3 (new QuantLib::FittedBondDiscountCurve(settlementDays, calendar, instrumentsA, dc, nelsonSiegel, tolerance, max)); curve = ts3; } // Return discount, forward rate, and zero coupon curves // int numCol = 3; // std::vector colNames(numCol); // colNames[0] = "date"; // colNames[1] = "zeroRates"; // colNames[2] = "discount"; // RcppFrame frame(colNames); QuantLib::Date current = curve->referenceDate();; int n = curve->maxDate() - curve->referenceDate(); //std::cout << curve->maxDate() << " " << curve->referenceDate() << " " << n << std::endl; Rcpp::DateVector dates(n); Rcpp::NumericVector zr(n); Rcpp::NumericVector di(n); for (int i = 0; i < n; i++) { QuantLib::Date d = current; dates[i] = Rcpp::Date(d.month(), d.dayOfMonth(), d.year()); zr[i] = curve->zeroRate(current, QuantLib::ActualActual(), QuantLib::Continuous); di[i] = curve->discount(current); current++; } Rcpp::DataFrame frame = Rcpp::DataFrame::create(Rcpp::Named("date") = dates, Rcpp::Named("zeroRates") = zr, Rcpp::Named("discount") = di); return Rcpp::List::create(Rcpp::Named("table") = frame); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/calendars.cpp0000644000175000017500000003311512271347225014270 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2009 Dirk Eddelbuettel // Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include // returns a reference-counted pointer to a matching Calendar object boost::shared_ptr getCalendar(const std::string &calstr) { boost::shared_ptr pcal; if (calstr == "TARGET") { // generic calendar pcal.reset(new QuantLib::TARGET()); } else if (calstr == "Brazil") { pcal.reset(new QuantLib::Brazil()); } else if (calstr == "Canada" || calstr == "Canada/Settlement") { pcal.reset(new QuantLib::Canada(QuantLib::Canada::Settlement)); } else if (calstr == "Canada/TSX") { pcal.reset(new QuantLib::Canada(QuantLib::Canada::TSX)); } else if (calstr == "Germany" || calstr == "Germany/FrankfurtStockExchange") { pcal.reset(new QuantLib::Germany(QuantLib::Germany::FrankfurtStockExchange)); } else if (calstr == "Germany/Settlement") { pcal.reset(new QuantLib::Germany(QuantLib::Germany::Settlement)); } else if (calstr == "Germany/Xetra") { pcal.reset(new QuantLib::Germany(QuantLib::Germany::Xetra)); } else if (calstr == "Germany/Eurex") { pcal.reset(new QuantLib::Germany(QuantLib::Germany::Eurex)); } else if (calstr == "Italy" || calstr == "Italy/Settlement") { pcal.reset(new QuantLib::Italy(QuantLib::Italy::Settlement)); } else if (calstr == "Italy/Exchange") { pcal.reset(new QuantLib::Italy(QuantLib::Italy::Exchange)); } else if (calstr == "Japan" || calstr == "Japan/Settlement") { pcal.reset(new QuantLib::Japan()); } else if (calstr == "SouthKorea" || calstr == "SouthKorea/Settlement") { pcal.reset(new QuantLib::SouthKorea(QuantLib::SouthKorea::Settlement)); } else if (calstr == "SouthKorea/KRX") { pcal.reset(new QuantLib::SouthKorea(QuantLib::SouthKorea::KRX)); } else if (calstr == "UnitedKingdom" || calstr == "UnitedKingdom/Settlement") { pcal.reset(new QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Settlement)); } else if (calstr == "UnitedKingdom/Exchange") { pcal.reset(new QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange)); } else if (calstr == "UnitedKingdom/Metals") { pcal.reset(new QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Metals)); } else if (calstr == "UnitedStates" || calstr == "UnitedStates/Settlement") { pcal.reset(new QuantLib::UnitedStates(QuantLib::UnitedStates::Settlement)); } else if (calstr == "UnitedStates/NYSE") { pcal.reset(new QuantLib::UnitedStates(QuantLib::UnitedStates::NYSE)); } else if (calstr == "UnitedStates/GovernmentBond") { pcal.reset(new QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond)); } else if (calstr == "UnitedStates/NERC") { pcal.reset(new QuantLib::UnitedStates(QuantLib::UnitedStates::NERC)); } else { throw std::invalid_argument("Calendar " + calstr + " not recognised "); } return pcal; } RcppExport SEXP setContext(SEXP parSEXP) { try { Rcpp::List par(parSEXP); // set fixingDays and settleDate RQLContext::instance().fixingDays = Rcpp::as(par["fixingDays"]); RQLContext::instance().settleDate = QuantLib::Date(dateFromR(Rcpp::as(par["settleDate"]))); boost::shared_ptr pcal( getCalendar(Rcpp::as(par["calendar"])) ); RQLContext::instance().calendar = *pcal; // set calendar in global singleton } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP isBusinessDay(SEXP calSexp, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector bizdays(n); for (int i=0; iisBusinessDay(day); } return Rcpp::wrap(bizdays); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP isHoliday(SEXP calSexp, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector hdays(n); for (int i=0; iisHoliday(day); } return Rcpp::wrap(hdays); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP isWeekend(SEXP calSexp, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector weekends(n); for (int i=0; iisWeekend(day.weekday()); } return Rcpp::wrap(weekends); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP isEndOfMonth(SEXP calSexp, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector eom(n); for (int i=0; iisEndOfMonth(day); } return Rcpp::wrap(eom); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP endOfMonth(SEXP calSexp, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector eom(n); for (int i=0; iendOfMonth(day); dates[i] = Rcpp::Date(eom[i].month(), eom[i].dayOfMonth(), eom[i].year()); } return Rcpp::wrap(dates); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP adjust(SEXP calSexp, SEXP bdcSEXP, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); QuantLib::BusinessDayConvention bdc = getBusinessDayConvention( Rcpp::as(bdcSEXP) ); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector adjusted(n); for (int i=0; iadjust(day, bdc); dates[i] = Rcpp::Date(adjusted[i].month(), adjusted[i].dayOfMonth(), adjusted[i].year()); } return Rcpp::wrap(dates); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP advance1(SEXP calSexp, SEXP params, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::List rparam(params); QuantLib::BusinessDayConvention bdc = getBusinessDayConvention( Rcpp::as(rparam["bdc"]) ); double emr = Rcpp::as(rparam["emr"]); double amount = Rcpp::as(rparam["amount"]); double unit = Rcpp::as(rparam["unit"]); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector advance(n); for (int i=0; iadvance(day, amount,getTimeUnit(unit), bdc, (emr == 1)?true:false ); dates[i] = Rcpp::Date(advance[i].month(), advance[i].dayOfMonth(), advance[i].year()); } return Rcpp::wrap(dates); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP advance2(SEXP calSexp, SEXP param, SEXP dateSexp){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::List rparam(param); QuantLib::BusinessDayConvention bdc = getBusinessDayConvention( Rcpp::as(rparam["bdc"]) ); double emr = Rcpp::as(rparam["emr"]); double period = Rcpp::as(rparam["period"]); Rcpp::DateVector dates = Rcpp::DateVector(dateSexp); int n = dates.size(); std::vector advance(n); for (int i=0; iadvance(day, QuantLib::Period(getFrequency(period)), bdc, (emr == 1)?true:false ); dates[i] = Rcpp::Date(advance[i].month(), advance[i].dayOfMonth(), advance[i].year()); } return Rcpp::wrap(dates); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP businessDaysBetween(SEXP calSexp, SEXP params, SEXP from, SEXP to){ try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::List rparam(params); double ifirst = Rcpp::as(rparam["includeFirst"]); double ilast = Rcpp::as(rparam["includeLast"]); Rcpp::DateVector dates1 = Rcpp::DateVector(from); Rcpp::DateVector dates2 = Rcpp::DateVector(to); int n = dates1.size(); std::vector between(n); for (int i=0; ibusinessDaysBetween(day1, day2, (ifirst == 1) ? true: false, (ilast == 1) ? true: false); } return Rcpp::wrap(between); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP holidayList(SEXP calSexp, SEXP params) { try { boost::shared_ptr pcal( getCalendar(Rcpp::as(calSexp)) ); Rcpp::List rparam(params); int iw = Rcpp::as(rparam["includeWeekends"]); std::vector holidays = QuantLib::Calendar::holidayList(*pcal, QuantLib::Date(dateFromR(Rcpp::as( rparam["from"]))), QuantLib::Date(dateFromR(Rcpp::as( rparam["to"] ))), iw == 1 ? true : false); if (holidays.size() > 0) { Rcpp::DateVector dv( holidays.size() ); for (unsigned int i = 0; i< holidays.size(); i++){ dv[i] = Rcpp::Date(holidays[i].month(), holidays[i].dayOfMonth(), holidays[i].year()); } return Rcpp::wrap(dv); } else { return R_NilValue; } } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/curves.cpp0000644000175000017500000002465112271347225013650 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib helper functions for term structure construction // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2012 Dirk Eddelbuettel // // $Id$ // // This program is part of the RQuantLib library for R (GNU S). // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version. // // 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 GNU General Public License for more // details. //#ifndef _MSC_VER //#include //#endif #include // Database of interest rate instrument contract details. ObservableDB::ObservableDB() { db_["d1w"] = new RQLObservable(RQLDeposit, 1, 0, QuantLib::Weeks); db_["d1m"] = new RQLObservable(RQLDeposit, 1, 0, QuantLib::Months); db_["d2m"] = new RQLObservable(RQLDeposit, 2, 0, QuantLib::Months); db_["d3m"] = new RQLObservable(RQLDeposit, 3, 0, QuantLib::Months); db_["d6m"] = new RQLObservable(RQLDeposit, 6, 0, QuantLib::Months); db_["d9m"] = new RQLObservable(RQLDeposit, 9, 0, QuantLib::Months); db_["d1y"] = new RQLObservable(RQLDeposit, 1, 0, QuantLib::Years); db_["s2y"] = new RQLObservable(RQLSwap, 2, 0, QuantLib::Years); db_["s3y"] = new RQLObservable(RQLSwap, 3, 0, QuantLib::Years); db_["s5y"] = new RQLObservable(RQLSwap, 5, 0, QuantLib::Years); db_["s10y"] = new RQLObservable(RQLSwap, 10, 0, QuantLib::Years); db_["s15y"] = new RQLObservable(RQLSwap, 15, 0, QuantLib::Years); db_["s20y"] = new RQLObservable(RQLSwap, 20, 0, QuantLib::Years); db_["s30y"] = new RQLObservable(RQLSwap, 30, 0, QuantLib::Years); db_["fut1"] = new RQLObservable(RQLFuture, 1, 0, QuantLib::Months); db_["fut2"] = new RQLObservable(RQLFuture, 2, 0, QuantLib::Months); db_["fut3"] = new RQLObservable(RQLFuture, 3, 0, QuantLib::Months); db_["fut4"] = new RQLObservable(RQLFuture, 4, 0, QuantLib::Months); db_["fut5"] = new RQLObservable(RQLFuture, 5, 0, QuantLib::Months); db_["fut6"] = new RQLObservable(RQLFuture, 6, 0, QuantLib::Months); db_["fut7"] = new RQLObservable(RQLFuture, 7, 0, QuantLib::Months); db_["fut8"] = new RQLObservable(RQLFuture, 8, 0, QuantLib::Months); db_["fra3x6"] = new RQLObservable(RQLFRA, 3, 6, QuantLib::Months); db_["fra6x9"] = new RQLObservable(RQLFRA, 6, 9, QuantLib::Months); db_["fra6x12"] = new RQLObservable(RQLFRA, 6, 12, QuantLib::Months); } // Get RateHelper used to build the yield curve corresponding to a // database key ('ticker') and observed rate/price. boost::shared_ptr ObservableDB::getRateHelper(std::string& ticker, QuantLib::Rate r) { RQLMapIterator iter = db_.find(ticker); if(iter == db_.end()) { std::ostringstream oss; oss << "Unknown curve construction instrument: " << ticker; throw std::range_error(oss.str()); } RQLObservable *p = iter->second; RQLObservableType type = p->getType(); int n1 = p->getN1(), n2 = p->getN2(); QuantLib::TimeUnit units = p->getUnits(); QuantLib::Date settlementDate = RQLContext::instance().settleDate; QuantLib::Calendar calendar = RQLContext::instance().calendar; QuantLib::Integer fixingDays = RQLContext::instance().fixingDays; QuantLib::DayCounter depositDayCounter = QuantLib::Actual360(); // Tried to use a switch statement here, but there was an // internal compiler error using g++ Version 3.2.2. if(type == RQLDeposit) { boost::shared_ptr quote(new QuantLib::SimpleQuote(r)); boost::shared_ptr depo(new QuantLib::DepositRateHelper( QuantLib::Handle(quote), n1*units, fixingDays, calendar, QuantLib::ModifiedFollowing, true, /*fixingDays,*/ depositDayCounter)); return depo; } else if (type == RQLSwap) { QuantLib::Frequency swFixedLegFrequency = QuantLib::Annual; QuantLib::BusinessDayConvention swFixedLegConvention = QuantLib::Unadjusted; QuantLib::DayCounter swFixedLegDayCounter = QuantLib::Thirty360(QuantLib::Thirty360::European); boost::shared_ptr swFloatingLegIndex(new QuantLib::Euribor6M); boost::shared_ptr quote(new QuantLib::SimpleQuote(r)); boost::shared_ptr swap(new QuantLib::SwapRateHelper( QuantLib::Handle(quote), n1*QuantLib::Years, /*fixingDays,*/ calendar, swFixedLegFrequency, swFixedLegConvention, swFixedLegDayCounter, swFloatingLegIndex)); return swap; } else if(type == RQLFuture) { QuantLib::Integer futMonths = 3; QuantLib::Date imm = QuantLib::IMM::nextDate(settlementDate); for(int i = 1; i < n1; i++) imm = QuantLib::IMM::nextDate(imm+1); //Rcpp::Rcout << "Curves: IMM Date is " << imm << std::endl; boost::shared_ptr quote(new QuantLib::SimpleQuote(r)); boost::shared_ptr future(new QuantLib::FuturesRateHelper( QuantLib::Handle(quote), imm, futMonths, calendar, QuantLib::ModifiedFollowing, true, // added bool endOfMonth variable depositDayCounter)); return future; } else if(type == RQLFRA) { boost::shared_ptr quote(new QuantLib::SimpleQuote(r)); boost::shared_ptr FRA(new QuantLib::FraRateHelper( QuantLib::Handle(quote), n1, n2, fixingDays, calendar, QuantLib::ModifiedFollowing, true, /*fixingDays,*/ depositDayCounter)); return FRA; } else { throw std::range_error("Bad type in curve construction"); } } // Return the term structure built using a set of RateHelpers (curveInput) // employing the specified interpolation method and day counter. boost::shared_ptr getTermStructure (std::string& interpWhat, std::string& interpHow, const QuantLib::Date& settlementDate, const std::vector >& curveInput, QuantLib::DayCounter& dayCounter, QuantLib::Real tolerance) { if(interpWhat.compare("discount") == 0 && interpHow.compare("linear") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("discount") == 0 && interpHow.compare("loglinear") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("discount") == 0 && interpHow.compare("spline") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("forward") == 0 && interpHow.compare("linear") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("forward") == 0 && interpHow.compare("loglinear") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("forward") == 0 && interpHow.compare("spline") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("zero") == 0 && interpHow.compare("linear") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("zero") == 0 && interpHow.compare("loglinear") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else if(interpWhat.compare("zero") == 0 && interpHow.compare("spline") == 0) { boost::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else { Rprintf((char*)"interpWhat = %s\n", interpWhat.c_str()); Rprintf((char*)"interpHow = %s\n", interpHow.c_str()); throw std::range_error("What/How term structure options not recognized"); } } RQuantLib/src/daycounter.cpp0000644000175000017500000000604112271347225014507 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2009 - 2011 Dirk Eddelbuettel and Khanh Nguyen // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include "rquantlib.h" RcppExport SEXP dayCount(SEXP startDates, SEXP endDates, SEXP dayCounter){ try { Rcpp::DateVector s = Rcpp::DateVector(startDates); Rcpp::DateVector e = Rcpp::DateVector(endDates); Rcpp::NumericVector dc(dayCounter); int n = dc.size(); std::vector result(n); for (int i=0; i< n; i++){ QuantLib::Date d1( dateFromR(s[i]) ); QuantLib::Date d2( dateFromR(e[i]) ); QuantLib::DayCounter counter = getDayCounter(dc[i]); result[i] = static_cast(counter.dayCount(d1, d2)); } return Rcpp::wrap(result); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP yearFraction(SEXP startDates, SEXP endDates, SEXP dayCounter){ try { Rcpp::DateVector s = Rcpp::DateVector(startDates); Rcpp::DateVector e = Rcpp::DateVector(endDates); Rcpp::NumericVector dc(dayCounter); int n = dc.size(); std::vector result(n); for (int i=0; i< n; i++){ QuantLib::Date d1( dateFromR(s[i]) ); QuantLib::Date d2( dateFromR(e[i]) ); QuantLib::DayCounter counter = getDayCounter(dc[i]); result[i] = (double)counter.yearFraction(d1, d2); } return Rcpp::wrap(result); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } // this could go into another file too... maybe regroup all calendar / date functions? RcppExport SEXP setEvaluationDate(SEXP evalDateSEXP) { try { // set the date QuantLib::Settings::instance().evaluationDate() = QuantLib::Date(dateFromR(Rcpp::as(evalDateSEXP))); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/discount.cpp0000644000175000017500000001557612271347225014177 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib function DiscountCurve // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2009 Dirk Eddelbuettel // Copyright (C) 2009 - 2011 Dirk Eddelbuettel and Khanh Nguyen // Copyright (C) 2012 - 2013 Dirk Eddelbuettel // // $Id$ // // This program is part of the RQuantLib library for R (GNU S). // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version. // // 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 GNU General Public License for more // details. #include "rquantlib.h" RcppExport SEXP DiscountCurve(SEXP params, SEXP tsQuotes, SEXP times) { try { Rcpp::List rparam(params); // parameter in list Rcpp::List tslist(tsQuotes); std::vector tsNames = tslist.names(); Rcpp::NumericVector tvec(times); int i; QuantLib::Date todaysDate( dateFromR( Rcpp::as(rparam["tradeDate"]))); QuantLib::Date settlementDate( dateFromR( Rcpp::as(rparam["settleDate"]))); //std::cout << "TradeDate: " << todaysDate << std::endl << "Settle: " << settlementDate << std::endl; RQLContext::instance().settleDate = settlementDate; QuantLib::Date evalDate = QuantLib::Settings::instance().evaluationDate(); QuantLib::Settings::instance().evaluationDate() = todaysDate; std::string firstQuoteName = tsNames[0]; double dt = Rcpp::as(rparam["dt"]); std::string interpWhat, interpHow; bool flatQuotes = true; if (firstQuoteName.compare("flat") != 0) { // Get interpolation method (not needed for "flat" case) interpWhat = Rcpp::as(rparam["interpWhat"]); interpHow = Rcpp::as(rparam["interpHow"]); flatQuotes = false; } // initialise from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; //Integer fixingDays = RQLContext::instance().fixingDays; // Any DayCounter would be fine. // ActualActual::ISDA ensures that 30 years is 30.0 QuantLib::DayCounter termStructureDayCounter = QuantLib::ActualActual(QuantLib::ActualActual::ISDA); double tolerance = 1.0e-8; boost::shared_ptr curve; if (firstQuoteName.compare("flat") == 0) { // Create a flat term structure. double rateQuote = Rcpp::as(tslist[0]); //boost::shared_ptr flatRate(new SimpleQuote(rateQuote)); //boost::shared_ptr ts(new FlatForward(settlementDate, // Handle(flatRate), // ActualActual())); boost::shared_ptr rRate(new QuantLib::SimpleQuote(rateQuote)); curve = flatRate(settlementDate,rRate,QuantLib::ActualActual()); } else { // Build curve based on a set of observed rates and/or prices. std::vector > curveInput; for(i = 0; i < tslist.size(); i++) { std::string name = tsNames[i]; double val = Rcpp::as(tslist[i]); boost::shared_ptr rh = ObservableDB::instance().getRateHelper(name, val); // edd 2009-11-01 FIXME NULL_RateHelper no longer builds under 0.9.9 // if (rh == NULL_RateHelper) if (rh.get() == NULL) throw std::range_error("Unknown rate in getRateHelper"); curveInput.push_back(rh); } boost::shared_ptr ts = getTermStructure(interpWhat, interpHow, settlementDate, curveInput, termStructureDayCounter, tolerance); curve = ts; } // Return discount, forward rate, and zero coupon curves //int numCol = 2; //std::vector colNames(numCol); //colNames[0] = "date"; //colNames[1] = "zeroRates"; //RcppFrame frame(colNames); int ntimes = tvec.size(); //Rf_length(times); //SEXP disc = PROTECT(Rf_allocVector(REALSXP, ntimes)); //SEXP fwds = PROTECT(Rf_allocVector(REALSXP, ntimes)); //SEXP zero = PROTECT(Rf_allocVector(REALSXP, ntimes)); Rcpp::NumericVector disc(ntimes), fwds(ntimes), zero(ntimes); QuantLib::Date current = settlementDate; for (i = 0; i < ntimes; i++) { //t = REAL(times)[i]; //REAL(disc)[i] = curve->discount(t); //REAL(fwds)[i] = curve->forwardRate(t, t+dt, Continuous); //REAL(zero)[i] = curve->zeroRate(t, Continuous); double t = tvec[i]; disc[i] = curve->discount(t); fwds[i] = curve->forwardRate(t, t+dt, QuantLib::Continuous); zero[i] = curve->zeroRate(t, QuantLib::Continuous); } int n = curve->maxDate() - settlementDate; //std::cout << "MaxDate " << curve->maxDate() << std::endl; //std::cout << "Settle " << settlementDate << std::endl; //n = std::min(300, n); QuantLib::Settings::instance().evaluationDate() = evalDate; Rcpp::DateVector dates(n); Rcpp::NumericVector zeroRates(n); QuantLib::Date d = current; for (int i = 0; imaxDate(); i++){ dates[i] = Rcpp::Date(d.month(), d.dayOfMonth(), d.year()); zeroRates[i] = curve->zeroRate(current, QuantLib::ActualActual(), QuantLib::Continuous); d++; } //Rcpp::DataFrame frame = Rcpp::DataFrame::create(Rcpp::Named("date") = dates, // Rcpp::Named("zeroRates") = zeroRates); Rcpp::List frame = Rcpp::List::create(Rcpp::Named("date") = dates, Rcpp::Named("zeroRates") = zeroRates); Rcpp::List rl = Rcpp::List::create(Rcpp::Named("times") = tvec, Rcpp::Named("discounts") = disc, Rcpp::Named("forwards") = fwds, Rcpp::Named("zerorates") = zero, Rcpp::Named("flatQuotes") = flatQuotes, Rcpp::Named("params") = params, Rcpp::Named("table") = frame); return rl; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/hullwhite.cpp0000644000175000017500000002130312271347225014335 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include RcppExport SEXP HullWhiteCalibrationUsingCap(SEXP termStrcDateVec, SEXP termStrcZeroVec, SEXP capDataDF, SEXP iborDateVec, SEXP iborZeroVec, SEXP iborparams, SEXP evaluationDate) { try { Rcpp::DateVector dv(evaluationDate); QuantLib::Date evalDate(dateFromR(dv[0])); QuantLib::Settings::instance().evaluationDate() = evalDate; QuantLib::Handle term(rebuildCurveFromZeroRates(termStrcDateVec, termStrcZeroVec)); //set up ibor index QuantLib::Handle indexStrc(rebuildCurveFromZeroRates(iborDateVec, iborZeroVec)); Rcpp::List param(iborparams); std::string iborType = Rcpp::as(param["type"]); boost::shared_ptr index = buildIborIndex(iborType, indexStrc); //process capDataDF std::vector > caps; try { Rcpp::DataFrame capDF(capDataDF); Rcpp::NumericVector i0v = capDF[0]; Rcpp::CharacterVector s1v = capDF[1]; Rcpp::NumericVector d2v = capDF[2]; Rcpp::NumericVector i3v = capDF[3]; Rcpp::NumericVector i4v = capDF[4]; Rcpp::NumericVector i5v = capDF[5]; //std::vector > table = capDF.getTableData(); //int nrow = table.size(); int nrow = i0v.size(); for (int row=0; row(s1v[row])); boost::shared_ptr vol(new QuantLib::SimpleQuote(d2v[row])); QuantLib::DayCounter dc = getDayCounter(i4v[row]); boost::shared_ptr helper(new QuantLib::CapHelper(p, QuantLib::Handle(vol), index, getFrequency(i3v[row]), dc, (i5v[row]==1) ? true : false, term)); boost::shared_ptr engine(new QuantLib::BlackCapFloorEngine(term, d2v[row])); helper->setPricingEngine(engine); caps.push_back(helper); } } catch(std::exception& ex) { forward_exception_to_r(ex); } //set up the HullWhite model boost::shared_ptr model(new QuantLib::HullWhite(term)); //calibrate the data QuantLib::LevenbergMarquardt optimizationMethod(1.0e-8,1.0e-8,1.0e-8); QuantLib::EndCriteria endCriteria(10000, 100, 1e-6, 1e-8, 1e-8); model->calibrate(caps, optimizationMethod, endCriteria); //EndCriteria::Type ecType = model->endCriteria(); //return the result QuantLib::Array xMinCalculated = model->params(); return Rcpp::List::create(Rcpp::Named("alpha") = xMinCalculated[0], Rcpp::Named("sigma") = xMinCalculated[1]); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP HullWhiteCalibrationUsingSwap(SEXP termStrcDateVec, SEXP termStrcZeroVec, SEXP swapDataDF, SEXP iborDateVec, SEXP iborZeroVec, SEXP iborparams, SEXP evaluationDate){ try { Rcpp::DateVector dv(evaluationDate); QuantLib::Date evalDate(dateFromR(dv[0])); QuantLib::Settings::instance().evaluationDate() = evalDate; //set up the HullWhite model QuantLib::Handle term(rebuildCurveFromZeroRates(termStrcDateVec, termStrcZeroVec)); boost::shared_ptr model(new QuantLib::HullWhite(term)); //set up ibor index QuantLib::Handle indexStrc(rebuildCurveFromZeroRates(iborDateVec, iborZeroVec)); Rcpp::List param(iborparams); std::string iborType = Rcpp::as(param["type"]); boost::shared_ptr index = buildIborIndex(iborType, indexStrc); //process capDataDF boost::shared_ptr engine(new QuantLib::JamshidianSwaptionEngine(model)); std::vector > swaps; try { //RcppFrame swapDF(swapDataDF); Rcpp::DataFrame swapDF(swapDataDF); Rcpp::NumericVector i0v = swapDF[0]; Rcpp::CharacterVector s1v = swapDF[1]; Rcpp::NumericVector i2v = swapDF[2]; Rcpp::CharacterVector s3v = swapDF[3]; Rcpp::NumericVector d4v = swapDF[4]; Rcpp::NumericVector i5v = swapDF[5]; Rcpp::CharacterVector s6v = swapDF[6]; Rcpp::NumericVector i7v = swapDF[7]; Rcpp::NumericVector i8v = swapDF[8]; //std::vector > table = swapDF.getTableData(); //int nrow = table.size(); int nrow = i0v.size(); for (int row=0; row(s1v[row])); QuantLib::Period length = periodByTimeUnit(i0v[row], Rcpp::as(s3v[row])); boost::shared_ptr vol(new QuantLib::SimpleQuote(d4v[row])); QuantLib::Period fixedLegTenor = periodByTimeUnit(i5v[row], Rcpp::as(s6v[row])); QuantLib::DayCounter fixedLegDayCounter = getDayCounter(i7v[row]); QuantLib::DayCounter floatingLegDayCounter = getDayCounter(i8v[row]); boost::shared_ptr helper(new QuantLib::SwaptionHelper(maturity, length, QuantLib::Handle(vol), index, fixedLegTenor, fixedLegDayCounter, floatingLegDayCounter, term)); helper->setPricingEngine(engine); swaps.push_back(helper); } } catch(std::exception& ex) { forward_exception_to_r(ex); } //calibrate the data QuantLib::LevenbergMarquardt optimizationMethod(1.0e-8,1.0e-8,1.0e-8); QuantLib::EndCriteria endCriteria(10000, 100, 1e-6, 1e-8, 1e-8); model->calibrate(swaps, optimizationMethod, endCriteria); //EndCriteria::Type ecType = model->endCriteria(); //return the result QuantLib::Array xMinCalculated = model->params(); return Rcpp::List::create(Rcpp::Named("alpha") = xMinCalculated[0], Rcpp::Named("sigma") = xMinCalculated[1]); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/implieds.cpp0000644000175000017500000001532112271347225014141 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2009 Dirk Eddelbuettel // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include "rquantlib.h" RcppExport SEXP EuropeanOptionImpliedVolatility(SEXP optionParameters) { const QuantLib::Size maxEvaluations = 100; const double tolerance = 1.0e-6; try { Rcpp::List rparam(optionParameters); std::string type = Rcpp::as(rparam["type"]); double value = Rcpp::as(rparam["value"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better double volatility = Rcpp::as(rparam["volatility"]); QuantLib::Option::Type optionType = getOptionType(type); QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; // new framework as per QuantLib 0.3.5 // updated for 0.3.7 QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today,qRate,dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today,rRate,dc); QuantLib::Date exDate = today + length; boost::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); double implVol = 0.0; // just to remove a warning... boost::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS, Analytic, QuantLib::Null(), QuantLib::Null()); boost::shared_ptr process = makeProcess(spot, qTS, rTS,volTS); double volguess = volatility; vol->setValue(volguess); implVol = option->impliedVolatility(value, process, tolerance, maxEvaluations); return Rcpp::List::create(Rcpp::Named("impliedVol") = implVol, Rcpp::Named("parameters") = optionParameters); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP AmericanOptionImpliedVolatility(SEXP optionParameters) { const QuantLib::Size maxEvaluations = 100; const double tolerance = 1.0e-6; try { Rcpp::List rparam(optionParameters); std::string type = Rcpp::as(rparam["type"]); double value = Rcpp::as(rparam["value"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better double volguess = Rcpp::as(rparam["volatility"]); QuantLib::Option::Type optionType = getOptionType(type); QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; // new framework as per QuantLib 0.3.5 QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr vol(new QuantLib::SimpleQuote(volguess)); boost::shared_ptr volTS = flatVol(today, vol,dc); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today,qRate,dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today,rRate,dc); QuantLib::Date exDate = today + length; QuantLib::Settings::instance().evaluationDate() = today; //boost::shared_ptr exercise(new EuropeanExercise(exDate)); boost::shared_ptr exercise(new QuantLib::AmericanExercise(today, exDate)); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); boost::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS, JR); boost::shared_ptr process = makeProcess(spot, qTS, rTS,volTS); double implVol = 0.0; // just to remove a warning... implVol = option->impliedVolatility(value, process, tolerance, maxEvaluations); return Rcpp::List::create(Rcpp::Named("impliedVol") = implVol, Rcpp::Named("parameters") = optionParameters); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/modules.cpp0000644000175000017500000000572012271347225014005 0ustar00eddedd// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // trying something with Rcpp modules #include using namespace QuantLib; Real BlackFormula(std::string type, Real strike, Real fwd, Real stdDev, Real discount, Real displacement) { if (type=="call") return blackFormula(Option::Call, strike, fwd, stdDev, discount, displacement); else if (type=="put") return blackFormula(Option::Put, strike, fwd, stdDev, discount, displacement); else { Rcpp::stop("Unrecognised option type"); return(-42); // never reached } } Real BlackFormulaImpliedStdDevApproximation(std::string type, Real strike, Real fwd, Real blackPrice, Real discount, Real displacement) { if (type=="call") return blackFormulaImpliedStdDevApproximation(Option::Call, strike, fwd, blackPrice, discount, displacement); else if (type=="put") return blackFormulaImpliedStdDevApproximation(Option::Put, strike, fwd, blackPrice, discount, displacement); else { Rcpp::stop("Unrecognised option type"); return(-42); // never reached } } RCPP_MODULE(BlackMod) { using namespace Rcpp; function("BlackFormula", // name of the identifier at the R level &BlackFormula, // function pointer to helper function defined above List::create(Named("type") = "character", Named("strike") = "numeric", // function arguments including default value Named("fwd") = "numeric", Named("stddev") = "numeric", Named("discount") = 1.0, // cf ql/pricingengines/blackformula.hpp Named("displacement") = 0.0), // cf ql/pricingengines/blackformula.hpp "Black (1976) formula for an option [note that stdev=vol*sqrt(timeToExp)]"); function("BlackFormulaImpliedStdDevApproximation", // name of the identifier at the R level &BlackFormulaImpliedStdDevApproximation, // function pointer to helper function defined above List::create(Named("type") = "character", Named("strike") = "numeric", // function arguments including default value Named("fwd") = "numeric", Named("blackPrice") = "numeric", Named("discount") = 1.0, // cf ql/pricingengines/blackformula.hpp Named("displacement") = 0.0), // cf ql/pricingengines/blackformula.hpp "Approximated Black 1976 implied standard deviation, i.e. volatility*sqrt(timeToMaturityBlack"); // also see blackFormulaImpliedStdDev() } class Bonds; RCPP_EXPOSED_CLASS(Bonds) RCPP_MODULE(BondsMod) { Rcpp::class_("Bond") ; } RQuantLib/src/utils.cpp0000644000175000017500000005523512271347225013503 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2012 Dirk Eddelbuettel // Copyright (C) 2005 - 2006 Dominick Samperi // Copyright (C) 2009 - 2012 Dirk Eddelbuettel and Khanh Nguyen // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include QuantLib::Option::Type getOptionType(const std::string &type) { QuantLib::Option::Type optionType; if (type=="call") { optionType = QuantLib::Option::Call; } else if (type=="put") { optionType = QuantLib::Option::Put; } else { throw std::range_error("Unknown option " + type); } return optionType; } // cf QuantLib-0.9.0/test-suite/europeanoption.cpp boost::shared_ptr makeOption(const boost::shared_ptr& payoff, const boost::shared_ptr& exercise, const boost::shared_ptr& u, const boost::shared_ptr& q, const boost::shared_ptr& r, const boost::shared_ptr& vol, EngineType engineType, QuantLib::Size binomialSteps, QuantLib::Size samples) { boost::shared_ptr stochProcess = makeProcess(u,q,r,vol); boost::shared_ptr engine; typedef boost::shared_ptr spPE; // shorthand used below switch (engineType) { case Analytic: engine = spPE(new QuantLib::AnalyticEuropeanEngine(stochProcess)); break; case JR: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case CRR: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case EQP: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case TGEO: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case TIAN: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case LR: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case JOSHI: engine = spPE(new QuantLib::BinomialVanillaEngine(stochProcess, binomialSteps)); break; case FiniteDifferences: engine = spPE(new QuantLib::FDEuropeanEngine(stochProcess, binomialSteps, samples)); break; case Integral: engine = spPE(new QuantLib::IntegralEngine(stochProcess)); break; case PseudoMonteCarlo: engine = QuantLib::MakeMCEuropeanEngine(stochProcess) .withStepsPerYear(1) .withSamples(samples) .withSeed(42); break; case QuasiMonteCarlo: engine = QuantLib::MakeMCEuropeanEngine(stochProcess) .withStepsPerYear(1) .withSamples(samples); break; default: QL_FAIL("Unknown engine type"); } boost::shared_ptr option(new QuantLib::EuropeanOption(payoff, exercise)); option->setPricingEngine(engine); return option; } // QuantLib option setup utils, copied from the test-suite sources boost::shared_ptr buildTermStructure(SEXP params, SEXP tsQuotes, SEXP times){ boost::shared_ptr curve; try { Rcpp::List rparam(params); Rcpp::List tslist(tsQuotes); Rcpp::CharacterVector tsnames = tslist.names(); QuantLib::Date todaysDate( dateFromR( Rcpp::as(rparam["tradeDate"]))); QuantLib::Date settlementDate( dateFromR( Rcpp::as(rparam["settleDate"]))); // cout << "TradeDate: " << todaysDate << endl << "Settle: " << settlementDate << endl; RQLContext::instance().settleDate = settlementDate; QuantLib::Settings::instance().evaluationDate() = todaysDate; std::string firstQuoteName = Rcpp::as(tsnames[0]); //double dt = rparam.getDoubleValue("dt"); std::string interpWhat, interpHow; if (firstQuoteName.compare("flat") != 0) { // Get interpolation method (not needed for "flat" case) interpWhat = Rcpp::as(rparam["interpWhat"]); interpHow = Rcpp::as(rparam["interpHow"]); } // initialise from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; //Integer fixingDays = RQLContext::instance().fixingDays; // Any DayCounter would be fine; ActualActual::ISDA ensures that 30 years is 30.0 QuantLib::DayCounter termStructureDayCounter = QuantLib::ActualActual(QuantLib::ActualActual::ISDA); double tolerance = 1.0e-15; if (firstQuoteName.compare("flat") == 0) { // Create a flat term structure. double rateQuote = Rcpp::as(tslist[0]); boost::shared_ptr flatRate(new QuantLib::SimpleQuote(rateQuote)); boost::shared_ptr ts(new QuantLib::FlatForward(settlementDate, QuantLib::Handle(flatRate), QuantLib::Actual365Fixed())); curve = ts; } else { // Build curve based on a set of observed rates and/or prices. std::vector > curveInput; for (int i = 0; i < tslist.size(); i++) { std::string name = Rcpp::as(tsnames[i]); double val = Rcpp::as(tslist[i]); boost::shared_ptr rh = ObservableDB::instance().getRateHelper(name, val); // edd 2009-11-01 FIXME NULL_RateHelper no longer builds under 0.9.9 // if (rh == NULL_RateHelper) if (rh.get() == NULL) throw std::range_error("Unknown rate in getRateHelper"); curveInput.push_back(rh); } boost::shared_ptr ts = getTermStructure(interpWhat, interpHow, settlementDate, curveInput, termStructureDayCounter, tolerance); curve = ts; } return curve; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return curve; } QuantLib::Schedule getSchedule(SEXP sch) { Rcpp::List rparam(sch); QuantLib::Date effectiveDate(dateFromR( Rcpp::as(rparam["effectiveDate"]) )); QuantLib::Date maturityDate(dateFromR( Rcpp::as(rparam["maturityDate"]) )); double frequency = Rcpp::as(rparam["period"]); std::string cal = Rcpp::as(rparam["calendar"]); double businessDayConvention = Rcpp::as(rparam["businessDayConvention"]); double terminationDateConvention = Rcpp::as(rparam["terminationDateConvention"]); QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); if (cal == "us"){ calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); } else if (cal == "uk"){ calendar = QuantLib::UnitedKingdom(QuantLib::UnitedKingdom::Exchange); } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::BusinessDayConvention t_bdc = getBusinessDayConvention(terminationDateConvention); QuantLib::Schedule schedule(effectiveDate, maturityDate, QuantLib::Period(getFrequency(frequency)), calendar, bdc, t_bdc, QuantLib::DateGeneration::Backward, false); return schedule; } boost::shared_ptr rebuildCurveFromZeroRates(SEXP dateSexp, SEXP zeroSexp) { Rcpp::DateVector rcppdates = Rcpp::DateVector(dateSexp); int n = rcppdates.size(); std::vector dates(n); for (int i = 0;i rebuilt_curve(new QuantLib::InterpolatedZeroCurve(dates, Rcpp::as< std::vector >(zeros), QuantLib::ActualActual())); return rebuilt_curve; } boost::shared_ptr getFlatCurve(SEXP flatcurve){ Rcpp::List curve(flatcurve); QuantLib::Rate riskFreeRate = Rcpp::as(curve["riskFreeRate"]); QuantLib::Date today(dateFromR( Rcpp::as(curve["todayDate"]))); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::Settings::instance().evaluationDate() = today; return flatRate(today, rRate, QuantLib::Actual360()); } boost::shared_ptr getIborIndex(SEXP index, const QuantLib::Date today){ Rcpp::List rparam(index); std::string type = Rcpp::as(rparam["type"]); if (type == "USDLibor"){ double riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); double period = Rcpp::as(rparam["period"]); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::Handle curve(flatRate(today, rRate, QuantLib::Actual360())); boost::shared_ptr iindex(new QuantLib::USDLibor(period * QuantLib::Months, curve)); return iindex; } else return boost::shared_ptr(); } std::vector getDoubleVector(SEXP vecSexp) { if (::Rf_length(vecSexp) == 0) { return(std::vector()); } else { return std::vector( Rcpp::as >( Rcpp::NumericVector(vecSexp) ) ); } } boost::shared_ptr makeFlatCurve(const QuantLib::Date& today, const boost::shared_ptr& forward, const QuantLib::DayCounter& dc) { return boost::shared_ptr(new QuantLib::FlatForward(today, QuantLib::Handle(forward), dc)); } boost::shared_ptr flatRate(const QuantLib::Date& today, const boost::shared_ptr& forward, const QuantLib::DayCounter& dc) { return boost::shared_ptr(new QuantLib::FlatForward(today, QuantLib::Handle(forward), dc)); } boost::shared_ptr makeFlatVolatility(const QuantLib::Date& today, const boost::shared_ptr& vol, const QuantLib::DayCounter dc) { return boost::shared_ptr(new QuantLib::BlackConstantVol(today, QuantLib::NullCalendar(), QuantLib::Handle(vol), dc)); } boost::shared_ptr flatVol(const QuantLib::Date& today, const boost::shared_ptr& vol, const QuantLib::DayCounter& dc) { return boost::shared_ptr( new QuantLib::BlackConstantVol(today, QuantLib::NullCalendar(), QuantLib::Handle(vol), dc)); } typedef QuantLib::BlackScholesMertonProcess BSMProcess; // shortcut boost::shared_ptr makeProcess(const boost::shared_ptr& u, const boost::shared_ptr& q, const boost::shared_ptr& r, const boost::shared_ptr& vol) { return boost::shared_ptr(new BSMProcess(QuantLib::Handle(u), QuantLib::Handle(q), QuantLib::Handle(r), QuantLib::Handle(vol))); } // R uses dates indexed to Jan 1, 1970. RcppDate uses an internal Julian Date representation, // but Quantlib uses the 'spreadsheet' format indexed to 1905 so we need to adjust // int dateFromR(const RcppDate &d) { // return(d.getJDN() - RcppDate::Jan1970Offset + RcppDate::QLtoJan1970Offset); // } static const unsigned int QLtoJan1970Offset = 25569; // Offset between R / Unix epoch // R and Rcpp::Date use the same 'days since epoch' representation; QL uses Excel style int dateFromR(const Rcpp::Date &d) { return(d.getDate() + QLtoJan1970Offset); } QuantLib::DayCounter getDayCounter(const double n){ if (n==0) return QuantLib::Actual360(); else if (n==1) return QuantLib::Actual365Fixed(); else if (n==2) return QuantLib::ActualActual(); else if (n==3) return QuantLib::Business252(); else if (n==4) return QuantLib::OneDayCounter(); else if (n==5) return QuantLib::SimpleDayCounter(); else return QuantLib::Thirty360(); } QuantLib::BusinessDayConvention getBusinessDayConvention(const double n){ if (n==0) return QuantLib::Following; else if (n==1) return QuantLib::ModifiedFollowing; else if (n==2) return QuantLib::Preceding; else if (n==3) return QuantLib::ModifiedPreceding; else return QuantLib::Unadjusted; } QuantLib::Compounding getCompounding(const double n){ if (n==0) return QuantLib::Simple; else if (n==1) return QuantLib::Compounded; else if (n==2) return QuantLib::Continuous; else return QuantLib::SimpleThenCompounded; } QuantLib::Frequency getFrequency(const double n){ if (n==-1) return QuantLib::NoFrequency; else if (n==0) return QuantLib::Once; else if (n==1) return QuantLib::Annual; else if (n==2) return QuantLib::Semiannual; else if (n==3) return QuantLib::EveryFourthMonth; else if (n==4) return QuantLib::Quarterly; else if (n==6) return QuantLib::Bimonthly; else if (n==12) return QuantLib::Monthly; else if (n==13) return QuantLib::EveryFourthWeek; else if (n==26) return QuantLib::Biweekly; else if (n==52) return QuantLib::Weekly; else if (n==365) return QuantLib::Daily; else return QuantLib::OtherFrequency; } QuantLib::Period periodByTimeUnit(int length, std::string unit){ QuantLib::TimeUnit tu = QuantLib::Years; if (unit=="Days") tu = QuantLib::Days; if (unit=="Weeks") tu = QuantLib::Weeks; if (unit=="Months") tu = QuantLib::Months; return QuantLib::Period(length, tu); } QuantLib::TimeUnit getTimeUnit(const double n){ if (n==0) return QuantLib::Days; else if (n==1) return QuantLib::Weeks; else if (n==2) return QuantLib::Months; else return QuantLib::Years; } QuantLib::DateGeneration::Rule getDateGenerationRule(const double n){ if (n==0) return QuantLib::DateGeneration::Backward; else if (n==1) return QuantLib::DateGeneration::Forward; else if (n==2) return QuantLib::DateGeneration::Zero; else if (n==3) return QuantLib::DateGeneration::ThirdWednesday; else if (n==4) return QuantLib::DateGeneration::Twentieth; else return QuantLib::DateGeneration::TwentiethIMM; } boost::shared_ptr buildIborIndex(std::string type, const QuantLib::Handle& iborStrc){ if (type == "Euribor10M") return boost::shared_ptr(new QuantLib::Euribor10M(iborStrc)); if (type == "Euribor11M") return boost::shared_ptr(new QuantLib::Euribor11M(iborStrc)); if (type == "Euribor1M") return boost::shared_ptr(new QuantLib::Euribor1M(iborStrc)); if (type == "Euribor1Y") return boost::shared_ptr(new QuantLib::Euribor1Y(iborStrc)); if (type == "Euribor2M") return boost::shared_ptr(new QuantLib::Euribor2M(iborStrc)); if (type == "Euribor2W") return boost::shared_ptr(new QuantLib::Euribor2W(iborStrc)); if (type == "Euribor3M") return boost::shared_ptr(new QuantLib::Euribor3M(iborStrc)); if (type == "Euribor3W") return boost::shared_ptr(new QuantLib::Euribor3W(iborStrc)); if (type == "Euribor4M") return boost::shared_ptr(new QuantLib::Euribor4M(iborStrc)); if (type == "Euribor5M") return boost::shared_ptr(new QuantLib::Euribor5M(iborStrc)); if (type == "Euribor6M") return boost::shared_ptr(new QuantLib::Euribor6M(iborStrc)); if (type == "Euribor7M") return boost::shared_ptr(new QuantLib::Euribor7M(iborStrc)); if (type == "Euribor8M") return boost::shared_ptr(new QuantLib::Euribor8M(iborStrc)); if (type == "Euribor9M") return boost::shared_ptr(new QuantLib::Euribor9M(iborStrc)); if (type == "EuriborSW") return boost::shared_ptr(new QuantLib::EuriborSW(iborStrc)); return boost::shared_ptr(); } Rcpp::DataFrame getCashFlowDataFrame(const QuantLib::Leg &bondCashFlow) { Rcpp::DateVector dates(bondCashFlow.size()); Rcpp::NumericVector amount(bondCashFlow.size()); for (unsigned int i = 0; i< bondCashFlow.size(); i++){ QuantLib::Date d = bondCashFlow[i]->date(); dates[i] = Rcpp::Date(d.month(), d.dayOfMonth(), d.year()); amount[i] = bondCashFlow[i]->amount(); } return Rcpp::DataFrame::create(Rcpp::Named("Date") = dates, Rcpp::Named("Amount") = amount); } QuantLib::DividendSchedule getDividendSchedule(SEXP dividendScheduleFrame) { QuantLib::DividendSchedule dividendSchedule; try { Rcpp::DataFrame divScheDF(dividendScheduleFrame); Rcpp::CharacterVector s0v = divScheDF[0]; Rcpp::NumericVector n1v = divScheDF[1]; Rcpp::NumericVector n2v = divScheDF[2]; Rcpp::NumericVector n3v = divScheDF[3]; int nrow = s0v.size(); for (int row=0; row(new QuantLib::FixedDividend(amount, d))); } else { dividendSchedule.push_back(boost::shared_ptr(new QuantLib::FractionalDividend(rate, amount, d))); } } } catch (std::exception& ex) { forward_exception_to_r(ex); } return dividendSchedule; } QuantLib::CallabilitySchedule getCallabilitySchedule(SEXP callabilityScheduleFrame) { QuantLib::CallabilitySchedule callabilitySchedule; try { // RcppFrame rcppCallabilitySchedule(callabilityScheduleFrame); // std::vector > table = rcppCallabilitySchedule.getTableData(); // int nrow = table.size(); Rcpp::DataFrame callScheDF(callabilityScheduleFrame); Rcpp::NumericVector n0v = callScheDF[0]; Rcpp::CharacterVector s1v = callScheDF[1]; Rcpp::NumericVector n2v = callScheDF[2]; int nrow = n0v.size(); for (int row=0; row (new QuantLib::Callability(QuantLib::Callability::Price(price, QuantLib::Callability::Price::Clean), QuantLib::Callability::Put,d ))); } else { callabilitySchedule.push_back(boost::shared_ptr (new QuantLib::Callability(QuantLib::Callability::Price(price, QuantLib::Callability::Price::Clean), QuantLib::Callability::Call,d ))); } } } catch (std::exception& ex){ forward_exception_to_r(ex); } return callabilitySchedule; } RQuantLib/src/vanilla.cpp0000644000175000017500000002745512271347225013774 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2010 Dirk Eddelbuettel // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include RcppExport SEXP EuropeanOption(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); // Parameters via R list object std::string type = Rcpp::as(rparam["type"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better double volatility = Rcpp::as(rparam["volatility"]); QuantLib::Option::Type optionType = getOptionType(type); QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; // new framework as per QuantLib 0.3.5 QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote( underlying )); boost::shared_ptr vol(new QuantLib::SimpleQuote( volatility )); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr qRate(new QuantLib::SimpleQuote( dividendYield )); boost::shared_ptr qTS = flatRate(today, qRate, dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote( riskFreeRate )); boost::shared_ptr rTS = flatRate(today, rRate, dc); QuantLib::Date exDate = today + length; boost::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); boost::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS); Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = option->NPV(), Rcpp::Named("delta") = option->delta(), Rcpp::Named("gamma") = option->gamma(), Rcpp::Named("vega") = option->vega(), Rcpp::Named("theta") = option->theta(), Rcpp::Named("rho") = option->rho(), Rcpp::Named("divRho") = option->dividendRho(), Rcpp::Named("parameters") = optionParameters); return rl; } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP AmericanOption(SEXP optionParameters) { try { Rcpp::List rparam(optionParameters); std::string type = Rcpp::as(rparam["type"]); double underlying = Rcpp::as(rparam["underlying"]); double strike = Rcpp::as(rparam["strike"]); QuantLib::Spread dividendYield = Rcpp::as(rparam["dividendYield"]); QuantLib::Rate riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); QuantLib::Time maturity = Rcpp::as(rparam["maturity"]); int length = int(maturity*360 + 0.5); // FIXME: this could be better double volatility = Rcpp::as(rparam["volatility"]); int timeSteps = Rcpp::as(rparam["timeSteps"]); int gridPoints = Rcpp::as(rparam["gridPoints"]); std::string engine = Rcpp::as(rparam["engine"]); QuantLib::Option::Type optionType = getOptionType(type); // new framework as per QuantLib 0.3.5, updated for 0.3.7 // updated again for 0.9.0, see eg test-suite/americanoption.cpp QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::DayCounter dc = QuantLib::Actual360(); boost::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); boost::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); boost::shared_ptr qTS = flatRate(today,qRate,dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); boost::shared_ptr rTS = flatRate(today,rRate,dc); boost::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); QuantLib::Date exDate = today + length; boost::shared_ptr exercise(new QuantLib::AmericanExercise(today, exDate)); boost::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); QuantLib::VanillaOption option(payoff, exercise); if (engine=="BaroneAdesiWhaley") { // new from 0.3.7 BaroneAdesiWhaley boost::shared_ptr engine(new QuantLib::BaroneAdesiWhaleyApproximationEngine(stochProcess)); option.setPricingEngine(engine); Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(), Rcpp::Named("delta") = R_NaReal, Rcpp::Named("gamma") = R_NaReal, Rcpp::Named("vega") = R_NaReal, Rcpp::Named("theta") = R_NaReal, Rcpp::Named("rho") = R_NaReal, Rcpp::Named("divRho") = R_NaReal, Rcpp::Named("parameters") = optionParameters); return rl; } else if (engine=="CrankNicolson") { // suggestion by Bryan Lewis: use CrankNicolson for greeks boost::shared_ptr fdcnengine(new QuantLib::FDAmericanEngine(stochProcess, timeSteps, gridPoints)); option.setPricingEngine(fdcnengine); Rcpp::List rl = Rcpp::List::create(Rcpp::Named("value") = option.NPV(), Rcpp::Named("delta") = option.delta(), Rcpp::Named("gamma") = option.gamma(), Rcpp::Named("vega") = R_NaReal, Rcpp::Named("theta") = R_NaReal, Rcpp::Named("rho") = R_NaReal, Rcpp::Named("divRho") = R_NaReal, Rcpp::Named("parameters") = optionParameters); return rl; } else { throw std::range_error("Unknown engine " + engine); } } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP EuropeanOptionArrays(SEXP typesexp, SEXP parsexp) { try { QuantLib::Option::Type optionType = getOptionType( Rcpp::as(typesexp) ); Rcpp::NumericMatrix par(parsexp); // matrix of parameters as per expand.grid() in R int n = par.nrow(); Rcpp::NumericVector value(n), delta(n), gamma(n), vega(n), theta(n), rho(n), divrho(n); QuantLib::Date today = QuantLib::Date::todaysDate(); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::DayCounter dc = QuantLib::Actual360(); for (int i=0; i spot(new QuantLib::SimpleQuote( underlying )); boost::shared_ptr vol(new QuantLib::SimpleQuote( volatility )); boost::shared_ptr volTS = flatVol(today, vol, dc); boost::shared_ptr qRate(new QuantLib::SimpleQuote( dividendYield )); boost::shared_ptr qTS = flatRate(today, qRate, dc); boost::shared_ptr rRate(new QuantLib::SimpleQuote( riskFreeRate )); boost::shared_ptr rTS = flatRate(today, rRate, dc); QuantLib::Date exDate = today + length; boost::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); boost::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); boost::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS); value[i] = option->NPV(); delta[i] = option->delta(); gamma[i] = option->gamma(); vega[i] = option->vega(); theta[i] = option->theta(); rho[i] = option->rho(); divrho[i] = option->dividendRho(); } return Rcpp::List::create(Rcpp::Named("value") = value, Rcpp::Named("delta") = delta, Rcpp::Named("gamma") = gamma, Rcpp::Named("vega") = vega, Rcpp::Named("theta") = theta, Rcpp::Named("rho") = rho, Rcpp::Named("divRho") = divrho); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/src/zero.cpp0000644000175000017500000002146112271347225013314 0ustar00eddedd// -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2009 - 2012 Dirk Eddelbuettel and Khanh Nguyen // // $Id$ // // This file is part of the RQuantLib library for GNU R. // It is made available under the terms of the GNU General Public // License, version 2, or at your option, any later version, // incorporated herein by reference. // // 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 GNU General Public License for more // details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA #include RcppExport SEXP zeroprice(SEXP params) { try { Rcpp::List rparam(params); double yield = Rcpp::as(rparam["Yield"]); QuantLib::Date maturity(dateFromR(Rcpp::as(rparam["Maturity"]))); QuantLib::Date settle(dateFromR(Rcpp::as(rparam["Settle"]))); QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); QuantLib::Integer fixingDays = 2; QuantLib::Date todaysDate = calendar.advance(settle, -fixingDays, QuantLib::Days); QuantLib::Settings::instance().evaluationDate() = todaysDate; double period = Rcpp::as(rparam["Period"]); double basis = Rcpp::as(rparam["Basis"]); QuantLib::DayCounter dayCounter = getDayCounter(basis); QuantLib::Frequency freq = getFrequency(period); QuantLib::Period p(freq); //double EMR = Rcpp::as(rparam["EMR"); QuantLib::ZeroCouponBond bond(1, calendar, 100, maturity, QuantLib::Unadjusted, 100.0, settle); double price = bond.cleanPrice(yield, dayCounter, QuantLib::Compounded, freq); return Rcpp::wrap(price); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP zeroyield(SEXP params){ try { Rcpp::List rparam(params); double price = Rcpp::as(rparam["Price"]); QuantLib::Date maturity(dateFromR(Rcpp::as(rparam["Maturity"]))); QuantLib::Date settle(dateFromR(Rcpp::as(rparam["Settle"]))); QuantLib::Calendar calendar = QuantLib::UnitedStates(QuantLib::UnitedStates::GovernmentBond); QuantLib::Integer fixingDays = 2; QuantLib::Date todaysDate = calendar.advance(settle, -fixingDays, QuantLib::Days); QuantLib::Settings::instance().evaluationDate() = todaysDate; double period = Rcpp::as(rparam["Period"]); double basis = Rcpp::as(rparam["Basis"]); QuantLib::DayCounter dayCounter = getDayCounter(basis); QuantLib::Frequency freq = getFrequency(period); QuantLib::Period p(freq); //double EMR = Rcpp::as(rparam["EMR"); QuantLib::ZeroCouponBond bond(1, calendar, 100, maturity, QuantLib::Unadjusted, 100.0, settle); double yield = bond.yield(price, dayCounter, QuantLib::Compounded, freq); return Rcpp::wrap(yield); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RcppExport SEXP zbtyield(SEXP MatVec, SEXP BondMat, SEXP yieldVec, SEXP SettlVec, SEXP cpVec, SEXP param) { try { Rcpp::List par(param); //double oc = Rcpp::as(rparam["OC"); Rcpp::DateVector rmat(MatVec); Rcpp::DateVector rsettle(SettlVec); Rcpp::NumericVector yields(yieldVec); Rcpp::NumericVector cleanPrice(cpVec); Rcpp::NumericMatrix bondparam(BondMat); //std::vector cleanPrice(rcp.stlVector()); //std::vector yields(ryields.stlVector()); //std::vector > bondparam(rbondmat.stlMatrix()); int n = rmat.size(); std::vector MatDates(rmat.size()); for (int i = 0;i SettleDates(rsettle.size()); for (int i = 0;i > instruments; std::vector< boost::shared_ptr > quote; for (QuantLib::Size i=0; i cp(new QuantLib::SimpleQuote(cleanPrice[i])); quote.push_back(cp); } std::vector< QuantLib::RelinkableHandle > quoteHandle(numberOfBonds); for (QuantLib::Size i=0; i 1) { p = QuantLib::Period(getFrequency(bondparam(j,2))); faceAmount = bondparam(j,1); dayCounter = getDayCounter(3); emr = (bondparam(j,4)==0) ? false : true; } QuantLib::Schedule schedule(SettleDates[j], MatDates[j],p, calendar, QuantLib::Unadjusted, QuantLib::Unadjusted, QuantLib::DateGeneration::Backward, emr); boost::shared_ptr helper(new QuantLib::FixedRateBondHelper(quoteHandle[j], 1, faceAmount, schedule, std::vector(1,bondparam(j,0)), dayCounter, QuantLib::Unadjusted, 100, SettleDates[j])); instruments.push_back(helper); } /* bool constrainAtZero = true; Real tolerance = 1.0e-10; Size max = 5000; boost::shared_ptr curve; NelsonSiegelFitting nelsonSiegel; boost::shared_ptr ts3 ( new FittedBondDiscountCurve(1, calendar, instruments, dayCounter, nelsonSiegel, tolerance, max)); curve = ts3; */ boost::shared_ptr curve(new QuantLib::PiecewiseYieldCurve(1, calendar, instruments, dayCounter)); int numCol = 2; std::vector colNames(numCol); colNames[0] = "date"; colNames[1] = "zeroRates"; Rcpp::DateVector dates(numberOfBonds); Rcpp::NumericVector zeros(numberOfBonds); QuantLib::Date current = SettleDates[0]; //int n1 = curve->maxDate() - SettleDates[0]; for (unsigned int i = 0; izeroRate(d, QuantLib::ActualActual(), QuantLib::Simple); current++; // ? } return Rcpp::DataFrame::create(Rcpp::Named("date")=dates, Rcpp::Named("zeroRates")=zeros); } catch(std::exception &ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } return R_NilValue; } RQuantLib/tests/0000755000175000017500000000000012271333436012177 5ustar00eddeddRQuantLib/tests/RQuantlib.R0000644000175000017500000001476412271333436014237 0ustar00eddedd stopifnot(require(RQuantLib)) ## values from Quantlib's test-suite ## Reference: Haug, Option Pricing Formulas, McGraw-Hill, 1998 ## ## and generally sourced from the code in the test-suite/ ## directory of the QuantLib distribution ## europeanoption.cpp: call value == 2.1334 print(EuropeanOption("call", underlying=60, strike=65, div=0, riskFree=0.08, maturity=0.25, vol=0.3), digits=5) ## europeanoption.cpp: put value == 2.4648 print(EuropeanOption("put", underlying=100, strike=95, div=0.05, riskFree=0.1, maturity=0.5, vol=0.2), digits=5) ## europeanoption.cpp: call delta == 0.5946 print(EuropeanOption("call", underlying=105, strike=100,div=0.1,riskFree=0.1, maturity=0.5, vol=0.36), digits=4) ## europeanoption.cpp: put delta == -0.3566 print(EuropeanOption("put", underlying=105, strike=100,div=0.1,riskFree=0.1, maturity=0.5, vol=0.36), digits=4) ## europeanoption.cpp: call gamma == 0.0278 print(EuropeanOption("call", underlying=55, strike=60,div=0.0,riskFree=0.1, maturity=0.75, vol=0.30), digits=4) ## europeanoption.cpp: put gamma == 0.0278 print(EuropeanOption("put", underlying=55, strike=60,div=0.0,riskFree=0.1, maturity=0.75, vol=0.30), digits=4) ## europeanoption.cpp: call vega == 18.9358 print(EuropeanOption("call", underlying=55, strike=60,div=0.0,riskFree=0.1, maturity=0.75, vol=0.30), digits=4) ## europeanoption.cpp: put vega == 18.9358 print(EuropeanOption("put", underlying=55, strike=60,div=0.0,riskFree=0.1, maturity=0.75, vol=0.30), digits=4) ## americanoption.cpp: call value == 10.0089 -- we show 10.00606 print(AmericanOption("call", underlying=110, strike=100, div=0.1, riskFree=0.1, maturity=0.1, vol=0.15), digits=5) ## americanoption.cpp: put value == 0.3159 print(AmericanOption("call", underlying=90, strike=100, div=0.1, riskFree=0.1, maturity=0.1, vol=0.25), digits=5) ## barrier: down and out call == 9.0246 print(BarrierOption("downout", barrier=95, rebate=3, type="call", strike=90, underlying=100, div=0.04, riskF=0.08, mat=0.5, vol=0.25), digits=4) ## barrier: down and in call == 7.7627 print(BarrierOption("downin", barrier=95, rebate=3, type="call", strike=90, underlying=100, div=0.04, riskF=0.08, mat=0.5, vol=0.25), digits=4) ## binary aka digital: put == 2.6710 print(BinaryOption(binType="cash", type="put", excType="european", strike=80, underl=100, div=0.06, r=0.06, mat=0.75, vol=0.35, cash=10), digits=4) ## asianoption.cpp: put == 4.6922 (from testAnalyticContinuousGeometricAveragePrice()) print( AsianOption("geometric", "put", underlying=80, strike=85, div=-0.03, riskFree=0.05, maturity=0.25, vol=0.2)) # simple call with unnamed parameters bond <- list(faceAmount=100,issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100 ) dateparams <-list(settlementDays=1, calendar="us", businessDayConvention='Unadjusted') discountCurve.param <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-15'), dt=0.25, interpWhat='discount', interpHow='loglinear') discountCurve <- DiscountCurve(discountCurve.param, list(flat=0.05)) ZeroCouponBond(bond, discountCurve, dateparams) ## bond.cpp: examples from Fixed Income page of Matlab ZeroYield(95, 100, as.Date("1993-6-24"), as.Date("1993-11-1")) ## bond.cpp: test theoretical price of bond by its yield ZeroPriceByYield(0.1478, 100, as.Date("1993-6-24"), as.Date("1993-11-1")) ## bond.cpp: test theoretical yield of a fixed rate bond, = 0.0307 FixedRateBondYield(,99.282, 100000, as.Date("2004-11-30"), as.Date("2008-11-30"), 3, , c(0.02875), , , , ,as.Date("2004-11-30")) ## bond.cpp: test theoretical price of a fixed rate bond = 99.2708 FixedRateBondPriceByYield(,0.0307, 100000, as.Date("2004-11-30"), as.Date("2008-11-30"), 3, , c(0.02875), , , , ,as.Date("2004-11-30")) ## bond.cpp #Simple call with a flat curve bond <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100, effectiveDate=as.Date("2004-11-30")) dateparams <- list(settlementDays=1, calendar="us", dayCounter = 'Thirty360', period=2, businessDayConvention = 4, terminationDateConvention=4, dateGeneration=1, endOfMonth=1) coupon.rate <- c(0.02875) params <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-19'), dt=.25, interpWhat="discount", interpHow="loglinear") discountCurve.flat <- DiscountCurve(params, list(flat=0.05)) FixedRateBond(bond, coupon.rate, discountCurve.flat, dateparams) ## bond.cpp FloatingRateBond, following test-suite/bonds.cpp bond <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), redemption=100, effectiveDate=as.Date("2004-11-30")) dateparams <- list(settlementDays=1, calendar="us", dayCounter = 'ActualActual', period=2, businessDayConvention = 1, terminationDateConvention=1, dateGeneration=0, endOfMonth=0, fixingDays = 1) gearings <- c() spreads <- c() caps <- c() floors <- c() params <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-19'), dt=.25, interpWhat="discount", interpHow="loglinear") tsQuotes <- list(d1w =0.0382, d1m =0.0372, fut1=96.2875, fut2=96.7875, fut3=96.9875, fut4=96.6875, fut5=96.4875, fut6=96.3875, fut7=96.2875, fut8=96.0875, s3y =0.0398, s5y =0.0443, s10y =0.05165, s15y =0.055175) ## when both discount and libor curves are flat. discountCurve.flat <- DiscountCurve(params, list(flat=0.05)) termstructure <- DiscountCurve(params, list(flat=0.03)) iborIndex.params <- list(type="USDLibor", length=6, inTermOf="Month", term=termstructure) FloatingRateBond(bond, gearings, spreads, caps, floors, iborIndex.params, discountCurve.flat, dateparams) RQuantLib/tests/RQuantlib.Rout.save0000644000175000017500000002614712271333436015722 0ustar00eddedd R version 2.12.0 (2010-10-15) Copyright (C) 2010 The R Foundation for Statistical Computing ISBN 3-900051-07-0 Platform: x86_64-pc-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. > > stopifnot(require(RQuantLib)) Loading required package: RQuantLib Loading required package: Rcpp > > ## values from Quantlib's test-suite > ## Reference: Haug, Option Pricing Formulas, McGraw-Hill, 1998 > ## > ## and generally sourced from the code in the test-suite/ > ## directory of the QuantLib distribution > > ## europeanoption.cpp: call value == 2.1334 > print(EuropeanOption("call", underlying=60, strike=65, div=0, riskFree=0.08, + maturity=0.25, vol=0.3), digits=5) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 2.13337 0.37248 0.04204 11.35154 -8.42817 5.05390 -5.58724 > ## europeanoption.cpp: put value == 2.4648 > print(EuropeanOption("put", underlying=100, strike=95, div=0.05, riskFree=0.1, + maturity=0.5, vol=0.2), digits=5) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 2.46479 -0.26418 0.02284 22.83957 -3.00053 -14.44147 13.20908 > > ## europeanoption.cpp: call delta == 0.5946 > print(EuropeanOption("call", underlying=105, strike=100,div=0.1,riskFree=0.1, + maturity=0.5, vol=0.36), digits=4) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 12.4328 0.5946 0.0135 26.7781 -8.3968 25.0016 -31.2180 > ## europeanoption.cpp: put delta == -0.3566 > print(EuropeanOption("put", underlying=105, strike=100,div=0.1,riskFree=0.1, + maturity=0.5, vol=0.36), digits=4) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 7.6767 -0.3566 0.0135 26.7781 -8.8725 -22.5599 18.7215 > > ## europeanoption.cpp: call gamma == 0.0278 > print(EuropeanOption("call", underlying=55, strike=60,div=0.0,riskFree=0.1, + maturity=0.75, vol=0.30), digits=4) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 5.3928 0.5333 0.0278 18.9358 -6.1813 17.9557 -22.0003 > ## europeanoption.cpp: put gamma == 0.0278 > print(EuropeanOption("put", underlying=55, strike=60,div=0.0,riskFree=0.1, + maturity=0.75, vol=0.30), digits=4) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 6.0574 -0.4667 0.0278 18.9358 -0.6148 -23.7927 19.2497 > > ## europeanoption.cpp: call vega == 18.9358 > print(EuropeanOption("call", underlying=55, strike=60,div=0.0,riskFree=0.1, + maturity=0.75, vol=0.30), digits=4) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 5.3928 0.5333 0.0278 18.9358 -6.1813 17.9557 -22.0003 > ## europeanoption.cpp: put vega == 18.9358 > print(EuropeanOption("put", underlying=55, strike=60,div=0.0,riskFree=0.1, + maturity=0.75, vol=0.30), digits=4) Concise summary of valuation for EuropeanOption value delta gamma vega theta rho divRho 6.0574 -0.4667 0.0278 18.9358 -0.6148 -23.7927 19.2497 > > > ## americanoption.cpp: call value == 10.0089 -- we show 10.00606 > print(AmericanOption("call", underlying=110, strike=100, div=0.1, riskFree=0.1, + maturity=0.1, vol=0.15), digits=5) Concise summary of valuation for AmericanOption value delta gamma vega theta rho divRho 10.00606 NA NA NA NA NA NA > ## americanoption.cpp: put value == 0.3159 > print(AmericanOption("call", underlying=90, strike=100, div=0.1, riskFree=0.1, + maturity=0.1, vol=0.25), digits=5) Concise summary of valuation for AmericanOption value delta gamma vega theta rho divRho 0.3159 NA NA NA NA NA NA > > > ## barrier: down and out call == 9.0246 > print(BarrierOption("downout", barrier=95, rebate=3, type="call", + strike=90, underlying=100, div=0.04, riskF=0.08, + mat=0.5, vol=0.25), digits=4) Concise summary of valuation for BarrierOption value delta gamma vega theta rho divRho 9.0246 NaN NaN NaN NaN NaN NaN > ## barrier: down and in call == 7.7627 > print(BarrierOption("downin", barrier=95, rebate=3, type="call", + strike=90, underlying=100, div=0.04, riskF=0.08, + mat=0.5, vol=0.25), digits=4) Concise summary of valuation for BarrierOption value delta gamma vega theta rho divRho 7.7627 NaN NaN NaN NaN NaN NaN > > > ## binary aka digital: put == 2.6710 > print(BinaryOption(binType="cash", type="put", excType="european", + strike=80, underl=100, div=0.06, r=0.06, + mat=0.75, vol=0.35, cash=10), digits=4) Concise summary of valuation for BinaryOption value delta gamma vega theta rho divRho 2.6710 -0.1061 0.0031 8.1539 -1.7423 -9.9577 7.9545 > > ## asianoption.cpp: put == 4.6922 (from testAnalyticContinuousGeometricAveragePrice()) > print( AsianOption("geometric", "put", underlying=80, strike=85, div=-0.03, riskFree=0.05, maturity=0.25, vol=0.2)) Concise summary of valuation for AsianOption value delta gamma vega theta rho divRho 4.6922 -0.8031 0.0594 6.8662 0.0580 -9.2039 8.0309 > > # simple call with unnamed parameters > > bond <- list(faceAmount=100,issueDate=as.Date("2004-11-30"), + maturityDate=as.Date("2008-11-30"), redemption=100 ) > > dateparams <-list(settlementDays=1, calendar="us", businessDayConvention='Unadjusted') > > > discountCurve.param <- list(tradeDate=as.Date('2002-2-15'), + settleDate=as.Date('2002-2-15'), + dt=0.25, + interpWhat='discount', interpHow='loglinear') > discountCurve <- DiscountCurve(discountCurve.param, list(flat=0.05)) > > ZeroCouponBond(bond, discountCurve, dateparams) Concise summary of valuation for ZeroCouponBond Net present value : 71.21519 clean price : 81.884 dirty price : 81.884 accrued coupon : 0 yield : 0.050516 cash flows : Date Amount 2008-11-30 100 > > > ## bond.cpp: examples from Fixed Income page of Matlab > ZeroYield(95, 100, as.Date("1993-6-24"), as.Date("1993-11-1")) [1] 0.1477733 attr(,"class") [1] "ZeroYield" > > ## bond.cpp: test theoretical price of bond by its yield > ZeroPriceByYield(0.1478, 100, as.Date("1993-6-24"), as.Date("1993-11-1")) [1] 94.99914 attr(,"class") [1] "ZeroPriceByYield" > > ## bond.cpp: test theoretical yield of a fixed rate bond, = 0.0307 > FixedRateBondYield(,99.282, 100000, as.Date("2004-11-30"), as.Date("2008-11-30"), 3, , c(0.02875), , , , ,as.Date("2004-11-30")) [1] 0.03066526 attr(,"class") [1] "FixedRateBondYield" > > ## bond.cpp: test theoretical price of a fixed rate bond = 99.2708 > FixedRateBondPriceByYield(,0.0307, 100000, as.Date("2004-11-30"), as.Date("2008-11-30"), 3, , c(0.02875), , , , ,as.Date("2004-11-30")) [1] 99.26903 attr(,"class") [1] "FixedRateBondPriceByYield" > > ## bond.cpp > > #Simple call with a flat curve > bond <- list(faceAmount=100, + issueDate=as.Date("2004-11-30"), + maturityDate=as.Date("2008-11-30"), + redemption=100, + effectiveDate=as.Date("2004-11-30")) > dateparams <- list(settlementDays=1, + calendar="us", dayCounter = 'Thirty360', period=2, + businessDayConvention = 4, terminationDateConvention=4, + dateGeneration=1, endOfMonth=1) > coupon.rate <- c(0.02875) > > params <- list(tradeDate=as.Date('2002-2-15'), + settleDate=as.Date('2002-2-19'), + dt=.25, + interpWhat="discount", + interpHow="loglinear") > > discountCurve.flat <- DiscountCurve(params, list(flat=0.05)) > FixedRateBond(bond, coupon.rate, discountCurve.flat, dateparams) Concise summary of valuation for FixedRateBond Net present value : 80.21276 clean price : 92.167 dirty price : 92.167 accrued coupon : 0 yield : 0.050517 cash flows : Date Amount 2005-05-31 1.4375 2005-11-30 1.4375 2006-05-31 1.4375 2006-11-30 1.4375 2007-05-31 1.4375 2007-11-30 1.4375 2008-05-31 1.4375 2008-11-30 1.4375 2008-11-30 100.0000 > ## bond.cpp FloatingRateBond, following test-suite/bonds.cpp > > bond <- list(faceAmount=100, issueDate=as.Date("2004-11-30"), + maturityDate=as.Date("2008-11-30"), redemption=100, + effectiveDate=as.Date("2004-11-30")) > dateparams <- list(settlementDays=1, calendar="us", + dayCounter = 'ActualActual', period=2, + businessDayConvention = 1, terminationDateConvention=1, + dateGeneration=0, endOfMonth=0, fixingDays = 1) > > gearings <- c() > spreads <- c() > caps <- c() > floors <- c() > > params <- list(tradeDate=as.Date('2002-2-15'), + settleDate=as.Date('2002-2-19'), + dt=.25, + interpWhat="discount", + interpHow="loglinear") > > tsQuotes <- list(d1w =0.0382, + d1m =0.0372, + fut1=96.2875, + fut2=96.7875, + fut3=96.9875, + fut4=96.6875, + fut5=96.4875, + fut6=96.3875, + fut7=96.2875, + fut8=96.0875, + s3y =0.0398, + s5y =0.0443, + s10y =0.05165, + s15y =0.055175) > > > ## when both discount and libor curves are flat. > > discountCurve.flat <- DiscountCurve(params, list(flat=0.05)) > termstructure <- DiscountCurve(params, list(flat=0.03)) > iborIndex.params <- list(type="USDLibor", length=6, + inTermOf="Month", term=termstructure) > FloatingRateBond(bond, gearings, spreads, caps, floors, + iborIndex.params, discountCurve.flat, dateparams) Concise summary of valuation for FloatingRateBond Net present value : 80.54557 clean price : 92.549 dirty price : 92.549 accrued coupon : 0 yield : 0.050517 cash flows : Date Amount 2005-05-31 1.4851 2005-11-30 1.4947 2006-05-30 1.4783 2006-11-30 1.5029 2007-05-30 1.4783 2007-11-30 1.5031 2008-05-30 1.4797 2008-11-28 1.4783 2008-11-28 100.0000 > > RQuantLib/tests/doRUnit.R0000644000175000017500000000173612271333436013715 0ustar00eddedd## doRUnit.R --- Run RUnit tests ## ## Origianlly follows Gregor Gojanc's example in CRAN package 'gdata' ## and the corresponding section in the R Wiki: ## http://wiki.r-project.org/rwiki/doku.php?id=developers:runit ## ## Changed by Martin Maechler for Rmetrics, making them "runnable" ## for *installed* packages without ./tests/ directory by placing ## the bulk of the code e.g. in ../inst/unitTests/runTests.R ## ## Adapted for RQuantLib by Dirk Eddelbuettel, 29 Dec 2007 if (require("RUnit", quietly=TRUE)) { #wd <- getwd() #pkg <- sub("\\.Rcheck$", '', basename(dirname(wd))) # sub out trailing .Rcheck #pkg <- gsub("[0-9.-]*$", '', pkg) # sub out -0.1.2 number pkg <- "RQuantLib" # cannot read from current dir in SVN tree library(package=pkg, character.only=TRUE) path <- system.file("unitTests", package = pkg) stopifnot(file.exists(path), file.info(path.expand(path))$isdir) source(file.path(path, "runTests.R"), echo = TRUE) }