RQuantLib/0000755000176200001440000000000013607525142012120 5ustar liggesusersRQuantLib/NAMESPACE0000644000176200001440000000646413340507515013347 0ustar liggesusers## Emacs, make this -*- mode: R; -*- import("methods") importFrom("Rcpp", "Rcpp.plugin.maker", "sourceCpp") importFrom("stats", "sd") importFrom("graphics", "par", "plot", "lines", "legend") importFrom("utils", "compareVersion") importFrom("zoo","zoo","na.spline") useDynLib("RQuantLib", .registration=TRUE) export( ##--arrays.R "oldEuropeanOptionArrays", "EuropeanOptionArrays", "plotOptionSurface", "matchParams", ##--asian.R "AsianOption", ##--bermudan.R "BermudanSwaption", "AffineSwaption", #"sabrengine", "SabrSwaption", "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", "addHolidays", "removeHolidays", ##--dayCounter.R "dayCount", "yearFraction", "setEvaluationDate", ##--dates.cpp "advanceDate", ##--discount.R "DiscountCurve", "plot.DiscountCurve", ##--implied.R "EuropeanOptionImpliedVolatility", "AmericanOptionImpliedVolatility", "BinaryOptionImpliedVolatility", ##--option.R "EuropeanOption", "AmericanOption", "BinaryOption", "BarrierOption", ##--schedule.R "Schedule", ##--utils.R "getQuantLibVersion", "getQuantLibCapabilities" ) S3method("AmericanOption", "default") S3method("AmericanOptionImpliedVolatility", "default") S3method("AsianOption", "default") S3method("BarrierOption", "default") S3method("BermudanSwaption", "default") S3method("AffineSwaption", "default") S3method("SabrSwaption", "default") S3method("BinaryOption", "default") S3method("BinaryOptionImpliedVolatility", "default") S3method("CallableBond", "default") S3method("ConvertibleFixedCouponBond", "default") S3method("ConvertibleFloatingCouponBond", "default") S3method("ConvertibleZeroCouponBond", "default") S3method("DiscountCurve", "default") S3method("EuropeanOption", "default") S3method("EuropeanOptionImpliedVolatility", "default") S3method("FittedBondCurve", "default") S3method("FixedRateBond", "default") S3method("FixedRateBondPriceByYield", "default") S3method("FixedRateBondYield", "default") S3method("FloatingRateBond", "default") S3method("plot", "DiscountCurve") S3method("Schedule", "default") S3method("summary", "BKTree") S3method("summary", "G2Analytic") S3method("summary", "HWAnalytic") S3method("summary", "HWTree") S3method("summary", "G2AnalyticAffineSwaption") S3method("summary", "HWAnalyticAffineSwaption") S3method("summary", "HWTreeAffineSwaption") S3method("ZeroCouponBond", "default") S3method("ZeroPriceByYield", "default") S3method("ZeroYield", "default") S3method("plot", "Option") S3method("print", "Option") S3method("summary", "Option") S3method("plot", "Bond") S3method("print", "Bond") S3method("summary", "Bond") S3method("print", "FixedRateBond") RQuantLib/demo/0000755000176200001440000000000012466654326013055 5ustar liggesusersRQuantLib/demo/OptionSurfaces.R0000644000176200001440000000455012435715442016141 0ustar liggesusers ## 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/demo/ShinyDiscountCurves.R0000644000176200001440000000046212466654326017175 0ustar liggesusers ## use shiny, if installed to show Shiny App installed with package if (require("shiny")) { library(RQuantLib) runApp(system.file("shiny", "DiscountCurve", package="RQuantLib"), port=8765 ## add host="0.0.0.0" if access from outside current machine needed ) } RQuantLib/demo/00Index0000644000176200001440000000017212466654326014207 0ustar liggesusersOptionSurfaces European Option surfaces (requires rgl) ShinyDiscountCurves Shiny application with Discount Curve example RQuantLib/tools/0000755000176200001440000000000013522344635013262 5ustar liggesusersRQuantLib/tools/build_RQuantLib.sh0000644000176200001440000001127113403306333016627 0ustar liggesusers#!/bin/sh #set -x set -e ############################################################################### # NOTES: # # All directories must be specified as Windows paths (e.g. C:/Windows) # # This file has only been tested using MinGW's msys_1.0. Attempts to use msys2 # were not successful. Use msys.bat to call build_RQuantLib.sh # # Download QuantLib and boost sources and unzip them into $BUILD_ROOT/src. # Update the $BOOST_VERSION and $QL_VERSION environment variables to reflect # the versions used. # # The current RQuantLib Makefile deletes all object files and downloads the # pre-built QuantLib library from https://github.com/rwinlib/quantlib. Update # the Makefile to point to your local libQuantLib.a and remove/comment the # 'make all' commands to prevent the deletion and download. ############################################################################### # build environment BOOST_VERSION=1_68_0 QL_VERSION=1.14 RQL_VERSION=0.4.5.2 BUILD_ROOT="E:/build" R_TOOLS_DIR="E:/R/Rtools35" BINPREF=$R_TOOLS_DIR/mingw_32/bin/ BINPREF64=$R_TOOLS_DIR/mingw_64/bin/ QUANTLIB_SRC="$BUILD_ROOT/src/QuantLib-$QL_VERSION" BOOSTLIB="$BUILD_ROOT/src/boost_$BOOST_VERSION" QUANTLIB_ROOT="$BUILD_ROOT/QuantLib" ############################################################################### # Check Rtools locations if [ ! -d "$R_TOOLS_DIR/mingw_32" ]; then echo "$R_TOOLS_DIR/mingw_32 not found" exit 1 fi if [ ! -d "$R_TOOLS_DIR/mingw_64" ]; then echo "$R_TOOLS_DIR/mingw_64 not found" exit 1 fi # Check for boost headers if [ ! -d "$BOOSTLIB/boost" ]; then echo "Did not find boost headers in $BOOSTLIB/boost" exit 1 fi # Check for quantlib source if [ ! -d "$QUANTLIB_SRC" ]; then echo "Did not find QuantLib source in $QUANTLIB_SRC" exit 1 fi # Ensure there is an /etc/fstab if [ -n "/etc/fstab" ]; then touch /etc/fstab fi # Install architecture-specific files into these directories via the # --exec-prefix argument to QuantLib's configure script mkdir -p $QUANTLIB_ROOT/lib/i386 mkdir -p $QUANTLIB_ROOT/lib/x64 # Ensure a mount point exists and add bin/ to PATH mkdir -p /mingw export PATH="$(cygpath -u $R_TOOLS_DIR)/bin":/mingw/bin:$PATH # Use ccache if available if [ -x "$(command -v ccache)" ]; then export PATH=/usr/lib/ccache/bin:$PATH fi ################################################################################ ## 32-bit QuantLib mount --replace $R_TOOLS_DIR/mingw_32 /mingw ## Create and change to build directory #mkdir -p $BUILD_ROOT/ql32 #cd $BUILD_ROOT/ql32 # QuantLib 'buglet' prevents building outside source directory cd $QUANTLIB_SRC # Clean prior build before (re-)running configure if [ -f "Makefile" ]; then make -j6 distclean fi CXXFLAGS="-g0 -O2" $QUANTLIB_SRC/configure --prefix=$QUANTLIB_ROOT \ --exec-prefix=$QUANTLIB_ROOT/lib/i386 --with-boost-include=$BOOSTLIB \ --enable-intraday --enable-shared --enable-static --with-gnu-ld make -j6 make install # Shrink quantlib library cp $QUANTLIB_ROOT/lib/i386/libQuantLib.a \ $QUANTLIB_ROOT/lib/i386/libQuantLib.a.bak strip --strip-unneeded $QUANTLIB_ROOT/lib/i386/libQuantLib.a ################################################################################ ## 64-bit QuantLib mount --replace $R_TOOLS_DIR/mingw_64 /mingw ## Create and change to build directory #mkdir -p $BUILD_ROOT/ql64 #cd $BUILD_ROOT/ql64 # QuantLib 'bug' prevents building outside source directory cd $QUANTLIB_SRC # Clean prior build before (re-)running configure if [ -f "Makefile" ]; then make -j6 distclean fi CXXFLAGS="-m64 -g0 -O2" $QUANTLIB_SRC/configure --prefix=$QUANTLIB_ROOT \ --exec-prefix=$QUANTLIB_ROOT/lib/x64 --with-boost-include=$BOOSTLIB \ --enable-intraday --enable-shared --enable-static --with-gnu-ld make -j6 make install ## Shrink quantlib library cp $QUANTLIB_ROOT/lib/x64/libQuantLib.a \ $QUANTLIB_ROOT/lib/x64/libQuantLib.a.bak strip --strip-unneeded $QUANTLIB_ROOT/lib/x64/libQuantLib.a ############################################################################### # Install RQuantLib #export QUANTLIB_ROOT #export BOOSTLIB # RQuantLib expects headers in $QUANTLIB_ROOT/ql, not $QUANTLIB_ROOT/include/ql #ln -s $QUANTLIB_ROOT/include/ql $QUANTLIB_ROOT/. #mkdir -p $BUILD_ROOT/library #R_CMD="Rscript -e 'install.packages(c(\"Rcpp\",\"zoo\"), lib = \"$BUILD_ROOT/library\")'" #Rscript -e $R_CMD # ## Need to remove the OS_type: unix from DESCRIPTION #cd $BUILD_ROOT #R CMD INSTALL RQuantLib_${RQL_VERSION}.tar.gz --library=$BUILD_ROOT/library --no-clean-on-error --preclean --build # ## run tests on each system #Rscript --arch x64 -e 'source(system.file(package=\"RQuantLib\", \"unitTests/runTests.R\"))' #Rscript --arch i386 -e 'source(system.file(package=\"RQuantLib\", \"unitTests/runTests.R\"))' RQuantLib/tools/winlibs.R0000644000176200001440000000127413522344635015060 0ustar liggesusers# Build against mingw-w64 build of quantlib if (!file.exists("../windows/quantlib-1.16/include/ql/quantlib.hpp")) { if (getRversion() < "3.3.0") setInternet2() download.file("https://github.com/rwinlib/quantlib/archive/v1.16.zip", "quantlib-1.16.zip", quiet = TRUE) dir.create("../windows", showWarnings = FALSE) unzip("quantlib-1.16.zip", exdir = "../windows") unlink("quantlib-1.16.zip") # Static libraries for the told toolchain unzip("../windows/quantlib-1.16/lib-4.9.3.zip", exdir = "../windows/quantlib-1.16") # Static libraries for the new toolchain if (getRversion() > "3.6.99"){ unzip("../windows/quantlib-1.16/lib.zip", exdir = "../windows/quantlib-1.16") } } RQuantLib/ChangeLog0000644000176200001440000016253013607470311013676 0ustar liggesusers2020-01-15 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.11 * configure.ac: Mark as 0.4.11 * configure: Rebuilt 2020-01-14 Dirk Eddelbuettel * src/utils.cpp (getCallabilitySchedule): Generalize support for Bond::Price to fall back to Callability::Price for QL < 1.17 2020-01-13 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor release * src/utils.cpp (makeOption): Update from now-deprecated FDEuropeanEngine to FdBlackScholesVanillaEngine (getCallabilitySchedule): Update from now-deprecated Callability::Price to Bond::Price * src/vanilla.cpp (americanOptionEngine): Update from now-deprecated FDDividendAmericanEngine and FDAmericanEngine to FdBlackScholesVanillaEngine 2019-11-17 Dirk Eddelbuettel * inst/tinytest/*: Converted from RUnit to tinytest * inst/unitTests/*: Idem * tests/tinytest.R: Idem * tests/doRUnit.R: Idem * docker/ci/Dockerfile: Add tinytest, remove RUnit 2019-08-24 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor release * src/calendars.cpp (getCalendar): Allow for Null calendar 2019-08-07 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.10 * configure.ac: Mark as 0.4.10 * configure: Rebuilt 2019-08-06 Dirk Eddelbuettel * docker/ci/Dockerfile: Add -t unstable to get QuantLib 1.16 2019-08-06 Jeroen Ooms * src/Makevars.win: Updated for QuantLib 1.16 (for current and next Window toolchain) * tools/winlibs.R: Idem 2019-05-15 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.9 * configure.ac: Mark as 0.4.9 * configure: Rebuilt 2019-05-14 Dirk Eddelbuettel * DESCRIPTION (Date, Version): New minor version * src/asian.cpp: Use QuantLib::ext namespace for shared_ptr * src/bermudan.cpp: Idem * src/calendars.cpp: Idem * inst/include/rquantlib_internal.h: Idem 2019-03-17 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.8 * configure.ac: Mark as 0.4.8 * configure: Rebuilt 2019-03-16 Dirk Eddelbuettel * src/calendars.cpp: Use QuantLib::ext for shared_ptr * src/curves.cpp: Idem * src/discount.cpp: Idem * src/hullwhite.cpp: Idem * src/implieds.cpp: Idem * src/sabr.cpp: Idem * src/schedule.cpp: Idem * src/utils.cpp: Idem * src/vanilla.cpp: Idem * src/zero.cpp: Idem * src/*: Removed Emacs formatting header line * inst/include/*: Idem * .editorconfig: Added to provide consistent settings * .Rbuildignore: Exclude .editorconfig 2019-03-15 Dirk Eddelbuettel * inst/include/rquantlib_internal.h: Include ql/shared_ptr.hpp> * src/affine.cpp: Use QuantLib::ext namespace for shared_ptr * src/asian.cpp: Idem * src/barrier_binary.cpp: Idem * src/bermudan.cpp: Idem * src/bonds.cpp: Idem 2019-03-14 Dirk Eddelbuettel * configure.ac: Correct use of AC_DEFUN (leaves configure unaffected) 2019-01-12 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New minor version * R/arrays.R (plotOptionSurface): Call to utils::globalVariables() now outside function where it triggered locked namespace error 2018-12-24 Dirk Eddelbuettel * README.md: Updates to README.me 2018-12-10 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.7 * configure.ac: Mark as 0.4.7 * configure: Rebuilt 2018-12-09 Dirk Eddelbuettel * man/AffineSwaption.Rd: Re-comment-out example for i386 2018-12-08 Dirk Eddelbuettel * man/*.Rd: Remove remaining SVN commit tag identifiers 2018-12-07 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/Makevars.win: Reflect updated directory layout in updated Windows library * man/AffineSwaption.Rd: Restore example now that Windows works * man/BermudanSwaption.Rd: Idem * man/DiscountCurve.Rd: Idem * tools/build_RQuantLib.sh: Added build script by Josh (with a big thank you for setting it up and running a series of builds) 2018-12-03 Dirk Eddelbuettel * man/Bond.Rd: Restore example with correctly-built Windows library * man/FixedRateBond.Rd: Idem * man/FloaringRateBond.Rd: Idem * man/SabrSwaption.Rd: Idem * man/ZeroCouponBond.Rd: Idem * tests/RQuantLib.R: Restore tests for Windows * tests/doRUnit.R: Idem 2018-11-28 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * man/CallableBond.Rd: Set evaluation date * src/Makevars.in (PKG_CXXFLAGS): Add -DBOOST_NO_AUTO_PTR * src/Makevars.win (PKG_CXXFLAGS): Idem * inst/NEWS.Rd: A few post-release edits 2018-11-25 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.6 2018-11-22 Dirk Eddelbuettel * configure.ac: Test for QuantLib 1.14 * configure: Idem * tools/winlibs.R: Updated for QL 1.14 build by Josh * man/Bond.Rd: Do not run examples to avoid Windows issue * man/FixedRateBond.Rd: Idem * man/FloaringRateBond.Rd: Idem * man/SabrSwaption.Rd: Idem * man/ZeroCouponBond.Rd: Idem * tests/RQuantLib.R: Test for Windows, only run a portion of tests * tests/doRUnit.R: Test for Windows * src/Makevars.win: Set -Wno-deprecated-declarations options to make the build less noisy 2018-11-20 Dirk Eddelbuettel * man/Bond.Rd: Example now uses dayCounter not accrualDayCounter * man/FixedRateBond.Rd: Idem * tests/RQuantLib.R: Idem * tests/RQuantLib.Rout.save: Idem 2018-11-11 Dirk Eddelbuettel * src/Makevars.in (PKG_CXXFLAGS): No longer need the opt-in for -DRCPP_NEW_DATE_DATETIME_VECTORS which is now on by default 2018-10-28 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/asian.cpp: Patch fron Debian #911957 to support Boost 1.67 * src/barrier_binary.cpp: Idem * src/implieds.cpp: Idem * src/vanilla.cpp: Idem * src/affine.cpp: Use BlackCalibrationHelper not CalibrationHelper * src/bermudan.cpp: Idem * src/hullwhite.cpp: Idem * docker/ci/Dockerfile: Moved from ../Dockerfile * docker/run/Dockerfile: Added, providing run-time * .travis.yml: Use rquantlib/ci for Travis CI 2018-08-26 Dirk Eddelbuettel * .travis.yml: Remove unneeded compiler and language tags 2018-08-22 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/calendars.cpp (addHolidays, removeHolidays): New functions * man/Calendars.Rd: Added documentation 2018-08-16 Dirk Eddelbuettel * .travis.yml: Prettification for Travis file 2018-08-14 Dirk Eddelbuettel * docker/Dockerfile: Add Dockerfile to create test container * .travis.yml: Adapted to use Docker container 2018-08-13 Dirk Eddelbuettel * .travis.yml: Try 20 minute timeout parameter 2018-08-11 Dirk Eddelbuettel * README.md: Updated to mention renewed Windows support 2018-08-10 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.5 * configure.ac: Mark as 0.4.5 * configure: Rebuilt * src/Makevars.in: Set CXX_STD=CXX11 * src/Makevars.win: Idem 2018-04-29 Dirk Eddelbuettel * man/AffineSwaption.Rd: Do not run example as win32 is fragile * man/BermudanSwaption.Rd: Idem * man/DiscountCurve.Rd: Idem * .Rbuildignore: Also ignore .tar.gz * inst/include/RQuantLib_RcppExports.h: Updated via current Rcpp::compileAttributes() version * src/RcppExports.cpp: Idem 2018-04-27 Jeroen Ooms * src/Makevars.win: Rewritten using rwinlib repo for Quantlib library * tools/winlibs.R: New helper script to gather libraries from repo * DESCRIPTION: Remove 'OS_type: unix' 2018-01-07 Dirk Eddelbuettel * src/affine.cpp (affineWithRebuiltCurveEngine): Remove declaration and assignment of one unused variable * src/bermudan.cpp (bermudanFromYieldEngine): Idem * src/sabr.cpp (sabrengine): Idem (twice); also rename one variable ('todaysDate') to its parameter name ('tradeDate') 2018-01-01 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New minor version * src/affine.cpp: Use #include * src/asian.cpp: Idem * src/barrier_binary.cpp: Idem * src/bermudan.cpp: Idem * src/bonds.cpp: Idem * src/calendars.cpp: Idem * src/curves.cpp: Idem * src/dates.cpp: Idem * src/daycounter.cpp: Idem * src/discount.cpp: Idem * src/hullwhite.cpp: Idem * src/implieds.cpp: Idem * src/modules.cpp: Idem * src/sabr.cpp: Idem * src/schedule.cpp: Idem * src/utils.cpp: Idem * src/vanilla.cpp: Idem * src/zero.cpp: Idem * src/deprecated/rquantlib.h: Moved from src/ 2017-11-07 Dirk Eddelbuettel * DESCRIPTION (Version, Date): New release 0.4.4 * configure.ac: Mark as 0.4.4 * configure: Rebuilt * README.md: Minor edits * src/utils.cpp: Corrected deprecation of Actual365NoLeap() 2017-10-15 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version * src/utils.cpp (getDayCounter): Deprecate Actual365NoLeap() as needed for use with QuantLib 1.11 * man/Enum.Rd: Mark as deprecated Actual365NoLeap() * man/BondUtilities.Rd: Note that Actual365NoLeap() deprecated 2017-08-03 Dirk Eddelbuettel * DESCRIPTION (Version, Date): Roll minor version and date * NAMESPACE: Set .registration=TRUE * R/RcppExports.R: Updated again with .registration=TRUE 2017-08-02 Dirk Eddelbuettel * src/affine.cpp (affineWithRebuiltCurveEngine): Correction to BKTree * src/RcppExports.cpp: Updated with current Rcpp Attributes * inst/include/RQuantLib_RcppExports.h: Ditto * R/RcppExports.R: Ditto 2017-04-16 Dirk Eddelbuettel * .travis.yml (before_install): Use https to download 2016-11-24 Dirk Eddelbuettel * inst/include/rquantlib_impl.h (Rcpp): Adjust to new date(time)Vector classes in Rcpp 0.12.8 * inst/unitTests/cpp/dates.cpp: Add one explicit copy where we used to have implicit copy * src/Makevars.in (PKG_CXXFLAGS): Set define for new date(time)vector classes to work with Rcpp 0.12.8; has no effect on earlier versions 2016-10-31 Dirk Eddelbuettel * src/vanilla.cpp (europeanOptionEngine, americanOptionEngine): Correct use of divtimes in case of no high-res. times in QuantLib; only use duration type when high-res time defined 2016-10-28 Dirk Eddelbuettel * src/vanilla.cpp (europeanOptionEngine, americanOptionEngine): Use Nullable<> on dividend parameters, other small rewrites * R/options.R: Corresponding changes 2016-10-24 Francois Cocquemas * src/vanilla.cpp: Adjust intra-daily part (via patch by Dirk) 2016-10-23 Dirk Eddelbuettel * man/BermudanSwaption.Rd: Add links to SabrSwaption 2016-10-22 Francois Cocquemas * R/option.R: Support discrete dividends for European and American options * src/vanilla.cpp: Ditto * man/EuropeanOption.Rd: Documentation update * man/AmericanOption.Rd: Ditto * tests/RQuantLib.R: Added test 2016-08-21 Dirk Eddelbuettel * DESCRIPTION(Version): Rolled minor version to 0.4.3.1 * configure.ac: Require at least QuantLib 1.8 * configire: Rebuilt * NAMESPACE: Also import zoo from zoo * man/FittedBondCurve.Rd: No longer need to test for (imported) zoo 2016-08-19 Dirk Eddelbuettel * DESCRIPTION (Version): Release 0.4.3 * DESCRIPTION (OS_type): Set to 'OS_type: unix' as CRAN has not installed an updated QuantLib library despite repeated emailed offers offer several months. A Windows binary will be provided. * configure.ac: Mark as 0.4.3 * configure: Rebuilt * README.md: Add Terry to Authors, add Installation note, add link to Contributing document 2016-08-12 Dirk Eddelbuettel * R/inline.R (.onLoad): Check for quantlib-config before using it 2016-08-04 Dirk Eddelbuettel * DESCRIPTION: Roll minor version * data/tsQuotes.RData: More explicit name and loading * data/vcube.Rdata: Idem * R/datasets.R: Dataset documentation * man/tsQuotes.Rd: Idem * man/vcube.Rdata: Idem * .travis.yml: Switch to using run.sh for Travis CI 2016-07-20 Terry Leitch * R/sabr.R: New function for SABR swaption model * src/sabr.cpp: C++ implementation for SABR model * inst/shiny/SabrSwaption/*: Shiny application for SABR model * data/rqlib.RData: Sample data 2016-05-29 Dirk Eddelbuettel * DESCRIPTION (Version): Increased patch version and Date * .travis.yml: Minor edits 2016-05-27 Guillaume Horel * inst/unitTests/runit.businessdayconvention.R: New tests * inst/unitTests/runit.schedule.R: Small cleanup 2016-05-19 Guillaume Horel * src/curves.cpp: Added extra swap tenors * man/DiscountCurve.Rd: Idem 2016-05-19 Terry Leitch * src/curve.cpp: Added swap tenors from 40-100 years to curve build * src/discount.cpp: Increased max date from 2099 to 2150 * man/DiscountCurve.Rd: Updated doc to reflect new tenor choices 2016-05-12 Dirk Eddelbuettel * .travis.yml (script): Turn travis_wait back on 2016-05-09 Terry Leitch * NAMESPACE: Updated to refelct new methods for affine swaption * R/affine.R: New generic swaption model based on bermudan affine model * src/affine.cpp: New engine for affine swaption model * man/AffineSwaption.Rd: created * R/bermudan.R: Swaption model modified to take more general tenor & expiration dates and curve input * src/bermudan.cpp: Swaptions for fit selection & yield curve fit moved up into bermudan.R * man/BermudanSwaption.Rd: Modified to reflect DiscountCurve option and example updated 2016-04-02 Dirk Eddelbuettel * R/zzz.R: Correct version comparison check 2016-03-26 Dirk Eddelbuettel * Contributing.md: New files 2016-03-25 Dirk Eddelbuettel * R/discount.R: Minor edits and cleanups * src/discount.cpp: Idem * man/DiscountCurve.Rd: Minor correction 2016-03-28 Terry Leitch * R/bond.R: Added converters for float frequencies * R/discount.R: nUse float frequency textual descriptions, pass float and fixed as one new combined parameter for swap legs * src/bermudan.cpp: Use new parameter setting * R/bermudan.R: Support old default values 2016-03-19 Dirk Eddelbuettel * R/discount.R: Restored standard indentation style, untabified * inst/include/rquantlib_internal.h: Idem * src/discount.cpp: Idem * src/curves.cpp: Idem * man/DiscountCurve.Rd: Idem, corrected parameter naming * README.md: Use canonical CRAN URL to please R-devel CMD check 2016-03-17 Terry Leitch * R/discount.R: Support arguments for day counter, frequency and floating frequency to enable more flexible curve building * inst/include/rquantlib_internal.h: Idem * src/discount.cpp: Idem * src/curves.cpp: Idem; new getRateHelper() function 2015-12-03 Dirk Eddelbuettel * DESCRIPTION: Release 0.4.2 * configure.ac: Mark as 0.4.2 * configure: Rebuilt 2015-12-02 Dirk Eddelbuettel * R/zzz.R (.onAttach): Add detection of QuantLib version and intra-day capability and warn via startup message (if not interactive) 2015-11-30 Dirk Eddelbuettel * src/implieds.cpp: Use intra-day time calculation if available with QuantLib (>= 1.7) has been compiled for it * .travis.yml: Switch to using Ubuntu 14.04 aka 'trusty'; switch to my copy of r-travis to use 'apt-get install -y'; run without travis_wait 2015-11-29 Dirk Eddelbuettel * src/utils.cpp: New helper functions getQuantLibVersion() and getQuantLibCapabilties() which reports configuration options * man/getQuantLibVersion.Rd: New manual page (via roxygen2) * man/getQuantLibCapabilities.Rd: Idem 2015-11-28 Dirk Eddelbuettel * src/asian.cpp: Use intra-day time calculation if available with QuantLib (>= 1.7) has been compiled for it * src/barrier_binary.cpp: Idem 2015-11-26 Dirk Eddelbuettel * DESCRIPTION (Version): Roll Date and Version * src/vanilla.cpp: Use intra-day time calculation if available with QuantLib (>= 1.7) has been compiled for it * man/BondUtilities.Rd: Add 'Monthly' to documentation * .travis.yml: Wrapped in 'travis_wait' to avoid timeout * tests/doRUnit.R: Updated 2015-10-29 Dirk Eddelbuettel * R/bond.R: Add missing parameter 'Monthly' to freq arguments in function matchFrequency() (issue ticket #19) 2015-09-11 Dirk Eddelbuettel * DESCRIPTION: Release 0.4.1 2015-09-10 Dirk Eddelbuettel * NAMESPACE: Added more new S3method declarations * R/arrays.R (plotOptionSurface): Use requireNamespace to condition on the optional rgl package * README.md: Added badges 2015-07-07 Dirk Eddelbuettel * R/arrays.R (plotOptionSurface): Change from require() to the now-preferred requireNamespace() * NAMESPACE: Added more explicit S3method() registrations 2015-02-22 Dirk Eddelbuettel * .travis.yml (install): Now use only r-cran-* binary packages 2015-02-21 Dirk Eddelbuettel * .travis.yml (install): Use more r-cran-* packages from ppa:edd/misc 2015-02-12 Dirk Eddelbuettel * src/Makevars.win: Tweak suggested by Jeroen (cf GitHub issue #12) 2015-02-11 Dirk Eddelbuettel * .travis.yml (install): Switch to using ppa:edd/misc for QuantLib debs 2014-12-03 Dirk Eddelbuettel * DESCRIPTION: Bump dev version, add Suggests: shiny * .travis.yml: Add shiny as Suggests: are needed by R CMD check * inst/shiny/DiscountCurve/ui.R: UI part of simple shiny app * inst/shiny/DiscountCurve/server.R: Server part of shiny app * demo/ShinyDiscountCurves.R: New demo() wrapper for shiny app 2014-12-01 Dirk Eddelbuettel * DESCRIPTION: Release 0.4.0 * DESCRIPTION: Update to note we need QL 1.4.0 or later * configure.ac: Mark as 0.4.0, allow for newer g++ versions * configure: Rebuilt 2014-11-29 Dirk Eddelbuettel * inst/NEWS.Rd: Expanded reflecting changes since last release 2014-11-27 Dirk Eddelbuettel * inst/NEWS.Rd: Added -- better late than never * man/Calendars.Rd: Add documentation for advanceDate * man/Schedule.Rd: Add standard reference to QuantLib to the details section (which was empty) 2014-11-07 Dirk Eddelbuettel * .travis.yml: Call via travis_wait to allow for potential timeout * NAMESPACE: Also export advanceDate() 2014-11-07 Michele Salvadore * DESCRIPTION: New minor version * NAMESPACE: Export Schedule * R/schedule.R: Added Schedule function to expose the QuantLib::Schedule to R * man/schedule.Rd: Ditto * src/schedule.cpp: Ditto 2014-10-30 Dirk Eddelbuettel * NAMESPACE: Tighten exportPattern for .default as suggested by Bill Dunlap 2014-10-29 Michele Salvadore * R/bond.R: Added a price parameter to FixedRateBond to calculate based on clean price * src/bonds.cpp: new function wrapping price based calculation * man/Bond.Rd: updated documentation and examples * man/FixedRateBond.Rd: Ditto * tests/RQuantLib.R: Corresponding test update * tests/RQuantLib.Rout.save: Ditto 2014-10-27 Dirk Eddelbuettel * DESCRIPTION: New minor version * src/bonds.cpp: Remove last SEXP instances in function interfaces * src/hullwhite.cpp: Idem * src/utils.cpp: Idem * inst/include/rquantlib_internal.h: Updated accordingly 2014-10-26 Dirk Eddelbuettel * src/discount.cpp: Curve exported in 'table' object now advances by roughly one business months, also switched to using STL containers grown and then exported back to R * inst/include/rquantlib_internal.h: Declare advanceDate() function * man/Bond.Rd: Re-set evaluation date in bond example 2014-10-25 Dirk Eddelbuettel * inst/unitTests/runit.dates.R: R side of new date conversion tests * inst/unitTests/cpp/dates.cpp: C++ side of new date conversion tests * R/unitTest.R: Added new support function unitTestSetup() * NAMESPACE: Also import sourceCpp from Rcpp 2014-10-24 Dirk Eddelbuettel * src/bonds.cpp: Use the calendar from the RQL context * src/zero.cpp: Ditto 2014-10-23 Dirk Eddelbuettel * src/dates.cpp (advanceDate): Use a calendar from the RQL context 2014-10-22 Dirk Eddelbuettel * inst/include/rquantlib_impl.h: New header with implementations for as<>() and wrap(), currently only for Date mapping between QL and R * inst/include/rquantlib_wrappers.h: Reduced to declarations only * inst/include/RQuantLib.h: Include new header rquantlib_impl.h if and only if a #define is set accordingly * src/dates.cpp: Include new header rquantlib_impl.h to have it in default build for package just once * R/inline.R (CFlags): Plugin builds set the #define for new header file 2014-10-20 Dirk Eddelbuettel * man/DiscountCurve.Rd: Do not include two-year swap ("s2y") in curve parameters, and correct evaluation date -- with thanks to Luigi Ballabio * man/Bond.Rd: Ditto 2014-10-18 Dirk Eddelbuettel * inst/unitTests/runit.options.R: Skip AsianOption() test on Windows 2014-10-17 Dirk Eddelbuettel * src/Makevars.in: Add OpenMP support (conditional on R having it) * configure.ac: Renamed from configure.in; also updated check for QuantLib to ensure version 1.4.0 or later is used * inst/unitTests/runit.calendar.R (test.isBusinessDay): adjust parens 2014-10-15 Dirk Eddelbuettel * DESCRIPTION: New minor version * src/dates.cpp: New place for as<> and wrap() for Quantlib::Date * inst/include/RQuantLib.h: No longer include rquantlib_wrappers.h * src/Makevars.win: Add -fpermissive to cope with a 'long long' conversion, also enable support for OpenMP on Windows 2014-10-15 Michele Salvadore * src/bonds.cpp: Updated FixedRateBond() to better match the function signature in the QuantLib library while making it more flexible * src/utils.cpp: * bond.R: Ditto * man/Bond.Rd: Updated accordingly * man/FixedRateBond.Rd: Ditto * tests/RQuantLib.R: Corresponding test update * tests/RQuantLib.Rout.save: Ditto 2014-10-14 Dirk Eddelbuettel * DESCRIPTION: Added minor version, shorter Description 2014-10-13 Michele Salvadore * src/bonds.cpp: Fixed-income functionality cleanup * src/utils.cpp: Ditto * R/bonds.R: Ditto * man/Bond.Rd: Corresponding documentation update * man/BondUtilities.Rd: Ditto * man/CallableBond.Rd: Ditto * man/ConvertibleBond.Rd: Ditto * man/Enum.Rd: Ditto * man/FixedRateBond.Rd: Ditto * man/FloatingRateBond.Rd: Ditto * man/ZeroCouponBond.Rd: Ditto * tests/RQuantLib.R: Corresponding test update * tests/RQuantLib.Rout.save: Ditto 2014-06-16 Dirk Eddelbuettel * inst/QuantLib_LICENSE.TXT: Renamed from QuantLib-License.txt per CRAN request * inst/Boost_LICENSE.TXT: Renamed from Boost-License.txt for symmetry 2014-05-28 Dirk Eddelbuettel * R/asian.R: Set default values for first, length and fixing used for arithemtic asian options * man/asian.Rd: Update documentation * src/asian.cpp: For arithmetic option, check parameters first, length and fixings * src/asian.cpp (asianOptionEngine): Use NA not NaN on missing greeks * src/barrier_binary.cpp (barrierOptionEngine): Idem * tests/RQuantlib.Rout.save: Updated accordingly 2014-05-20 Dirk Eddelbuettel * src/utils.cpp: Converted three more functions interfaces * src/bonds.cpp: Idem * inst/include/rquantlib_internal.h: Idem 2014-05-18 Dirk Eddelbuettel * src/utils.cpp: Change getIborIndex and getFlatCurve to use List * src/bonds.cpp: Idem * inst/include/rquantlib_internal.h: Idem 2014-05-17 Dirk Eddelbuettel * src/utils.cpp: Change getSchedule to use List argument * inst/include/rquantlib_internal.h: Idem 2014-04-06 Dirk Eddelbuettel * src/utils.cpp (buildTermStructure): Simplified interface * inst/include/rquantlib_internal.h: Corresponding declation * src/bonds.cpp: Use simpler interface to builtTermStructure() 2014-04-05 Dirk Eddelbuettel * src/bonds.cpp: Finishing conversion to Rcpp Attributes * R/bond.R: More corresponding changes * src/utils.cpp: Retire getDoubleVector() helper * src/bonds.cpp: Corresponding adjustments * R/bond.R: Idem * man/bond.Rd: Use vector() for empty vector * man/FloatingRateBond.Rd: Idem * tests/RQuantLib.R*: Idem 2014-04-04 Dirk Eddelbuettel * src/bonds.cpp: More Rcpp Attributes * R/bond.R: More corresponding changes 2014-04-03 Dirk Eddelbuettel * src/bonds.cpp: More Rcpp Attributes * R/bond.R: More corresponding changes 2014-04-02 Dirk Eddelbuettel * src/bonds.cpp: More Rcpp Attributes * R/bond.R: More corresponding changes 2014-04-01 Dirk Eddelbuettel * src/bonds.cpp: Partially changed to use Rcpp Attributes * R/bond.R: Corresponding changes 2014-03-31 Dirk Eddelbuettel * src/curves.cpp: Some updates reflecting newer Rcpp 2014-03-30 Dirk Eddelbuettel * src/vanilla.cpp: Changed to use Rcpp Attributes * R/option.R: Changed calls accordingly * R/arrays.R: Idem * man/AmericanOption.Rd: Updated as param. list no longer returned * man/EuropeanOption.Rd: Idem 2014-03-29 Dirk Eddelbuettel * src/implieds.cpp: Changed to use Rcpp Attributes * R/implieds.R: Changed calls accordingly * man/AmericanOptionImpliedVolatility.Rd: Updated * man/EuropeanOptionImpliedVolatility.Rd: Updated 2014-03-28 Dirk Eddelbuettel * src/bermudan.cpp: Changed to use Rcpp Attributes * R/bermudan.R: Changed call accordingly * src/bermudan.cpp: Updated copyright header with gnu.org URL * R/bermudan.R: Idem 2014-03-27 Dirk Eddelbuettel * src/hullwhite.cpp: Changed to use Rcpp Attributes * R/hullWhiteCalibration.R: Changed call accordingly * src/hullwhite.cpp: Updated copyright header with gnu.org URL * R/hullWhiteCalibration.R: Idem * .travis.yml: Revert to main repo now that pull request is in 2014-03-26 Dirk Eddelbuettel * src/discount.cpp: Changed to use Rcpp Attributes * R/discount.R: Changed call in default methods accordingly * src/discount.cpp: Updated copyright header with gnu.org URL * R/discount.R: Idem 2014-03-25 Dirk Eddelbuettel * src/barrier_binary.cpp: Changed to use Rcpp Attributes * R/implied.R: Changed call in default methods accordingly * R/option.R: Idem * man/BarrierOption.Rd: Updated as param. list no longer returned * man/BinaryOption.Rd: Idem * man/BinaryOptionImpliedVolatility.Rd: Idem * src/barrier_binary.cpp: Updated copyright header with gnu.org URL * R/implied.R: Idem * R/option.R: Idem 2014-03-24 Dirk Eddelbuettel * src/asian.cpp: Changed to use Rcpp Attributes * R/asian.R: Changed call in default method accordingly * man/asian.Rd: Updated as parameter list no longer returned * src/asian.cpp: Updated copyright header with gnu.org URL * R/asian.R: Idem * inst/unitTests/runit.calendar.R: Corrected mode 2014-03-23 Dirk Eddelbuettel * src/zero.cpp: Changed to use Rcpp Attributes 2014-03-22 Dirk Eddelbuettel * src/calendars.cpp: Changed to use Rcpp Attributes * src/daycounter.cpp: Idem * R/calendars.R: Commented-out / adapted as RcppExports.R takes over * R/dayCounter.R: Commented-out as RcppExports.R takes over * man/Calendars.Rd: Minor adjustments to documentation of default argument * src/rquantlib.h: Moved from inst/include to avoid lower / uppercase clash; this header really is an internal definition header; sources the content formerly in quantlib.h * inst/include/rquantlib_internal.h: Formerly known as rquantlib.h * inst/include/rquantlib_wrappers.h (Rcpp): Moved definition of as<> and wrap for Date and DateVector here to be read by plugin; added definitions for vector of dates * src/rquantlib: New as<> and wrap converters for DateVector * src/bermudan.cpp: Use as<> and wrap converters for Date and DateVector * src/bonds.cpp: Idem * src/calendars.cpp: Idem * src/daycounter.cpp: Idem * src/discount.cpp: Idem * src/hullwhite.cpp: Idem * src/utils.cpp: Idem * src/zero.cpp: Idem * src/utils.cpp: Retire old dateFromR() converter replaces by as<> * inst/include/RQuantLib.h: Also include 'wrapper' header for converters * R/inline.R (inlineCxxPlugin): Plugin reads header RQuantLib.h 2014-03-21 Dirk Eddelbuettel * src/utils.cpp: Added as<> and wrap conversion for QuantLib::Date * src/dates.cpp (advanceDate): Added simple test date function, also uses Rcpp Attributes as a first test case * inst/include/RQuantLib.h: Added and edited to allow inclusion of actual rquantlib.h header via RcppExports 2014-03-20 Dirk Eddelbuettel * src/bonds.cpp (FittedBondCurve): Converted from deprecated FixedRateBondHelper to BondHelper with a FixedRateBond 2014-03-16 Dirk Eddelbuettel * src/calendars.cpp: Applied patch by Danilo Dias da Silva to support more calendars by adding more than two dozen new identifiers * man/Calendars.Rd: Updated accordingly 2014-03-09 Dirk Eddelbuettel * DESCRIPTION: Release 0.3.12 * man/FittedBondCurve.Rd: Test for suggested package zoo before use 2014-03-08 Dirk Eddelbuettel * configure: Updated for Rcpp 0.11.0 and later * configure.in: Idem * src/Makevars.win: Updated for Rcpp 0.11.0 and later * R/inline.R (.onLoad): Set a default value of NULL for the QL libs and headers, and only override if either the corresponding env.vars are set are the quantlib-config script can be found * R/inline.R: Only supply LdFlags() and CFlags() results if stored values are non-null 2014-02-05 Dirk Eddelbuettel * R/inline.R (.onLoad): No longer need to add LdFlags() from Rcpp to PKG_LIBS when preparing ql_libs. * R/inline.R (inlineCxxPlugin): Rcpp.plugin.maker() can now be called directly as it is imported from Rcpp * DESCRIPTION: Add a requirement for Rcpp 0.11.0 or later * NAMESPACE: Import Rcpp.plugin.maker from Rcpp 2014-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/README.md0000644000176200001440000000477513410312314013377 0ustar liggesusers## RQuantLib [![Build Status](https://travis-ci.org/eddelbuettel/rquantlib.svg)](https://travis-ci.org/eddelbuettel/rquantlib) [![License](http://img.shields.io/badge/license-GPL%20%28%3E=%202%29-brightgreen.svg?style=flat)](http://www.gnu.org/licenses/gpl-2.0.html) [![CRAN](http://www.r-pkg.org/badges/version/RQuantLib)](https://cran.r-project.org/package=RQuantLib) [![Dependencies](https://tinyverse.netlify.com/badge/RQuantLib)](https://cran.r-project.org/package=RQuantLib) [![Downloads](http://cranlogs.r-pkg.org/badges/RQuantLib?color=brightgreen)](http://www.r-pkg.org/pkg/RQuantLib) ### About 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. ### Status The package is actively maintained, and is still being extended. Contributions are welcome, and initial discussions via [GitHub issue tickets](https://github.com/eddelbuettel/rquantlib/issues) are encouraged as suggested in the [Contributing guide](https://github.com/eddelbuettel/rquantlib/blob/master/Contributing.md). ### Installation #### From Source The package is on [CRAN](https://cran.r-project.org) and can be installed as usual: ```{r} install.packages("RQuantLib") ``` Windows binary packages are available via [CRAN](https://cran.r-project.org) thanks to the library provided by [Joshua Ulrich](https://about.me/joshuaulrich) via the [rwinlib/quantlib](https://github.com/rwinlib/quantlib) repository. Binaries for macOS _could_ be provided if we had a similar binary library, ideally via the [s-u/recipes](https://github.com/s-u/recipes) repository. Some efforts are under way and coordinated on the [rquantlib mailing list](http://rquantlib.groups.io) so stay tuned. For more OS-specific installation options, please see [the wiki](https://github.com/eddelbuettel/rquantlib/wiki/RQuantLib). ### Support Come to the friendly and low-volume [rquantlib mailing list](http://rquantlib.groups.io) for help. ### Authors Dirk Eddelbuettel, Khanh Nguyen (during 2009-2010) and Terry Leitch (since 2016) ### License GPL (>= 2) RQuantLib/data/0000755000176200001440000000000013376525200013027 5ustar liggesusersRQuantLib/data/vcube.RData0000644000176200001440000001360113607470337015060 0ustar liggesusers‹í\”UÚf’QÌ(b@ ˆ.bA ²‚¨;À º£(*+"‹Y ,¢®b^Öœ³®¢.¤®ê\Õa"iAEaß{}«æ_øýÏÙÙŸsDzÎyLOO׫îw¿ûÝWÃèó®è×îŠvyyyùy­óóò ÄË–ùâŸy-óÚŠï­nš<{RQ^^Áò7â{GñÔþó–¿ZA3ZËf´V»¡µnFkÓŒ¶O3ZÛf´vÍhí›Ñ:4£ulFËa<‡ñƽß1‹‘ÿ>Fr1´çÄP.ryâ·Žñ\žøuÆH.†öœÊÅ@.Oä0žÃxãÿn¶..º©¨x¦xÕIý6ûnAß>ãù2¿ïï•÷^?ïUï·ý½÷Nõ^ ð^ ô>7Ð{ï4ïÕ ïÕéãwvp'ÎtÇçzjáäY%¥âÕöÿÒÓ͵\Û“ÚîÈ5¹–k¿¦¶;jä\˵½©íO(×rí×ÔvGíšk¹¶7µæx5¹–k{RkŽ·˜k¹¶5i™æïÈ˺¤mòvqq ú6Y±ž[ЯϮŽnAÿ>ÿÓ¾U=¸=ÿ¯þkžò_wìØ1H´ëE{J´¢UŠV“—ýê*Z?ц‹6E´ÇDûæ—®m­h¢mmûùJzëû‰Öù?í³9ãØÛÆž»&‡“ßúØs×ìÙ8Ù›ûÜÛöú×<ßܺþ¶Çž»fÏÆÉÞÜç޶׿æùæÖõ·=öÜ59œüÖÇž»æÿ¾F´}¥ŠêZ}Òâ…Hh_8äR„ü#Ϩð7˜ïlÿzúÄm06–\wÞµƒ ßrVhÞ¤÷¡ýêÀ[÷{ù©+njÕ9›0áûðØçŸºùIøN>sÙÚ¼J£ê•ŠeBÅçnŸøˆÞF9”6ÏãûÑcÿÊ”/Qú&Ð^Ù㎧/ Ûž½åçn;4"ÐøòOˆ,úvÄõ]ŽDØ—ùý9÷ž†ð ÝÛÏ)¸¡?¿yiÇ?@¨ke›kJ°ÞYRç¼u,^g÷Fuß)ï:òL˜™ÕGtN} kð¶ÛÞ±¡¹‡…Gu­Däˆê'õ“ÏBü¢ÚåGTÿöã×´Þòç ¼q®ÏþŒL›o†_U>ÉÙÇ]ÐÀ¾§ò†ÁÛæ!~Ø>OæÏ>‘²GŸ¸êV„Õ2žë­M·‰¥ƒù~Ý~?”^Sö2óN‡NX?ù¨û`ìè-îxäƒ>ZÕ©ìDÔçùß?øŠ$R‡ütÙE]6Âi¿ßñŸ²ñ†ÃÏ=ù¥[½vÐüÇE‹‹ÛæÇa­üþ´¿?*Ì›®±^õÅhn$Æ 3z¿ýUè‹g}rýí?Bo¡Þðæ³yZ[}É!=Qû·/Æ®^¸i¹KWþŽØD±³ˆËnû?…øùÏ­ù|Áˆ©o%ˆµýÇÜ~¢óKò¦E@´õƒ|´jD–vŸ5fÑ·ˆ4<üØ''Õ€~¢Ïg׈°šn[„Þéµï¸–]z×7÷O+bw¾Õ¹ðΈ ;öôÏÖ#úØÇ¯JÞ‰Íê6ÝQsÈI¢‡}áô,H÷@"qÆ” ‡¿†˜Zþ>7¾¼­¦ø~„Üþóµ;¼³¤Á9ÅÇLkkÀ‹5¯ìQèïßqêô¯ƒÐžV@à‡È1JظôÁKE—È´bfý»Ó`/¼{qléĹ‘%ó[w‚ÐòëI˜›ïþéÃc_@P åÌeë`?ú#2PBcܾ\½¾l[޼TìÌXW˜ÞZôóýH­ºå¯+Úܖ"ˆ®ˆþ@ø¦oþ.BÖÓºóåÅ0;«@„ ›ièÜgMLöÜ%ó¡|Nt‰@ÿ§öý,ñ"üK·ô¼¾Æðö·Q†åÃKQ͸KqÞÎY Àˆg·ÑqòÏ üÐľ[ùB¥ž?hÃXúÏß¾wþó°îew<ìFXÄGH®Æ¡Ï¢þE œ»ä¼cM'=Ñ-Î@hð£/´Ó¦ZöÓ¨øøño Ç"b΀–¼sˆØhœg xóQÝzÝ ?×Ó·î‘i¥ouC-Çé7Ñ% sÞ–¢—+$Î ÞW?D´¯^&B©ê ~®¿¯¦àÍ÷ë:ÁGž¨ùD›°ðî?è¾ÿµ¹KB˜+F2æUå“Ï9† ƒCè;íÚghû‡¸CnÜ+ðÕoÍï–ß ¯›û>ôu+øT8MF•âq†Õâ·w­<¶ºMG„%j/{–DÃ1þ&\u¹»g~‡aMxRð˜ÃÂ#?µþ*Pá{éV‰tT‘_*ýÎDZ²Ñí[)7öKXbg/:AâZç¾TXÀÏÏù*Àײ~Ø@%ï[A–«iwFYZëÞ6 ´<·æ dMÍÃñ¹G²yÉuˆ ˆ‚°\ž{ŸE8_%,/ßY2¼Ÿ+ƒµè¾ÅÒÃ’Ñ?ñD˜*Ÿ s®L•nî@P¥ËîAæÉ`¡ìðP™—-9ŠÖ[*Q„õÌ©u2ñ?Š,}ïƒè•ÐÊæ?ïºà ¬~0m 7 :õƒ6fke¨ËÝ×üMã‡Ã/ásžõÜ礼]§2Ä *ðò¥Òë5Êô;ßjÊ "ɶ~ðChò§Á'! Ó×ÇOÀ/»ö|ÜoŸ’#½Q§¶é`8o¨Ä…¨ÚžãJÉ 3"„X'âO—ìÞêh~m¾i¿”g>ãß7K-ª~’@œƒíRFܲõoýÕ_^J!%iuðbØân=ênAì¥ýŸ²goEXNëêe°ÈæÉêE“¾X­ ñèæ“ q^s›L¼ka‡?ünü»>DävQK°ü3ŸÝŒ ó«A\éY‰@Zçzø¾O\9þ¡*áÁ÷º 4T1®*ÉßÕ¥r"…MÝ–ì?ýŸ°D0‹E|®/WB šˆæ£6eéóõ×à¿á³ÝY7Â'Xþ„jàSÃŒJîoåÁ_|úÒþO#£hz"÷ e¸/BÜgS-ÿpr¸ãÿ|«qÜ›ðs¼ý&.ªämNÿ•Ù¸CÇ‘é!oxâ.Ëižý*‚ŒK]·0q`¼xûM«"Ž*ßøã8‘Q1N%B”sŸåd Þü@èÁ¬ŠËôÑc>"Ÿ)Á€÷ÕŒIP‹ u!·ï¦ÕЩ=|3>ü2=µœï®§Ëã;ÇV-fä;Ô0¿ØÔ³ %·F!Þçò~…sGŒq=t ÜDÈkaÆ[˜ëViÂjºÝ<~Šž¤8âÝð`w’‰ù8E `Hfñ²óø†ä}+…òÁبdTkԱȌQ„´¢«‘H+š.EJªË!b=U: I®sR¥­b8Ô%ñãæ1»nŽTDH(¸NAL ûxD“]‹zj_""Ù©g¾;ï]Öq3õÄzêÍ:‰–·¢š¼œQáÛé_ Õž=i¡2–>xÒ¬ÇRÔå©s• E’ùÓ廤¤«ÍpÔ6[.»E‚ù8¶PnˆL÷q„»HaúÅ}ßBÜ7¨òãwHS泌óRÝ”ÀA’|í°¾rî—ü18=Ub‚-Ót‡waSØS” òzÄõͨ£½zNÙ4í½º+¨dÀxoWÄ… ¢ùöMõÝ2•0`(º?°iߨŸtæ ãe¸!H}`*ùßõe’0dÜx8çç,Ö…Ág”@‚Á¸Ó6¨…@@Ùˆ¢ž¦>÷˰>úkø¨Ó}¬ûj™?â0"ÕíA+’ô×Þ)‡ýô;Þ|<¼1ÿ8o?},ýuM}Ï®ƒýž"~„ÊP„EþsyFoH¸ ý¨õ“Ÿüã£ñÉôsXUô‡*é+m&þk8GuÛqê׿sëB×§4¨;tß/ŸÔçrèôKôl^†®ì»Û Ëðóªé³Ø²lœWŽý “þA}î^ Ïè§žò °²x6|M‚‚›ô1õs…’ñW#ãúäÛy¤c¨eñ2vó=ð³.õQTו*\@㽜þPF-ËÄ]Ž~Fþ«þ¬2È  v½ø£«áWeâÅðQ¸þwyÛ­SÊY_•‹‹àH3Þb®ÏH]dÐOÒ‰›u˜§ß9ž*ú¿•Ì ÌÓåôÁʨgè'$™?c÷Ê܈ˆPçzQÇ›—I"݃û¢ÓÑ蓨›Ô~•v‚OÉßã~YwwuäÙÔ<•p¤¿™$ï:Ä£Cýd«òó<ØÄ½}ž$lY¦}ð1ÊŽ9Ôósì–jâžîtè»$©?Sç)#}WÝËxØ@?ºŽù:£äÄ,¤é—¥é×¹¾FоJJ–å[~FR•!-%`4©VϺ˜>”§™çã¬ó]îÖCôŸwg#óhù½†÷O3ÿ¥‰ƒõkŠç2©V²0ú ÉåŠÅøäÁÉ MúñâÖ]óƒë»ÇéSyú…:Š~Ï/îû·¤Q÷6¨ª‰û ÏuÒµ*a!=NmRôµRÔCÉÔÁ’Œ·äh%¤Þq²Æ úùËÅCÿ5™Õu^ýØŠþ»[g»º0ú!Å:ÍṂM?7ÎxÒÏŽ!µ]‡Á:[ ⣛æÏüUK$Ã8H)ÙÑu™íêbÖCQê÷Ü+Dþ3yÎDß»éœJÉï®È(ƒëW‡º.‘õmcÞ‹GüŸU.¿*¼óª ß7²¾ÿ®õ·:Èy<«Ÿ§†L¶þ@†y2M]æü¼z–ù?Éù%ÉÓIÖSN@zÓá'^éÆý{ê€Êó#쬿ë­GóGŠ:ÚaýäÖ'î9R„z6D>´Ô±ÇM0©ÝuÐ¥<8m4Þ÷;ž›Ô¸xs}W‡“ßܺ;$mÀ½°T¸¶AyǠߨçñæúSô×2¼M?2F}Qra.B¬³,úÜAòŠñ"Fèâ‡1[«<ß: a|ðJøéŸ¬g½’Êž'!Aß1êê_Ö·îùªç»:ˆõ”—w•ÝÕÙëßßC)›‘Qérbœ—IÊËÛô%<7òñ<¸ÊR„JÖ…¬«Ëé–©cØ °†ºi }½zÖ}ýÏ}"‹~¢!?5ᮦsMª0€63ë/iÊà÷Ö+@ÞtÇçÍu²Ÿç¥~[^¾týæ uhH¢~ø*¬g¿i%Có‘8F"keá'ò2ý,×7èo뜷&é­êU¯nðÓW÷sßýÄuÃKʨFRÊõ¢%ˆñ¼%̺Úbd=©×«ƒhä‰]ükúÂ>Öç>™.’ ØÌóøZêb‡:×;—ÇŒ§š0y^èžY߹Ϫ¼˜ƒúB—Û´ðè<'e]ï¸þ´Fý ‘÷ÝúÜõÝs€:ú.qåç<ž% éÂõ~§©n£¿äé|ú&>K ø¨«XßÕ¨r»#lÆC„8µø\[ç¸ç?ù.0C†ðSxçsÔÏUʦ9 •JþC”Uã‚°ù@XÑÃH˜Ä‘Áq¸ëæÖÁþMjcàWöáéMú[ÑÓA¨$.+˜7•Ýtªé£Û¬bÔ aV-a*:Òt~ƺÆå7×—vñ«QÇꪠD5ç‘ /"Ÿšââ׿9ªížC0&˜l9ìÛÞ…ãê|ò]j†Úð]ƹŽuI-óL†~@ŠÏ›¸ã±/®_ê>!_‡©wùüLÓ:ð\´–õf†ú:u€"8|>+±\bôC½~yçGSG³þÕ®:žþÊ:êÕÚÃÕ ÒÔÞyókЏH*;ÿX$é¯$Éë[‡ãvx>æ0¯ÛôÏlž{ÙÒFZ½6}&'‹3o|XïdܺG-ÿipÔ2wBBº ûþ1æ­ˆ²†"Äüm‘/Læ ,×ý#ûˆwŸz%³ú Åç¬âÙ&oyºç!>wbÑW6é[¸Ï?¸þ‰{^·…¼[Ãç^ÜºØæõq®·yÏ›…è;XŒ³¿úBxrý4]îÖZVGìZWR§6?k˜ÇÓä³$}3›y(A5Îç<¿ÿseX!&í³û"h¤þrë=›u“ç·gë%„Y·Z|®ÈT6G ‚Y¹ƒãÑYW»¾‹›'×ߥi7nÉ{1æµ0Ÿ‡²”M×&÷ÇóÛy.¨s<q rŸj ÎK’ã¼>BŸ:DÝâò®ûœ„Ás'ü¥©òa"Ôé~ò³ŸüR§h¼µm¥¾K›xèW°È[Á¬Áßô\ó÷|ýP?}?ëq_6çíô_–Î(œ^43/û'ó-Ý?™?ΠוÞâ~dlÑŒ’R÷Wcn(-*œÂŸ:\RríÈ’Òé…ÅãJŠwê¹miÉͽÝÞå皇øgÇŽ¿ØéõóyA»)…³ {Ï*œT\ôoïL-ìÔùþ½¯›1«¨tFaqï™EÅSK‹¦Š7»°mgûÿ˜R¶³C{µ½kRQuantLib/data/tsQuotes.RData0000644000176200001440000000027013607470337015601 0ustar liggesusers‹ r‰0âŠàb```b`fcb`b2Y˜€# 'æ(),Í/I-*ñ˜$o_ä{éãÊ?p~[»6ç.8¿kþ¾²[,áüNƒ}¼o5záü‰ÖôbÆÂù“_ˆ¼¿3Ο´×ÆLÐÁ‡™â>Ö¼Ä\ãÀŽƒ2§æÂ˜ÅF•p¦1‚i c² ±‘Ä‘ÄMl† "÷Y4RQuantLib/man/0000755000176200001440000000000013403450441012664 5ustar liggesusersRQuantLib/man/EuropeanOption.Rd0000644000176200001440000000635413403306333016132 0ustar liggesusers\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, discreteDividends, discreteDividendsTimeUntil) } \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{discreteDividends}{Vector of discrete dividends (optional)} \item{discreteDividendsTimeUntil}{Vector of times to discrete dividends (in fractional years, optional)} } \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} } \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) ## simple call with slightly shorter maturity: QuantLib 1.7 compiled with ## intra-day time calculation support with create slightly changed values EuropeanOption(type="call", underlying=100, strike=100, dividendYield=0.01, riskFreeRate=0.03, maturity=0.499, volatility=0.5) } \keyword{misc} RQuantLib/man/vcube.Rd0000644000176200001440000000065713072527607014302 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/datasets.R \docType{data} \name{vcube} \alias{vcube} \title{Vol Cube Example Data} \format{two data frames: \code{vcube}, a data frame with four columns: \code{Expiry}, \code{Tenor}, \code{LogNormalVol}, and \code{Spread}} \source{ TBA } \usage{ data(vcube) } \description{ Data for valuing swaption examples including rates and a lognormal vol cube } RQuantLib/man/ImpliedVolatility.Rd0000644000176200001440000000310313403306333016614 0ustar liggesusers\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/BinaryOption.Rd0000644000176200001440000000531713403306333015576 0ustar liggesusers\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} } \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/BermudanSwaption.Rd0000644000176200001440000001321013403306333016432 0ustar liggesusers\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, ts, swaptionMaturities, swapTenors, volMatrix) } \arguments{ \item{params}{A list specifying the \code{tradeDate} (month/day/year), \code{settlementDate}, \code{startDate}, \code{maturity}, \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{ts}{A term structure built with DiscounCurve or 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} , if there are sufficient swaption vols to fit an affine model, 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} If there are insufficient swaption vols to calibrate it throws a warning and returns {NULL} } \details{ This function was update for \code{QuantLib} Version 1.7.1 or later. It introduces support for fixed-income instruments in \code{RQuantLib}. It implements the full function and should work in most cases as long as there are suuficient swaption vol data points to fit the affine model. At least 5 unique points are required. The data point search attempts to find 5 or more points with one being the closet match in terms in of expiration and maturity. See the \code{\link{SabrSwaption}} function for an alternative. } \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}}, \code{\link{SabrSwaption}}} \examples{ # This data replicates sample code shipped with QuantLib 0.3.10 results params <- list(tradeDate=as.Date('2002-2-15'), settleDate=as.Date('2002-2-19'), startDate=as.Date('2003-2-19'), maturity=as.Date('2008-2-19'), dt=.25, payFixed=TRUE, strike=.05, method="G2Analytic", interpWhat="discount", interpHow="loglinear") setEvaluationDate(as.Date('2002-2-15')) # Market data used to construct the term structure of interest rates tsQuotes <- list(d1w =0.05, # 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.05, s5y =0.05, s10y =0.05, s15y =0.05) times=seq(0,14.75,.25) swcurve=DiscountCurve(params,tsQuotes,times) # 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) volMatrix <- matrix( c(rep(.20,25)), ncol=5, byrow=TRUE) # Price the Bermudan swaption pricing <- BermudanSwaption(params, ts=.05, swaptionMaturities, swapTenors, volMatrix) summary(pricing) } \keyword{models} RQuantLib/man/Calendars.Rd0000644000176200001440000002331213340507515015055 0ustar liggesusers\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} \alias{advanceDate} \alias{addHolidays} \alias{removeHolidays} \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. The \code{advanceDate} function advances the given date by the given number of days in the current calendar instance. The \code{addHolidays} and \code{removeHolidays} add (and remove) holidays to (from) the given calendar. Note that this change is transitory and does not persist the session as all actual calendar information comes from the QuantLib library that this package is linked against. } \usage{ isBusinessDay(calendar, dates) businessDay(calendar="TARGET", dates=Sys.Date()) # deprecated form isHoliday(calendar, dates) isWeekend(calendar, dates) isEndOfMonth(calendar, dates) getEndOfMonth(calendar, dates) endOfMonth(calendar="TARGET", dates=Sys.Date()) getHolidayList(calendar, from, to, includeWeekends=FALSE) holidayList(calendar="TARGET", from=Sys.Date(), to = Sys.Date() + 5, includeWeekends = FALSE) adjust(calendar, dates, bdc = 0L) 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, from, to, includeFirst = TRUE, includeLast = FALSE) dayCount(startDates, endDates, dayCounters) yearFraction(startDates, endDates, dayCounters) setCalendarContext(calendar, fixingDays, settleDate) setEvaluationDate(evalDate) addHolidays(calendar, dates) removeHolidays(calendar, dates) } \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), Argentina, Australia, Brazil, Canada and Canada/Settlement, Canada/TSX, China, CzechRepublic, Denmark, Finland, Germany and Germany/FrankfurtStockExchange, Germany/Settlement, Germany/Xetra, Germany/Eurex, HongKong, Hungary, Iceland, India, Indonesia, Italy and Italy/Settlement, Italy/Exchange, Japan, Mexico, NewZealand, Norway, Poland, Russia, SaudiArabia, Singapore, Slovakia, SouthAfrica, SouthKorea, SouthKorea/KRX, Sweden, Switzerland, Taiwan, Turkey, Ukraine, UnitedKingdom and UnitedKingdom/Settlement, UnitedKingdom/Exchange, UnitedKingdom/Metals, UnitedStates and UnitedStates/Settlement, UnitedStates/NYSE, UnitedStates/GovernmentBond, UnitedStates/NERC and WeekendsOnly. (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/Schedule.Rd0000644000176200001440000000522612435703533014723 0ustar liggesusers% $Id$ \name{Schedule} \alias{Schedule} \alias{Schedule.default} \title{Schedule generation} \description{ The \code{Schedule} function generates a schedule of dates conformant to a given convention in a given calendar. } \usage{ \method{Schedule}{default}(params) } \arguments{ \item{params}{a named list, QuantLib's parameters of the schedule. \tabular{ll}{ \code{effectiveDate} \tab a Date, when the schedule becomes effective. \cr \code{maturityDate} \tab a Date, when the schedule matures. \cr \code{period} \tab (Optional) a number or string, the frequency of \cr \code{} \tab the schedule. Default value is 'Semiannual'. \cr \code{calendar} \tab (Optional) a string, the calendar name. \cr \code{} \tab Defaults to 'TARGET' \cr \code{businessDayConvention} \tab (Optional) a number or string, the \cr \code{} \tab day convention to use. \cr \code{} \tab Defaults to 'Following'. \cr \code{terminationDateConvention} \tab (Optional) a number or string, the \cr \code{} \tab day convention to use for the terminal date. \cr \code{} \tab Defaults to 'Following'. \cr \code{dateGeneration} \tab (Optional) a number or string, the \cr \code{} \tab date generation rule. \cr \code{} \tab Defaults to 'Backward'. \cr \code{endOfMonth} \tab (Optional) 1 or 0, use End of Month rule for \cr \code{} \tab schedule dates. Defaults to 0 (false). } See example below. } } \value{ The \code{Schedule} function returns an object of class \code{Schedule}. It contains the list of dates in the schedule. } \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{ Michele Salvadore \email{michele.salvadore@gmail.com} for the inplementation; Dirk Eddelbuettel \email{edd@debian.org} for the \R interface; the QuantLib Group for \code{QuantLib} } \seealso{ \code{\link{FixedRateBond}} } \examples{ params <- list(effectiveDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), period='Semiannual', calendar='UnitedStates/GovernmentBond', businessDayConvention='Unadjusted', terminationDateConvention='Unadjusted', dateGeneration='Forward', endOfMonth=1) Schedule(params) } \keyword{misc} RQuantLib/man/AffineSwaption.Rd0000644000176200001440000001573113403334517016104 0ustar liggesusers\name{AffineSwaption} \alias{AffineSwaption} \alias{AffineSwaption.default} \alias{summary.G2AnalyticAffineSwaption} \alias{summary.HWAnalyticAffineSwaption} \alias{summary.HWTreeAffineSwaption} \alias{summary.BKTreeAffineSwaption} \title{Affine swaption valuation using several short-rate models} \description{ \code{AffineSwaption} prices a swaption with specified strike and maturity (in years), after calibrating the selected affine 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 swaption is exercisable at the start of the swap if {params$european} flag is set to {TRUE} or on each reset date (Bermudan) of the underlying swap if {params$european} flag is set to {FALSE}. } \usage{ AffineSwaption(params, ts, swaptionMaturities, swapTenors, volMatrix,legparams) } \arguments{ \item{params}{A list specifying the \code{tradeDate} (month/day/year), \code{settlementDate}, logical flags \code{payFixed} & \code{european} (european=FALSE generates Bermudan vlaue), \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{ts}{A term structure built with DiscountCurve is required. See the help page for \code{\link{DiscountCurve}} and example below 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.} \item{legparams}{A list specifying the \code{dayCounter} the day count convention for the fixed leg (default is Thirty360), and \code{fixFreq}, fixed coupon frequecny (defualt is Annual), \code{floatFreq}, floating leg reset frequency (default is Semiannual). } } \value{ \code{AffineSwaption} returns a list containing calibrated model paramters (what parameters are returned depends on the model selected) along with: \item{NPV}{NPV 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{Terry Leitch} \seealso{\code{\link{DiscountCurve}}} \examples{ if (.Platform$OS.type != "windows" && .Platform$r_arch != "i386") { # This data was generated to match the original quantlib example for Bermudan Swaption params <- list(tradeDate=as.Date('2016-2-15'), settleDate=as.Date('2016-2-17'), startDate=as.Date('2017-2-17'), maturity=as.Date('2022-2-17'), payFixed=TRUE, european=FALSE, dt=.25, 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) # 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) legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual") setEvaluationDate(as.Date("2016-2-16")) times<-times <- seq(0,14.75,.25) dcurve <- DiscountCurve(params, tsQuotes, times=times,legparams) # Price the Bermudan swaption pricing <- AffineSwaption(params, dcurve,swaptionMaturities, swapTenors, volMatrix,legparams) summary(pricing) } } \keyword{models} RQuantLib/man/FloatingRateBond.Rd0000644000176200001440000001741713403306333016347 0ustar liggesusers\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="UnitedStates/GovernmentBond", dayCounter = 'ActualActual', period=2, businessDayConvention = 1, terminationDateConvention=1, dateGeneration=0, endOfMonth=0, fixingDays = 1) gearings <- spreads <- caps <- floors <- vector() 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/CallableBond.Rd0000644000176200001440000001312513403306333015457 0ustar liggesusers\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="UnitedStates/GovernmentBond", dayCounter = "ActualActual", period="Quarterly", businessDayConvention = "Unadjusted", terminationDateConvention= "Unadjusted") coupon <- c(0.0465) setEvaluationDate(as.Date("2004-11-22")) 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/FittedBondCurve.Rd0000644000176200001440000000562712756336327016234 0ustar liggesusers\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) z <- zoo::zoo(curve$table$zeroRates, order.by=curve$table$date) plot(z) } RQuantLib/man/AmericanOptionImpliedVolatility.Rd0000644000176200001440000000442013403306333021450 0ustar liggesusers\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 numeric variable with volatility implied by the given market prices and given parameters. } \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/FixedRateBond.Rd0000644000176200001440000003315713403306333015642 0ustar liggesusers\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, the yield or the clean price. More specificly, when a discount curve is provided the calculation is done by DiscountingBondEngine from QuantLib. The NPV, clean price, dirty price, accrued interest, yield, duration, actual settlement date and cash flows of the bond is returned. When a yield is provided instead, no engine is provided to the bond class and prices are computed from yield. In the latter case, NPV is set to NA. Same situation when the clean price is given instead of discount curve or yield. 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, schedule, calc=list(dayCounter='ActualActual.ISMA', compounding='Compounded', freq='Annual', durationType='Modified'), discountCurve = NULL, yield = NA, price = NA) \method{FixedRateBondPriceByYield}{default}( settlementDays=1, yield, faceAmount=100, effectiveDate, maturityDate, period, calendar="UnitedStates/GovernmentBond", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption=100, issueDate) \method{FixedRateBondYield}{default}( settlementDays=1, price, faceAmount=100, effectiveDate, maturityDate, period, calendar="UnitedStates/GovernmentBond", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption=100, issueDate) } \arguments{ \item{bond}{(Optional) bond parameters, a named list whose elements are: \tabular{ll}{ \code{settlementDays} \tab (Optional) a double, settlement days. \cr \code{} \tab Default value is 1.\cr \code{faceAmount} \tab (Optional) a double, face amount of the bond.\cr \code{} \tab Default value is 100. \cr \code{dayCounter} \tab (Optional) a number or string, \cr \code{} \tab day counter convention. Defaults to 'Thirty360' \cr \code{issueDate} \tab (Optional) a Date, the bond's issue date\cr \code{} \tab Defaults to QuantLib default. \cr \code{paymentConvention} \tab (Optional) a number or string, the bond \cr \code{} \tab payment convention. \cr \code{} \tab Defaults to QuantLib default. \cr \code{redemption} \tab (Optional) a double, the redemption amount. \cr \code{} \tab Defaults to QuantLib default (100). \cr \code{paymentCalendar} \tab (Optional) a string, the name of the calendar. \cr \code{} \tab Defaults to QuantLib default. \cr \code{exCouponPeriod} \tab (Optional) a number, the number of days when \cr \code{} \tab the coupon goes ex relative to the coupon date. \cr \code{} \tab Defaults to QuantLib default. \cr \code{exCouponCalendar} \tab (Optional) a string, the name of the \cr \code{} \tab ex-coupon calendar. \cr \code{} \tab Defaults to QuantLib default. \cr \code{exCouponConvention} \tab (Optional) a number or string, the coupon \cr \code{} \tab payment convention. \cr \code{} \tab Defaults to QuantLib default. \cr \code{exCouponEndOfMonth} \tab (Optional) 1 or 0, use End of Month rule for \cr \code{} \tab ex-coupon dates. Defaults to 0 (false). } } \item{rates}{a numeric vector, bond's coupon rates} \item{schedule}{(Optional) a named list, QuantLib's parameters of the bond's schedule. \tabular{ll}{ \code{effectiveDate} \tab a Date, when the schedule becomes effective. \cr \code{maturityDate} \tab a Date, when the schedule matures. \cr \code{period} \tab (Optional) a number or string, the frequency of \cr \code{} \tab the schedule. Default value is 'Semiannual'. \cr \code{calendar} \tab (Optional) a string, the calendar name. \cr \code{} \tab Defaults to 'TARGET' \cr \code{businessDayConvention} \tab (Optional) a number or string, the \cr \code{} \tab day convention to use. \cr \code{} \tab Defaults to 'Following'. \cr \code{terminationDateConvention} \tab (Optional) a number or string, the \cr \code{} \tab day convention to use for the terminal date. \cr \code{} \tab Defaults to 'Following'. \cr \code{dateGeneration} \tab (Optional) a number or string, the \cr \code{} \tab date generation rule. \cr \code{} \tab Defaults to 'Backward'. \cr \code{endOfMonth} \tab (Optional) 1 or 0, use End of Month rule for \cr \code{} \tab schedule dates. Defaults to 0 (false). } See example below. } \item{calc}{(Optional) a named list, QuantLib's parameters for calculations. \tabular{ll}{ \code{dayCounter} \tab (Optional) a number or string, day counter \cr \code{} \tab convention. Defaults to 'ActualActual.ISMA' \cr \code{compounding} \tab a string, what kind of compounding to use. \cr \code{} \tab Defaults to 'Compounded' \cr \code{freq} \tab (Optional) a number or string, the frequency \cr \code{} \tab to use. Default value is 'Annual'. \cr \code{durationType} \tab (Optional) a number or string, the type of \cr \code{} \tab duration to calculate. Defaults to 'Simple' \cr \code{accuracy} \tab (Optional) a number, the accuracy required. \cr \code{} \tab Defaults to 1.0e-8. \cr \code{maxEvaluations} \tab (Optional) a number, max number of iterations. \cr \code{} \tab Defaults to 100. } } \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 } } \item{yield}{yield of the bond} \item{price}{clean price of the bond} \item{settlementDays}{an integer, 1 for T+1, 2 for T+2, etc...} \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=EveryFourthWeek,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{duration}{the duration of the bond} \item{settlementDate}{the actual settlement date used for 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(settlementDays=1, issueDate=as.Date("2004-11-30"), faceAmount=100, dayCounter='Thirty360', paymentConvention='Unadjusted') schedule <- list(effectiveDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), period='Semiannual', calendar='UnitedStates/GovernmentBond', businessDayConvention='Unadjusted', terminationDateConvention='Unadjusted', dateGeneration='Forward', endOfMonth=1) calc=list(dayCounter='Actual360', compounding='Compounded', freq='Annual', durationType='Modified') 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, schedule, calc, discountCurve=discountCurve.flat) #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, schedule, calc, discountCurve=discountCurve) #Same bond calculated from yield rather than from the discount curve yield <- 0.02 FixedRateBond(bond, coupon.rate, schedule, calc, yield=yield) #same example with clean price price <- 103.31 FixedRateBond(bond, coupon.rate, schedule, calc, price = price) #example with default calc parameter FixedRateBond(bond, coupon.rate, schedule, discountCurve=discountCurve) #example with default calc and schedule parameters schedule <- list(effectiveDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30")) FixedRateBond(bond, coupon.rate, schedule, discountCurve=discountCurve) #example with default calc, schedule and bond parameters FixedRateBond(, coupon.rate, schedule, discountCurve=discountCurve) 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/ConvertibleBond.Rd0000644000176200001440000003316113403306333016236 0ustar liggesusers\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 = "UnitedStates/GovernmentBond", 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 = "UnitedStates/GovernmentBond", 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 = "UnitedStates/GovernmentBond", 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/ZeroCouponBond.Rd0000644000176200001440000001676313403306333016076 0ustar liggesusers\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="UnitedStates/GovernmentBond", 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/man/Enum.Rd0000644000176200001440000000563513403306333014070 0ustar liggesusers\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{6} \tab Thirty360 \cr \code{7} \tab Actual365NoLeap (NB: deprecated) \cr \code{8} \tab ActualActual.ISMA \cr \code{9} \tab ActualActual.Bond \cr \code{10} \tab ActualActual.ISDA \cr \code{11} \tab ActualActual.Historical \cr \code{12} \tab ActualActual.AFB \cr \code{anything else} \tab ActualActual.Euro } } \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{4} \tab Unadjusted \cr \code{5} \tab HalfMonthModifiedFollowing \cr \code{6} \tab Nearest \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{5} \tab TwentiethIMM \cr \code{6} \tab OldCDS \cr \code{7} \tab CDS \cr \code{anything else} \tab TwentiethIMM } } \item{durationType}{an int value to specify duration type \tabular{ll}{ \code{0} \tab Simple \cr \code{1} \tab Macaulay \cr \code{2} \tab Modified } } } \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/Bond.Rd0000644000176200001440000001105013403306333014032 0ustar liggesusers\name{Bond} \alias{Bond} \alias{plot.Bond} \alias{print.Bond} \alias{print.FixedRateBond} \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{print}{FixedRateBond}(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-09-20")) ## 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 ## Removing s2y helps, as kindly pointed out by Luigi Ballabio 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, ## s2y perturbs s3y = 0.0398, s5y = 0.0443, s10y = 0.05165, s15y = 0.055175) times <- seq(0,10,.1) setEvaluationDate(params$tradeDate) 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="UnitedStates/GovernmentBond", businessDayConvention=4) ZeroCouponBond(bondparams, discountCurve, dateparams) # price a fixed rate coupon bond bond <- list(settlementDays=1, issueDate=as.Date("2004-11-30"), faceAmount=100, dayCounter='Thirty360', paymentConvention='Unadjusted') schedule <- list(effectiveDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), period='Semiannual', calendar='UnitedStates/GovernmentBond', businessDayConvention='Unadjusted', terminationDateConvention='Unadjusted', dateGeneration='Forward', endOfMonth=1) calc=list(dayCounter='Actual360', compounding='Compounded', freq='Annual', durationType='Modified') rates <- c(0.02875) FixedRateBond(bond, rates, schedule, calc, discountCurve=discountCurve) # price a fixed rate coupon bond from yield yield <- 0.050517 FixedRateBond(bond, rates, schedule, calc, yield=yield) # calculate the same bond from the clean price price <- 92.167 FixedRateBond(bond, rates, schedule, calc, price=price) # 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="UnitedStates/GovernmentBond", dayCounter = 1, period=3, businessDayConvention = 1, terminationDateConvention=1, dateGeneration=0, endOfMonth=0, fixingDays = 1) gearings <- spreads <- caps <- floors <- vector() 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/AmericanOption.Rd0000644000176200001440000000705413403306333016071 0ustar liggesusers\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", discreteDividends, discreteDividendsTimeUntil) } \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}} \item{discreteDividends}{Vector of discrete dividends (optional)} \item{discreteDividendsTimeUntil}{Vector of times to discrete dividends (in fractional years, optional)} } \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} 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. The \dQuote{CrankNicolson} engine needs to be used when setting discrete dividends. } \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/BondUtilities.Rd0000644000176200001440000000547513200457551015750 0ustar liggesusers% $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", "HalfMonthModifiedFollowing", "Nearest")) matchCompounding(cp = c("Simple", "Compounded", "Continuous", "SimpleThenCompounded")) matchDayCounter(daycounter = c("Actual360", "ActualFixed", "ActualActual", "Business252", "OneDayCounter", "SimpleDayCounter", "Thirty360", "Actual365NoLeap", "ActualActual.ISMA", "ActualActual.Bond", "ActualActual.ISDA", "ActualActual.Historical", "ActualActual.AFB", "ActualActual.Euro")) matchDateGen(dg = c("Backward", "Forward", "Zero", "ThirdWednesday", "Twentieth", "TwentiethIMM", "OldCDS", "CDS")) matchFrequency(freq = c("NoFrequency","Once", "Annual", "Semiannual", "EveryFourthMonth", "Quarterly", "Bimonthly", "Monthly", "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. Note that \code{Actual365NoLeap} is deprecated as of QuantLib 1.11 and no longer supported by default. It can be reinstated by defining \code{RQUANTLIB_USE_ACTUAL365NOLEAP}. } \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/BinaryOptionImpliedVolatility.Rd0000644000176200001440000000407313403306333021161 0ustar liggesusers\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 numeric variable with volatility implied by the given market prices. } \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/getQuantLibVersion.Rd0000644000176200001440000000106213072527607016752 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R \name{getQuantLibVersion} \alias{getQuantLibVersion} \title{Return the QuantLib version number} \usage{ getQuantLibVersion() } \value{ A character variable } \description{ This function returns the QuantLib version string as encoded in the header file \code{config.hpp} and determined at compilation time of the QuantLib library. } \examples{ getQuantLibVersion() } \references{ \url{http://quantlib.org} for details on \code{QuantLib}. } \author{ Dirk Eddelbuettel } RQuantLib/man/DiscountCurve.Rd0000644000176200001440000001620013403306333015747 0ustar liggesusers\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, legparams) } \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{s4y} \tab 4-year swap rate\cr \code{s5y} \tab 5-year swap rate\cr \code{s6y} \tab 6-year swap rate\cr \code{s7y} \tab 7-year swap rate\cr \code{s8y} \tab 8-year swap rate\cr \code{s9y} \tab 9-year swap rate\cr \code{s10y} \tab 10-year swap rate\cr \code{s12y} \tab 12-year swap rate\cr \code{s15y} \tab 15-year swap rate\cr \code{s20y} \tab 20-year swap rate\cr \code{s25y} \tab 25-year swap rate\cr \code{s30y} \tab 30-year swap rate\cr \code{s40y} \tab 40-year swap rate\cr \code{s50y} \tab 50-year swap rate\cr \code{s60y} \tab 60-year swap rate\cr \code{s70y} \tab 70-year swap rate\cr \code{s80y} \tab 80-year swap rate\cr \code{s90y} \tab 90-year swap rate\cr \code{s100y} \tab 100-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). } \item{legparams}{A list specifying the \code{dayCounter} the day count convention for the fixed leg (default is Thirty360), and \code{fixFreq}, fixed coupon frequecny (defualt is Annual), \code{floatFreq}, floating leg reset frequency (default is Semiannual). } } \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-09-20")) ## 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 ## Removing s2y helps, as kindly pointed out by Luigi Ballabio 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) 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" curves <- DiscountCurve(params, tsQuotes, times) plot(curves,setpar=FALSE) par(savepar) } \keyword{models} RQuantLib/man/getQuantLibCapabilities.Rd0000644000176200001440000000124713072527607017723 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/RcppExports.R \name{getQuantLibCapabilities} \alias{getQuantLibCapabilities} \title{Return configuration options of the QuantLib library} \usage{ getQuantLibCapabilities() } \value{ A named vector of logical variables } \description{ This function returns a named vector of boolean variables describing several configuration options determined at compilation time of the QuantLib library. } \details{ Not all of these features are used (yet) by RQuantLib. } \examples{ getQuantLibCapabilities() } \references{ \url{http://quantlib.org} for details on \code{QuantLib}. } \author{ Dirk Eddelbuettel } RQuantLib/man/Option.Rd0000644000176200001440000000245713403306333014433 0ustar liggesusers\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/EuropeanOptionArrays.Rd0000644000176200001440000001152613403306333017311 0ustar liggesusers\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/SabrSwaption.Rd0000644000176200001440000001151013403306333015565 0ustar liggesusers\name{SabrSwaption} \alias{SabrSwaption} \alias{SabrSwaption.default} \title{SABR swaption using vol cube data with bermudan alternative using markovfunctional} \description{ \code{SabrSwaption} prices a swaption with specified expiration or time range if Bermudan, strike, and maturity, using quantlibs SABR model for europeans and quantlib's markovfunctional for Bermudans. Currently the input is a zero offset log-normal vol surface. An example of a dataset can be found in the dataset {rqlib} inlcuded with Rquantlib. It is assumed that the swaption is exercisable at the start of a forward start swap if {params$european} flag is set to {TRUE} or starting immediately on each reset date (Bermudan) of an existing underlying swap or spot start swap if {params$european} flag is set to {FALSE}. } \usage{ SabrSwaption(params, ts, volCubeDF, legparams = list(dayCounter = "Thirty360", fixFreq = "Annual", floatFreq = "Semiannual"), tsUp01 = NA, tsDn01 = NA, vega = FALSE)} \arguments{ \item{params}{A list specifying the \code{tradeDate} (month/day/year), \code{settlementDate}, logical flags \code{payFixed} & \code{european} (european=FALSE generates Bermudan vlaue), \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. } \item{ts}{A term structure built with DiscountCurve is required. See the help page for \code{\link{DiscountCurve}} and example below for details.} \item{volCubeDF}{The swaption volatility cube in dataframe format with columns Expiry, Tenor, Spread, and LogNormalVol stored by rows. See the example below.} \item{legparams}{A list specifying the \code{dayCounter} the day count convention for the fixed leg (default is Thirty360), and \code{fixFreq}, fixed coupon frequecny (defualt is Annual), \code{floatFreq}, floating leg reset frequency (default is Semiannual). } \item{tsUp01}{Discount for a user specied up move in rates.} \item{tsDn01}{Discount for a user specied down move in rates.} \item{vega}{Discount for a user specied up move.} } \value{ \code{SabrSwaption} returns a list containing the value of the payer and receiver swaptions at the strike specified in \code{params}. \item{NPV}{NPV of swaption in basis points (actual price equals \code{price} times notional divided by 10,000)} \item{strike}{swaption strike} \item{params}{Input parameter list} \item{atmRate}{fair rate for swap at swap start date for european or fair swap rate for swap at expiration for bermudan} \item{vol}{vol for swaption at swap start date and rate strike for european or vol for swaption for given expiration and strike for bermudan} \item{rcvDv01}{reveiver value for a change in rates defined by dv01Up} \item{payDv01}{payer value for a change in rates defined by dv01Up} \item{rcvCnvx}{reveiver second order value change for a change in rates defined by dv01Up & dv01Dn} \item{payCnvx}{payer second order value for a change in rates defined by dv01Up & dv01Dn} \item{strike}{swaption strike} } \details{ This function is based on \code{QuantLib} Version 1.64. It introduces support for fixed-income instruments in \code{RQuantLib}. } \references{ Brigo, D. and Mercurio, F. (2006) \emph{Interest Rate Models: Theory and Practice, 2nd Edition}, 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{Terry Leitch} \seealso{\code{\link{AffineSwaption}}} \examples{ params <- list(tradeDate=as.Date('2016-2-15'), settleDate=as.Date('2016-2-17'), startDate=as.Date('2017-2-17'), maturity=as.Date('2022-2-17'), european=TRUE, dt=.25, expiryDate=as.Date('2017-2-17'), strike=.02, interpWhat="discount", interpHow="loglinear") # Set leg paramters for generating discount curve dclegparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual") setEvaluationDate(as.Date("2016-2-16")) times<-times <- seq(0,14.75,.25) data(tsQuotes) dcurve <- DiscountCurve(params, tsQuotes, times=times,dclegparams) # Price the Bermudan swaption swaplegparams=list(fixFreq="Semiannual",floatFreq="Quarterly") data(vcube) pricing <- SabrSwaption(params, dcurve,vcube,swaplegparams) pricing } \keyword{models} RQuantLib/man/tsQuotes.Rd0000644000176200001440000000054713072527607015023 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/datasets.R \docType{data} \name{tsQuotes} \alias{tsQuotes} \title{Vol Cube Example Data Short time series examples} \format{A series of tenors and rates approppriate for calling DiscountCurve} \source{ TBA } \description{ Vol Cube Example Data Short time series examples } RQuantLib/man/AsianOption.Rd0000644000176200001440000000600712347554037015416 0ustar liggesusers% $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=11.0/12.0, fixings=26) } \arguments{ \item{averageType}{Specifiy averaging type, either \dQuote{geometric} or \dQuote{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}{(Only for arithmetic averaging) Time step to first average, can be zero} \item{length}{(Only for arithmetic averaging) Total time length for averaging period} \item{fixings}{(Only for arithmetic averaging) Total number of averaging fixings} } \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} } \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/EuropeanOptionImpliedVolatility.Rd0000644000176200001440000000411113403306333021504 0ustar liggesusers\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 numeric variable with volatility implied by the given market prices and given parameters. } \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/BarrierOption.Rd0000644000176200001440000000565313403306333015743 0ustar liggesusers\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}. 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/DESCRIPTION0000644000176200001440000000210513607525142013624 0ustar liggesusersPackage: RQuantLib Title: R Interface to the 'QuantLib' Library Version: 0.4.11 Date: 2020-01-15 Maintainer: Dirk Eddelbuettel Author: Dirk Eddelbuettel, Khanh Nguyen (2009-2010), Terry Leitch (since 2016) Description: The 'RQuantLib' package makes parts of 'QuantLib' accessible from R 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. Depends: R (>= 2.10.0) Suggests: tinytest, rgl, shiny LazyLoad: true Imports: methods, Rcpp (>= 0.11.0), stats, graphics, zoo LinkingTo: Rcpp SystemRequirements: QuantLib library (>= 1.14) from http://quantlib.org, Boost library from http://www.boost.org License: GPL (>= 2) URL: http://dirk.eddelbuettel.com/code/rquantlib.html BugReports: https://github.com/eddelbuettel/rquantlib/issues RoxygenNote: 6.0.1 NeedsCompilation: yes Packaged: 2020-01-15 01:54:39.253352 UTC; edd Repository: CRAN Date/Publication: 2020-01-15 06:00:02 UTC RQuantLib/tests/0000755000176200001440000000000013607470337013267 5ustar liggesusersRQuantLib/tests/tinytest.R0000644000176200001440000000103413564352402015265 0ustar liggesusers if (requireNamespace("tinytest", quietly=TRUE) && utils::packageVersion("tinytest") >= "1.0.0") { ## Set a seed to make the test deterministic set.seed(42) ## R makes us to this Sys.setenv("R_TESTS"="") ## there are several more granular ways to test files in a tinytest directory, ## see its package vignette; tests can also run once the package is installed ## using the same command `test_package(pkgName)`, or by director or file tinytest::test_package("RQuantLib", ncpu=getOption("Ncpus", 1)) } RQuantLib/tests/RQuantlib.R0000644000176200001440000002014513403306333015301 0ustar liggesusers 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) # Discrete dividend ## europeanoption.cpp: call value == 3.67 ## Reference pg. 253 - Hull 5th ed Exercise 12.8 - From QuantLib tests print(EuropeanOption("call", underlying=40, strike=40, div=0, riskFree=0.09, maturity=0.5, vol=0.3, discreteDividends = c(0.5, 0.5), discreteDividendsTimeUntil = c(2/12, 5/12)), digits=5) ## americanoption.cpp: call value == 3.72 (Hull) -- we show 3.75 ## Reference p. 256 - Hull 5th ed. Exercise 12.9 using (flawed) Roll, Geske, Whaley formula print(AmericanOption("call", underlying=40, strike=40, div=0, riskFree=0.09, maturity=0.5, vol=0.3, engine = "CrankNicolson", discreteDividends = c(0.5, 0.5), discreteDividendsTimeUntil = c(2/12, 5/12)), 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)) #.onWindows <- .Platform$OS.type == "windows" ## 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="UnitedStates/GovernmentBond", 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(settlementDays=1, issueDate=as.Date("2004-11-30"), faceAmount=100, dayCounter='Thirty360', paymentConvention='Unadjusted') schedule <- list(effectiveDate=as.Date("2004-11-30"), maturityDate=as.Date("2008-11-30"), period='Semiannual', calendar='UnitedStates/GovernmentBond', businessDayConvention='Unadjusted', terminationDateConvention='Unadjusted', dateGeneration='Forward', endOfMonth=1) calc=list(dayCounter='Actual360', compounding='Compounded', freq='Annual', durationType='Modified') 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, schedule, calc, discountCurve=discountCurve.flat) ## Same bond calculated from yield rather than from the discount curve yield <- 0.02 FixedRateBond(bond, coupon.rate, schedule, calc, yield=yield) #same example with clean price price <- 103.31 FixedRateBond(bond, coupon.rate, schedule, calc, price = price) ## 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="UnitedStates/GovernmentBond", dayCounter = 'ActualActual', period=2, businessDayConvention = 1, terminationDateConvention=1, dateGeneration=0, endOfMonth=0, fixingDays = 1) gearings <- spreads <- caps <- floors <- vector() 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/configure.ac0000644000176200001440000001262413607470213014411 0ustar liggesusers# 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 # require at least autoconf 2.50 AC_PREREQ(2.50) # Process this file with autoconf to produce a configure script. AC_INIT(RQuantlib, 0.4.11) # Set CXX and CXXFLAGS based on the R configuration (with thanks to KH) : ${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` # 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.*|4.9.*|5.*|6.*|7.*|8.*|9.*|10.*) gxx_newer_than_45="-fpermissive" ;; esac fi AC_DEFUN([AC_PROG_R], [AC_CHECK_PROG(R,R,yes)]) AC_PROG_R ## We no longer need to set LDFLAGS for Rcpp 0.11.0 or later, ## and hence no longer need to check for Rscipt ## ## ## 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.*|1.0.*|1.1.*|1.2.*|1.3.*|1.4.*|1.5.*|1.6.*|1.7.*|1.8*|1.9.*|1.10.*|1.11.*|1.12.*|1.13.*) AC_MSG_WARN([RQuantLib requires QuantLib (>= 1.14).]) AC_MSG_ERROR([Please upgrade to a current 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/src/0000755000176200001440000000000013607470157012714 5ustar liggesusersRQuantLib/src/schedule.cpp0000644000176200001440000000212513443253624015210 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2014 Michele Salvadore and Dirk Eddelbuettel // Copyright (C) 2015 - 2018 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . // [[Rcpp::interfaces(r, cpp)]] #include // [[Rcpp::export]] Rcpp::DateVector CreateSchedule(Rcpp::List params) { QuantLib::Schedule schedule = getSchedule(params); return Rcpp::wrap(schedule.dates()); } RQuantLib/src/asian.cpp0000644000176200001440000001544513467001143014511 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2019 Dirk Eddelbuettel // Copyright (C) 2009 - 2010 Dirk Eddelbuettel and Khanh Nguyen // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::export]] Rcpp::List asianOptionEngine(std::string averageType, std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double first, double length, size_t fixings) { 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; QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today, qRate, dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today, rRate, dc); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::ext::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType,strike)); Rcpp::List rl = R_NilValue; if (averageType=="geometric"){ QuantLib::ext::shared_ptr engine(new QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(stochProcess)); #ifdef QL_HIGH_RESOLUTION_DATE // in minutes QuantLib::Date exDate(today.dateTime() + boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60))); #else QuantLib::Date exDate = today + int(maturity * 360 + 0.5); #endif QuantLib::ext::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ContinuousAveragingAsianOption option(QuantLib::Average::Geometric, 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()); } else if (averageType=="arithmetic") { // TODO: check fixings > 1, first, length if (first < 0) Rcpp::stop("Parameter 'first' must be non-negative."); if (length < 0) Rcpp::stop("Parameter 'length' must be non-negative."); if (fixings <= 1) Rcpp::stop("Parameter 'fixings' must be larger than one."); QuantLib::ext::shared_ptr engine = QuantLib::MakeMCDiscreteArithmeticAPEngine(stochProcess) .withSamples(2047) .withControlVariate(); //QuantLib::ext::shared_ptr engine = // MakeMCDiscreteArithmeticASEngine(stochProcess) // .withSeed(3456789) // .withSamples(1023); 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_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); } return rl; } RQuantLib/src/zero.cpp0000644000176200001440000001415713443253624014403 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2009 - 2012 Dirk Eddelbuettel and Khanh Nguyen // Copyright (C) 2013 - 2019 Dirk Eddelbuettel // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::export]] double zeroprice(double yield, QuantLib::Date maturity, QuantLib::Date settle, int period, int basis) { //setup bond; initialise calendar from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; QuantLib::Integer fixingDays = RQLContext::instance().fixingDays; QuantLib::Date todaysDate = calendar.advance(settle, -fixingDays, QuantLib::Days); QuantLib::Settings::instance().evaluationDate() = todaysDate; 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); return bond.cleanPrice(yield, dayCounter, QuantLib::Compounded, freq); } // [[Rcpp::export]] double zeroyield(double price, QuantLib::Date maturity, QuantLib::Date settle, int period, int basis) { //setup bond; initialise calendar from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; QuantLib::Integer fixingDays = RQLContext::instance().fixingDays; QuantLib::Date todaysDate = calendar.advance(settle, -fixingDays, QuantLib::Days); QuantLib::Settings::instance().evaluationDate() = todaysDate; 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); return bond.yield(price, dayCounter, QuantLib::Compounded, freq); } Rcpp::DataFrame zbtyield(std::vector MatDates, Rcpp::NumericMatrix bondparam, Rcpp::NumericVector yields, std::vector SettleDates, Rcpp::NumericVector cleanPrice) { //setting up the bonds const QuantLib::Size numberOfBonds = MatDates.size(); std::vector > instruments; std::vector< QuantLib::ext::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); QuantLib::ext::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; QuantLib::ext::shared_ptr curve; NelsonSiegelFitting nelsonSiegel; QuantLib::ext::shared_ptr ts3 ( new FittedBondDiscountCurve(1, calendar, instruments, dayCounter, nelsonSiegel, tolerance, max)); curve = ts3; */ QuantLib::ext::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); } RQuantLib/src/modules.cpp0000644000176200001440000000720413443253624015067 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2013 - 2018 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . // trying something with Rcpp modules -- still experimental #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/dates.cpp0000644000176200001440000000242213443253624014514 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2018 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // the actual implementation is now in this header which is also pulled into // compilation units when using 'plugin' mode via Rcpp Attributes #include // [[Rcpp::interfaces(r, cpp)]] // [[Rcpp::export]] QuantLib::Date advanceDate(QuantLib::Date issueDate, int days) { QuantLib::Calendar cal = RQLContext::instance().calendar; QuantLib::Date newDate = cal.advance(issueDate, days, QuantLib::Days); return(newDate); } RQuantLib/src/bermudan.cpp0000644000176200001440000006760513467001143015220 0ustar liggesusers // RQuantLib function BermudanSwaption // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2019 Dirk Eddelbuettel // Copyright (C) 2016 Terry Leitch // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // Calibrates underlying swaptions to the input volatility matrix. void calibrateModel(const QuantLib::ext::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, 1.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); } } // [[Rcpp::export]] Rcpp::List bermudanFromYieldEngine(Rcpp::List rparam, Rcpp::NumericVector yield, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericMatrix swaptionVols) { QuantLib::Size i; //int *swaptionMat=0, *swapLengths=0; //double **swaptionVols=0; double notional = 10000; // prices in basis points QuantLib::Date todaysDate(Rcpp::as(rparam["tradeDate"])); QuantLib::Date settlementDate(Rcpp::as(rparam["settleDate"])); QuantLib::Date startDate(Rcpp::as(rparam["startDate"])); QuantLib::Date maturity(Rcpp::as(rparam["maturity"])); //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"]); // 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); QuantLib::ext::shared_ptr flatRate(new QuantLib::SimpleQuote(yield[0])); // FIXME: hardcoded? QuantLib::Handle rhTermStructure(QuantLib::ext::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; QuantLib::ext::shared_ptr indexSixMonths(new QuantLib::Euribor6M(rhTermStructure)); //QuantLib::Date startDate = calendar.advance(settlementDate, 1, QuantLib::Years, floatingLegConvention); //took out hard coded //QuantLib::Date maturity = calendar.advance(startDate, 5, QuantLib::Years, floatingLegConvention); //dates 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; QuantLib::ext::shared_ptr swap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, dummyFixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths->dayCounter())); swap->setPricingEngine(QuantLib::ext::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. QuantLib::ext::shared_ptr mySwap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths->dayCounter())); swap->setPricingEngine(QuantLib::ext::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++) { //QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols[i][numCols-i-1])); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols(i, numCols-i-1))); swaptions.push_back(QuantLib::ext::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 = QuantLib::ext::dynamic_pointer_cast(leg[i]); bermudanDates.push_back(coupon->accrualStartDate()); } QuantLib::ext::shared_ptr bermudaExercise(new QuantLib::BermudanExercise(bermudanDates)); // Price based on method selected. if (method.compare("G2Analytic") == 0) { QuantLib::ext::shared_ptr modelG2(new QuantLib::G2(rhTermStructure)); Rprintf((char*)"G2/Jamshidian (analytic) calibration\n"); for(i = 0; i < swaptions.size(); i++) swaptions[i]->setPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::G2SwaptionEngine(modelG2, 6.0, 16))); calibrateModel(modelG2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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) { QuantLib::ext::shared_ptr modelHW(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (analytic) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::JamshidianSwaptionEngine(modelHW))); calibrateModel(modelHW, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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) { QuantLib::ext::shared_ptr modelHW2(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (tree) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::TreeSwaptionEngine(modelHW2,grid))); calibrateModel(modelHW2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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) { QuantLib::ext::shared_ptr modelBK(new QuantLib::BlackKarasinski(rhTermStructure)); Rprintf((char*)"Black-Karasinski (tree) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::TreeSwaptionEngine(modelBK,grid))); calibrateModel(modelBK, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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"); } } // [[Rcpp::export]] Rcpp::List bermudanWithRebuiltCurveEngine(Rcpp::List rparam, std::vector dateVec, std::vector zeroVec, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericMatrix swaptionVols) { // 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(Rcpp::as(rparam["tradeDate"])); QuantLib::Date settlementDate(Rcpp::as(rparam["settleDate"])); QuantLib::Date startDate(Rcpp::as(rparam["startDate"])); QuantLib::Date maturity(Rcpp::as(rparam["maturity"])); bool payfix = Rcpp::as(rparam["payFixed"]); //cout << "TradeDate: " << todaysDate << endl << "Settle: " << settlementDate << endl; RQLContext::instance().settleDate = settlementDate; QuantLib::Settings::instance().evaluationDate() = todaysDate; // initialise from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; //Integer fixingDays = RQLContext::instance().fixingDays; double strike = Rcpp::as(rparam["strike"]); std::string method = Rcpp::as(rparam["method"]); QuantLib::Handle rhTermStructure(rebuildCurveFromZeroRates(dateVec, zeroVec)); // Get swaption maturities //Rcpp::NumericVector swaptionMat(maturities); int numRows = swaptionMat.size(); // Get swaption vol matrix. //Rcpp::NumericMatrix swaptionVols(vols); int dim1 = swaptionVols.nrow(); int dim2 = swaptionVols.ncol(); // 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; QuantLib::ext::shared_ptr indexSixMonths(new QuantLib::Euribor6M(rhTermStructure)); //QuantLib::Date startDate = calendar.advance(settlementDate, 1, QuantLib::Years, floatingLegConvention); //took out hard coded //QuantLib::Date maturity = calendar.advance(startDate, 5, QuantLib::Years, floatingLegConvention); //dates 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; if(payfix){ type = QuantLib::VanillaSwap::Payer; } else{ type = QuantLib::VanillaSwap::Receiver; } QuantLib::ext::shared_ptr swap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, dummyFixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths->dayCounter())); swap->setPricingEngine(QuantLib::ext::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. QuantLib::ext::shared_ptr mySwap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths->dayCounter())); swap->setPricingEngine(QuantLib::ext::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++) { //QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols[i][numCols-i-1])); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols(i, numCols-i-1))); swaptions.push_back(QuantLib::ext::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 = QuantLib::ext::dynamic_pointer_cast(leg[i]); bermudanDates.push_back(coupon->accrualStartDate()); } QuantLib::ext::shared_ptr bermudaExercise(new QuantLib::BermudanExercise(bermudanDates)); // Price based on method selected. if (method.compare("G2Analytic") == 0) { QuantLib::ext::shared_ptr modelG2(new QuantLib::G2(rhTermStructure)); Rprintf((char*)"G2/Jamshidian (analytic) calibration\n"); for(i = 0; i < swaptions.size(); i++) swaptions[i]->setPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::G2SwaptionEngine(modelG2, 6.0, 16))); calibrateModel(modelG2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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) { QuantLib::ext::shared_ptr modelHW(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (analytic) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::JamshidianSwaptionEngine(modelHW))); calibrateModel(modelHW, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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) { QuantLib::ext::shared_ptr modelHW2(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (tree) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::TreeSwaptionEngine(modelHW2,grid))); calibrateModel(modelHW2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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) { QuantLib::ext::shared_ptr modelBK(new QuantLib::BlackKarasinski(rhTermStructure)); Rprintf((char*)"Black-Karasinski (tree) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::TreeSwaptionEngine(modelBK,grid))); calibrateModel(modelBK, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::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"); } } RQuantLib/src/daycounter.cpp0000644000176200001440000000413513443253624015574 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2009 - 2011 Dirk Eddelbuettel and Khanh Nguyen // Copyright (C) 2012 - 2018 Dirk Eddelbuettel // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::interfaces(r, cpp)]] // [[Rcpp::export]] std::vector dayCount(std::vector startDates, std::vector endDates, std::vector dayCounters) { int n = dayCounters.size(); std::vector result(n); for (int i=0; i< n; i++){ QuantLib::DayCounter counter = getDayCounter(dayCounters[i]); result[i] = static_cast(counter.dayCount(startDates[i], endDates[i])); } return result; } // [[Rcpp::export]] std::vector yearFraction(std::vector startDates, std::vector endDates, std::vector dayCounters) { int n = dayCounters.size(); std::vector result(n); for (int i=0; i< n; i++){ QuantLib::DayCounter counter = getDayCounter(dayCounters[i]); result[i] = (double)counter.yearFraction(startDates[i], endDates[i]); } return result; } // this could go into another file too... maybe regroup all calendar / date functions? // [[Rcpp::export]] bool setEvaluationDate(QuantLib::Date evalDate) { QuantLib::Settings::instance().evaluationDate() = evalDate; return true; } RQuantLib/src/barrier_binary.cpp0000644000176200001440000003225713443253624016417 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2019 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::export]] Rcpp::List binaryOptionEngine(std::string binType, std::string type, std::string excType, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double cashPayoff) { #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity*360 + 0.5); // FIXME: this could be better, but same rounding in QL #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today,qRate,dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today,rRate,dc); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::ext::shared_ptr payoff; if (binType=="cash") { QuantLib::ext::shared_ptr con(new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff)); payoff = con; } else if (binType=="asset") { QuantLib::ext::shared_ptr aon(new QuantLib::AssetOrNothingPayoff(optionType, strike)); payoff = aon; } else if (binType=="gap") { QuantLib::ext::shared_ptr gap(new QuantLib::GapPayoff(optionType, strike, cashPayoff)); payoff = gap; } else { throw std::range_error("Unknown binary option type " + binType); } #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr exercise; if (excType=="american") { QuantLib::ext::shared_ptr amEx(new QuantLib::AmericanExercise(today, exDate)); exercise = amEx; } else if (excType=="european") { QuantLib::ext::shared_ptr euEx(new QuantLib::EuropeanExercise(exDate)); exercise = euEx; } else { throw std::range_error("Unknown binary exercise type " + excType); } QuantLib::ext::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); QuantLib::ext::shared_ptr engine; if (excType=="american") { QuantLib::ext::shared_ptr amEng(new QuantLib::AnalyticDigitalAmericanEngine(stochProcess)); engine = amEng; } else if (excType=="european") { QuantLib::ext::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); return rl; } // dumped core when we tried last // no longer under 0.3.10 and g++ 4.0.1 (Aug 2005) // [[Rcpp::export]] double binaryOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double cashPayoff) { #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity*360 + 0.5); // FIXME: this could be better #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today, qRate, dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today, rRate, dc); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::ext::shared_ptr payoff(new QuantLib::CashOrNothingPayoff(optionType, strike, cashPayoff)); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ext::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); //QuantLib::ext::shared_ptr engine(new AnalyticEuropeanEngine(stochProcess)); QuantLib::ext::shared_ptr engine(new QuantLib::AnalyticBarrierEngine(stochProcess)); QuantLib::VanillaOption opt(payoff, exercise); opt.setPricingEngine(engine); return opt.impliedVolatility(value, stochProcess); } // [[Rcpp::export]] Rcpp::List barrierOptionEngine(std::string barrType, std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double barrier, double rebate) { #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity*360 + 0.5); // FIXME: this could be better #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today, qRate, dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today,rRate,dc); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); QuantLib::ext::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; QuantLib::ext::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_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); return rl; } RQuantLib/src/bonds.cpp0000644000176200001440000016203013443253624014523 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2019 Dirk Eddelbuettel // Copyright (C) 2009 - 2012 Khanh Nguyen and Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . // [[Rcpp::interfaces(r, cpp)]] #include // [[Rcpp::export]] double zeroPriceByYieldEngine(double yield, double faceAmount, double dayCounter, double frequency, double businessDayConvention, double compound, QuantLib::Date maturityDate, QuantLib::Date issueDate) { //setup bond; initialise calendar from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; QuantLib::Integer fixingDays = RQLContext::instance().fixingDays; 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 zbond.cleanPrice(yield, dc, cp, freq); } // [[Rcpp::export]] double zeroYieldByPriceEngine(double price, double faceAmount, double dayCounter, double frequency, double businessDayConvention, double compound, QuantLib::Date maturityDate, QuantLib::Date issueDate) { //setup bond; initialise calendar from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; QuantLib::Integer fixingDays = RQLContext::instance().fixingDays; 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 zbond.yield(price, dc, cp, freq); } // [[Rcpp::export]] double fixedRateBondYieldByPriceEngine(double settlementDays, double price, std::string cal, double faceAmount, double businessDayConvention, double compound, double redemption, double dayCounter, double frequency, QuantLib::Date maturityDate, QuantLib::Date issueDate, QuantLib::Date effectiveDate, std::vector rates) { //set up BusinessDayConvetion QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::Compounding cp = getCompounding(compound); QuantLib::Calendar calendar; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } //build the bond QuantLib::Schedule sch(effectiveDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::FixedRateBond bond(settlementDays, faceAmount, sch, rates, dc, bdc, redemption, issueDate); return bond.yield(price, dc, cp, freq); } // [[Rcpp::export]] double fixedRateBondPriceByYieldEngine(double settlementDays, double yield, std::string cal, double faceAmount, double businessDayConvention, double compound, double redemption, double dayCounter, double frequency, QuantLib::Date maturityDate, QuantLib::Date issueDate, QuantLib::Date effectiveDate, std::vector rates) { //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; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } //build the bond QuantLib::Schedule sch(effectiveDate, maturityDate, QuantLib::Period(freq), calendar, bdc, bdc, QuantLib::DateGeneration::Backward, false); QuantLib::FixedRateBond bond(settlementDays, faceAmount, sch, rates, dc, bdc, redemption, issueDate); return bond.cleanPrice(yield, dc, cp, freq); } // not exported to R but called below Rcpp::List FloatingBond(Rcpp::List rparam, std::vector gearings, std::vector spreads, std::vector caps, std::vector floors, QuantLib::Handle &index, Rcpp::List iborparams, QuantLib::Handle &discountCurve, Rcpp::List datemisc) { double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Date issueDate(Rcpp::as(rparam["issueDate"])); QuantLib::Date effectiveDate(Rcpp::as(rparam["effectiveDate"])); double redemption = Rcpp::as(rparam["redemption"]); double settlementDays = Rcpp::as(datemisc["settlementDays"]); std::string cal = Rcpp::as(datemisc["calendar"]); double dayCounter = Rcpp::as(datemisc["dayCounter"]); double frequency = Rcpp::as(datemisc["period"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); double terminationDateConvention = Rcpp::as(datemisc["terminationDateConvention"]); double dateGeneration = Rcpp::as(datemisc["dateGeneration"]); double endOfMonthRule = Rcpp::as(datemisc["endOfMonth"]); double fixingDays = Rcpp::as(datemisc["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; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } 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); std::string type = Rcpp::as(iborparams["type"]); double length = Rcpp::as(iborparams["length"]); std::string inTermOf = Rcpp::as(iborparams["inTermOf"]); QuantLib::ext::shared_ptr iborindex(new QuantLib::USDLibor(6 * QuantLib::Months, index)); if (type=="USDLibor") { if (inTermOf=="Months") { QuantLib::ext::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Months, index)); iborindex = temp; } else if (inTermOf=="Years") { QuantLib::ext::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 QuantLib::ext::shared_ptr bondEngine(new QuantLib::DiscountingBondEngine(discountCurve)); bond.setPricingEngine(bondEngine); //cashflow QuantLib::ext::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())); } // [[Rcpp::export]] Rcpp::List FloatBond1(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index, Rcpp::List discountCurve, Rcpp::List dateparams) { QuantLib::Handle discount_curve(getFlatCurve(discountCurve)); QuantLib::Handle ibor_curve(getFlatCurve(index)); return FloatingBond(bond, gearings, spreads, caps, floors, ibor_curve, indexparams, discount_curve, dateparams); } // [[Rcpp::export]] Rcpp::List FloatBond2(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index_params, Rcpp::List index_tsQuotes, Rcpp::List index_times, Rcpp::List discountCurve, Rcpp::List dateparams) { QuantLib::Handle discount_curve(getFlatCurve(discountCurve)); QuantLib::Handle ibor_curve(buildTermStructure(index_params, index_tsQuotes)); return FloatingBond(bond, gearings, spreads, caps, floors, ibor_curve, indexparams, discount_curve, dateparams); } // [[Rcpp::export]] Rcpp::List FloatBond3(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index, Rcpp::List disc_params, Rcpp::List disc_tsQuotes, Rcpp::List disc_times, Rcpp::List dateparams) { QuantLib::Handle ibor_curve(getFlatCurve(index)); QuantLib::Handle discount_curve(buildTermStructure(disc_params, disc_tsQuotes)); return FloatingBond(bond, gearings, spreads, caps, floors, ibor_curve, indexparams, discount_curve, dateparams); } // [[Rcpp::export]] Rcpp::List FloatBond4(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index_params, Rcpp::List index_tsQuotes, Rcpp::List index_times, Rcpp::List disc_params, Rcpp::List disc_tsQuotes, Rcpp::List disc_times, Rcpp::List dateparams) { QuantLib::Handle ibor_curve(buildTermStructure(index_params, index_tsQuotes)); QuantLib::Handle discount_curve(buildTermStructure(disc_params, disc_tsQuotes)); return FloatingBond(bond, gearings, spreads, caps, floors, ibor_curve, indexparams, discount_curve, dateparams); } // [[Rcpp::export]] Rcpp::List floatingWithRebuiltCurveEngine(Rcpp::List bondparams, std::vector gearings, std::vector spreads, std::vector caps, std::vector floors, Rcpp::List indexparams, std::vector iborDateVec, std::vector iborzeroVec, std::vector dateVec, std::vector zeroVec, Rcpp::List dateparams) { QuantLib::Handle ibor_curve(rebuildCurveFromZeroRates(iborDateVec, iborzeroVec)); QuantLib::Handle curve(rebuildCurveFromZeroRates(dateVec, zeroVec)); return FloatingBond(bondparams, gearings, spreads, caps, floors, ibor_curve, indexparams, curve, dateparams); } // [[Rcpp::export]] Rcpp::List FixedRateWithYield(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, double yield) { // get calc parameters QuantLib::DayCounter calcDayCounter = getDayCounter(Rcpp::as(calcparam["dayCounter"])); QuantLib::Compounding compounding = getCompounding(Rcpp::as(calcparam["compounding"])); QuantLib::Frequency calcFreq = getFrequency(Rcpp::as(calcparam["freq"])); QuantLib::Duration::Type durationType = getDurationType(Rcpp::as(calcparam["durationType"])); QuantLib::ext::shared_ptr bond = getFixedRateBond(bondparam, ratesVec, scheduleparam); QuantLib::Date sd = bond->settlementDate(); const Rcpp::Date settlementDate(sd.month(), sd.dayOfMonth(), sd.year()); return Rcpp::List::create(Rcpp::Named("NPV") = std::numeric_limits::quiet_NaN(), Rcpp::Named("cleanPrice") = bond->cleanPrice(yield, calcDayCounter, compounding, calcFreq), Rcpp::Named("dirtyPrice") = bond->dirtyPrice(yield, calcDayCounter, compounding, calcFreq), Rcpp::Named("accruedCoupon") = bond->accruedAmount(), Rcpp::Named("yield") = yield, Rcpp::Named("duration") = QuantLib::BondFunctions::duration(*bond, yield, calcDayCounter, compounding, calcFreq, durationType, sd), Rcpp::Named("settlementDate") = settlementDate, Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond->cashflows())); } // [[Rcpp::export]] Rcpp::List FixedRateWithPrice(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, double price) { // get calc parameters QuantLib::DayCounter calcDayCounter = getDayCounter(Rcpp::as(calcparam["dayCounter"])); QuantLib::Compounding compounding = getCompounding(Rcpp::as(calcparam["compounding"])); QuantLib::Frequency calcFreq = getFrequency(Rcpp::as(calcparam["freq"])); QuantLib::Duration::Type durationType = getDurationType(Rcpp::as(calcparam["durationType"])); double accuracy = Rcpp::as(calcparam["accuracy"]); double maxEvaluations = Rcpp::as(calcparam["maxEvaluations"]); QuantLib::ext::shared_ptr bond = getFixedRateBond(bondparam, ratesVec, scheduleparam); QuantLib::Date sd = bond->settlementDate(); const Rcpp::Date settlementDate(sd.month(), sd.dayOfMonth(), sd.year()); const double accrued = bond->accruedAmount(); const double yield = QuantLib::BondFunctions::yield(*bond, price, calcDayCounter, compounding, calcFreq, sd, accuracy, maxEvaluations); return Rcpp::List::create(Rcpp::Named("NPV") = std::numeric_limits::quiet_NaN(), Rcpp::Named("cleanPrice") = price, Rcpp::Named("dirtyPrice") = price + accrued, Rcpp::Named("accruedCoupon") = accrued, Rcpp::Named("yield") = yield, Rcpp::Named("duration") = QuantLib::BondFunctions::duration(*bond, yield, calcDayCounter, compounding, calcFreq, durationType, sd), Rcpp::Named("settlementDate") = settlementDate, Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond->cashflows())); } // [[Rcpp::export]] Rcpp::List FixedRateWithRebuiltCurve(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, std::vector dateVec, std::vector zeroVec) { // get calc parameters QuantLib::DayCounter calcDayCounter = getDayCounter(Rcpp::as(calcparam["dayCounter"])); QuantLib::Compounding compounding = getCompounding(Rcpp::as(calcparam["compounding"])); QuantLib::Frequency calcFreq = getFrequency(Rcpp::as(calcparam["freq"])); QuantLib::Duration::Type durationType = getDurationType(Rcpp::as(calcparam["durationType"])); double accuracy = Rcpp::as(calcparam["accuracy"]); double maxEvaluations = Rcpp::as(calcparam["maxEvaluations"]); QuantLib::ext::shared_ptr bond = getFixedRateBond(bondparam, ratesVec, scheduleparam); QuantLib::Handle discountCurve(rebuildCurveFromZeroRates(dateVec, zeroVec)); //bond price QuantLib::ext::shared_ptr bondEngine(new QuantLib::DiscountingBondEngine(discountCurve)); bond->setPricingEngine(bondEngine); const double yield = bond->yield(calcDayCounter, compounding, calcFreq, accuracy, maxEvaluations); QuantLib::Date sd = bond->settlementDate(); const Rcpp::Date settlementDate(sd.month(), sd.dayOfMonth(), sd.year()); 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") = yield, Rcpp::Named("duration") = QuantLib::BondFunctions::duration(*bond, yield, calcDayCounter, compounding, calcFreq, durationType, sd), Rcpp::Named("settlementDate") = settlementDate, Rcpp::Named("cashFlow") = getCashFlowDataFrame(bond->cashflows())); } // TODO: R interface -- cannot use Attribute with converter for Handle<> // currently NOT exported but called below Rcpp::List zeroBondEngine(Rcpp::List rparam, QuantLib::Handle &discountCurve, Rcpp::List datemisc) { double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Date issueDate(Rcpp::as(rparam["issueDate"])); double redemption = Rcpp::as(rparam["redemption"]); double settlementDays = Rcpp::as(datemisc["settlementDays"]); std::string cal = Rcpp::as(datemisc["calendar"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); QuantLib::Date refDate(Rcpp::as(datemisc["refDate"])); QuantLib::Settings::instance().evaluationDate() = refDate; /* test-suite/bonds.cpp */ //set up QuantLib::BusinessDayConvetion QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::Calendar calendar; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } QuantLib::ZeroCouponBond bond(settlementDays, calendar, faceAmount, maturityDate, bdc, redemption, issueDate); QuantLib::ext::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())); } // [[Rcpp::export]] Rcpp::List ZeroBondWithRebuiltCurve(Rcpp::List bond, std::vector dateVec, std::vector zeroVec, Rcpp::List dateparams) { QuantLib::Handle curve(rebuildCurveFromZeroRates(dateVec, zeroVec)); return zeroBondEngine(bond, curve, dateparams); } // [[Rcpp::export]] Rcpp::List convertibleZeroBondEngine(Rcpp::List rparam, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { QuantLib::DividendSchedule dividendSchedule = getDividendSchedule(dividendScheduleFrame); QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); //double faceAmount = Rcpp::as(rparam["faceAmount"); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Date issueDate(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"]); double settlementDays = Rcpp::as(datemisc["settlementDays"]); std::string cal = Rcpp::as(datemisc["calendar"]); double dayCounter = Rcpp::as(datemisc["dayCounter"]); double frequency = Rcpp::as(datemisc["period"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); QuantLib::Date todayDate = issueDate; QuantLib::Calendar calendar; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::RelinkableHandle underlying; QuantLib::RelinkableHandle volatility; QuantLib::ext::shared_ptr blackProcess; QuantLib::Handle dividendYield(rebuildCurveFromZeroRates(dividendYieldDateVec, dividendYieldZeroVec)); QuantLib::Handle rff(rebuildCurveFromZeroRates(rffDateVec, rffZeroVec)); double underlyingQuote = Rcpp::as(processParam["underlying"]); double volatilityQuote = Rcpp::as(processParam["volatility"]); underlying.linkTo(QuantLib::ext::shared_ptr(new QuantLib::SimpleQuote(underlyingQuote))); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote( volatilityQuote )); volatility.linkTo(flatVol(todayDate, vol, dc)); blackProcess = QuantLib::ext::shared_ptr(new QuantLib::BlackScholesMertonProcess(underlying, dividendYield, rff, volatility)); QuantLib::RelinkableHandle creditSpread; creditSpread.linkTo(QuantLib::ext::shared_ptr(new QuantLib::SimpleQuote(creditSpreadQuote))); QuantLib::ext::shared_ptr euExercise(new QuantLib::EuropeanExercise(maturityDate)); QuantLib::ext::shared_ptr amExercise(new QuantLib::AmericanExercise(issueDate, maturityDate)); QuantLib::ext::shared_ptr ex = (exercise == "eu") ? euExercise : amExercise; QuantLib::Size timeSteps = 1001; QuantLib::ext::shared_ptr engine(new QuantLib::BinomialConvertibleEngine(blackProcess, timeSteps)); QuantLib::Handle discountCurve(QuantLib::ext::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())); } // [[Rcpp::export]] Rcpp::List convertibleFixedBondEngine(Rcpp::List rparam, Rcpp::NumericVector rates, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { QuantLib::DividendSchedule dividendSchedule = getDividendSchedule(dividendScheduleFrame); QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); //double faceAmount = Rcpp::as(rparam["faceAmount"); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Date issueDate(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"]); double settlementDays = Rcpp::as(datemisc["settlementDays"]); std::string cal = Rcpp::as(datemisc["calendar"]); double dayCounter = Rcpp::as(datemisc["dayCounter"]); double frequency = Rcpp::as(datemisc["period"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); QuantLib::Date todayDate = issueDate; QuantLib::Settings::instance().evaluationDate() = todayDate; QuantLib::Calendar calendar; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } 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(dividendYieldDateVec, dividendYieldZeroVec)); QuantLib::Handle rff(rebuildCurveFromZeroRates(rffDateVec, rffZeroVec)); double underlyingQuote = Rcpp::as(processParam["underlying"]); double volatilityQuote = Rcpp::as(processParam["volatility"]); underlying.linkTo(QuantLib::ext::shared_ptr(new QuantLib::SimpleQuote(underlyingQuote))); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote( volatilityQuote )); volatility.linkTo(flatVol(todayDate, vol, dc)); QuantLib::ext::shared_ptr blackProcess; blackProcess = QuantLib::ext::shared_ptr(new QuantLib::BlackScholesMertonProcess(underlying, dividendYield, rff, volatility)); // QuantLib::ext::shared_ptr blackProcess; //ackProcess = QuantLib::ext::shared_ptr( // new QuantLib::BlackScholesProcess(underlying, // rff, volatility)); QuantLib::RelinkableHandle creditSpread; creditSpread.linkTo(QuantLib::ext::shared_ptr(new QuantLib::SimpleQuote(creditSpreadQuote))); QuantLib::ext::shared_ptr euExercise(new QuantLib::EuropeanExercise(maturityDate)); QuantLib::ext::shared_ptr amExercise(new QuantLib::AmericanExercise(issueDate, maturityDate)); QuantLib::ext::shared_ptr ex = (exercise == "eu") ? euExercise : amExercise; QuantLib::Size timeSteps = 1001; QuantLib::ext::shared_ptr engine(new QuantLib::BinomialConvertibleEngine(blackProcess, timeSteps)); QuantLib::Handle discountCurve(QuantLib::ext::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())); } // [[Rcpp::export]] Rcpp::List convertibleFloatingBondEngine(Rcpp::List rparam, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, std::vector iborIndexDateVec, std::vector iborIndexZeroVec, Rcpp::List iborparams, std::vector spreads, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { QuantLib::DividendSchedule dividendSchedule = getDividendSchedule(dividendScheduleFrame); QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); //double faceAmount = Rcpp::as(rparam["faceAmount"); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Date issueDate(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 iborindex curve QuantLib::Handle index(rebuildCurveFromZeroRates(iborIndexDateVec, iborIndexZeroVec)); std::string type = Rcpp::as(iborparams["type"]); double length = Rcpp::as(iborparams["length"]); std::string inTermOf = Rcpp::as(iborparams["inTermOf"]); QuantLib::ext::shared_ptr iborindex(new QuantLib::USDLibor(6 * QuantLib::Months, index)); if (type=="USDLibor") { if (inTermOf=="Months") { QuantLib::ext::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Months, index)); iborindex = temp; } else if (inTermOf=="Years") { QuantLib::ext::shared_ptr temp(new QuantLib::USDLibor(length * QuantLib::Years, index)); iborindex = temp; } } double settlementDays = Rcpp::as(datemisc["settlementDays"]); std::string cal = Rcpp::as(datemisc["calendar"]); double dayCounter = Rcpp::as(datemisc["dayCounter"]); double frequency = Rcpp::as(datemisc["period"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); QuantLib::Date todayDate = issueDate; QuantLib::Calendar calendar; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); QuantLib::RelinkableHandle underlying; QuantLib::RelinkableHandle volatility; QuantLib::ext::shared_ptr blackProcess; QuantLib::Handle dividendYield(rebuildCurveFromZeroRates(dividendYieldDateVec, dividendYieldZeroVec)); QuantLib::Handle rff(rebuildCurveFromZeroRates(rffDateVec, rffZeroVec)); double underlyingQuote = Rcpp::as(processParam["underlying"]); double volatilityQuote = Rcpp::as(processParam["volatility"]); underlying.linkTo(QuantLib::ext::shared_ptr(new QuantLib::SimpleQuote(underlyingQuote))); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote( volatilityQuote )); volatility.linkTo(flatVol(todayDate, vol, dc)); blackProcess = QuantLib::ext::shared_ptr(new QuantLib::BlackScholesMertonProcess(underlying, dividendYield, rff, volatility)); QuantLib::RelinkableHandle creditSpread; creditSpread.linkTo(QuantLib::ext::shared_ptr(new QuantLib::SimpleQuote(creditSpreadQuote))); QuantLib::ext::shared_ptr euExercise(new QuantLib::EuropeanExercise(maturityDate)); QuantLib::ext::shared_ptr amExercise(new QuantLib::AmericanExercise(issueDate, maturityDate)); QuantLib::ext::shared_ptr ex = (exercise == "eu") ? euExercise : amExercise; QuantLib::Size timeSteps = 1001; QuantLib::ext::shared_ptr engine(new QuantLib::BinomialConvertibleEngine(blackProcess, timeSteps)); QuantLib::Handle discountCurve(QuantLib::ext::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())); } // [[Rcpp::export]] Rcpp::List callableBondEngine(Rcpp::List rparam, Rcpp::List hwparam, Rcpp::NumericVector coupon, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { QuantLib::CallabilitySchedule callabilitySchedule = getCallabilitySchedule(callabilityScheduleFrame); double faceAmount = Rcpp::as(rparam["faceAmount"]); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Date issueDate(Rcpp::as(rparam["issueDate"])); double redemption = Rcpp::as(rparam["redemption"]); double settlementDays = Rcpp::as(datemisc["settlementDays"]); std::string cal = Rcpp::as(datemisc["calendar"]); double dayCounter = Rcpp::as(datemisc["dayCounter"]); double frequency = Rcpp::as(datemisc["period"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); QuantLib::Calendar calendar; if (!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(businessDayConvention); QuantLib::DayCounter dc = getDayCounter(dayCounter); QuantLib::Frequency freq = getFrequency(frequency); //extract coupon rates vector Rcpp::NumericVector rates(coupon); double alpha = Rcpp::as(hwparam["alpha"]); double sigma = Rcpp::as(hwparam["sigma"]); double gridIntervals = Rcpp::as(hwparam["gridIntervals"]); double rate = Rcpp::as(hwparam["term"]); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(rate)); QuantLib::Handle termStructure(flatRate(issueDate,rRate,QuantLib::Actual360())); //QuantLib::Handle termStructure(rebuildCurveFromZeroRates( // hwTermDateSexp, // hwTermZeroSexp)); QuantLib::ext::shared_ptr hw0(new QuantLib::HullWhite(termStructure,alpha,sigma)); QuantLib::ext::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())); 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"); // QuantLib::ext::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; // if(!cal.empty()) { // QuantLib::ext::shared_ptr p = getCalendar(cal); // calendar = *p; // } // QuantLib::BusinessDayConvention fixedLegBDC = getBusinessDayConvention(fixedLegConvention); // QuantLib::DayCounter fixedLedDC = getDayCounter(fixedLegDayCounter); // QuantLib::ext::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( // QuantLib::ext::shared_ptr // new QuantLib::SwaptionVolatilityMatrix(swapCal, // swaptionBDC, // atmOptionTenors, // atmSwapTenors, // m, // swaptionDC)); // QuantLib::ext::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; // } // [[Rcpp::export]] Rcpp::List fittedBondCurveEngine(Rcpp::List curveparam, Rcpp::NumericVector length, Rcpp::NumericVector coupons, Rcpp::NumericVector marketQuotes, Rcpp::List datemisc) { double settlementDays = Rcpp::as(datemisc["settlementDays"]); double dayCounter = Rcpp::as(datemisc["dayCounter"]); double frequency = Rcpp::as(datemisc["period"]); double businessDayConvention = Rcpp::as(datemisc["businessDayConvention"]); std::string method = Rcpp::as(curveparam["method"]); QuantLib::Date origDate(Rcpp::as(curveparam["origDate"]));; QuantLib::Settings::instance().evaluationDate() = origDate; const QuantLib::Size numberOfBonds = length.size(); std::vector< QuantLib::ext::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); QuantLib::ext::shared_ptr bond(new QuantLib::FixedRateBond(settlementDays, 100.0, schedule, std::vector(1,coupons[j]), dc, bdc, redemption, issue, calendar)); QuantLib::ext::shared_ptr helperA(new QuantLib::BondHelper(quoteHandle[j], bond)); instrumentsA.push_back(helperA); } bool constrainAtZero = true; QuantLib::Real tolerance = 1.0e-10; QuantLib::Size max = 5000; QuantLib::ext::shared_ptr curve; if (method=="ExponentialSplinesFitting") { QuantLib::ExponentialSplinesFitting exponentialSplines(constrainAtZero); QuantLib::ext::shared_ptr ts1 (new QuantLib::FittedBondDiscountCurve(settlementDays, calendar, instrumentsA, dc, exponentialSplines, tolerance, max)); curve = ts1; } else if (method == "SimplePolynomialFitting") { double degree = Rcpp::as(curveparam["degree"]); QuantLib::SimplePolynomialFitting simplePolynomial(degree, constrainAtZero); QuantLib::ext::shared_ptr ts2 (new QuantLib::FittedBondDiscountCurve(settlementDays, calendar, instrumentsA, dc, simplePolynomial, tolerance, max)); curve = ts2; } else if (method == "NelsonSiegelFitting") { QuantLib::NelsonSiegelFitting nelsonSiegel; QuantLib::ext::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); } RQuantLib/src/Makevars.win0000644000176200001440000000154013522344635015201 0ustar liggesusers# -*- mode: Makefile -*- # # Copyright 2005 - 2006 Dominick Samperi # Copyright 2005 Uwe Ligges # Copyright 2008 - 2018 Dirk Eddelbuettel # Copyright 2011 Uwe Ligges, Brian Ripley, and Josh Ulrich # Copyright 2018 - 2019 Jeroen Ooms RWINLIB=../windows/quantlib-1.16 PKG_CPPFLAGS=-I$(RWINLIB)/include -I../inst/include PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) -DBOOST_NO_AUTO_PTR -Wno-deprecated-declarations ## NB directory layout with arch/lib is quantlib upstream default which is followed here TARGET = $(subst gcc,lib,$(COMPILED_BY)) PKG_LIBS = \ -L$(RWINLIB)/$(TARGET)$(R_ARCH)/lib \ -L$(RWINLIB)/lib$(R_ARCH)/lib \ -lQuantLib $(SHLIB_OPENMP_CXXFLAGS) # Use C++11 for long long in Boost headers CXX_STD=CXX11 all: clean winlibs clean: rm -f $(SHLIB) $(OBJECTS) winlibs: "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" "../tools/winlibs.R" RQuantLib/src/utils.cpp0000644000176200001440000007203613607470157014570 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2020 Dirk Eddelbuettel // Copyright (C) 2005 - 2006 Dominick Samperi // Copyright (C) 2009 - 2012 Dirk Eddelbuettel and Khanh Nguyen // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::interfaces(r, cpp)]] 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 QuantLib::ext::shared_ptr makeOption(const QuantLib::ext::shared_ptr& payoff, const QuantLib::ext::shared_ptr& exercise, const QuantLib::ext::shared_ptr& u, const QuantLib::ext::shared_ptr& q, const QuantLib::ext::shared_ptr& r, const QuantLib::ext::shared_ptr& vol, EngineType engineType, QuantLib::Size binomialSteps, QuantLib::Size samples) { QuantLib::ext::shared_ptr stochProcess = makeProcess(u,q,r,vol); QuantLib::ext::shared_ptr engine; typedef QuantLib::ext::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::FdBlackScholesVanillaEngine(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"); } QuantLib::ext::shared_ptr option(new QuantLib::EuropeanOption(payoff, exercise)); option->setPricingEngine(engine); return option; } // QuantLib option setup utils, copied from the test-suite sources QuantLib::ext::shared_ptr buildTermStructure(Rcpp::List rparam, Rcpp::List tslist) { QuantLib::ext::shared_ptr curve; try { Rcpp::CharacterVector tsnames = tslist.names(); QuantLib::Date todaysDate(Rcpp::as(rparam["tradeDate"])); QuantLib::Date settlementDate(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]); QuantLib::ext::shared_ptr flatRate(new QuantLib::SimpleQuote(rateQuote)); QuantLib::ext::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]); QuantLib::ext::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); } QuantLib::ext::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(Rcpp::List rparam) { QuantLib::Date effectiveDate(Rcpp::as(rparam["effectiveDate"])); QuantLib::Date maturityDate(Rcpp::as(rparam["maturityDate"])); QuantLib::Period period = QuantLib::Period(getFrequency(Rcpp::as(rparam["period"]))); std::string cal = Rcpp::as(rparam["calendar"]); QuantLib::Calendar calendar; if(!cal.empty()) { QuantLib::ext::shared_ptr p = getCalendar(cal); calendar = *p; } QuantLib::BusinessDayConvention businessDayConvention = getBusinessDayConvention(Rcpp::as(rparam["businessDayConvention"])); QuantLib::BusinessDayConvention terminationDateConvention = getBusinessDayConvention(Rcpp::as(rparam["terminationDateConvention"])); // keep these default values for the last two parameters for backward compatibility // (although in QuantLib::schedule they have no default values) QuantLib::DateGeneration::Rule dateGeneration = QuantLib::DateGeneration::Backward; if(rparam.containsElementNamed("dateGeneration") ) { dateGeneration = getDateGenerationRule(Rcpp::as(rparam["dateGeneration"])); } bool endOfMonth = false; if(rparam.containsElementNamed("endOfMonth") ) { endOfMonth = (Rcpp::as(rparam["endOfMonth"]) == 1) ? true : false; } QuantLib::Schedule schedule(effectiveDate, maturityDate, period, calendar, businessDayConvention, terminationDateConvention, dateGeneration, endOfMonth); return schedule; } QuantLib::ext::shared_ptr getFixedRateBond( Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam) { // get bond parameters double settlementDays = Rcpp::as(bondparam["settlementDays"]); double faceAmount = Rcpp::as(bondparam["faceAmount"]); QuantLib::DayCounter accrualDayCounter = getDayCounter(Rcpp::as(bondparam["dayCounter"])); QuantLib::BusinessDayConvention paymentConvention = QuantLib::Following; if(bondparam.containsElementNamed("paymentConvention") ) { paymentConvention = getBusinessDayConvention(Rcpp::as(bondparam["paymentConvention"])); } double redemption = 100.0; if(bondparam.containsElementNamed("redemption") ) { redemption = Rcpp::as(bondparam["redemption"]); } QuantLib::Date issueDate; if(bondparam.containsElementNamed("issueDate") ) { issueDate = Rcpp::as(bondparam["issueDate"]); } QuantLib::Calendar paymentCalendar; if(bondparam.containsElementNamed("paymentCalendar") ) { QuantLib::ext::shared_ptr p = getCalendar(Rcpp::as(bondparam["paymentCalendar"])); paymentCalendar = *p; } QuantLib::Period exCouponPeriod; if(bondparam.containsElementNamed("exCouponPeriod") ) { exCouponPeriod = QuantLib::Period(Rcpp::as(bondparam["exCouponPeriod"]), QuantLib::Days); } QuantLib::Calendar exCouponCalendar; if(bondparam.containsElementNamed("exCouponCalendar") ) { QuantLib::ext::shared_ptr p = getCalendar(Rcpp::as(bondparam["exCouponCalendar"])); exCouponCalendar = *p; } QuantLib::BusinessDayConvention exCouponConvention = QuantLib::Unadjusted; if(bondparam.containsElementNamed("exCouponConvention") ) { exCouponConvention = getBusinessDayConvention(Rcpp::as(bondparam["exCouponConvention"])); } bool exCouponEndOfMonth = false; if(bondparam.containsElementNamed("exCouponEndOfMonth") ) { exCouponEndOfMonth = (Rcpp::as(bondparam["exCouponEndOfMonth"]) == 1) ? true : false; } QuantLib::Schedule schedule = getSchedule(scheduleparam); QuantLib::ext::shared_ptr result( new QuantLib::FixedRateBond(settlementDays, faceAmount, schedule, ratesVec, accrualDayCounter, paymentConvention, redemption, issueDate, paymentCalendar, exCouponPeriod, exCouponCalendar, exCouponConvention, exCouponEndOfMonth)); return result; } QuantLib::ext::shared_ptr rebuildCurveFromZeroRates(std::vector dates, std::vector zeros) { QuantLib::ext::shared_ptr rebuilt_curve(new QuantLib::InterpolatedZeroCurve(dates, zeros, QuantLib::ActualActual())); return rebuilt_curve; } QuantLib::ext::shared_ptr getFlatCurve(Rcpp::List curve) { QuantLib::Rate riskFreeRate = Rcpp::as(curve["riskFreeRate"]); QuantLib::Date today(Rcpp::as(curve["todayDate"])); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::Settings::instance().evaluationDate() = today; return flatRate(today, rRate, QuantLib::Actual360()); } QuantLib::ext::shared_ptr getIborIndex(Rcpp::List rparam, const QuantLib::Date today) { std::string type = Rcpp::as(rparam["type"]); if (type == "USDLibor"){ double riskFreeRate = Rcpp::as(rparam["riskFreeRate"]); double period = Rcpp::as(rparam["period"]); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::Settings::instance().evaluationDate() = today; QuantLib::Handle curve(flatRate(today, rRate, QuantLib::Actual360())); QuantLib::ext::shared_ptr iindex(new QuantLib::USDLibor(period * QuantLib::Months, curve)); return iindex; } else return QuantLib::ext::shared_ptr(); } // std::vector getDoubleVector(SEXP vecSexp) { // if (::Rf_length(vecSexp) == 0) { // return(std::vector()); // } else { // return std::vector( Rcpp::as >( Rcpp::NumericVector(vecSexp) ) ); // } // } QuantLib::ext::shared_ptr makeFlatCurve(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& forward, const QuantLib::DayCounter& dc) { return QuantLib::ext::shared_ptr(new QuantLib::FlatForward(today, QuantLib::Handle(forward), dc)); } QuantLib::ext::shared_ptr flatRate(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& forward, const QuantLib::DayCounter& dc) { return QuantLib::ext::shared_ptr(new QuantLib::FlatForward(today, QuantLib::Handle(forward), dc)); } QuantLib::ext::shared_ptr makeFlatVolatility(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& vol, const QuantLib::DayCounter dc) { return QuantLib::ext::shared_ptr(new QuantLib::BlackConstantVol(today, QuantLib::NullCalendar(), QuantLib::Handle(vol), dc)); } QuantLib::ext::shared_ptr flatVol(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& vol, const QuantLib::DayCounter& dc) { return QuantLib::ext::shared_ptr( new QuantLib::BlackConstantVol(today, QuantLib::NullCalendar(), QuantLib::Handle(vol), dc)); } typedef QuantLib::BlackScholesMertonProcess BSMProcess; // shortcut QuantLib::ext::shared_ptr makeProcess(const QuantLib::ext::shared_ptr& u, const QuantLib::ext::shared_ptr& q, const QuantLib::ext::shared_ptr& r, const QuantLib::ext::shared_ptr& vol) { return QuantLib::ext::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) { // static const unsigned int QLtoJan1970Offset = 25569; // Offset to R / Unix epoch // 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 if (n==6) return QuantLib::Thirty360(); #ifdef RQUANTLIB_USE_ACTUAL365NOLEAP else if (n==7) return QuantLib::Actual365NoLeap(); #endif else if (n==8) return QuantLib::ActualActual(QuantLib::ActualActual::ISMA); else if (n==9) return QuantLib::ActualActual(QuantLib::ActualActual::Bond); else if (n==10) return QuantLib::ActualActual(QuantLib::ActualActual::ISDA); else if (n==11) return QuantLib::ActualActual(QuantLib::ActualActual::Historical); else if (n==12) return QuantLib::ActualActual(QuantLib::ActualActual::AFB); else // if (n==13) return QuantLib::ActualActual(QuantLib::ActualActual::Euro); } 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 if (n==4) return QuantLib::Unadjusted; else if (n==5) return QuantLib::HalfMonthModifiedFollowing; else if (n==6) return QuantLib::Nearest; 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 if (n==5) return QuantLib::DateGeneration::TwentiethIMM; else if (n==6) return QuantLib::DateGeneration::OldCDS; else if (n==7) return QuantLib::DateGeneration::CDS; else return QuantLib::DateGeneration::TwentiethIMM; } QuantLib::ext::shared_ptr buildIborIndex(std::string type, const QuantLib::Handle& iborStrc){ if (type == "Euribor10M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor10M(iborStrc)); if (type == "Euribor11M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor11M(iborStrc)); if (type == "Euribor1M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor1M(iborStrc)); if (type == "Euribor1Y") return QuantLib::ext::shared_ptr(new QuantLib::Euribor1Y(iborStrc)); if (type == "Euribor2M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor2M(iborStrc)); if (type == "Euribor2W") return QuantLib::ext::shared_ptr(new QuantLib::Euribor2W(iborStrc)); if (type == "Euribor3M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor3M(iborStrc)); if (type == "Euribor3W") return QuantLib::ext::shared_ptr(new QuantLib::Euribor3W(iborStrc)); if (type == "Euribor4M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor4M(iborStrc)); if (type == "Euribor5M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor5M(iborStrc)); if (type == "Euribor6M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor6M(iborStrc)); if (type == "Euribor7M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor7M(iborStrc)); if (type == "Euribor8M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor8M(iborStrc)); if (type == "Euribor9M") return QuantLib::ext::shared_ptr(new QuantLib::Euribor9M(iborStrc)); if (type == "EuriborSW") return QuantLib::ext::shared_ptr(new QuantLib::EuriborSW(iborStrc)); return QuantLib::ext::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(Rcpp::DataFrame divScheDF) { QuantLib::DividendSchedule dividendSchedule; try { 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(Rcpp::wrap(rd))); //table[row][3].getDateValue())); if (type==1) { dividendSchedule.push_back(QuantLib::ext::shared_ptr(new QuantLib::FixedDividend(amount, d))); } else { dividendSchedule.push_back(QuantLib::ext::shared_ptr(new QuantLib::FractionalDividend(rate, amount, d))); } } } catch (std::exception& ex) { forward_exception_to_r(ex); } return dividendSchedule; } QuantLib::CallabilitySchedule getCallabilitySchedule(Rcpp::DataFrame callScheDF) { QuantLib::CallabilitySchedule callabilitySchedule; // QuantLib::Callability::Price triggers 'deprecated' under clang++-9 // yet the new QuantLib::Bond::Price appeared only in QuantLib 1.17 so // it is a little nice to protect buildability under 1.16 with this // it also shortens the line a little below :) #if QL_HEX_VERSION >= 0x011700f0 typedef QuantLib::Bond::Price QlBondPrice; #else typedef QuantLib::Callability::Price QlBondPrice; #endif try { // RcppFrame rcppCallabilitySchedule(callabilityScheduleFrame); // std::vector > table = rcppCallabilitySchedule.getTableData(); // int nrow = table.size(); Rcpp::NumericVector n0v = callScheDF[0]; Rcpp::CharacterVector s1v = callScheDF[1]; Rcpp::NumericVector n2v = callScheDF[2]; int nrow = n0v.size(); for (int row=0; row(Rcpp::wrap(rd))); if (type==1){ callabilitySchedule.push_back(QuantLib::ext::shared_ptr (new QuantLib::Callability(QlBondPrice(price, QlBondPrice::Clean), QuantLib::Callability::Put,d ))); } else { callabilitySchedule.push_back(QuantLib::ext::shared_ptr (new QuantLib::Callability(QlBondPrice(price, QlBondPrice::Clean), QuantLib::Callability::Call,d ))); } } } catch (std::exception& ex){ forward_exception_to_r(ex); } return callabilitySchedule; } QuantLib::Duration::Type getDurationType(const double n) { if (n==0) return QuantLib::Duration::Simple; else if (n==1) return QuantLib::Duration::Macaulay; else if (n==2) return QuantLib::Duration::Modified; else { throw std::range_error("Invalid duration type " + boost::lexical_cast(n)); } } //' This function returns the QuantLib version string as encoded in the header //' file \code{config.hpp} and determined at compilation time of the QuantLib library. //' //' @title Return the QuantLib version number //' @return A character variable //' @references \url{http://quantlib.org} for details on \code{QuantLib}. //' @author Dirk Eddelbuettel //' @examples //' getQuantLibVersion() // [[Rcpp::export]] std::string getQuantLibVersion() { return std::string(QL_PACKAGE_VERSION); } //' This function returns a named vector of boolean variables describing several //' configuration options determined at compilation time of the QuantLib library. //' //' Not all of these features are used (yet) by RQuantLib. //' @title Return configuration options of the QuantLib library //' @return A named vector of logical variables //' @references \url{http://quantlib.org} for details on \code{QuantLib}. //' @author Dirk Eddelbuettel //' @examples //' getQuantLibCapabilities() // [[Rcpp::export]] Rcpp::LogicalVector getQuantLibCapabilities() { bool hasSessions = false, // not (yet?) used by RQuantLib hasHighResolutionDate=false, // supported as of RQuantLib 0.4.2 hasNegativeRates=false; // not explicitly supported or denied #ifdef QL_ENABLE_SESSIONS hasSessions = true; #endif #ifdef QL_HIGH_RESOLUTION_DATE hasHighResolutionDate=true; #endif #ifdef QL_NEGATIVE_RATES hasNegativeRates=true; #endif return Rcpp::LogicalVector::create(Rcpp::Named("sessions") = hasSessions, Rcpp::Named("intradayDate") = hasHighResolutionDate, Rcpp::Named("negativeRates") = hasNegativeRates); } RQuantLib/src/deprecated/0000755000176200001440000000000013224507117015004 5ustar liggesusersRQuantLib/src/deprecated/rquantlib.h0000644000176200001440000000362413224507117017163 0ustar liggesusers// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // // RQuantLib header // // Copyright 2014 - 2018 Dirk Eddelbuettel // // 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_src_h #define rquantlib_src_h // Rcpp Attributes requires a file with package name in inst/include, // in our case inst/include/RQuantLib.h -- but R does not want us to have // another header file with the same name, differing only by case // // So we place the existing 'rquantlib.h' in src/ instead so that the // issue of equal names (for everything but the case) no longer // matters. This provides us with a backwards compatible // 'rquantlib.h' file, and its definitons are now in a file // inst/include/rquantlib_internal.h which we source here. // // Moreover, a particular silly company in Cupertino, CA, insists on // case non-existing for files and file systems, leading to a surprise // or warning here or there. So in the current implementation, this file // exists but is not actually explicitly sourced. Rather, all C++ files // directly use '#include as well. And for the // same reason, and to be totally safe, it is even moved to a directory // 'deprecated/' below 'src/'. Should you need it, you can move it back. #include "rquantlib_internal.h" #endif RQuantLib/src/hullwhite.cpp0000644000176200001440000001706313443253624015430 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen // Copyright (C) 2011 - 2019 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::export]] Rcpp::List calibrateHullWhiteUsingCapsEngine(std::vector termStrcDateVec, std::vector termStrcZeroVec, Rcpp::DataFrame capDF, std::vector iborDateVec, std::vector iborZeroVec, std::string iborType, QuantLib::Date evalDate) { QuantLib::Settings::instance().evaluationDate() = evalDate; QuantLib::Handle term(rebuildCurveFromZeroRates(termStrcDateVec, termStrcZeroVec)); //set up ibor index QuantLib::Handle indexStrc(rebuildCurveFromZeroRates(iborDateVec, iborZeroVec)); QuantLib::ext::shared_ptr index = buildIborIndex(iborType, indexStrc); //process capDataDF std::vector > caps; //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])); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(d2v[row])); QuantLib::DayCounter dc = getDayCounter(i4v[row]); QuantLib::ext::shared_ptr helper(new QuantLib::CapHelper(p, QuantLib::Handle(vol), index, getFrequency(i3v[row]), dc, (i5v[row]==1) ? true : false, term)); QuantLib::ext::shared_ptr engine(new QuantLib::BlackCapFloorEngine(term, d2v[row])); helper->setPricingEngine(engine); caps.push_back(helper); } //set up the HullWhite model QuantLib::ext::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]); } // [[Rcpp::export]] Rcpp::List calibrateHullWhiteUsingSwapsEngine(std::vector termStrcDateVec, std::vector termStrcZeroVec, Rcpp::DataFrame swapDF, std::vector iborDateVec, std::vector iborZeroVec, std::string iborType, QuantLib::Date evalDate) { QuantLib::Settings::instance().evaluationDate() = evalDate; //set up the HullWhite model QuantLib::Handle term(rebuildCurveFromZeroRates(termStrcDateVec, termStrcZeroVec)); QuantLib::ext::shared_ptr model(new QuantLib::HullWhite(term)); //set up ibor index QuantLib::Handle indexStrc(rebuildCurveFromZeroRates(iborDateVec, iborZeroVec)); QuantLib::ext::shared_ptr index = buildIborIndex(iborType, indexStrc); //process capDataDF QuantLib::ext::shared_ptr engine(new QuantLib::JamshidianSwaptionEngine(model)); std::vector > swaps; //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])); QuantLib::ext::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]); QuantLib::ext::shared_ptr helper(new QuantLib::SwaptionHelper(maturity, length, QuantLib::Handle(vol), index, fixedLegTenor, fixedLegDayCounter, floatingLegDayCounter, term)); helper->setPricingEngine(engine); swaps.push_back(helper); } //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]); } RQuantLib/src/curves.cpp0000644000176200001440000004266313443253624014736 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2019 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . // [[Rcpp::interfaces(r, cpp)]] #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_["s4y"] = new RQLObservable(RQLSwap, 4, 0, QuantLib::Years); db_["s5y"] = new RQLObservable(RQLSwap, 5, 0, QuantLib::Years); db_["s6y"] = new RQLObservable(RQLSwap, 6, 0, QuantLib::Years); db_["s7y"] = new RQLObservable(RQLSwap, 7, 0, QuantLib::Years); db_["s8y"] = new RQLObservable(RQLSwap, 8, 0, QuantLib::Years); db_["s9y"] = new RQLObservable(RQLSwap, 9, 0, QuantLib::Years); db_["s10y"] = new RQLObservable(RQLSwap, 10, 0, QuantLib::Years); db_["s12y"] = new RQLObservable(RQLSwap, 12, 0, QuantLib::Years); db_["s15y"] = new RQLObservable(RQLSwap, 15, 0, QuantLib::Years); db_["s20y"] = new RQLObservable(RQLSwap, 20, 0, QuantLib::Years); db_["s25y"] = new RQLObservable(RQLSwap, 25, 0, QuantLib::Years); db_["s30y"] = new RQLObservable(RQLSwap, 30, 0, QuantLib::Years); db_["s40y"] = new RQLObservable(RQLSwap, 40, 0, QuantLib::Years); db_["s50y"] = new RQLObservable(RQLSwap, 50, 0, QuantLib::Years); db_["s60y"] = new RQLObservable(RQLSwap, 60, 0, QuantLib::Years); db_["s70y"] = new RQLObservable(RQLSwap, 70, 0, QuantLib::Years); db_["s80y"] = new RQLObservable(RQLSwap, 80, 0, QuantLib::Years); db_["s90y"] = new RQLObservable(RQLSwap, 90, 0, QuantLib::Years); db_["s100y"] = new RQLObservable(RQLSwap, 100, 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. QuantLib::ext::shared_ptr ObservableDB::getRateHelper(std::string& ticker, QuantLib::Rate r, double fixDayCount, double fixFreq, int floatFreq) { RQLMapIterator iter = db_.find(ticker); if (iter == db_.end()) { std::string errortxt = "Unknown curve construction instrument: " + ticker; Rcpp::stop(errortxt); } 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) { QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::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 = getFrequency(fixFreq); QuantLib::BusinessDayConvention swFixedLegConvention = QuantLib::Unadjusted; QuantLib::DayCounter swFixedLegDayCounter = getDayCounter(fixDayCount); QuantLib::ext::shared_ptr swFloatingLegIndex(new QuantLib::Euribor(QuantLib::Period(floatFreq,QuantLib::Months))); QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::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; QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::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) { QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::shared_ptr FRA(new QuantLib::FraRateHelper(QuantLib::Handle(quote), n1, n2, fixingDays, calendar, QuantLib::ModifiedFollowing, true, /*fixingDays,*/ depositDayCounter)); return FRA; } else { Rcpp::stop("Bad type in curve construction"); } // not reached QuantLib::ext::shared_ptr tmp; return tmp; } //*** original rate helper, kept to ensure Bermudan works. Change in future - Terry Leitch 16 Mar '16 QuantLib::ext::shared_ptr ObservableDB::getRateHelper(std::string& ticker, QuantLib::Rate r) { RQLMapIterator iter = db_.find(ticker); if (iter == db_.end()) { std::string errortxt = "Unknown curve construction instrument: " + ticker; Rcpp::stop(errortxt); } 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) { QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::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); QuantLib::ext::shared_ptr swFloatingLegIndex(new QuantLib::Euribor6M); QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::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; QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::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) { QuantLib::ext::shared_ptr quote(new QuantLib::SimpleQuote(r)); QuantLib::ext::shared_ptr FRA(new QuantLib::FraRateHelper(QuantLib::Handle(quote), n1, n2, fixingDays, calendar, QuantLib::ModifiedFollowing, true, /*fixingDays,*/ depositDayCounter)); return FRA; } else { Rcpp::stop("Bad type in curve construction"); } // not reached QuantLib::ext::shared_ptr tmp; return tmp; } // Return the term structure built using a set of RateHelpers (curveInput) // employing the specified interpolation method and day counter. QuantLib::ext::shared_ptr getTermStructure (std::string& interpWhat, std::string& interpHow, const QuantLib::Date& settlementDate, const std::vector >& curveInput, QuantLib::DayCounter& dayCounter, QuantLib::Real tolerance) { // the identifiers are just too bloody long so this functions like a 120 col or so display if (interpWhat.compare("discount") == 0 && interpHow.compare("linear") == 0) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::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) { QuantLib::ext::shared_ptr ts(new QuantLib::PiecewiseYieldCurve(settlementDate, curveInput, dayCounter, std::vector >(), std::vector(), tolerance)); return ts; } else { Rcpp::Rcout << "interpWhat = " << interpWhat << std::endl; Rcpp::Rcout << "interpHow = " << interpHow << std::endl; Rcpp::stop("What/How term structure options not recognized"); } // not reached -- just here to make g++ -pendantic happy QuantLib::ext::shared_ptr tmp; return tmp; } RQuantLib/src/implieds.cpp0000644000176200001440000001431213443253624015223 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2019 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::interfaces(r, cpp)]] // [[Rcpp::export]] double europeanOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility) { const QuantLib::Size maxEvaluations = 100; const double tolerance = 1.0e-6; #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity*360 + 0.5); // FIXME: this could be better #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today,qRate,dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today,rRate,dc); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); QuantLib::ext::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS, Analytic, QuantLib::Null(), QuantLib::Null()); QuantLib::ext::shared_ptr process = makeProcess(spot, qTS, rTS,volTS); double volguess = volatility; vol->setValue(volguess); return option->impliedVolatility(value, process, tolerance, maxEvaluations); } // [[Rcpp::export]] double americanOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volguess, int timesteps, int gridpoints) { const QuantLib::Size maxEvaluations = 100; const double tolerance = 1.0e-6; #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity*360 + 0.5); // FIXME: this could be better #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volguess)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol,dc); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today,qRate,dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today,rRate,dc); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::Settings::instance().evaluationDate() = today; QuantLib::ext::shared_ptr exercise(new QuantLib::AmericanExercise(today, exDate)); QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); QuantLib::ext::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS, JR); QuantLib::ext::shared_ptr process = makeProcess(spot, qTS, rTS,volTS); return option->impliedVolatility(value, process, tolerance, maxEvaluations); } RQuantLib/src/discount.cpp0000644000176200001440000001422513443253624015250 0ustar liggesusers // RQuantLib function DiscountCurve // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2019 Dirk Eddelbuettel // Copyright (C) 2009 - 2011 Dirk Eddelbuettel and Khanh Nguyen // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::export]] Rcpp::List discountCurveEngine(Rcpp::List rparams, Rcpp::List tslist, Rcpp::NumericVector times, Rcpp::List legParams) { std::vector tsNames = tslist.names(); int i; QuantLib::Date todaysDate(Rcpp::as(rparams["tradeDate"])); QuantLib::Date settlementDate(Rcpp::as(rparams["settleDate"])); 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(rparams["dt"]); std::string interpWhat, interpHow; bool flatQuotes = true; if (firstQuoteName.compare("flat") != 0) { // Get interpolation method (not needed for "flat" case) interpWhat = Rcpp::as(rparams["interpWhat"]); interpHow = Rcpp::as(rparams["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; QuantLib::ext::shared_ptr curve; if (firstQuoteName.compare("flat") == 0) { // Create a flat term structure. double rateQuote = Rcpp::as(tslist[0]); //QuantLib::ext::shared_ptr flatRate(new SimpleQuote(rateQuote)); //QuantLib::ext::shared_ptr ts(new FlatForward(settlementDate, // Handle(flatRate), // ActualActual())); QuantLib::ext::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 general swap inputs, not elegant but necessary to pass to getRateHelper() double fixDayCount = Rcpp::as(legParams["dayCounter"]); double fixFreq = Rcpp::as(legParams["fixFreq"]) ; int floatFreq = Rcpp::as(legParams["floatFreq"]); //int floatFreq2 = 6; for(i = 0; i < tslist.size(); i++) { std::string name = tsNames[i]; double val = Rcpp::as(tslist[i]); QuantLib::ext::shared_ptr rh = ObservableDB::instance().getRateHelper(name, val, fixDayCount,fixFreq, floatFreq); // 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); } QuantLib::ext::shared_ptr ts = getTermStructure(interpWhat, interpHow, settlementDate, curveInput, termStructureDayCounter, tolerance); curve = ts; } // Return discount, forward rate, and zero coupon curves int ntimes = times.size(); Rcpp::NumericVector disc(ntimes), fwds(ntimes), zero(ntimes); QuantLib::Date current = settlementDate; for (i = 0; i < ntimes; i++) { double t = times[i]; disc[i] = curve->discount(t); fwds[i] = curve->forwardRate(t, t+dt, QuantLib::Continuous); zero[i] = curve->zeroRate(t, QuantLib::Continuous); } QuantLib::Settings::instance().evaluationDate() = evalDate; std::vector dates; std::vector zeroRates; QuantLib::Date d = current; QuantLib::Date maxDate(31, QuantLib::December, 2150); while (d < curve->maxDate() && d < maxDate) { // TODO set a max of, say, 5 or 10 years for flat curve double z = curve->zeroRate(d, QuantLib::ActualActual(), QuantLib::Continuous); dates.push_back(d); zeroRates.push_back(z); d = advanceDate(d, 21); // TODO: make the increment a parameter } //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") = times, Rcpp::Named("discounts") = disc, Rcpp::Named("forwards") = fwds, Rcpp::Named("zerorates") = zero, Rcpp::Named("flatQuotes") = flatQuotes, Rcpp::Named("params") = rparams, Rcpp::Named("table") = frame); return rl; } RQuantLib/src/affine.cpp0000644000176200001440000003405513443253624014653 0ustar liggesusers // RQuantLib function AffineSwaption // // Copyright (C) 2005 - 2007 Dominick Samperi // Copyright (C) 2007 - 2019 Dirk Eddelbuettel // Copyright (C) 2016 Terry Leitch // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // Calibrates underlying swaptions to the input volatility matrix. void calibrateModel2(const QuantLib::ext::shared_ptr& model, const std::vector > &helpers, QuantLib::Real lambda, Rcpp::NumericVector &swaptionMat, Rcpp::NumericVector &swapLengths, Rcpp::NumericVector &swaptionVols) { QuantLib::Size numRows = swaptionVols.size(); //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, 1.50); QuantLib::Volatility diff = implied - swaptionVols(i); Rprintf((char*) "%dx%d: model %lf, market %lf, diff %lf\n", swaptionMat[i], swapLengths[i], implied, swaptionVols(i), diff); } } // [[Rcpp::export]] Rcpp::List affineWithRebuiltCurveEngine(Rcpp::List rparam, Rcpp::List legparams, std::vector dateVec, std::vector zeroVec, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericVector swaptionVols) { // 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(Rcpp::as(rparam["tradeDate"])); QuantLib::Date settlementDate(Rcpp::as(rparam["settleDate"])); QuantLib::Date startDate(Rcpp::as(rparam["startDate"])); QuantLib::Date maturity(Rcpp::as(rparam["maturity"])); bool payfix = Rcpp::as(rparam["payFixed"]); bool european = Rcpp::as(rparam["european"]); //cout << "TradeDate: " << todaysDate << endl << "Settle: " << settlementDate << endl; RQLContext::instance().settleDate = settlementDate; QuantLib::Settings::instance().evaluationDate() = todaysDate; // initialise from the singleton instance QuantLib::Calendar calendar = RQLContext::instance().calendar; //Integer fixingDays = RQLContext::instance().fixingDays; double strike = Rcpp::as(rparam["strike"]); std::string method = Rcpp::as(rparam["method"]); QuantLib::Handle rhTermStructure(rebuildCurveFromZeroRates(dateVec, zeroVec)); // Get swaption maturities //Rcpp::NumericVector swaptionMat(maturities); int numRows = swaptionMat.size(); // Create dummy swap to get schedules. QuantLib::Frequency fixedLegFrequency = getFrequency(Rcpp::as(legparams["fixFreq"])); QuantLib::BusinessDayConvention fixedLegConvention = QuantLib::Unadjusted; QuantLib::BusinessDayConvention floatingLegConvention = QuantLib::ModifiedFollowing; QuantLib::DayCounter swFixedLegDayCounter = getDayCounter(Rcpp::as(legparams["dayCounter"])); QuantLib::ext::shared_ptr swFloatingLegIndex(new QuantLib::Euribor(QuantLib::Period(Rcpp::as(legparams["floatFreq"]),QuantLib::Months),rhTermStructure)); QuantLib::Rate dummyFixedRate = 0.03; QuantLib::Schedule fixedSchedule(startDate,maturity, QuantLib::Period(fixedLegFrequency),calendar, fixedLegConvention,fixedLegConvention, QuantLib::DateGeneration::Forward,false); QuantLib::Schedule floatSchedule(startDate,maturity,QuantLib::Period(Rcpp::as(legparams["floatFreq"]),QuantLib::Months), calendar, floatingLegConvention,floatingLegConvention, QuantLib::DateGeneration::Forward,false); QuantLib::VanillaSwap::Type type; if (payfix) { type = QuantLib::VanillaSwap::Payer;} else { type = QuantLib::VanillaSwap::Receiver; } QuantLib::ext::shared_ptr swap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, dummyFixedRate, swFixedLegDayCounter, floatSchedule, swFloatingLegIndex, 0.0, swFloatingLegIndex->dayCounter())); swap->setPricingEngine(QuantLib::ext::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 Affine swaption. QuantLib::ext::shared_ptr mySwap(new QuantLib::VanillaSwap(type, notional, fixedSchedule, fixedRate,swFixedLegDayCounter, floatSchedule, swFloatingLegIndex, 0.0, swFloatingLegIndex->dayCounter())); swap->setPricingEngine(QuantLib::ext::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++) { //QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols[i][numCols-i-1])); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(swaptionVols(i))); swaptions.push_back(QuantLib::ext::shared_ptr(new QuantLib::SwaptionHelper(swaptionMaturities[i], QuantLib::Period(swapLengths[i], QuantLib::Years), QuantLib::Handle(vol), swFloatingLegIndex, swFloatingLegIndex->tenor(), swFloatingLegIndex->dayCounter(), swFloatingLegIndex->dayCounter(), rhTermStructure))); swaptions.back()->addTimesTo(times); } // Building time-grid QuantLib::TimeGrid grid(times.begin(), times.end(), 30); // Get Affine swaption exercise dates, single date if europen, coupon dates if bermudan std::vector affineDates; const std::vector >& leg = swap->fixedLeg(); if(european){ QuantLib::ext::shared_ptr coupon = QuantLib::ext::dynamic_pointer_cast(leg[0]); affineDates.push_back(coupon->accrualStartDate()); } else{ for (i=0; i coupon = QuantLib::ext::dynamic_pointer_cast(leg[i]); affineDates.push_back(coupon->accrualStartDate()); } } QuantLib::ext::shared_ptr affineExercise(new QuantLib::BermudanExercise(affineDates)); // Price based on method selected. if (method.compare("G2Analytic") == 0) { QuantLib::ext::shared_ptr modelG2(new QuantLib::G2(rhTermStructure)); Rprintf((char*)"G2/Jamshidian (analytic) calibration\n"); for(i = 0; i < swaptions.size(); i++) swaptions[i]->setPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::G2SwaptionEngine(modelG2, 6.0, 16))); calibrateModel2(modelG2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelG2, 50)); QuantLib::Swaption affineSwaption(mySwap, affineExercise); affineSwaption.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("NPV") = affineSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate); //Rcpp::Named("params") = params); } else if (method.compare("HWAnalytic") == 0) { QuantLib::ext::shared_ptr modelHW(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (analytic) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::JamshidianSwaptionEngine(modelHW))); calibrateModel2(modelHW, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelHW, 50)); QuantLib::Swaption affineSwaption(mySwap, affineExercise); affineSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelHW->params()[0], Rcpp::Named("sigma") = modelHW->params()[1], Rcpp::Named("NPV") = affineSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate); //Rcpp::Named("params") = params); } else if (method.compare("HWTree") == 0) { QuantLib::ext::shared_ptr modelHW2(new QuantLib::HullWhite(rhTermStructure)); Rprintf((char*)"Hull-White (tree) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::TreeSwaptionEngine(modelHW2,grid))); calibrateModel2(modelHW2, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelHW2, 50)); QuantLib::Swaption affineSwaption(mySwap, affineExercise); affineSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelHW2->params()[0], Rcpp::Named("sigma") = modelHW2->params()[1], Rcpp::Named("NPV") = affineSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate); //Rcpp::Named("params") = params); } else if (method.compare("BKTree") == 0) { QuantLib::ext::shared_ptr modelBK(new QuantLib::BlackKarasinski(rhTermStructure)); Rprintf((char*)"Black-Karasinski (tree) calibration\n"); for (i=0; isetPricingEngine(QuantLib::ext::shared_ptr(new QuantLib::TreeSwaptionEngine(modelBK,grid))); calibrateModel2(modelBK, swaptions, 0.05, swaptionMat, swapLengths, swaptionVols); QuantLib::ext::shared_ptr engine(new QuantLib::TreeSwaptionEngine(modelBK, 50)); QuantLib::Swaption affineSwaption(mySwap, affineExercise); affineSwaption.setPricingEngine(engine); return Rcpp::List::create(Rcpp::Named("a") = modelBK->params()[0], Rcpp::Named("sigma") = modelBK->params()[1], Rcpp::Named("price") = affineSwaption.NPV(), Rcpp::Named("ATMStrike") = fixedATMRate); //Rcpp::Named("params") = params); } else { throw std::range_error("Unknown method in AffineSwaption\n"); } } RQuantLib/src/sabr.cpp0000644000176200001440000003125313443253624014347 0ustar liggesusers /* Copyright (C) 2012 Peter Caspers Copyright (C) 2016 Terry Leitch This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email . The license is also available online at . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include using namespace QuantLib; //using namespace boost::unit_test_framework; using std::fabs; namespace { typedef SwaptionVolatilityStructure SwpVolStr; // shorthand used below typedef SwaptionVolatilityMatrix SwpVolMat; // shorthand used below Handle swptnVolCube(Rcpp::NumericVector &expiries, Rcpp::NumericVector &tenors, Rcpp::NumericMatrix &atmVols, Rcpp::NumericVector &strikes, Rcpp::NumericMatrix &smirkVols, QuantLib::Handle &yldCrv ) { std::vector optionTenors; std::vector swapTenors; QuantLib::Size numExp = expiries.size(); for (Size i = 0; i (12*expiries[i]); optionTenors.push_back(Months*n); } else { int n = static_cast(expiries[i]); optionTenors.push_back(Years*n); } } QuantLib::Size numTenor = tenors.size(); for (Size i = 0; i < numTenor; i++){ if(tenors[i]<1.0){ int n = static_cast(12*tenors[i]); swapTenors.push_back(Months*n); } else { int n = static_cast(tenors[i]); swapTenors.push_back(Years*n); } } std::vector > > qSwAtm; for (unsigned int i = 0; i < numExp; i++) { std::vector > qSwAtmTmp; for (unsigned int j = 0; j < numTenor; j++) { double qt=atmVols(i,j); qSwAtmTmp.push_back(Handle(QuantLib::ext::shared_ptr(new SimpleQuote(qt)))); } qSwAtm.push_back(qSwAtmTmp); } Handle swaptionVolAtm(QuantLib::ext::shared_ptr(new SwpVolMat(TARGET(), ModifiedFollowing, optionTenors, swapTenors, qSwAtm, Actual365Fixed()))); std::vector optionTenorsSmile; std::vector swapTenorsSmile; std::vector strikeSpreads; for (Size i = 0; i < numExp; i++){ if(expiries[i]<1.0){ int n = static_cast(12*expiries[i]); optionTenorsSmile.push_back(n*Months); } else { int n = static_cast(expiries[i]); optionTenorsSmile.push_back(n*Years); } } for (Size i = 0; i < numTenor; i++){ if(tenors[i]<1.0){ int n = static_cast(12*tenors[i]); swapTenorsSmile.push_back(Months*n); } else { int n = static_cast(tenors[i]); swapTenorsSmile.push_back(Years*n); } } QuantLib::Size numStrike = strikes.size(); for (Size i = 0; i < numStrike; i++) strikeSpreads.push_back(strikes[i]); std::vector > > qSwSmile; for (unsigned int i = 0; i < numExp*numTenor; i++) { std::vector > qSwSmileTmp; for (unsigned int j = 0; j < numStrike; j++) { double qt=smirkVols(i,j); qSwSmileTmp.push_back(Handle(QuantLib::ext::shared_ptr(new SimpleQuote(qt)))); } qSwSmile.push_back(qSwSmileTmp); } double qSwSmileh1[] = { 0.01, 0.2, 0.8, -0.2 }; std::vector parameterFixed; parameterFixed.push_back(false); parameterFixed.push_back(false); // beta could be fixed parameterFixed.push_back(false); parameterFixed.push_back(false); std::vector > > parameterGuess; for (unsigned int i = 0; i < numExp*numTenor; i++) { std::vector > parameterGuessTmp; for (unsigned int j = 0; j < 4; j++) { parameterGuessTmp.push_back(Handle(QuantLib::ext::shared_ptr(new SimpleQuote(qSwSmileh1[j])))); } parameterGuess.push_back(parameterGuessTmp); } QuantLib::ext::shared_ptr ec(new EndCriteria(5000000, 250, 1E-6, 1E-6, 1E-6)); QuantLib::ext::shared_ptr swapIndex(new EuriborSwapIsdaFixA(30 * Years, Handle(yldCrv))); QuantLib::ext::shared_ptr shortSwapIndex(new EuriborSwapIsdaFixA(1 * Years, Handle(yldCrv))); Handle res(QuantLib::ext::shared_ptr(new SwaptionVolCube1(swaptionVolAtm, optionTenorsSmile, swapTenorsSmile, strikeSpreads, qSwSmile, swapIndex, shortSwapIndex, true, parameterGuess, parameterFixed, true, ec, .050))); // put a big error tolerance here ... we just want a // smooth cube for testing res->enableExtrapolation(); return res; } } /// closes name space // [[Rcpp::export]] Rcpp::List sabrengine(Rcpp::List rparam, Rcpp::List legParams, std::vector dateVec, std::vector zeroVec, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericMatrix atmVols, Rcpp::NumericVector strikes, Rcpp::NumericMatrix smirkVols){ QuantLib::Date tradeDate(Rcpp::as(rparam["tradeDate"])); QuantLib::Date settlementDate(Rcpp::as(rparam["settleDate"])); QuantLib::Date startDate(Rcpp::as(rparam["startDate"])); QuantLib::Date expiryDate(Rcpp::as(rparam["expiryDate"])); QuantLib::Date maturity(Rcpp::as(rparam["maturity"])); bool european = Rcpp::as(rparam["european"]); double strike = Rcpp::as(rparam["strike"]); //double fixDayCount = Rcpp::as(legParams["dayCounter"]); // currently not used, fix in future double fixFreq = Rcpp::as(legParams["fixFreq"]) ; int floatFreq = Rcpp::as(legParams["floatFreq"]); // BOOST_TEST_MESSAGE("Testing Markov functional vanilla engines..."); Settings::instance().evaluationDate() = tradeDate; QuantLib::Handle yldCrv(rebuildCurveFromZeroRates(dateVec, zeroVec)); Handle volCube = swptnVolCube(swaptionMat,swapLengths,atmVols, strikes,smirkVols,yldCrv); QuantLib::ext::shared_ptr iborIndex1(new Euribor(floatFreq * Months, yldCrv)); QuantLib::ext::shared_ptr swapIndexBase (new EuriborSwapIsdaFixA(fixFreq * Years)); // create swaps for european swaption here to get atm fwd rate, these are ignored for bermudan // QuantLib::ext::shared_ptr underlyingCall = MakeVanillaSwap(Years*(((maturity-expiryDate)/365.0)), iborIndex1, strike) .withEffectiveDate(expiryDate) .receiveFixed(false); QuantLib::ext::shared_ptr underlyingPut = MakeVanillaSwap(Years*((maturity-expiryDate)/365.0), iborIndex1, strike) .withEffectiveDate(expiryDate) .receiveFixed(true); QuantLib::ext::shared_ptr swapEngine(new DiscountingSwapEngine(yldCrv)); underlyingCall->setPricingEngine(swapEngine); underlyingPut->setPricingEngine(swapEngine); Real vol,pricePay,priceRcv,rate; vol=volCube->volatility(Years*((expiryDate-settlementDate)/365.0), Years*((maturity-expiryDate)/365.0), strike); rate=underlyingCall->fairRate(); // calculate if bermudan here // if(!european) { QuantLib::ext::shared_ptr underlyingCall2 = MakeVanillaSwap(Years*(((maturity-startDate)/365.0)), iborIndex1, strike) .withEffectiveDate(startDate) .receiveFixed(false); QuantLib::ext::shared_ptr underlyingPut2 = MakeVanillaSwap(Years*((maturity-startDate)/365.0), iborIndex1, strike) .withEffectiveDate(startDate) .receiveFixed(true); QuantLib::ext::shared_ptr swapEngine(new DiscountingSwapEngine(yldCrv)); underlyingCall2->setPricingEngine(swapEngine); underlyingPut2->setPricingEngine(swapEngine); std::vector volStepDates; std::vector vols; vols.push_back(1.0); std::vector exerciseDates; std::vector underlyingTenors; const std::vector >& leg = underlyingCall2->fixedLeg(); for (unsigned int i=0; i coupon = QuantLib::ext::dynamic_pointer_cast(leg[i]); if(coupon->accrualStartDate() <= expiryDate && coupon->accrualStartDate() >= startDate) { exerciseDates.push_back(coupon->accrualStartDate()); underlyingTenors.push_back(Years*((maturity-(coupon->accrualStartDate()))/365.0)); } } // create expiry backet, get maturity QuantLib::ext::shared_ptr mf1(new MarkovFunctional(yldCrv, 0.01, volStepDates, vols,volCube, exerciseDates, underlyingTenors, swapIndexBase, MarkovFunctional::ModelSettings() .withYGridPoints(32) .withYStdDevs(7.0) .withGaussHermitePoints(16) .withMarketRateAccuracy(1e-7) .withDigitalGap(1e-5) .withLowerRateBound(0.0) .withUpperRateBound(2.0))); QuantLib::ext::shared_ptr mfSwaptionEngine1(new Gaussian1dSwaptionEngine(mf1, 64, 7.0)); QuantLib::ext::shared_ptr bermudanExercise(new BermudanExercise(exerciseDates)); Swaption bermudanSwaptionC(underlyingCall2, bermudanExercise); Swaption bermudanSwaptionP(underlyingPut2, bermudanExercise); bermudanSwaptionC.setPricingEngine(mfSwaptionEngine1); bermudanSwaptionP.setPricingEngine(mfSwaptionEngine1); pricePay = bermudanSwaptionC.NPV(); priceRcv = bermudanSwaptionP.NPV(); } else { // calculate european here // QuantLib::ext::shared_ptr blackSwaptionEngine1(new BlackSwaptionEngine(yldCrv, volCube)); QuantLib::ext::shared_ptr exercise(new EuropeanExercise(startDate)); // Rprintf("%d %d %d\n",outputs1.expiries_[i].dayOfMonth(),outputs1.expiries_[i].month(),outputs1.expiries_[i].year()); Swaption swaptionC(underlyingCall, exercise); Swaption swaptionP(underlyingPut, exercise); swaptionC.setPricingEngine(blackSwaptionEngine1); swaptionP.setPricingEngine(blackSwaptionEngine1); pricePay = swaptionC.NPV(); priceRcv = swaptionP.NPV(); } ////////men at work///////////////// return Rcpp::List::create(Rcpp::Named("pay") = pricePay, Rcpp::Named("rcv") = priceRcv, Rcpp::Named("sigma") = vol, Rcpp::Named("atmRate") = rate); } RQuantLib/src/vanilla.cpp0000644000176200001440000003636613607470157015064 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2020 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // [[Rcpp::interfaces(r, cpp)]] // [[Rcpp::export]] Rcpp::List europeanOptionEngine(std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, Rcpp::Nullable discreteDividends, Rcpp::Nullable discreteDividendsTimeUntil) { #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity*360 + 0.5); // FIXME: this could be better #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote( underlying )); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote( volatility )); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote( dividendYield )); QuantLib::ext::shared_ptr qTS = flatRate(today, qRate, dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote( riskFreeRate )); QuantLib::ext::shared_ptr rTS = flatRate(today, rRate, dc); bool withDividends = discreteDividends.isNotNull() && discreteDividendsTimeUntil.isNotNull(); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); if (withDividends) { Rcpp::NumericVector divvalues(discreteDividends), divtimes(discreteDividendsTimeUntil); int n = divvalues.size(); std::vector discDivDates(n); std::vector discDividends(n); for (int i = 0; i < n; i++) { #ifdef QL_HIGH_RESOLUTION_DATE boost::posix_time::time_duration discreteDividendLength = boost::posix_time::minutes(boost::uint64_t(divtimes[i] * 360 * 24 * 60)); discDivDates[i] = QuantLib::Date(today.dateTime() + discreteDividendLength); #else discDivDates[i] = today + int(divtimes[i] * 360 + 0.5); #endif discDividends[i] = divvalues[i]; } QuantLib::ext::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); QuantLib::ext::shared_ptr engine(new QuantLib::AnalyticDividendEuropeanEngine(stochProcess)); QuantLib::DividendVanillaOption option(payoff, exercise, discDivDates, discDividends); option.setPricingEngine(engine); return 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") = R_NaReal); } else { QuantLib::ext::shared_ptr option = makeOption(payoff, exercise, spot, qTS, rTS, volTS); return 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::export]] Rcpp::List americanOptionEngine(std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, int timeSteps, int gridPoints, std::string engine, Rcpp::Nullable discreteDividends, Rcpp::Nullable discreteDividendsTimeUntil) { #ifdef QL_HIGH_RESOLUTION_DATE // in minutes boost::posix_time::time_duration length = boost::posix_time::minutes(boost::uint64_t(maturity * 360 * 24 * 60)); #else int length = int(maturity * 360 + 0.5); // FIXME: this could be better #endif 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(); QuantLib::ext::shared_ptr spot(new QuantLib::SimpleQuote(underlying)); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote(dividendYield)); QuantLib::ext::shared_ptr qTS = flatRate(today,qRate,dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote(riskFreeRate)); QuantLib::ext::shared_ptr rTS = flatRate(today,rRate,dc); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote(volatility)); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); bool withDividends = discreteDividends.isNotNull() && discreteDividendsTimeUntil.isNotNull(); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); QuantLib::ext::shared_ptr exercise(new QuantLib::AmericanExercise(today, exDate)); QuantLib::ext::shared_ptr stochProcess(new QuantLib::BlackScholesMertonProcess(QuantLib::Handle(spot), QuantLib::Handle(qTS), QuantLib::Handle(rTS), QuantLib::Handle(volTS))); if (withDividends) { Rcpp::NumericVector divvalues(discreteDividends), divtimes(discreteDividendsTimeUntil); int n = divvalues.size(); std::vector discDivDates(n); std::vector discDividends(n); for (int i = 0; i < n; i++) { #ifdef QL_HIGH_RESOLUTION_DATE boost::posix_time::time_duration discreteDividendLength = boost::posix_time::minutes(boost::uint64_t(divtimes[i] * 360 * 24 * 60)); discDivDates[i] = QuantLib::Date(today.dateTime() + discreteDividendLength); #else discDivDates[i] = today + int(divtimes[i] * 360 + 0.5); #endif discDividends[i] = divvalues[i]; } QuantLib::DividendVanillaOption option(payoff, exercise, discDivDates, discDividends); if (engine=="BaroneAdesiWhaley") { Rcpp::warning("Discrete dividends, engine switched to CrankNicolson"); engine = "CrankNicolson"; } if (engine=="CrankNicolson") { // FDDividendAmericanEngine only works with CrankNicolson // suggestion by Bryan Lewis: use CrankNicolson for greeks QuantLib::ext::shared_ptr fdcnengine(new QuantLib::FdBlackScholesVanillaEngine(stochProcess, timeSteps, gridPoints)); option.setPricingEngine(fdcnengine); return 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); } else { throw std::range_error("Unknown engine " + engine); } } else { QuantLib::VanillaOption option(payoff, exercise); if (engine=="BaroneAdesiWhaley") { // new from 0.3.7 BaroneAdesiWhaley QuantLib::ext::shared_ptr engine(new QuantLib::BaroneAdesiWhaleyApproximationEngine(stochProcess)); option.setPricingEngine(engine); return 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); } else if (engine=="CrankNicolson") { // suggestion by Bryan Lewis: use CrankNicolson for greeks QuantLib::ext::shared_ptr fdcnengine(new QuantLib::FdBlackScholesVanillaEngine(stochProcess, timeSteps, gridPoints)); option.setPricingEngine(fdcnengine); return 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); } else { throw std::range_error("Unknown engine " + engine); } } } // [[Rcpp::export]] Rcpp::List europeanOptionArraysEngine(std::string type, Rcpp::NumericMatrix par) { QuantLib::Option::Type optionType = getOptionType(type); 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 )); QuantLib::ext::shared_ptr vol(new QuantLib::SimpleQuote( volatility )); QuantLib::ext::shared_ptr volTS = flatVol(today, vol, dc); QuantLib::ext::shared_ptr qRate(new QuantLib::SimpleQuote( dividendYield )); QuantLib::ext::shared_ptr qTS = flatRate(today, qRate, dc); QuantLib::ext::shared_ptr rRate(new QuantLib::SimpleQuote( riskFreeRate )); QuantLib::ext::shared_ptr rTS = flatRate(today, rRate, dc); #ifdef QL_HIGH_RESOLUTION_DATE QuantLib::Date exDate(today.dateTime() + length); #else QuantLib::Date exDate = today + length; #endif QuantLib::ext::shared_ptr exercise(new QuantLib::EuropeanExercise(exDate)); QuantLib::ext::shared_ptr payoff(new QuantLib::PlainVanillaPayoff(optionType, strike)); QuantLib::ext::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); } RQuantLib/src/Makevars.in0000644000176200001440000000050013466602605015006 0ustar liggesusers# -*- mode: Makefile -*- # # Copyright 2008 - 2018 Dirk Eddelbuettel # See configure.in for how these variables are computed PKG_CXXFLAGS=@CXXFLAGS@ -I../inst/include -I. -DBOOST_NO_AUTO_PTR $(SHLIB_OPENMP_CXXFLAGS) PKG_LIBS=@LDFLAGS@ $(SHLIB_OPENMP_CXXFLAGS) # Use C++11 for long long in Boost headers CXX_STD=CXX11 RQuantLib/src/RcppExports.cpp0000644000176200001440000032735313340507515015717 0ustar liggesusers// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include "../inst/include/RQuantLib.h" #include #include #include using namespace Rcpp; // affineWithRebuiltCurveEngine Rcpp::List affineWithRebuiltCurveEngine(Rcpp::List rparam, Rcpp::List legparams, std::vector dateVec, std::vector zeroVec, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericVector swaptionVols); RcppExport SEXP _RQuantLib_affineWithRebuiltCurveEngine(SEXP rparamSEXP, SEXP legparamsSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP swaptionMatSEXP, SEXP swapLengthsSEXP, SEXP swaptionVolsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type legparams(legparamsSEXP); Rcpp::traits::input_parameter< std::vector >::type dateVec(dateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type zeroVec(zeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swaptionMat(swaptionMatSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swapLengths(swapLengthsSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swaptionVols(swaptionVolsSEXP); rcpp_result_gen = Rcpp::wrap(affineWithRebuiltCurveEngine(rparam, legparams, dateVec, zeroVec, swaptionMat, swapLengths, swaptionVols)); return rcpp_result_gen; END_RCPP } // asianOptionEngine Rcpp::List asianOptionEngine(std::string averageType, std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double first, double length, size_t fixings); RcppExport SEXP _RQuantLib_asianOptionEngine(SEXP averageTypeSEXP, SEXP typeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP firstSEXP, SEXP lengthSEXP, SEXP fixingsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type averageType(averageTypeSEXP); Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); Rcpp::traits::input_parameter< double >::type first(firstSEXP); Rcpp::traits::input_parameter< double >::type length(lengthSEXP); Rcpp::traits::input_parameter< size_t >::type fixings(fixingsSEXP); rcpp_result_gen = Rcpp::wrap(asianOptionEngine(averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first, length, fixings)); return rcpp_result_gen; END_RCPP } // binaryOptionEngine Rcpp::List binaryOptionEngine(std::string binType, std::string type, std::string excType, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double cashPayoff); RcppExport SEXP _RQuantLib_binaryOptionEngine(SEXP binTypeSEXP, SEXP typeSEXP, SEXP excTypeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP cashPayoffSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type binType(binTypeSEXP); Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< std::string >::type excType(excTypeSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); Rcpp::traits::input_parameter< double >::type cashPayoff(cashPayoffSEXP); rcpp_result_gen = Rcpp::wrap(binaryOptionEngine(binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff)); return rcpp_result_gen; END_RCPP } // binaryOptionImpliedVolatilityEngine double binaryOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double cashPayoff); RcppExport SEXP _RQuantLib_binaryOptionImpliedVolatilityEngine(SEXP typeSEXP, SEXP valueSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP cashPayoffSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type value(valueSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); Rcpp::traits::input_parameter< double >::type cashPayoff(cashPayoffSEXP); rcpp_result_gen = Rcpp::wrap(binaryOptionImpliedVolatilityEngine(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff)); return rcpp_result_gen; END_RCPP } // barrierOptionEngine Rcpp::List barrierOptionEngine(std::string barrType, std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, double barrier, double rebate); RcppExport SEXP _RQuantLib_barrierOptionEngine(SEXP barrTypeSEXP, SEXP typeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP barrierSEXP, SEXP rebateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type barrType(barrTypeSEXP); Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); Rcpp::traits::input_parameter< double >::type barrier(barrierSEXP); Rcpp::traits::input_parameter< double >::type rebate(rebateSEXP); rcpp_result_gen = Rcpp::wrap(barrierOptionEngine(barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate)); return rcpp_result_gen; END_RCPP } // bermudanFromYieldEngine Rcpp::List bermudanFromYieldEngine(Rcpp::List rparam, Rcpp::NumericVector yield, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericMatrix swaptionVols); RcppExport SEXP _RQuantLib_bermudanFromYieldEngine(SEXP rparamSEXP, SEXP yieldSEXP, SEXP swaptionMatSEXP, SEXP swapLengthsSEXP, SEXP swaptionVolsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type yield(yieldSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swaptionMat(swaptionMatSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swapLengths(swapLengthsSEXP); Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type swaptionVols(swaptionVolsSEXP); rcpp_result_gen = Rcpp::wrap(bermudanFromYieldEngine(rparam, yield, swaptionMat, swapLengths, swaptionVols)); return rcpp_result_gen; END_RCPP } // bermudanWithRebuiltCurveEngine Rcpp::List bermudanWithRebuiltCurveEngine(Rcpp::List rparam, std::vector dateVec, std::vector zeroVec, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericMatrix swaptionVols); RcppExport SEXP _RQuantLib_bermudanWithRebuiltCurveEngine(SEXP rparamSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP swaptionMatSEXP, SEXP swapLengthsSEXP, SEXP swaptionVolsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< std::vector >::type dateVec(dateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type zeroVec(zeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swaptionMat(swaptionMatSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swapLengths(swapLengthsSEXP); Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type swaptionVols(swaptionVolsSEXP); rcpp_result_gen = Rcpp::wrap(bermudanWithRebuiltCurveEngine(rparam, dateVec, zeroVec, swaptionMat, swapLengths, swaptionVols)); return rcpp_result_gen; END_RCPP } // zeroPriceByYieldEngine double zeroPriceByYieldEngine(double yield, double faceAmount, double dayCounter, double frequency, double businessDayConvention, double compound, QuantLib::Date maturityDate, QuantLib::Date issueDate); static SEXP _RQuantLib_zeroPriceByYieldEngine_try(SEXP yieldSEXP, SEXP faceAmountSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< double >::type yield(yieldSEXP); Rcpp::traits::input_parameter< double >::type faceAmount(faceAmountSEXP); Rcpp::traits::input_parameter< double >::type dayCounter(dayCounterSEXP); Rcpp::traits::input_parameter< double >::type frequency(frequencySEXP); Rcpp::traits::input_parameter< double >::type businessDayConvention(businessDayConventionSEXP); Rcpp::traits::input_parameter< double >::type compound(compoundSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type maturityDate(maturityDateSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type issueDate(issueDateSEXP); rcpp_result_gen = Rcpp::wrap(zeroPriceByYieldEngine(yield, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_zeroPriceByYieldEngine(SEXP yieldSEXP, SEXP faceAmountSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_zeroPriceByYieldEngine_try(yieldSEXP, faceAmountSEXP, dayCounterSEXP, frequencySEXP, businessDayConventionSEXP, compoundSEXP, maturityDateSEXP, issueDateSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // zeroYieldByPriceEngine double zeroYieldByPriceEngine(double price, double faceAmount, double dayCounter, double frequency, double businessDayConvention, double compound, QuantLib::Date maturityDate, QuantLib::Date issueDate); static SEXP _RQuantLib_zeroYieldByPriceEngine_try(SEXP priceSEXP, SEXP faceAmountSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< double >::type price(priceSEXP); Rcpp::traits::input_parameter< double >::type faceAmount(faceAmountSEXP); Rcpp::traits::input_parameter< double >::type dayCounter(dayCounterSEXP); Rcpp::traits::input_parameter< double >::type frequency(frequencySEXP); Rcpp::traits::input_parameter< double >::type businessDayConvention(businessDayConventionSEXP); Rcpp::traits::input_parameter< double >::type compound(compoundSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type maturityDate(maturityDateSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type issueDate(issueDateSEXP); rcpp_result_gen = Rcpp::wrap(zeroYieldByPriceEngine(price, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_zeroYieldByPriceEngine(SEXP priceSEXP, SEXP faceAmountSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_zeroYieldByPriceEngine_try(priceSEXP, faceAmountSEXP, dayCounterSEXP, frequencySEXP, businessDayConventionSEXP, compoundSEXP, maturityDateSEXP, issueDateSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // fixedRateBondYieldByPriceEngine double fixedRateBondYieldByPriceEngine(double settlementDays, double price, std::string cal, double faceAmount, double businessDayConvention, double compound, double redemption, double dayCounter, double frequency, QuantLib::Date maturityDate, QuantLib::Date issueDate, QuantLib::Date effectiveDate, std::vector rates); static SEXP _RQuantLib_fixedRateBondYieldByPriceEngine_try(SEXP settlementDaysSEXP, SEXP priceSEXP, SEXP calSEXP, SEXP faceAmountSEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP redemptionSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP, SEXP effectiveDateSEXP, SEXP ratesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< double >::type settlementDays(settlementDaysSEXP); Rcpp::traits::input_parameter< double >::type price(priceSEXP); Rcpp::traits::input_parameter< std::string >::type cal(calSEXP); Rcpp::traits::input_parameter< double >::type faceAmount(faceAmountSEXP); Rcpp::traits::input_parameter< double >::type businessDayConvention(businessDayConventionSEXP); Rcpp::traits::input_parameter< double >::type compound(compoundSEXP); Rcpp::traits::input_parameter< double >::type redemption(redemptionSEXP); Rcpp::traits::input_parameter< double >::type dayCounter(dayCounterSEXP); Rcpp::traits::input_parameter< double >::type frequency(frequencySEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type maturityDate(maturityDateSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type issueDate(issueDateSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type effectiveDate(effectiveDateSEXP); Rcpp::traits::input_parameter< std::vector >::type rates(ratesSEXP); rcpp_result_gen = Rcpp::wrap(fixedRateBondYieldByPriceEngine(settlementDays, price, cal, faceAmount, businessDayConvention, compound, redemption, dayCounter, frequency, maturityDate, issueDate, effectiveDate, rates)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_fixedRateBondYieldByPriceEngine(SEXP settlementDaysSEXP, SEXP priceSEXP, SEXP calSEXP, SEXP faceAmountSEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP redemptionSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP, SEXP effectiveDateSEXP, SEXP ratesSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_fixedRateBondYieldByPriceEngine_try(settlementDaysSEXP, priceSEXP, calSEXP, faceAmountSEXP, businessDayConventionSEXP, compoundSEXP, redemptionSEXP, dayCounterSEXP, frequencySEXP, maturityDateSEXP, issueDateSEXP, effectiveDateSEXP, ratesSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // fixedRateBondPriceByYieldEngine double fixedRateBondPriceByYieldEngine(double settlementDays, double yield, std::string cal, double faceAmount, double businessDayConvention, double compound, double redemption, double dayCounter, double frequency, QuantLib::Date maturityDate, QuantLib::Date issueDate, QuantLib::Date effectiveDate, std::vector rates); static SEXP _RQuantLib_fixedRateBondPriceByYieldEngine_try(SEXP settlementDaysSEXP, SEXP yieldSEXP, SEXP calSEXP, SEXP faceAmountSEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP redemptionSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP, SEXP effectiveDateSEXP, SEXP ratesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< double >::type settlementDays(settlementDaysSEXP); Rcpp::traits::input_parameter< double >::type yield(yieldSEXP); Rcpp::traits::input_parameter< std::string >::type cal(calSEXP); Rcpp::traits::input_parameter< double >::type faceAmount(faceAmountSEXP); Rcpp::traits::input_parameter< double >::type businessDayConvention(businessDayConventionSEXP); Rcpp::traits::input_parameter< double >::type compound(compoundSEXP); Rcpp::traits::input_parameter< double >::type redemption(redemptionSEXP); Rcpp::traits::input_parameter< double >::type dayCounter(dayCounterSEXP); Rcpp::traits::input_parameter< double >::type frequency(frequencySEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type maturityDate(maturityDateSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type issueDate(issueDateSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type effectiveDate(effectiveDateSEXP); Rcpp::traits::input_parameter< std::vector >::type rates(ratesSEXP); rcpp_result_gen = Rcpp::wrap(fixedRateBondPriceByYieldEngine(settlementDays, yield, cal, faceAmount, businessDayConvention, compound, redemption, dayCounter, frequency, maturityDate, issueDate, effectiveDate, rates)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_fixedRateBondPriceByYieldEngine(SEXP settlementDaysSEXP, SEXP yieldSEXP, SEXP calSEXP, SEXP faceAmountSEXP, SEXP businessDayConventionSEXP, SEXP compoundSEXP, SEXP redemptionSEXP, SEXP dayCounterSEXP, SEXP frequencySEXP, SEXP maturityDateSEXP, SEXP issueDateSEXP, SEXP effectiveDateSEXP, SEXP ratesSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_fixedRateBondPriceByYieldEngine_try(settlementDaysSEXP, yieldSEXP, calSEXP, faceAmountSEXP, businessDayConventionSEXP, compoundSEXP, redemptionSEXP, dayCounterSEXP, frequencySEXP, maturityDateSEXP, issueDateSEXP, effectiveDateSEXP, ratesSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FloatBond1 Rcpp::List FloatBond1(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index, Rcpp::List discountCurve, Rcpp::List dateparams); static SEXP _RQuantLib_FloatBond1_try(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP indexSEXP, SEXP discountCurveSEXP, SEXP dateparamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bond(bondSEXP); Rcpp::traits::input_parameter< std::vector >::type gearings(gearingsSEXP); Rcpp::traits::input_parameter< std::vector >::type caps(capsSEXP); Rcpp::traits::input_parameter< std::vector >::type spreads(spreadsSEXP); Rcpp::traits::input_parameter< std::vector >::type floors(floorsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type indexparams(indexparamsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index(indexSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type discountCurve(discountCurveSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type dateparams(dateparamsSEXP); rcpp_result_gen = Rcpp::wrap(FloatBond1(bond, gearings, caps, spreads, floors, indexparams, index, discountCurve, dateparams)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FloatBond1(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP indexSEXP, SEXP discountCurveSEXP, SEXP dateparamsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FloatBond1_try(bondSEXP, gearingsSEXP, capsSEXP, spreadsSEXP, floorsSEXP, indexparamsSEXP, indexSEXP, discountCurveSEXP, dateparamsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FloatBond2 Rcpp::List FloatBond2(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index_params, Rcpp::List index_tsQuotes, Rcpp::List index_times, Rcpp::List discountCurve, Rcpp::List dateparams); static SEXP _RQuantLib_FloatBond2_try(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP index_paramsSEXP, SEXP index_tsQuotesSEXP, SEXP index_timesSEXP, SEXP discountCurveSEXP, SEXP dateparamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bond(bondSEXP); Rcpp::traits::input_parameter< std::vector >::type gearings(gearingsSEXP); Rcpp::traits::input_parameter< std::vector >::type caps(capsSEXP); Rcpp::traits::input_parameter< std::vector >::type spreads(spreadsSEXP); Rcpp::traits::input_parameter< std::vector >::type floors(floorsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type indexparams(indexparamsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index_params(index_paramsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index_tsQuotes(index_tsQuotesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index_times(index_timesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type discountCurve(discountCurveSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type dateparams(dateparamsSEXP); rcpp_result_gen = Rcpp::wrap(FloatBond2(bond, gearings, caps, spreads, floors, indexparams, index_params, index_tsQuotes, index_times, discountCurve, dateparams)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FloatBond2(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP index_paramsSEXP, SEXP index_tsQuotesSEXP, SEXP index_timesSEXP, SEXP discountCurveSEXP, SEXP dateparamsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FloatBond2_try(bondSEXP, gearingsSEXP, capsSEXP, spreadsSEXP, floorsSEXP, indexparamsSEXP, index_paramsSEXP, index_tsQuotesSEXP, index_timesSEXP, discountCurveSEXP, dateparamsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FloatBond3 Rcpp::List FloatBond3(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index, Rcpp::List disc_params, Rcpp::List disc_tsQuotes, Rcpp::List disc_times, Rcpp::List dateparams); static SEXP _RQuantLib_FloatBond3_try(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP indexSEXP, SEXP disc_paramsSEXP, SEXP disc_tsQuotesSEXP, SEXP disc_timesSEXP, SEXP dateparamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bond(bondSEXP); Rcpp::traits::input_parameter< std::vector >::type gearings(gearingsSEXP); Rcpp::traits::input_parameter< std::vector >::type caps(capsSEXP); Rcpp::traits::input_parameter< std::vector >::type spreads(spreadsSEXP); Rcpp::traits::input_parameter< std::vector >::type floors(floorsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type indexparams(indexparamsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index(indexSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type disc_params(disc_paramsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type disc_tsQuotes(disc_tsQuotesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type disc_times(disc_timesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type dateparams(dateparamsSEXP); rcpp_result_gen = Rcpp::wrap(FloatBond3(bond, gearings, caps, spreads, floors, indexparams, index, disc_params, disc_tsQuotes, disc_times, dateparams)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FloatBond3(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP indexSEXP, SEXP disc_paramsSEXP, SEXP disc_tsQuotesSEXP, SEXP disc_timesSEXP, SEXP dateparamsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FloatBond3_try(bondSEXP, gearingsSEXP, capsSEXP, spreadsSEXP, floorsSEXP, indexparamsSEXP, indexSEXP, disc_paramsSEXP, disc_tsQuotesSEXP, disc_timesSEXP, dateparamsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FloatBond4 Rcpp::List FloatBond4(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index_params, Rcpp::List index_tsQuotes, Rcpp::List index_times, Rcpp::List disc_params, Rcpp::List disc_tsQuotes, Rcpp::List disc_times, Rcpp::List dateparams); static SEXP _RQuantLib_FloatBond4_try(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP index_paramsSEXP, SEXP index_tsQuotesSEXP, SEXP index_timesSEXP, SEXP disc_paramsSEXP, SEXP disc_tsQuotesSEXP, SEXP disc_timesSEXP, SEXP dateparamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bond(bondSEXP); Rcpp::traits::input_parameter< std::vector >::type gearings(gearingsSEXP); Rcpp::traits::input_parameter< std::vector >::type caps(capsSEXP); Rcpp::traits::input_parameter< std::vector >::type spreads(spreadsSEXP); Rcpp::traits::input_parameter< std::vector >::type floors(floorsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type indexparams(indexparamsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index_params(index_paramsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index_tsQuotes(index_tsQuotesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type index_times(index_timesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type disc_params(disc_paramsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type disc_tsQuotes(disc_tsQuotesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type disc_times(disc_timesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type dateparams(dateparamsSEXP); rcpp_result_gen = Rcpp::wrap(FloatBond4(bond, gearings, caps, spreads, floors, indexparams, index_params, index_tsQuotes, index_times, disc_params, disc_tsQuotes, disc_times, dateparams)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FloatBond4(SEXP bondSEXP, SEXP gearingsSEXP, SEXP capsSEXP, SEXP spreadsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP index_paramsSEXP, SEXP index_tsQuotesSEXP, SEXP index_timesSEXP, SEXP disc_paramsSEXP, SEXP disc_tsQuotesSEXP, SEXP disc_timesSEXP, SEXP dateparamsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FloatBond4_try(bondSEXP, gearingsSEXP, capsSEXP, spreadsSEXP, floorsSEXP, indexparamsSEXP, index_paramsSEXP, index_tsQuotesSEXP, index_timesSEXP, disc_paramsSEXP, disc_tsQuotesSEXP, disc_timesSEXP, dateparamsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // floatingWithRebuiltCurveEngine Rcpp::List floatingWithRebuiltCurveEngine(Rcpp::List bondparams, std::vector gearings, std::vector spreads, std::vector caps, std::vector floors, Rcpp::List indexparams, std::vector iborDateVec, std::vector iborzeroVec, std::vector dateVec, std::vector zeroVec, Rcpp::List dateparams); static SEXP _RQuantLib_floatingWithRebuiltCurveEngine_try(SEXP bondparamsSEXP, SEXP gearingsSEXP, SEXP spreadsSEXP, SEXP capsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP iborDateVecSEXP, SEXP iborzeroVecSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP dateparamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bondparams(bondparamsSEXP); Rcpp::traits::input_parameter< std::vector >::type gearings(gearingsSEXP); Rcpp::traits::input_parameter< std::vector >::type spreads(spreadsSEXP); Rcpp::traits::input_parameter< std::vector >::type caps(capsSEXP); Rcpp::traits::input_parameter< std::vector >::type floors(floorsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type indexparams(indexparamsSEXP); Rcpp::traits::input_parameter< std::vector >::type iborDateVec(iborDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type iborzeroVec(iborzeroVecSEXP); Rcpp::traits::input_parameter< std::vector >::type dateVec(dateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type zeroVec(zeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type dateparams(dateparamsSEXP); rcpp_result_gen = Rcpp::wrap(floatingWithRebuiltCurveEngine(bondparams, gearings, spreads, caps, floors, indexparams, iborDateVec, iborzeroVec, dateVec, zeroVec, dateparams)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_floatingWithRebuiltCurveEngine(SEXP bondparamsSEXP, SEXP gearingsSEXP, SEXP spreadsSEXP, SEXP capsSEXP, SEXP floorsSEXP, SEXP indexparamsSEXP, SEXP iborDateVecSEXP, SEXP iborzeroVecSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP dateparamsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_floatingWithRebuiltCurveEngine_try(bondparamsSEXP, gearingsSEXP, spreadsSEXP, capsSEXP, floorsSEXP, indexparamsSEXP, iborDateVecSEXP, iborzeroVecSEXP, dateVecSEXP, zeroVecSEXP, dateparamsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FixedRateWithYield Rcpp::List FixedRateWithYield(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, double yield); static SEXP _RQuantLib_FixedRateWithYield_try(SEXP bondparamSEXP, SEXP ratesVecSEXP, SEXP scheduleparamSEXP, SEXP calcparamSEXP, SEXP yieldSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bondparam(bondparamSEXP); Rcpp::traits::input_parameter< std::vector >::type ratesVec(ratesVecSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type scheduleparam(scheduleparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type calcparam(calcparamSEXP); Rcpp::traits::input_parameter< double >::type yield(yieldSEXP); rcpp_result_gen = Rcpp::wrap(FixedRateWithYield(bondparam, ratesVec, scheduleparam, calcparam, yield)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FixedRateWithYield(SEXP bondparamSEXP, SEXP ratesVecSEXP, SEXP scheduleparamSEXP, SEXP calcparamSEXP, SEXP yieldSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FixedRateWithYield_try(bondparamSEXP, ratesVecSEXP, scheduleparamSEXP, calcparamSEXP, yieldSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FixedRateWithPrice Rcpp::List FixedRateWithPrice(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, double price); static SEXP _RQuantLib_FixedRateWithPrice_try(SEXP bondparamSEXP, SEXP ratesVecSEXP, SEXP scheduleparamSEXP, SEXP calcparamSEXP, SEXP priceSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bondparam(bondparamSEXP); Rcpp::traits::input_parameter< std::vector >::type ratesVec(ratesVecSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type scheduleparam(scheduleparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type calcparam(calcparamSEXP); Rcpp::traits::input_parameter< double >::type price(priceSEXP); rcpp_result_gen = Rcpp::wrap(FixedRateWithPrice(bondparam, ratesVec, scheduleparam, calcparam, price)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FixedRateWithPrice(SEXP bondparamSEXP, SEXP ratesVecSEXP, SEXP scheduleparamSEXP, SEXP calcparamSEXP, SEXP priceSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FixedRateWithPrice_try(bondparamSEXP, ratesVecSEXP, scheduleparamSEXP, calcparamSEXP, priceSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // FixedRateWithRebuiltCurve Rcpp::List FixedRateWithRebuiltCurve(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, std::vector dateVec, std::vector zeroVec); static SEXP _RQuantLib_FixedRateWithRebuiltCurve_try(SEXP bondparamSEXP, SEXP ratesVecSEXP, SEXP scheduleparamSEXP, SEXP calcparamSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bondparam(bondparamSEXP); Rcpp::traits::input_parameter< std::vector >::type ratesVec(ratesVecSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type scheduleparam(scheduleparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type calcparam(calcparamSEXP); Rcpp::traits::input_parameter< std::vector >::type dateVec(dateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type zeroVec(zeroVecSEXP); rcpp_result_gen = Rcpp::wrap(FixedRateWithRebuiltCurve(bondparam, ratesVec, scheduleparam, calcparam, dateVec, zeroVec)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_FixedRateWithRebuiltCurve(SEXP bondparamSEXP, SEXP ratesVecSEXP, SEXP scheduleparamSEXP, SEXP calcparamSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_FixedRateWithRebuiltCurve_try(bondparamSEXP, ratesVecSEXP, scheduleparamSEXP, calcparamSEXP, dateVecSEXP, zeroVecSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // ZeroBondWithRebuiltCurve Rcpp::List ZeroBondWithRebuiltCurve(Rcpp::List bond, std::vector dateVec, std::vector zeroVec, Rcpp::List dateparams); static SEXP _RQuantLib_ZeroBondWithRebuiltCurve_try(SEXP bondSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP dateparamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type bond(bondSEXP); Rcpp::traits::input_parameter< std::vector >::type dateVec(dateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type zeroVec(zeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type dateparams(dateparamsSEXP); rcpp_result_gen = Rcpp::wrap(ZeroBondWithRebuiltCurve(bond, dateVec, zeroVec, dateparams)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_ZeroBondWithRebuiltCurve(SEXP bondSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP dateparamsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_ZeroBondWithRebuiltCurve_try(bondSEXP, dateVecSEXP, zeroVecSEXP, dateparamsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // convertibleZeroBondEngine Rcpp::List convertibleZeroBondEngine(Rcpp::List rparam, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc); static SEXP _RQuantLib_convertibleZeroBondEngine_try(SEXP rparamSEXP, SEXP processParamSEXP, SEXP dividendYieldDateVecSEXP, SEXP dividendYieldZeroVecSEXP, SEXP rffDateVecSEXP, SEXP rffZeroVecSEXP, SEXP dividendScheduleFrameSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type processParam(processParamSEXP); Rcpp::traits::input_parameter< std::vector >::type dividendYieldDateVec(dividendYieldDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type dividendYieldZeroVec(dividendYieldZeroVecSEXP); Rcpp::traits::input_parameter< std::vector >::type rffDateVec(rffDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type rffZeroVec(rffZeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type dividendScheduleFrame(dividendScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type callabilityScheduleFrame(callabilityScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type datemisc(datemiscSEXP); rcpp_result_gen = Rcpp::wrap(convertibleZeroBondEngine(rparam, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, dividendScheduleFrame, callabilityScheduleFrame, datemisc)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_convertibleZeroBondEngine(SEXP rparamSEXP, SEXP processParamSEXP, SEXP dividendYieldDateVecSEXP, SEXP dividendYieldZeroVecSEXP, SEXP rffDateVecSEXP, SEXP rffZeroVecSEXP, SEXP dividendScheduleFrameSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_convertibleZeroBondEngine_try(rparamSEXP, processParamSEXP, dividendYieldDateVecSEXP, dividendYieldZeroVecSEXP, rffDateVecSEXP, rffZeroVecSEXP, dividendScheduleFrameSEXP, callabilityScheduleFrameSEXP, datemiscSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // convertibleFixedBondEngine Rcpp::List convertibleFixedBondEngine(Rcpp::List rparam, Rcpp::NumericVector rates, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc); static SEXP _RQuantLib_convertibleFixedBondEngine_try(SEXP rparamSEXP, SEXP ratesSEXP, SEXP processParamSEXP, SEXP dividendYieldDateVecSEXP, SEXP dividendYieldZeroVecSEXP, SEXP rffDateVecSEXP, SEXP rffZeroVecSEXP, SEXP dividendScheduleFrameSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type rates(ratesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type processParam(processParamSEXP); Rcpp::traits::input_parameter< std::vector >::type dividendYieldDateVec(dividendYieldDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type dividendYieldZeroVec(dividendYieldZeroVecSEXP); Rcpp::traits::input_parameter< std::vector >::type rffDateVec(rffDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type rffZeroVec(rffZeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type dividendScheduleFrame(dividendScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type callabilityScheduleFrame(callabilityScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type datemisc(datemiscSEXP); rcpp_result_gen = Rcpp::wrap(convertibleFixedBondEngine(rparam, rates, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, dividendScheduleFrame, callabilityScheduleFrame, datemisc)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_convertibleFixedBondEngine(SEXP rparamSEXP, SEXP ratesSEXP, SEXP processParamSEXP, SEXP dividendYieldDateVecSEXP, SEXP dividendYieldZeroVecSEXP, SEXP rffDateVecSEXP, SEXP rffZeroVecSEXP, SEXP dividendScheduleFrameSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_convertibleFixedBondEngine_try(rparamSEXP, ratesSEXP, processParamSEXP, dividendYieldDateVecSEXP, dividendYieldZeroVecSEXP, rffDateVecSEXP, rffZeroVecSEXP, dividendScheduleFrameSEXP, callabilityScheduleFrameSEXP, datemiscSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // convertibleFloatingBondEngine Rcpp::List convertibleFloatingBondEngine(Rcpp::List rparam, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, std::vector iborIndexDateVec, std::vector iborIndexZeroVec, Rcpp::List iborparams, std::vector spreads, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc); static SEXP _RQuantLib_convertibleFloatingBondEngine_try(SEXP rparamSEXP, SEXP processParamSEXP, SEXP dividendYieldDateVecSEXP, SEXP dividendYieldZeroVecSEXP, SEXP rffDateVecSEXP, SEXP rffZeroVecSEXP, SEXP iborIndexDateVecSEXP, SEXP iborIndexZeroVecSEXP, SEXP iborparamsSEXP, SEXP spreadsSEXP, SEXP dividendScheduleFrameSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type processParam(processParamSEXP); Rcpp::traits::input_parameter< std::vector >::type dividendYieldDateVec(dividendYieldDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type dividendYieldZeroVec(dividendYieldZeroVecSEXP); Rcpp::traits::input_parameter< std::vector >::type rffDateVec(rffDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type rffZeroVec(rffZeroVecSEXP); Rcpp::traits::input_parameter< std::vector >::type iborIndexDateVec(iborIndexDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type iborIndexZeroVec(iborIndexZeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type iborparams(iborparamsSEXP); Rcpp::traits::input_parameter< std::vector >::type spreads(spreadsSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type dividendScheduleFrame(dividendScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type callabilityScheduleFrame(callabilityScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type datemisc(datemiscSEXP); rcpp_result_gen = Rcpp::wrap(convertibleFloatingBondEngine(rparam, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, iborIndexDateVec, iborIndexZeroVec, iborparams, spreads, dividendScheduleFrame, callabilityScheduleFrame, datemisc)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_convertibleFloatingBondEngine(SEXP rparamSEXP, SEXP processParamSEXP, SEXP dividendYieldDateVecSEXP, SEXP dividendYieldZeroVecSEXP, SEXP rffDateVecSEXP, SEXP rffZeroVecSEXP, SEXP iborIndexDateVecSEXP, SEXP iborIndexZeroVecSEXP, SEXP iborparamsSEXP, SEXP spreadsSEXP, SEXP dividendScheduleFrameSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_convertibleFloatingBondEngine_try(rparamSEXP, processParamSEXP, dividendYieldDateVecSEXP, dividendYieldZeroVecSEXP, rffDateVecSEXP, rffZeroVecSEXP, iborIndexDateVecSEXP, iborIndexZeroVecSEXP, iborparamsSEXP, spreadsSEXP, dividendScheduleFrameSEXP, callabilityScheduleFrameSEXP, datemiscSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // callableBondEngine Rcpp::List callableBondEngine(Rcpp::List rparam, Rcpp::List hwparam, Rcpp::NumericVector coupon, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc); static SEXP _RQuantLib_callableBondEngine_try(SEXP rparamSEXP, SEXP hwparamSEXP, SEXP couponSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type hwparam(hwparamSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type coupon(couponSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type callabilityScheduleFrame(callabilityScheduleFrameSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type datemisc(datemiscSEXP); rcpp_result_gen = Rcpp::wrap(callableBondEngine(rparam, hwparam, coupon, callabilityScheduleFrame, datemisc)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_callableBondEngine(SEXP rparamSEXP, SEXP hwparamSEXP, SEXP couponSEXP, SEXP callabilityScheduleFrameSEXP, SEXP datemiscSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_callableBondEngine_try(rparamSEXP, hwparamSEXP, couponSEXP, callabilityScheduleFrameSEXP, datemiscSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // fittedBondCurveEngine Rcpp::List fittedBondCurveEngine(Rcpp::List curveparam, Rcpp::NumericVector length, Rcpp::NumericVector coupons, Rcpp::NumericVector marketQuotes, Rcpp::List datemisc); static SEXP _RQuantLib_fittedBondCurveEngine_try(SEXP curveparamSEXP, SEXP lengthSEXP, SEXP couponsSEXP, SEXP marketQuotesSEXP, SEXP datemiscSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type curveparam(curveparamSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type length(lengthSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type coupons(couponsSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type marketQuotes(marketQuotesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type datemisc(datemiscSEXP); rcpp_result_gen = Rcpp::wrap(fittedBondCurveEngine(curveparam, length, coupons, marketQuotes, datemisc)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_fittedBondCurveEngine(SEXP curveparamSEXP, SEXP lengthSEXP, SEXP couponsSEXP, SEXP marketQuotesSEXP, SEXP datemiscSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_fittedBondCurveEngine_try(curveparamSEXP, lengthSEXP, couponsSEXP, marketQuotesSEXP, datemiscSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // setCalendarContext bool setCalendarContext(std::string calendar, int fixingDays, QuantLib::Date settleDate); RcppExport SEXP _RQuantLib_setCalendarContext(SEXP calendarSEXP, SEXP fixingDaysSEXP, SEXP settleDateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< int >::type fixingDays(fixingDaysSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type settleDate(settleDateSEXP); rcpp_result_gen = Rcpp::wrap(setCalendarContext(calendar, fixingDays, settleDate)); return rcpp_result_gen; END_RCPP } // isBusinessDay std::vector isBusinessDay(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_isBusinessDay(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(isBusinessDay(calendar, dates)); return rcpp_result_gen; END_RCPP } // isHoliday std::vector isHoliday(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_isHoliday(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(isHoliday(calendar, dates)); return rcpp_result_gen; END_RCPP } // isWeekend std::vector isWeekend(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_isWeekend(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(isWeekend(calendar, dates)); return rcpp_result_gen; END_RCPP } // isEndOfMonth std::vector isEndOfMonth(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_isEndOfMonth(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(isEndOfMonth(calendar, dates)); return rcpp_result_gen; END_RCPP } // getEndOfMonth std::vector getEndOfMonth(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_getEndOfMonth(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(getEndOfMonth(calendar, dates)); return rcpp_result_gen; END_RCPP } // adjust std::vector adjust(std::string calendar, std::vector dates, int bdc); RcppExport SEXP _RQuantLib_adjust(SEXP calendarSEXP, SEXP datesSEXP, SEXP bdcSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); Rcpp::traits::input_parameter< int >::type bdc(bdcSEXP); rcpp_result_gen = Rcpp::wrap(adjust(calendar, dates, bdc)); return rcpp_result_gen; END_RCPP } // advance1 std::vector advance1(std::string calendar, double amount, double unit, int bdcVal, double emr, std::vector dates); RcppExport SEXP _RQuantLib_advance1(SEXP calendarSEXP, SEXP amountSEXP, SEXP unitSEXP, SEXP bdcValSEXP, SEXP emrSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< double >::type amount(amountSEXP); Rcpp::traits::input_parameter< double >::type unit(unitSEXP); Rcpp::traits::input_parameter< int >::type bdcVal(bdcValSEXP); Rcpp::traits::input_parameter< double >::type emr(emrSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(advance1(calendar, amount, unit, bdcVal, emr, dates)); return rcpp_result_gen; END_RCPP } // advance2 std::vector advance2(std::string calendar, double period, int bdcVal, double emr, std::vector dates); RcppExport SEXP _RQuantLib_advance2(SEXP calendarSEXP, SEXP periodSEXP, SEXP bdcValSEXP, SEXP emrSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< double >::type period(periodSEXP); Rcpp::traits::input_parameter< int >::type bdcVal(bdcValSEXP); Rcpp::traits::input_parameter< double >::type emr(emrSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); rcpp_result_gen = Rcpp::wrap(advance2(calendar, period, bdcVal, emr, dates)); return rcpp_result_gen; END_RCPP } // businessDaysBetween std::vector businessDaysBetween(std::string calendar, std::vector from, std::vector to, bool includeFirst, bool includeLast); RcppExport SEXP _RQuantLib_businessDaysBetween(SEXP calendarSEXP, SEXP fromSEXP, SEXP toSEXP, SEXP includeFirstSEXP, SEXP includeLastSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type from(fromSEXP); Rcpp::traits::input_parameter< std::vector >::type to(toSEXP); Rcpp::traits::input_parameter< bool >::type includeFirst(includeFirstSEXP); Rcpp::traits::input_parameter< bool >::type includeLast(includeLastSEXP); rcpp_result_gen = Rcpp::wrap(businessDaysBetween(calendar, from, to, includeFirst, includeLast)); return rcpp_result_gen; END_RCPP } // getHolidayList std::vector getHolidayList(std::string calendar, QuantLib::Date from, QuantLib::Date to, bool includeWeekends); RcppExport SEXP _RQuantLib_getHolidayList(SEXP calendarSEXP, SEXP fromSEXP, SEXP toSEXP, SEXP includeWeekendsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type from(fromSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type to(toSEXP); Rcpp::traits::input_parameter< bool >::type includeWeekends(includeWeekendsSEXP); rcpp_result_gen = Rcpp::wrap(getHolidayList(calendar, from, to, includeWeekends)); return rcpp_result_gen; END_RCPP } // addHolidays void addHolidays(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_addHolidays(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); addHolidays(calendar, dates); return R_NilValue; END_RCPP } // removeHolidays void removeHolidays(std::string calendar, std::vector dates); RcppExport SEXP _RQuantLib_removeHolidays(SEXP calendarSEXP, SEXP datesSEXP) { BEGIN_RCPP Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::string >::type calendar(calendarSEXP); Rcpp::traits::input_parameter< std::vector >::type dates(datesSEXP); removeHolidays(calendar, dates); return R_NilValue; END_RCPP } // advanceDate QuantLib::Date advanceDate(QuantLib::Date issueDate, int days); static SEXP _RQuantLib_advanceDate_try(SEXP issueDateSEXP, SEXP daysSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< QuantLib::Date >::type issueDate(issueDateSEXP); Rcpp::traits::input_parameter< int >::type days(daysSEXP); rcpp_result_gen = Rcpp::wrap(advanceDate(issueDate, days)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_advanceDate(SEXP issueDateSEXP, SEXP daysSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_advanceDate_try(issueDateSEXP, daysSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // dayCount std::vector dayCount(std::vector startDates, std::vector endDates, std::vector dayCounters); static SEXP _RQuantLib_dayCount_try(SEXP startDatesSEXP, SEXP endDatesSEXP, SEXP dayCountersSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::vector >::type startDates(startDatesSEXP); Rcpp::traits::input_parameter< std::vector >::type endDates(endDatesSEXP); Rcpp::traits::input_parameter< std::vector >::type dayCounters(dayCountersSEXP); rcpp_result_gen = Rcpp::wrap(dayCount(startDates, endDates, dayCounters)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_dayCount(SEXP startDatesSEXP, SEXP endDatesSEXP, SEXP dayCountersSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_dayCount_try(startDatesSEXP, endDatesSEXP, dayCountersSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // yearFraction std::vector yearFraction(std::vector startDates, std::vector endDates, std::vector dayCounters); static SEXP _RQuantLib_yearFraction_try(SEXP startDatesSEXP, SEXP endDatesSEXP, SEXP dayCountersSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::vector >::type startDates(startDatesSEXP); Rcpp::traits::input_parameter< std::vector >::type endDates(endDatesSEXP); Rcpp::traits::input_parameter< std::vector >::type dayCounters(dayCountersSEXP); rcpp_result_gen = Rcpp::wrap(yearFraction(startDates, endDates, dayCounters)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_yearFraction(SEXP startDatesSEXP, SEXP endDatesSEXP, SEXP dayCountersSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_yearFraction_try(startDatesSEXP, endDatesSEXP, dayCountersSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // setEvaluationDate bool setEvaluationDate(QuantLib::Date evalDate); static SEXP _RQuantLib_setEvaluationDate_try(SEXP evalDateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< QuantLib::Date >::type evalDate(evalDateSEXP); rcpp_result_gen = Rcpp::wrap(setEvaluationDate(evalDate)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_setEvaluationDate(SEXP evalDateSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_setEvaluationDate_try(evalDateSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // discountCurveEngine Rcpp::List discountCurveEngine(Rcpp::List rparams, Rcpp::List tslist, Rcpp::NumericVector times, Rcpp::List legParams); RcppExport SEXP _RQuantLib_discountCurveEngine(SEXP rparamsSEXP, SEXP tslistSEXP, SEXP timesSEXP, SEXP legParamsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparams(rparamsSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type tslist(tslistSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type times(timesSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type legParams(legParamsSEXP); rcpp_result_gen = Rcpp::wrap(discountCurveEngine(rparams, tslist, times, legParams)); return rcpp_result_gen; END_RCPP } // calibrateHullWhiteUsingCapsEngine Rcpp::List calibrateHullWhiteUsingCapsEngine(std::vector termStrcDateVec, std::vector termStrcZeroVec, Rcpp::DataFrame capDF, std::vector iborDateVec, std::vector iborZeroVec, std::string iborType, QuantLib::Date evalDate); RcppExport SEXP _RQuantLib_calibrateHullWhiteUsingCapsEngine(SEXP termStrcDateVecSEXP, SEXP termStrcZeroVecSEXP, SEXP capDFSEXP, SEXP iborDateVecSEXP, SEXP iborZeroVecSEXP, SEXP iborTypeSEXP, SEXP evalDateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector >::type termStrcDateVec(termStrcDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type termStrcZeroVec(termStrcZeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type capDF(capDFSEXP); Rcpp::traits::input_parameter< std::vector >::type iborDateVec(iborDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type iborZeroVec(iborZeroVecSEXP); Rcpp::traits::input_parameter< std::string >::type iborType(iborTypeSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type evalDate(evalDateSEXP); rcpp_result_gen = Rcpp::wrap(calibrateHullWhiteUsingCapsEngine(termStrcDateVec, termStrcZeroVec, capDF, iborDateVec, iborZeroVec, iborType, evalDate)); return rcpp_result_gen; END_RCPP } // calibrateHullWhiteUsingSwapsEngine Rcpp::List calibrateHullWhiteUsingSwapsEngine(std::vector termStrcDateVec, std::vector termStrcZeroVec, Rcpp::DataFrame swapDF, std::vector iborDateVec, std::vector iborZeroVec, std::string iborType, QuantLib::Date evalDate); RcppExport SEXP _RQuantLib_calibrateHullWhiteUsingSwapsEngine(SEXP termStrcDateVecSEXP, SEXP termStrcZeroVecSEXP, SEXP swapDFSEXP, SEXP iborDateVecSEXP, SEXP iborZeroVecSEXP, SEXP iborTypeSEXP, SEXP evalDateSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector >::type termStrcDateVec(termStrcDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type termStrcZeroVec(termStrcZeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::DataFrame >::type swapDF(swapDFSEXP); Rcpp::traits::input_parameter< std::vector >::type iborDateVec(iborDateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type iborZeroVec(iborZeroVecSEXP); Rcpp::traits::input_parameter< std::string >::type iborType(iborTypeSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type evalDate(evalDateSEXP); rcpp_result_gen = Rcpp::wrap(calibrateHullWhiteUsingSwapsEngine(termStrcDateVec, termStrcZeroVec, swapDF, iborDateVec, iborZeroVec, iborType, evalDate)); return rcpp_result_gen; END_RCPP } // europeanOptionImpliedVolatilityEngine double europeanOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility); static SEXP _RQuantLib_europeanOptionImpliedVolatilityEngine_try(SEXP typeSEXP, SEXP valueSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type value(valueSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); rcpp_result_gen = Rcpp::wrap(europeanOptionImpliedVolatilityEngine(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_europeanOptionImpliedVolatilityEngine(SEXP typeSEXP, SEXP valueSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_europeanOptionImpliedVolatilityEngine_try(typeSEXP, valueSEXP, underlyingSEXP, strikeSEXP, dividendYieldSEXP, riskFreeRateSEXP, maturitySEXP, volatilitySEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // americanOptionImpliedVolatilityEngine double americanOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volguess, int timesteps, int gridpoints); static SEXP _RQuantLib_americanOptionImpliedVolatilityEngine_try(SEXP typeSEXP, SEXP valueSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volguessSEXP, SEXP timestepsSEXP, SEXP gridpointsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type value(valueSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volguess(volguessSEXP); Rcpp::traits::input_parameter< int >::type timesteps(timestepsSEXP); Rcpp::traits::input_parameter< int >::type gridpoints(gridpointsSEXP); rcpp_result_gen = Rcpp::wrap(americanOptionImpliedVolatilityEngine(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volguess, timesteps, gridpoints)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_americanOptionImpliedVolatilityEngine(SEXP typeSEXP, SEXP valueSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volguessSEXP, SEXP timestepsSEXP, SEXP gridpointsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_americanOptionImpliedVolatilityEngine_try(typeSEXP, valueSEXP, underlyingSEXP, strikeSEXP, dividendYieldSEXP, riskFreeRateSEXP, maturitySEXP, volguessSEXP, timestepsSEXP, gridpointsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // sabrengine Rcpp::List sabrengine(Rcpp::List rparam, Rcpp::List legParams, std::vector dateVec, std::vector zeroVec, Rcpp::NumericVector swaptionMat, Rcpp::NumericVector swapLengths, Rcpp::NumericMatrix atmVols, Rcpp::NumericVector strikes, Rcpp::NumericMatrix smirkVols); RcppExport SEXP _RQuantLib_sabrengine(SEXP rparamSEXP, SEXP legParamsSEXP, SEXP dateVecSEXP, SEXP zeroVecSEXP, SEXP swaptionMatSEXP, SEXP swapLengthsSEXP, SEXP atmVolsSEXP, SEXP strikesSEXP, SEXP smirkVolsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< Rcpp::List >::type rparam(rparamSEXP); Rcpp::traits::input_parameter< Rcpp::List >::type legParams(legParamsSEXP); Rcpp::traits::input_parameter< std::vector >::type dateVec(dateVecSEXP); Rcpp::traits::input_parameter< std::vector >::type zeroVec(zeroVecSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swaptionMat(swaptionMatSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type swapLengths(swapLengthsSEXP); Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type atmVols(atmVolsSEXP); Rcpp::traits::input_parameter< Rcpp::NumericVector >::type strikes(strikesSEXP); Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type smirkVols(smirkVolsSEXP); rcpp_result_gen = Rcpp::wrap(sabrengine(rparam, legParams, dateVec, zeroVec, swaptionMat, swapLengths, atmVols, strikes, smirkVols)); return rcpp_result_gen; END_RCPP } // CreateSchedule Rcpp::DateVector CreateSchedule(Rcpp::List params); static SEXP _RQuantLib_CreateSchedule_try(SEXP paramsSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< Rcpp::List >::type params(paramsSEXP); rcpp_result_gen = Rcpp::wrap(CreateSchedule(params)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_CreateSchedule(SEXP paramsSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_CreateSchedule_try(paramsSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // getQuantLibVersion std::string getQuantLibVersion(); static SEXP _RQuantLib_getQuantLibVersion_try() { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; rcpp_result_gen = Rcpp::wrap(getQuantLibVersion()); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_getQuantLibVersion() { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_getQuantLibVersion_try()); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // getQuantLibCapabilities Rcpp::LogicalVector getQuantLibCapabilities(); static SEXP _RQuantLib_getQuantLibCapabilities_try() { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; rcpp_result_gen = Rcpp::wrap(getQuantLibCapabilities()); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_getQuantLibCapabilities() { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_getQuantLibCapabilities_try()); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // europeanOptionEngine Rcpp::List europeanOptionEngine(std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, Rcpp::Nullable discreteDividends, Rcpp::Nullable discreteDividendsTimeUntil); static SEXP _RQuantLib_europeanOptionEngine_try(SEXP typeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP discreteDividendsSEXP, SEXP discreteDividendsTimeUntilSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); Rcpp::traits::input_parameter< Rcpp::Nullable >::type discreteDividends(discreteDividendsSEXP); Rcpp::traits::input_parameter< Rcpp::Nullable >::type discreteDividendsTimeUntil(discreteDividendsTimeUntilSEXP); rcpp_result_gen = Rcpp::wrap(europeanOptionEngine(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, discreteDividends, discreteDividendsTimeUntil)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_europeanOptionEngine(SEXP typeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP discreteDividendsSEXP, SEXP discreteDividendsTimeUntilSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_europeanOptionEngine_try(typeSEXP, underlyingSEXP, strikeSEXP, dividendYieldSEXP, riskFreeRateSEXP, maturitySEXP, volatilitySEXP, discreteDividendsSEXP, discreteDividendsTimeUntilSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // americanOptionEngine Rcpp::List americanOptionEngine(std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, int timeSteps, int gridPoints, std::string engine, Rcpp::Nullable discreteDividends, Rcpp::Nullable discreteDividendsTimeUntil); static SEXP _RQuantLib_americanOptionEngine_try(SEXP typeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP timeStepsSEXP, SEXP gridPointsSEXP, SEXP engineSEXP, SEXP discreteDividendsSEXP, SEXP discreteDividendsTimeUntilSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< double >::type underlying(underlyingSEXP); Rcpp::traits::input_parameter< double >::type strike(strikeSEXP); Rcpp::traits::input_parameter< double >::type dividendYield(dividendYieldSEXP); Rcpp::traits::input_parameter< double >::type riskFreeRate(riskFreeRateSEXP); Rcpp::traits::input_parameter< double >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< double >::type volatility(volatilitySEXP); Rcpp::traits::input_parameter< int >::type timeSteps(timeStepsSEXP); Rcpp::traits::input_parameter< int >::type gridPoints(gridPointsSEXP); Rcpp::traits::input_parameter< std::string >::type engine(engineSEXP); Rcpp::traits::input_parameter< Rcpp::Nullable >::type discreteDividends(discreteDividendsSEXP); Rcpp::traits::input_parameter< Rcpp::Nullable >::type discreteDividendsTimeUntil(discreteDividendsTimeUntilSEXP); rcpp_result_gen = Rcpp::wrap(americanOptionEngine(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps, gridPoints, engine, discreteDividends, discreteDividendsTimeUntil)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_americanOptionEngine(SEXP typeSEXP, SEXP underlyingSEXP, SEXP strikeSEXP, SEXP dividendYieldSEXP, SEXP riskFreeRateSEXP, SEXP maturitySEXP, SEXP volatilitySEXP, SEXP timeStepsSEXP, SEXP gridPointsSEXP, SEXP engineSEXP, SEXP discreteDividendsSEXP, SEXP discreteDividendsTimeUntilSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_americanOptionEngine_try(typeSEXP, underlyingSEXP, strikeSEXP, dividendYieldSEXP, riskFreeRateSEXP, maturitySEXP, volatilitySEXP, timeStepsSEXP, gridPointsSEXP, engineSEXP, discreteDividendsSEXP, discreteDividendsTimeUntilSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // europeanOptionArraysEngine Rcpp::List europeanOptionArraysEngine(std::string type, Rcpp::NumericMatrix par); static SEXP _RQuantLib_europeanOptionArraysEngine_try(SEXP typeSEXP, SEXP parSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::traits::input_parameter< std::string >::type type(typeSEXP); Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type par(parSEXP); rcpp_result_gen = Rcpp::wrap(europeanOptionArraysEngine(type, par)); return rcpp_result_gen; END_RCPP_RETURN_ERROR } RcppExport SEXP _RQuantLib_europeanOptionArraysEngine(SEXP typeSEXP, SEXP parSEXP) { SEXP rcpp_result_gen; { Rcpp::RNGScope rcpp_rngScope_gen; rcpp_result_gen = PROTECT(_RQuantLib_europeanOptionArraysEngine_try(typeSEXP, parSEXP)); } Rboolean rcpp_isInterrupt_gen = Rf_inherits(rcpp_result_gen, "interrupted-error"); if (rcpp_isInterrupt_gen) { UNPROTECT(1); Rf_onintr(); } bool rcpp_isLongjump_gen = Rcpp::internal::isLongjumpSentinel(rcpp_result_gen); if (rcpp_isLongjump_gen) { Rcpp::internal::resumeJump(rcpp_result_gen); } Rboolean rcpp_isError_gen = Rf_inherits(rcpp_result_gen, "try-error"); if (rcpp_isError_gen) { SEXP rcpp_msgSEXP_gen = Rf_asChar(rcpp_result_gen); UNPROTECT(1); Rf_error(CHAR(rcpp_msgSEXP_gen)); } UNPROTECT(1); return rcpp_result_gen; } // zeroprice double zeroprice(double yield, QuantLib::Date maturity, QuantLib::Date settle, int period, int basis); RcppExport SEXP _RQuantLib_zeroprice(SEXP yieldSEXP, SEXP maturitySEXP, SEXP settleSEXP, SEXP periodSEXP, SEXP basisSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< double >::type yield(yieldSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type settle(settleSEXP); Rcpp::traits::input_parameter< int >::type period(periodSEXP); Rcpp::traits::input_parameter< int >::type basis(basisSEXP); rcpp_result_gen = Rcpp::wrap(zeroprice(yield, maturity, settle, period, basis)); return rcpp_result_gen; END_RCPP } // zeroyield double zeroyield(double price, QuantLib::Date maturity, QuantLib::Date settle, int period, int basis); RcppExport SEXP _RQuantLib_zeroyield(SEXP priceSEXP, SEXP maturitySEXP, SEXP settleSEXP, SEXP periodSEXP, SEXP basisSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< double >::type price(priceSEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type maturity(maturitySEXP); Rcpp::traits::input_parameter< QuantLib::Date >::type settle(settleSEXP); Rcpp::traits::input_parameter< int >::type period(periodSEXP); Rcpp::traits::input_parameter< int >::type basis(basisSEXP); rcpp_result_gen = Rcpp::wrap(zeroyield(price, maturity, settle, period, basis)); return rcpp_result_gen; END_RCPP } // validate (ensure exported C++ functions exist before calling them) static int _RQuantLib_RcppExport_validate(const char* sig) { static std::set signatures; if (signatures.empty()) { signatures.insert("double(*zeroPriceByYieldEngine)(double,double,double,double,double,double,QuantLib::Date,QuantLib::Date)"); signatures.insert("double(*zeroYieldByPriceEngine)(double,double,double,double,double,double,QuantLib::Date,QuantLib::Date)"); signatures.insert("double(*fixedRateBondYieldByPriceEngine)(double,double,std::string,double,double,double,double,double,double,QuantLib::Date,QuantLib::Date,QuantLib::Date,std::vector)"); signatures.insert("double(*fixedRateBondPriceByYieldEngine)(double,double,std::string,double,double,double,double,double,double,QuantLib::Date,QuantLib::Date,QuantLib::Date,std::vector)"); signatures.insert("Rcpp::List(*FloatBond1)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); signatures.insert("Rcpp::List(*FloatBond2)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); signatures.insert("Rcpp::List(*FloatBond3)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); signatures.insert("Rcpp::List(*FloatBond4)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); signatures.insert("Rcpp::List(*floatingWithRebuiltCurveEngine)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List)"); signatures.insert("Rcpp::List(*FixedRateWithYield)(Rcpp::List,std::vector,Rcpp::List,Rcpp::List,double)"); signatures.insert("Rcpp::List(*FixedRateWithPrice)(Rcpp::List,std::vector,Rcpp::List,Rcpp::List,double)"); signatures.insert("Rcpp::List(*FixedRateWithRebuiltCurve)(Rcpp::List,std::vector,Rcpp::List,Rcpp::List,std::vector,std::vector)"); signatures.insert("Rcpp::List(*ZeroBondWithRebuiltCurve)(Rcpp::List,std::vector,std::vector,Rcpp::List)"); signatures.insert("Rcpp::List(*convertibleZeroBondEngine)(Rcpp::List,Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::DataFrame,Rcpp::DataFrame,Rcpp::List)"); signatures.insert("Rcpp::List(*convertibleFixedBondEngine)(Rcpp::List,Rcpp::NumericVector,Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::DataFrame,Rcpp::DataFrame,Rcpp::List)"); signatures.insert("Rcpp::List(*convertibleFloatingBondEngine)(Rcpp::List,Rcpp::List,std::vector,std::vector,std::vector,std::vector,std::vector,std::vector,Rcpp::List,std::vector,Rcpp::DataFrame,Rcpp::DataFrame,Rcpp::List)"); signatures.insert("Rcpp::List(*callableBondEngine)(Rcpp::List,Rcpp::List,Rcpp::NumericVector,Rcpp::DataFrame,Rcpp::List)"); signatures.insert("Rcpp::List(*fittedBondCurveEngine)(Rcpp::List,Rcpp::NumericVector,Rcpp::NumericVector,Rcpp::NumericVector,Rcpp::List)"); signatures.insert("QuantLib::Date(*advanceDate)(QuantLib::Date,int)"); signatures.insert("std::vector(*dayCount)(std::vector,std::vector,std::vector)"); signatures.insert("std::vector(*yearFraction)(std::vector,std::vector,std::vector)"); signatures.insert("bool(*setEvaluationDate)(QuantLib::Date)"); signatures.insert("double(*europeanOptionImpliedVolatilityEngine)(std::string,double,double,double,double,double,double,double)"); signatures.insert("double(*americanOptionImpliedVolatilityEngine)(std::string,double,double,double,double,double,double,double,int,int)"); signatures.insert("Rcpp::DateVector(*CreateSchedule)(Rcpp::List)"); signatures.insert("std::string(*getQuantLibVersion)()"); signatures.insert("Rcpp::LogicalVector(*getQuantLibCapabilities)()"); signatures.insert("Rcpp::List(*europeanOptionEngine)(std::string,double,double,double,double,double,double,Rcpp::Nullable,Rcpp::Nullable)"); signatures.insert("Rcpp::List(*americanOptionEngine)(std::string,double,double,double,double,double,double,int,int,std::string,Rcpp::Nullable,Rcpp::Nullable)"); signatures.insert("Rcpp::List(*europeanOptionArraysEngine)(std::string,Rcpp::NumericMatrix)"); } return signatures.find(sig) != signatures.end(); } // registerCCallable (register entry points for exported C++ functions) RcppExport SEXP _RQuantLib_RcppExport_registerCCallable() { R_RegisterCCallable("RQuantLib", "_RQuantLib_zeroPriceByYieldEngine", (DL_FUNC)_RQuantLib_zeroPriceByYieldEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_zeroYieldByPriceEngine", (DL_FUNC)_RQuantLib_zeroYieldByPriceEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_fixedRateBondYieldByPriceEngine", (DL_FUNC)_RQuantLib_fixedRateBondYieldByPriceEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_fixedRateBondPriceByYieldEngine", (DL_FUNC)_RQuantLib_fixedRateBondPriceByYieldEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FloatBond1", (DL_FUNC)_RQuantLib_FloatBond1_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FloatBond2", (DL_FUNC)_RQuantLib_FloatBond2_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FloatBond3", (DL_FUNC)_RQuantLib_FloatBond3_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FloatBond4", (DL_FUNC)_RQuantLib_FloatBond4_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_floatingWithRebuiltCurveEngine", (DL_FUNC)_RQuantLib_floatingWithRebuiltCurveEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FixedRateWithYield", (DL_FUNC)_RQuantLib_FixedRateWithYield_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FixedRateWithPrice", (DL_FUNC)_RQuantLib_FixedRateWithPrice_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_FixedRateWithRebuiltCurve", (DL_FUNC)_RQuantLib_FixedRateWithRebuiltCurve_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_ZeroBondWithRebuiltCurve", (DL_FUNC)_RQuantLib_ZeroBondWithRebuiltCurve_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_convertibleZeroBondEngine", (DL_FUNC)_RQuantLib_convertibleZeroBondEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_convertibleFixedBondEngine", (DL_FUNC)_RQuantLib_convertibleFixedBondEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_convertibleFloatingBondEngine", (DL_FUNC)_RQuantLib_convertibleFloatingBondEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_callableBondEngine", (DL_FUNC)_RQuantLib_callableBondEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_fittedBondCurveEngine", (DL_FUNC)_RQuantLib_fittedBondCurveEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_advanceDate", (DL_FUNC)_RQuantLib_advanceDate_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_dayCount", (DL_FUNC)_RQuantLib_dayCount_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_yearFraction", (DL_FUNC)_RQuantLib_yearFraction_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_setEvaluationDate", (DL_FUNC)_RQuantLib_setEvaluationDate_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_europeanOptionImpliedVolatilityEngine", (DL_FUNC)_RQuantLib_europeanOptionImpliedVolatilityEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_americanOptionImpliedVolatilityEngine", (DL_FUNC)_RQuantLib_americanOptionImpliedVolatilityEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_CreateSchedule", (DL_FUNC)_RQuantLib_CreateSchedule_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_getQuantLibVersion", (DL_FUNC)_RQuantLib_getQuantLibVersion_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_getQuantLibCapabilities", (DL_FUNC)_RQuantLib_getQuantLibCapabilities_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_europeanOptionEngine", (DL_FUNC)_RQuantLib_europeanOptionEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_americanOptionEngine", (DL_FUNC)_RQuantLib_americanOptionEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_europeanOptionArraysEngine", (DL_FUNC)_RQuantLib_europeanOptionArraysEngine_try); R_RegisterCCallable("RQuantLib", "_RQuantLib_RcppExport_validate", (DL_FUNC)_RQuantLib_RcppExport_validate); return R_NilValue; } RcppExport SEXP _rcpp_module_boot_BlackMod(); RcppExport SEXP _rcpp_module_boot_BondsMod(); static const R_CallMethodDef CallEntries[] = { {"_RQuantLib_affineWithRebuiltCurveEngine", (DL_FUNC) &_RQuantLib_affineWithRebuiltCurveEngine, 7}, {"_RQuantLib_asianOptionEngine", (DL_FUNC) &_RQuantLib_asianOptionEngine, 11}, {"_RQuantLib_binaryOptionEngine", (DL_FUNC) &_RQuantLib_binaryOptionEngine, 10}, {"_RQuantLib_binaryOptionImpliedVolatilityEngine", (DL_FUNC) &_RQuantLib_binaryOptionImpliedVolatilityEngine, 9}, {"_RQuantLib_barrierOptionEngine", (DL_FUNC) &_RQuantLib_barrierOptionEngine, 10}, {"_RQuantLib_bermudanFromYieldEngine", (DL_FUNC) &_RQuantLib_bermudanFromYieldEngine, 5}, {"_RQuantLib_bermudanWithRebuiltCurveEngine", (DL_FUNC) &_RQuantLib_bermudanWithRebuiltCurveEngine, 6}, {"_RQuantLib_zeroPriceByYieldEngine", (DL_FUNC) &_RQuantLib_zeroPriceByYieldEngine, 8}, {"_RQuantLib_zeroYieldByPriceEngine", (DL_FUNC) &_RQuantLib_zeroYieldByPriceEngine, 8}, {"_RQuantLib_fixedRateBondYieldByPriceEngine", (DL_FUNC) &_RQuantLib_fixedRateBondYieldByPriceEngine, 13}, {"_RQuantLib_fixedRateBondPriceByYieldEngine", (DL_FUNC) &_RQuantLib_fixedRateBondPriceByYieldEngine, 13}, {"_RQuantLib_FloatBond1", (DL_FUNC) &_RQuantLib_FloatBond1, 9}, {"_RQuantLib_FloatBond2", (DL_FUNC) &_RQuantLib_FloatBond2, 11}, {"_RQuantLib_FloatBond3", (DL_FUNC) &_RQuantLib_FloatBond3, 11}, {"_RQuantLib_FloatBond4", (DL_FUNC) &_RQuantLib_FloatBond4, 13}, {"_RQuantLib_floatingWithRebuiltCurveEngine", (DL_FUNC) &_RQuantLib_floatingWithRebuiltCurveEngine, 11}, {"_RQuantLib_FixedRateWithYield", (DL_FUNC) &_RQuantLib_FixedRateWithYield, 5}, {"_RQuantLib_FixedRateWithPrice", (DL_FUNC) &_RQuantLib_FixedRateWithPrice, 5}, {"_RQuantLib_FixedRateWithRebuiltCurve", (DL_FUNC) &_RQuantLib_FixedRateWithRebuiltCurve, 6}, {"_RQuantLib_ZeroBondWithRebuiltCurve", (DL_FUNC) &_RQuantLib_ZeroBondWithRebuiltCurve, 4}, {"_RQuantLib_convertibleZeroBondEngine", (DL_FUNC) &_RQuantLib_convertibleZeroBondEngine, 9}, {"_RQuantLib_convertibleFixedBondEngine", (DL_FUNC) &_RQuantLib_convertibleFixedBondEngine, 10}, {"_RQuantLib_convertibleFloatingBondEngine", (DL_FUNC) &_RQuantLib_convertibleFloatingBondEngine, 13}, {"_RQuantLib_callableBondEngine", (DL_FUNC) &_RQuantLib_callableBondEngine, 5}, {"_RQuantLib_fittedBondCurveEngine", (DL_FUNC) &_RQuantLib_fittedBondCurveEngine, 5}, {"_RQuantLib_setCalendarContext", (DL_FUNC) &_RQuantLib_setCalendarContext, 3}, {"_RQuantLib_isBusinessDay", (DL_FUNC) &_RQuantLib_isBusinessDay, 2}, {"_RQuantLib_isHoliday", (DL_FUNC) &_RQuantLib_isHoliday, 2}, {"_RQuantLib_isWeekend", (DL_FUNC) &_RQuantLib_isWeekend, 2}, {"_RQuantLib_isEndOfMonth", (DL_FUNC) &_RQuantLib_isEndOfMonth, 2}, {"_RQuantLib_getEndOfMonth", (DL_FUNC) &_RQuantLib_getEndOfMonth, 2}, {"_RQuantLib_adjust", (DL_FUNC) &_RQuantLib_adjust, 3}, {"_RQuantLib_advance1", (DL_FUNC) &_RQuantLib_advance1, 6}, {"_RQuantLib_advance2", (DL_FUNC) &_RQuantLib_advance2, 5}, {"_RQuantLib_businessDaysBetween", (DL_FUNC) &_RQuantLib_businessDaysBetween, 5}, {"_RQuantLib_getHolidayList", (DL_FUNC) &_RQuantLib_getHolidayList, 4}, {"_RQuantLib_addHolidays", (DL_FUNC) &_RQuantLib_addHolidays, 2}, {"_RQuantLib_removeHolidays", (DL_FUNC) &_RQuantLib_removeHolidays, 2}, {"_RQuantLib_advanceDate", (DL_FUNC) &_RQuantLib_advanceDate, 2}, {"_RQuantLib_dayCount", (DL_FUNC) &_RQuantLib_dayCount, 3}, {"_RQuantLib_yearFraction", (DL_FUNC) &_RQuantLib_yearFraction, 3}, {"_RQuantLib_setEvaluationDate", (DL_FUNC) &_RQuantLib_setEvaluationDate, 1}, {"_RQuantLib_discountCurveEngine", (DL_FUNC) &_RQuantLib_discountCurveEngine, 4}, {"_RQuantLib_calibrateHullWhiteUsingCapsEngine", (DL_FUNC) &_RQuantLib_calibrateHullWhiteUsingCapsEngine, 7}, {"_RQuantLib_calibrateHullWhiteUsingSwapsEngine", (DL_FUNC) &_RQuantLib_calibrateHullWhiteUsingSwapsEngine, 7}, {"_RQuantLib_europeanOptionImpliedVolatilityEngine", (DL_FUNC) &_RQuantLib_europeanOptionImpliedVolatilityEngine, 8}, {"_RQuantLib_americanOptionImpliedVolatilityEngine", (DL_FUNC) &_RQuantLib_americanOptionImpliedVolatilityEngine, 10}, {"_RQuantLib_sabrengine", (DL_FUNC) &_RQuantLib_sabrengine, 9}, {"_RQuantLib_CreateSchedule", (DL_FUNC) &_RQuantLib_CreateSchedule, 1}, {"_RQuantLib_getQuantLibVersion", (DL_FUNC) &_RQuantLib_getQuantLibVersion, 0}, {"_RQuantLib_getQuantLibCapabilities", (DL_FUNC) &_RQuantLib_getQuantLibCapabilities, 0}, {"_RQuantLib_europeanOptionEngine", (DL_FUNC) &_RQuantLib_europeanOptionEngine, 9}, {"_RQuantLib_americanOptionEngine", (DL_FUNC) &_RQuantLib_americanOptionEngine, 12}, {"_RQuantLib_europeanOptionArraysEngine", (DL_FUNC) &_RQuantLib_europeanOptionArraysEngine, 2}, {"_RQuantLib_zeroprice", (DL_FUNC) &_RQuantLib_zeroprice, 5}, {"_RQuantLib_zeroyield", (DL_FUNC) &_RQuantLib_zeroyield, 5}, {"_rcpp_module_boot_BlackMod", (DL_FUNC) &_rcpp_module_boot_BlackMod, 0}, {"_rcpp_module_boot_BondsMod", (DL_FUNC) &_rcpp_module_boot_BondsMod, 0}, {"_RQuantLib_RcppExport_registerCCallable", (DL_FUNC) &_RQuantLib_RcppExport_registerCCallable, 0}, {NULL, NULL, 0} }; RcppExport void R_init_RQuantLib(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); } RQuantLib/src/calendars.cpp0000644000176200001440000002750013564333065015356 0ustar liggesusers // RQuantLib -- R interface to the QuantLib libraries // // Copyright (C) 2002 - 2019 Dirk Eddelbuettel // Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . #include // returns a reference-counted pointer to a matching Calendar object QuantLib::ext::shared_ptr getCalendar(const std::string &calstr) { QuantLib::ext::shared_ptr pcal; if (calstr == "TARGET") { // generic calendar pcal.reset(new QuantLib::TARGET()); } else if (calstr == "Argentina") { pcal.reset(new QuantLib::Argentina()); } else if (calstr == "Australia") { pcal.reset(new QuantLib::Australia()); } 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 == "China") { pcal.reset(new QuantLib::China()); } else if (calstr == "CzechRepublic") { pcal.reset(new QuantLib::CzechRepublic()); } else if (calstr == "Denmark") { pcal.reset(new QuantLib::Denmark()); } else if (calstr == "Finland") { pcal.reset(new QuantLib::Finland()); } 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 == "HongKong") { pcal.reset(new QuantLib::HongKong()); } else if (calstr == "Hungary") { pcal.reset(new QuantLib::Hungary()); } else if (calstr == "Iceland") { pcal.reset(new QuantLib::Iceland()); } else if (calstr == "India") { pcal.reset(new QuantLib::India()); } else if (calstr == "Indonesia") { pcal.reset(new QuantLib::Indonesia()); } 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 == "Mexico") { pcal.reset(new QuantLib::Mexico()); } else if (calstr == "NewZealand") { pcal.reset(new QuantLib::NewZealand()); } else if (calstr == "Norway") { pcal.reset(new QuantLib::Norway()); } else if (calstr == "Poland") { pcal.reset(new QuantLib::Poland()); } else if (calstr == "Russia") { pcal.reset(new QuantLib::Russia()); } else if (calstr == "SaudiArabia") { pcal.reset(new QuantLib::SaudiArabia()); } else if (calstr == "Singapore") { pcal.reset(new QuantLib::Singapore()); } else if (calstr == "Slovakia") { pcal.reset(new QuantLib::Slovakia()); } else if (calstr == "SouthAfrica") { pcal.reset(new QuantLib::SouthAfrica()); } 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 == "Sweden") { pcal.reset(new QuantLib::Sweden()); } else if (calstr == "Switzerland") { pcal.reset(new QuantLib::Switzerland()); } else if (calstr == "Taiwan") { pcal.reset(new QuantLib::Taiwan()); } else if (calstr == "Turkey") { pcal.reset(new QuantLib::Turkey()); } else if (calstr == "Ukraine") { pcal.reset(new QuantLib::Ukraine()); } 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 if (calstr == "WeekendsOnly") { pcal.reset(new QuantLib::WeekendsOnly()); } else if (calstr == "Null" || calstr == "null" || calstr == "NULL") { pcal.reset(new QuantLib::NullCalendar()); } else { throw std::invalid_argument("Calendar " + calstr + " not recognised "); } return pcal; } //setCalendarContext <- function(calendar="TARGET", // fixingDays = 2, // settleDate = Sys.Date() + 2) { // [[Rcpp::export]] bool setCalendarContext(std::string calendar, int fixingDays, QuantLib::Date settleDate) { // Rcpp Attribute cannot reflect complicated default arguments if (settleDate.serialNumber() == 0) { calendar = "TARGET"; fixingDays = 2; settleDate = QuantLib::Date::todaysDate() + 2; } // set fixingDays and settleDate RQLContext::instance().fixingDays = fixingDays; RQLContext::instance().settleDate = settleDate; QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); RQLContext::instance().calendar = *pcal; // set calendar in global singleton return true; } // [[Rcpp::export]] std::vector isBusinessDay(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); std::vector bizdays(n); for (int i=0; iisBusinessDay(dates[i]); } return bizdays; } // [[Rcpp::export]] std::vector isHoliday(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); std::vector hdays(n); for (int i=0; iisHoliday(dates[i]); } return hdays; } // [[Rcpp::export]] std::vector isWeekend(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); std::vector weekends(n); for (int i=0; iisWeekend(dates[i].weekday()); } return weekends; } // [[Rcpp::export]] std::vector isEndOfMonth(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); std::vector eom(n); for (int i=0; iisEndOfMonth(dates[i]); } return eom; } // [[Rcpp::export]] std::vector getEndOfMonth(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); std::vector ndates(n); for (int i=0; iendOfMonth(dates[i]); } return ndates; } // [[Rcpp::export]] std::vector adjust(std::string calendar, std::vector dates, int bdc=0) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); QuantLib::BusinessDayConvention bdcval = getBusinessDayConvention(bdc); int n = dates.size(); std::vector adjusted(n); for (int i=0; iadjust(dates[i], bdcval); } return adjusted; } // [[Rcpp::export]] std::vector advance1(std::string calendar, double amount, double unit, int bdcVal, double emr, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(bdcVal); int n = dates.size(); std::vector advance(n); for (int i=0; iadvance(dates[i], amount, getTimeUnit(unit), bdc, (emr == 1) ? true : false); } return advance; } // [[Rcpp::export]] std::vector advance2(std::string calendar, double period, int bdcVal, double emr, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); QuantLib::BusinessDayConvention bdc = getBusinessDayConvention(bdcVal); int n = dates.size(); std::vector advance(n); for (int i=0; iadvance(dates[i], QuantLib::Period(getFrequency(period)), bdc, (emr == 1) ? true : false); } return advance; } // [[Rcpp::export]] std::vector businessDaysBetween(std::string calendar, std::vector from, std::vector to, bool includeFirst=true, bool includeLast=false) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = from.size(); std::vector between(n); for (int i=0; ibusinessDaysBetween(from[i], to[i], includeFirst, includeLast); } return between; } // [[Rcpp::export]] std::vector getHolidayList(std::string calendar, QuantLib::Date from, QuantLib::Date to, bool includeWeekends=false) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); std::vector holidays = QuantLib::Calendar::holidayList(*pcal, from, to, includeWeekends); return holidays; } // [[Rcpp::export]] void addHolidays(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); for (int i=0; iaddHoliday(dates[i]); } } // [[Rcpp::export]] void removeHolidays(std::string calendar, std::vector dates) { QuantLib::ext::shared_ptr pcal(getCalendar(calendar)); int n = dates.size(); for (int i=0; iremoveHoliday(dates[i]); } } RQuantLib/R/0000755000176200001440000000000013607470337012326 5ustar liggesusersRQuantLib/R/inline.R0000644000176200001440000000607512753434160013732 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2016 Dirk Eddelbuettel ## ## 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) { ## default to NULL qlcflags <- qllibs <- NULL if (.Platform$OS.type=="windows") { if (Sys.getenv("QUANTLIB_ROOT") != "") { ## 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("-L%s/lib%s -lQuantLib", qlroot, rarch) } } else { ## on Linux and OS X, see if we have quantlib-config which may well be ## false in the case of prebuild binary packages as eg r-cran-rquantlib ## on Debian / Ubuntu as well as the OS X package from CRAN ## first we check whether we have quantlib-config in the path if (isTRUE(unname(Sys.which("quantlib-config")) != "")) { qc <- system("bash -c 'type -p quantlib-config'", ignore.stderr=TRUE, intern=TRUE) if (is.character(qc) && nchar(qc) > 1) { qlcflags <- system(paste(qc, "--cflags"), intern = TRUE) qllibs <- system(paste(qc, "--libs"), intern = TRUE) } } } assign("ql_cflags", qlcflags, envir=.pkgglobalenv) assign("ql_libs", qllibs, envir=.pkgglobalenv) } LdFlags <- function(print = TRUE) { if (is.null(.pkgglobalenv$ql_libs)) stop("Cannot supply LdFlags as none set.") if (print) cat(.pkgglobalenv$ql_libs) else .pkgglobalenv$ql_libs } CFlags <- function(print = TRUE) { if (is.null(.pkgglobalenv$ql_cflags)) stop("Cannot supply CFlags as none set.") if (print) cat(.pkgglobalenv$ql_cflags) else .pkgglobalenv$ql_cflags } inlineCxxPlugin <- function(...) { plugin <- 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 <- paste("-DRQuantLib_Plugin", CFlags(FALSE)) settings } RQuantLib/R/bermudan.R0000644000176200001440000001670112714226467014254 0ustar liggesusers## RQuantLib function BermudanSwaption ## ## Copyright (C) 2005 Dominick Samperi ## Copyright (C) 2007 - 2014 Dirk Eddelbuettel ## Copyright (C) 2016 Terry Leitch ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . BermudanSwaption <- function(params, ts, swaptionMaturities, swapTenors, volMatrix) { UseMethod("BermudanSwaption") } BermudanSwaption.default <- function(params, ts, 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", call.=FALSE) } if(is.null(params$startDate)){ params$startDate=advance("UnitedStates",params$tradeDate, 1, 3) warning("swaption start date not set, defaulting to 1 year from trade date using US calendar") } if(is.null(params$maturity)){ params$maturity=advance("UnitedStates",params$startDate, 5, 3) warning("swaption maturity not set, defaulting to 5 years from startDate using US calendar") } matYears=as.numeric(params$maturity-params$tradeDate)/365 expYears=as.numeric(params$startDate-params$tradeDate)/365 increment=min(matYears/6,1.0) numObs=floor(matYears/increment)+1 optStart=as.numeric(params$startDate-params$tradeDate)/365 # find closest option to our target to ensure it is in calibration tenor=expiry=vol=vector(length=numObs,mode="numeric") expiryIDX=findInterval(expYears,swaptionMaturities) tenorIDX=findInterval(matYears-expYears,swapTenors) if(tenorIDX >0 & expiryIDX>0){ vol[1]=volMatrix[expiryIDX,tenorIDX] expiry[1]=swaptionMaturities[expiryIDX] tenor[1]=swapTenors[tenorIDX] } else { vol[1]=expiry[1]=tenor[1]=0 } for(i in 2:numObs){ expiryIDX=findInterval(i*increment,swaptionMaturities) tenorIDX=findInterval(matYears-(i-1)*increment,swapTenors) if(tenorIDX >0 & expiryIDX>0){ vol[i]=volMatrix[expiryIDX,tenorIDX] expiry[i]=swaptionMaturities[expiryIDX] tenor[i]=swapTenors[tenorIDX] } else { vol[i]=volMatrix[expiryIDX,tenorIDX+1] expiry[i]=swaptionMaturities[expiryIDX] tenor[i]=swapTenors[tenorIDX+1] } } # remove if search was out of bounds expiry=expiry[expiry>0];tenor=tenor[tenor>0];vol=vol[vol>0] if(length(expiry)<5){ warning("Insufficent vols to fit affine model") return(NULL) } #Take 1st 5 which includes closest to initial date expiry=expiry[1:5];tenor=tenor[1:5];vol=vol[1:5] # # Check that the term structure quotes are properly formatted. # if(is) # if (!is.list(ts) || length(ts) == 0) { # stop("Term structure quotes must be a non-empty list", call.=FALSE) # } # if (length(ts) != length(names(ts))) { # stop("Term structure quotes must include labels", call.=FALSE) # } # if (!is.numeric(unlist(ts))) { # stop("Term structure quotes must have numeric values", call.=FALSE) # } # 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", call.=FALSE) } # 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", call.=FALSE) } # 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. if(class(ts)=="DiscountCurve"){ val <- bermudanWithRebuiltCurveEngine(params, c(ts$table$date), ts$table$zeroRates, swaptionMaturities, swapTenors, volMatrix) } else{ if (!is.numeric(ts) | length(ts) !=1) { stop("Flat Term structure yield must have single numeric value", call.=FALSE) } val <- bermudanFromYieldEngine(params, ts, swaptionMaturities, swapTenors, volMatrix) } 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/sabr.R0000644000176200001440000001577612750726236013420 0ustar liggesusers## RQuantLib function sabrSwaption ## ## Copyright (C) 2005 Dominick Samperi ## Copyright (C) 2007 - 2015 Dirk Eddelbuettel ## Copyright (C) 2016 Terry Leitch and Dirk Eddelbuettel ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . SabrSwaption <- function(params, ts,volCubeDF, legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual"), tsUp01=NA,tsDn01=NA,vega=FALSE) { UseMethod("SabrSwaption") } SabrSwaption.default <- function(params, ts, volCubeDF, legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual"), tsUp01=NA,tsDn01=NA,vega=FALSE) { # Check that params list names if(is.null(params$startDate)){ params$startDate=advance("UnitedStates",params$tradeDate, 1, 3) warning("swaption start date not set, defaulting to 1 year from trade date using US calendar") } if(is.null(params$expiryDate)){ params$expiryDate=params$startDate warning("swaption expiry date not set, defaulting to 1 year from trade date using US calendar") } if(is.null(params$maturity)){ params$maturity=advance("UnitedStates",params$startDate, 5, 3) warning("swaption maturity not set, defaulting to 5 years from startDate using US calendar") } volCube=volDF2CubeK(params,volCubeDF) if(vega){ volCubeDF$LogNormalVol=volCubeDF$LogNormalVol+.01 volCubeUp=volDF2CubeK(params,volCubeDF) } swapTenors=volCube$tenors if (!is.list(params) || length(params) == 0) { stop("The params parameter must be a non-empty list", call.=FALSE) } swaptionMaturities=volCube$expiries ##reshape dataframe to fit QL call vc=volDF2CubeK(params,volCubeDF) matYears=as.numeric(params$maturity-params$tradeDate)/365 expYears=as.numeric(params$expiryDate-params$tradeDate)/365 if(class(ts)=="DiscountCurve"){ matchlegs<-matchParams(legparams) val <- sabrengine(params, matchlegs, c(ts$table$date), ts$table$zeroRates, volCube$expiries,volCube$tenors,volCube$atmVol,volCube$strikes,volCube$smirk) if(vega){ valUp <- sabrengine(params, matchlegs, c(ts$table$date), ts$table$zeroRates, volCubeUp$expiries,volCubeUp$tenors,volCubeUp$atmVol,volCubeUp$strikes,volCubeUp$smirk) val$payVega=valUp$pay-val$pay val$rcvVega=valUp$rcv-val$rcv if(anyNA(tsUp01)){ }else{ valTsUp <- sabrengine(params, matchlegs, c(tsUp01$table$date), tsUp01$table$zeroRates, volCube$expiries,volCube$tenors,volCube$atmVol,volCube$strikes,volCube$smirk) val$payDV01=valTsUp$pay-val$pay val$rcvDV01=valTsUp$rcv-val$rcv if(anyNA(tsDn01)){ } else{ valTsDn <- sabrengine(params, matchlegs, c(tsDn01$table$date), tsDn01$table$zeroRates, volCube$expiries,volCube$tenors,volCube$atmVol,volCube$strikes,volCube$smirk) val$payCnvx=(valTsUp$pay+valTsDn$pay-2*val$pay)/2 val$rcvCnvx=(valTsUp$rcv+valTsDn$rcv-2*val$rcv)/2 } } } } else{ stop("DiscountCurve class term structure required", call.=FALSE) } val$params=params val$atmRate=as.numeric(val$atmRate) class(val) <- "SabrSwaption" summary(val) val } volDF2CubeK <- function(params, tbl, source = "CME") { strikes <- levels(tbl$Spread)<-c(-200,-150,-100,-75,-50,-25,0,25,50,75,100,150,200) matYears <- as.numeric(params$maturity-params$tradeDate)/365 expYears <- as.numeric(params$expiryDate-params$tradeDate)/365 expLvl <- c( "1M","3M","6M","1Y","2Y","3Y","4Y", "5Y", "6Y", "7Y", "8Y", "9Y","10Y") tbl$Expiry <- factor(tbl$Expiry, levels <- expLvl) expiries <- c(1/12,.25,.5,1,2,3,4,5,6,7,8,9,10) tenorLvl <- c( "1Y", "2Y", "5Y", "10Y","15Y","20Y","30Y") tbl$Tenor <- factor(tbl$Tenor, levels = tenorLvl) tenors <- c(1,2,5,10,15,20,30) tenorIDX <- max(findInterval(matYears-expYears,tenors),1) tenorIDX <- min(tenorIDX,length(tenors)-3) expiryIDX <- findInterval(expYears,expiries) expiryIDX <- min(expiryIDX,length(expiries)-3) strikeIDX <- 1 expire <- expLvl[expiryIDX] tenor <- tenorLvl[tenorIDX] for(strike in levels(tbl$Spread)){ if(!is.na(tbl[tbl$Expiry==expire & tbl$Spread==strike &tbl$Tenor==tenor,]$LogNormalVol))break; strikeIDX <- strikeIDX+1 } strikes <- strikes[strikeIDX:length(strikes)] expLvl <- expLvl[expiryIDX:length(expLvl)] expiries <- expiries[expiryIDX:length(expiries)] tenorLvl <- tenorLvl[tenorIDX:length(tenorLvl)] tenors <- tenors[tenorIDX:length(tenors)] tbl <- tbl[tbl$Expiry%in%expLvl,] tbl <- tbl[tbl$Tenor%in%tenorLvl,] tbl <- tbl[tbl$Spread%in%strikes,] tbl <- tbl[with(tbl,order(Expiry,Tenor,Spread)),] tbl3 <- tbl[tbl$Spread==0,] # atm vol matrix #atmMat=acast(tbl3,Expiry~Tenor,value.var = "LogNormalVol") atmMat=matrix(data=NA,nrow=length(expLvl),ncol=length(tenorLvl),dimnames=list(expLvl,tenorLvl)) for(i in 1:length(expLvl)){ for(j in 1:length(tenorLvl)){ atmMat[i,j]=tbl[tbl$Expiry==expLvl[i]& tbl$Tenor==tenorLvl[j] & tbl$Spread==0,]$LogNormalVol } } smirk=matrix(ncol=length(strikes),nrow=length(expLvl)*length(tenorLvl)) #tmp3=acast(tbl,Expiry~Tenor~Spread,value.var="LogNormalVol") k=0 for(i in 1:length(expLvl)){ for(j in 1:length(tenorLvl)){ k=k+1 for(n in 1:length(strikes)){ #smirk[k,]=tmp3[i,j,]-tmp3[i,j,"0"] smirk[k,n]=tbl[tbl$Expiry==expLvl[i]& tbl$Tenor==tenorLvl[j] & tbl$Spread==strikes[n],]$LogNormalVol - tbl[tbl$Expiry==expLvl[i]& tbl$Tenor==tenorLvl[j] & tbl$Spread==0,]$LogNormalVol } } } smirk <- na.spline(smirk,method="natural") tmp <- list(atmVol=atmMat,tenors=tenors,expiries=expiries,smirk=smirk,strikes=strikes/10000) class(tmp) <- "volcube" return(tmp) } RQuantLib/R/zzz.R0000644000176200001440000000333212714700225013275 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2016 Dirk Eddelbuettel ## ## 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 ) #} .onAttach <- function(libname, pkgname) { ## if it is not interactive (as eg in testing or cronjobs), do nothing if (!interactive()) return(invisible(NULL)) ## else let's test the QuantLib version, and then the intraday capability qlver <- getQuantLibVersion() if (compareVersion(qlver, "1.7") < 0) { packageStartupMessage("QuantLib version ", qlver, " detected which is older than 1.7.") packageStartupMessage("Intra-daily options analytics unavailable with that version.") } else if (!getQuantLibCapabilities()[["intradayDate"]]) { packageStartupMessage("Sufficient QuantLib version with insufficient configuration.") packageStartupMessage("Try configuring your build with the --enable-intraday argument.") } } RQuantLib/R/arrays.R0000644000176200001440000001474413416474164013764 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2014 Dirk Eddelbuettel ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . 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 <- europeanOptionEngine(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) 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 <- europeanOptionArraysEngine(type, as.matrix(pars)) ## 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) { if (requireNamespace("rgl", quietly=TRUE)) { 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); } } else { message("Please install the 'rgl' package before using this function.") } } utils::globalVariables(c("clear3d", "bg3d", "ligh3d", "rgl.viewpoint", "rgl.surface", "tgl.texts")) RQuantLib/R/implied.R0000644000176200001440000000757312315617667014114 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2014 Dirk Eddelbuettel ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . ## 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 <- europeanOptionImpliedVolatilityEngine(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) 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 <- americanOptionImpliedVolatilityEngine(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps, gridPoints) class(val) <- c("AmericanOptionImpliedVolatility","ImpliedVolatility") val } 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 <- binaryOptionImpliedVolatilityEngine(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) 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/discount.R0000644000176200001440000001045712714226467014311 0ustar liggesusers## RQuantLib function DiscountCurve ## ## Copyright (C) 2005 Dominick Samperi ## Copyright (C) 2007 - 2016 Dirk Eddelbuettel ## Copyright (C) 2009 - 2010 Dirk Eddelbuettel and Khanh Nguyen ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . DiscountCurve <- function(params, tsQuotes, times=seq(0,10,.1), legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual")) { UseMethod("DiscountCurve") } DiscountCurve.default <- function(params, tsQuotes, times=seq(0,10,.1), legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual")) { ## Check that params is properly formatted. if (!is.list(params) || length(params) == 0) { stop("The params parameter must be a non-empty list", call.=FALSE) } ## 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", call.=FALSE) } if (length(tsQuotes) != length(names(tsQuotes))) { stop("Term structure quotes must include labels", call.=FALSE) } if (!is.numeric(unlist(tsQuotes))) { stop("Term structure quotes must have numeric values", call.=FALSE) } ## Check the times vector if (!is.numeric(times) || length(times) == 0) { stop("The times parameter must be a non-emptry numeric vector", call.=FALSE) } ## Finally ready to make the call... ##val <- .Call("DiscountCurve", params, tsQuotes, times, PACKAGE="RQuantLib") matchlegs<-matchParams(legparams) ##val <- discountCurveEngine(params, tsQuotes, times,matchCpnmonthFreq=as.integer(monthFreq)) val <- discountCurveEngine(params, tsQuotes, times,matchlegs) 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/schedule.R0000644000176200001440000000320712427163453014244 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2014 Michele Salvadore and Dirk Eddelbuettel ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . Schedule <- function(params){ UseMethod("Schedule") } Schedule.default <- function(params) { val <- 0 # check schedule params if (is.null(params$effectiveDate)){ stop("schedule effective date undefined.") } if (is.null(params$maturityDate)){ stop("schedule maturity date undefined.") } if (is.null(params$period)) params$period <- 'Semiannual' if (is.null(params$calendar)) params$calendar <- 'TARGET' if (is.null(params$businessDayConvention)) params$businessDayConvention <- 'Following' if (is.null(params$terminationDateConvention)) params$terminationDateConvention <- 'Following' if (is.null(params$dateGeneration)) params$dateGeneration <- 'Backward' if (is.null(params$endOfMonth)) params$endOfMonth <- 0 params <- matchParams(params) CreateSchedule(params) } RQuantLib/R/mod.R0000644000176200001440000000007512271333436013224 0ustar liggesusers #loadModule("BondsMod", TRUE) #loadModule("BlackMod", TRUE) RQuantLib/R/RcppExports.R0000644000176200001440000003220213607470337014741 0ustar liggesusers# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 affineWithRebuiltCurveEngine <- function(rparam, legparams, dateVec, zeroVec, swaptionMat, swapLengths, swaptionVols) { .Call(`_RQuantLib_affineWithRebuiltCurveEngine`, rparam, legparams, dateVec, zeroVec, swaptionMat, swapLengths, swaptionVols) } asianOptionEngine <- function(averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first, length, fixings) { .Call(`_RQuantLib_asianOptionEngine`, averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first, length, fixings) } binaryOptionEngine <- function(binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) { .Call(`_RQuantLib_binaryOptionEngine`, binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) } binaryOptionImpliedVolatilityEngine <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) { .Call(`_RQuantLib_binaryOptionImpliedVolatilityEngine`, type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) } barrierOptionEngine <- function(barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate) { .Call(`_RQuantLib_barrierOptionEngine`, barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate) } bermudanFromYieldEngine <- function(rparam, yield, swaptionMat, swapLengths, swaptionVols) { .Call(`_RQuantLib_bermudanFromYieldEngine`, rparam, yield, swaptionMat, swapLengths, swaptionVols) } bermudanWithRebuiltCurveEngine <- function(rparam, dateVec, zeroVec, swaptionMat, swapLengths, swaptionVols) { .Call(`_RQuantLib_bermudanWithRebuiltCurveEngine`, rparam, dateVec, zeroVec, swaptionMat, swapLengths, swaptionVols) } zeroPriceByYieldEngine <- function(yield, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate) { .Call(`_RQuantLib_zeroPriceByYieldEngine`, yield, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate) } zeroYieldByPriceEngine <- function(price, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate) { .Call(`_RQuantLib_zeroYieldByPriceEngine`, price, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate) } fixedRateBondYieldByPriceEngine <- function(settlementDays, price, cal, faceAmount, businessDayConvention, compound, redemption, dayCounter, frequency, maturityDate, issueDate, effectiveDate, rates) { .Call(`_RQuantLib_fixedRateBondYieldByPriceEngine`, settlementDays, price, cal, faceAmount, businessDayConvention, compound, redemption, dayCounter, frequency, maturityDate, issueDate, effectiveDate, rates) } fixedRateBondPriceByYieldEngine <- function(settlementDays, yield, cal, faceAmount, businessDayConvention, compound, redemption, dayCounter, frequency, maturityDate, issueDate, effectiveDate, rates) { .Call(`_RQuantLib_fixedRateBondPriceByYieldEngine`, settlementDays, yield, cal, faceAmount, businessDayConvention, compound, redemption, dayCounter, frequency, maturityDate, issueDate, effectiveDate, rates) } FloatBond1 <- function(bond, gearings, caps, spreads, floors, indexparams, index, discountCurve, dateparams) { .Call(`_RQuantLib_FloatBond1`, bond, gearings, caps, spreads, floors, indexparams, index, discountCurve, dateparams) } FloatBond2 <- function(bond, gearings, caps, spreads, floors, indexparams, index_params, index_tsQuotes, index_times, discountCurve, dateparams) { .Call(`_RQuantLib_FloatBond2`, bond, gearings, caps, spreads, floors, indexparams, index_params, index_tsQuotes, index_times, discountCurve, dateparams) } FloatBond3 <- function(bond, gearings, caps, spreads, floors, indexparams, index, disc_params, disc_tsQuotes, disc_times, dateparams) { .Call(`_RQuantLib_FloatBond3`, bond, gearings, caps, spreads, floors, indexparams, index, disc_params, disc_tsQuotes, disc_times, dateparams) } FloatBond4 <- function(bond, gearings, caps, spreads, floors, indexparams, index_params, index_tsQuotes, index_times, disc_params, disc_tsQuotes, disc_times, dateparams) { .Call(`_RQuantLib_FloatBond4`, bond, gearings, caps, spreads, floors, indexparams, index_params, index_tsQuotes, index_times, disc_params, disc_tsQuotes, disc_times, dateparams) } floatingWithRebuiltCurveEngine <- function(bondparams, gearings, spreads, caps, floors, indexparams, iborDateVec, iborzeroVec, dateVec, zeroVec, dateparams) { .Call(`_RQuantLib_floatingWithRebuiltCurveEngine`, bondparams, gearings, spreads, caps, floors, indexparams, iborDateVec, iborzeroVec, dateVec, zeroVec, dateparams) } FixedRateWithYield <- function(bondparam, ratesVec, scheduleparam, calcparam, yield) { .Call(`_RQuantLib_FixedRateWithYield`, bondparam, ratesVec, scheduleparam, calcparam, yield) } FixedRateWithPrice <- function(bondparam, ratesVec, scheduleparam, calcparam, price) { .Call(`_RQuantLib_FixedRateWithPrice`, bondparam, ratesVec, scheduleparam, calcparam, price) } FixedRateWithRebuiltCurve <- function(bondparam, ratesVec, scheduleparam, calcparam, dateVec, zeroVec) { .Call(`_RQuantLib_FixedRateWithRebuiltCurve`, bondparam, ratesVec, scheduleparam, calcparam, dateVec, zeroVec) } ZeroBondWithRebuiltCurve <- function(bond, dateVec, zeroVec, dateparams) { .Call(`_RQuantLib_ZeroBondWithRebuiltCurve`, bond, dateVec, zeroVec, dateparams) } convertibleZeroBondEngine <- function(rparam, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, dividendScheduleFrame, callabilityScheduleFrame, datemisc) { .Call(`_RQuantLib_convertibleZeroBondEngine`, rparam, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, dividendScheduleFrame, callabilityScheduleFrame, datemisc) } convertibleFixedBondEngine <- function(rparam, rates, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, dividendScheduleFrame, callabilityScheduleFrame, datemisc) { .Call(`_RQuantLib_convertibleFixedBondEngine`, rparam, rates, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, dividendScheduleFrame, callabilityScheduleFrame, datemisc) } convertibleFloatingBondEngine <- function(rparam, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, iborIndexDateVec, iborIndexZeroVec, iborparams, spreads, dividendScheduleFrame, callabilityScheduleFrame, datemisc) { .Call(`_RQuantLib_convertibleFloatingBondEngine`, rparam, processParam, dividendYieldDateVec, dividendYieldZeroVec, rffDateVec, rffZeroVec, iborIndexDateVec, iborIndexZeroVec, iborparams, spreads, dividendScheduleFrame, callabilityScheduleFrame, datemisc) } callableBondEngine <- function(rparam, hwparam, coupon, callabilityScheduleFrame, datemisc) { .Call(`_RQuantLib_callableBondEngine`, rparam, hwparam, coupon, callabilityScheduleFrame, datemisc) } fittedBondCurveEngine <- function(curveparam, length, coupons, marketQuotes, datemisc) { .Call(`_RQuantLib_fittedBondCurveEngine`, curveparam, length, coupons, marketQuotes, datemisc) } setCalendarContext <- function(calendar, fixingDays, settleDate) { .Call(`_RQuantLib_setCalendarContext`, calendar, fixingDays, settleDate) } isBusinessDay <- function(calendar, dates) { .Call(`_RQuantLib_isBusinessDay`, calendar, dates) } isHoliday <- function(calendar, dates) { .Call(`_RQuantLib_isHoliday`, calendar, dates) } isWeekend <- function(calendar, dates) { .Call(`_RQuantLib_isWeekend`, calendar, dates) } isEndOfMonth <- function(calendar, dates) { .Call(`_RQuantLib_isEndOfMonth`, calendar, dates) } getEndOfMonth <- function(calendar, dates) { .Call(`_RQuantLib_getEndOfMonth`, calendar, dates) } adjust <- function(calendar, dates, bdc = 0L) { .Call(`_RQuantLib_adjust`, calendar, dates, bdc) } advance1 <- function(calendar, amount, unit, bdcVal, emr, dates) { .Call(`_RQuantLib_advance1`, calendar, amount, unit, bdcVal, emr, dates) } advance2 <- function(calendar, period, bdcVal, emr, dates) { .Call(`_RQuantLib_advance2`, calendar, period, bdcVal, emr, dates) } businessDaysBetween <- function(calendar, from, to, includeFirst = TRUE, includeLast = FALSE) { .Call(`_RQuantLib_businessDaysBetween`, calendar, from, to, includeFirst, includeLast) } getHolidayList <- function(calendar, from, to, includeWeekends = FALSE) { .Call(`_RQuantLib_getHolidayList`, calendar, from, to, includeWeekends) } addHolidays <- function(calendar, dates) { invisible(.Call(`_RQuantLib_addHolidays`, calendar, dates)) } removeHolidays <- function(calendar, dates) { invisible(.Call(`_RQuantLib_removeHolidays`, calendar, dates)) } advanceDate <- function(issueDate, days) { .Call(`_RQuantLib_advanceDate`, issueDate, days) } dayCount <- function(startDates, endDates, dayCounters) { .Call(`_RQuantLib_dayCount`, startDates, endDates, dayCounters) } yearFraction <- function(startDates, endDates, dayCounters) { .Call(`_RQuantLib_yearFraction`, startDates, endDates, dayCounters) } setEvaluationDate <- function(evalDate) { .Call(`_RQuantLib_setEvaluationDate`, evalDate) } discountCurveEngine <- function(rparams, tslist, times, legParams) { .Call(`_RQuantLib_discountCurveEngine`, rparams, tslist, times, legParams) } calibrateHullWhiteUsingCapsEngine <- function(termStrcDateVec, termStrcZeroVec, capDF, iborDateVec, iborZeroVec, iborType, evalDate) { .Call(`_RQuantLib_calibrateHullWhiteUsingCapsEngine`, termStrcDateVec, termStrcZeroVec, capDF, iborDateVec, iborZeroVec, iborType, evalDate) } calibrateHullWhiteUsingSwapsEngine <- function(termStrcDateVec, termStrcZeroVec, swapDF, iborDateVec, iborZeroVec, iborType, evalDate) { .Call(`_RQuantLib_calibrateHullWhiteUsingSwapsEngine`, termStrcDateVec, termStrcZeroVec, swapDF, iborDateVec, iborZeroVec, iborType, evalDate) } europeanOptionImpliedVolatilityEngine <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) { .Call(`_RQuantLib_europeanOptionImpliedVolatilityEngine`, type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volatility) } americanOptionImpliedVolatilityEngine <- function(type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volguess, timesteps, gridpoints) { .Call(`_RQuantLib_americanOptionImpliedVolatilityEngine`, type, value, underlying, strike, dividendYield, riskFreeRate, maturity, volguess, timesteps, gridpoints) } sabrengine <- function(rparam, legParams, dateVec, zeroVec, swaptionMat, swapLengths, atmVols, strikes, smirkVols) { .Call(`_RQuantLib_sabrengine`, rparam, legParams, dateVec, zeroVec, swaptionMat, swapLengths, atmVols, strikes, smirkVols) } CreateSchedule <- function(params) { .Call(`_RQuantLib_CreateSchedule`, params) } #' This function returns the QuantLib version string as encoded in the header #' file \code{config.hpp} and determined at compilation time of the QuantLib library. #' #' @title Return the QuantLib version number #' @return A character variable #' @references \url{http://quantlib.org} for details on \code{QuantLib}. #' @author Dirk Eddelbuettel #' @examples #' getQuantLibVersion() getQuantLibVersion <- function() { .Call(`_RQuantLib_getQuantLibVersion`) } #' This function returns a named vector of boolean variables describing several #' configuration options determined at compilation time of the QuantLib library. #' #' Not all of these features are used (yet) by RQuantLib. #' @title Return configuration options of the QuantLib library #' @return A named vector of logical variables #' @references \url{http://quantlib.org} for details on \code{QuantLib}. #' @author Dirk Eddelbuettel #' @examples #' getQuantLibCapabilities() getQuantLibCapabilities <- function() { .Call(`_RQuantLib_getQuantLibCapabilities`) } europeanOptionEngine <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, discreteDividends, discreteDividendsTimeUntil) { .Call(`_RQuantLib_europeanOptionEngine`, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, discreteDividends, discreteDividendsTimeUntil) } americanOptionEngine <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps, gridPoints, engine, discreteDividends, discreteDividendsTimeUntil) { .Call(`_RQuantLib_americanOptionEngine`, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps, gridPoints, engine, discreteDividends, discreteDividendsTimeUntil) } europeanOptionArraysEngine <- function(type, par) { .Call(`_RQuantLib_europeanOptionArraysEngine`, type, par) } zeroprice <- function(yield, maturity, settle, period, basis) { .Call(`_RQuantLib_zeroprice`, yield, maturity, settle, period, basis) } zeroyield <- function(price, maturity, settle, period, basis) { .Call(`_RQuantLib_zeroyield`, price, maturity, settle, period, basis) } # Register entry points for exported C++ functions methods::setLoadAction(function(ns) { .Call('_RQuantLib_RcppExport_registerCCallable', PACKAGE = 'RQuantLib') }) RQuantLib/R/calendars.R0000644000176200001440000001344112313432536014400 0ustar liggesusers## 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) 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") val <- advance1(calendar, n, timeUnit, bdc, emr, dates) } if (call2) { ## val <- .Call("advance2", ## calendar, ## list(period = as.double(period), ## bdc = as.double(bdc), ## emr = as.double(emr)), ## dates, ## PACKAGE="RQuantLib") val <- advance2(calendar, period, bdc, emr, dates) } 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=FALSE) { 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/asian.R0000644000176200001440000000500612347554037013545 0ustar liggesusers ## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2014 Dirk Eddelbuettel ## Copyright (C) 2009 Khanh Nguyen ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . 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=11.0/12.0, fixings=26) { 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 <- asianOptionEngine(averageType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, first, length, fixings) 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/bond.R0000644000176200001440000007447312722576357013420 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2014 Dirk Eddelbuettel ## Copyright (C) 2009 Khanh Nguyen ## Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Khanh Nguyen ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . ZeroCouponBond <- function(bond, discountCurve, dateparams ) { UseMethod("ZeroCouponBond") } ## TODO: redo interface here ZeroCouponBond.default <- function(bond, discountCurve, dateparams=list(refDate=bond$issueDate, settlementDays=1, calendar='UnitedStates/GovernmentBond', 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 <- 'UnitedStates/GovernmentBond' if (is.null(dateparams$businessDayConvention)) dateparams$businessDayConvention <- 'Following' if (is.null(dateparams$refDate)) dateparams$refDate <- bond$issueDate dateparams <- matchParams(dateparams) val <- ZeroBondWithRebuiltCurve(bond, c(discountCurve$table$date), discountCurve$table$zeroRates, dateparams) 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 <- zeroPriceByYieldEngine(yield, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate) 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 <- zeroYieldByPriceEngine(price, faceAmount, dayCounter, frequency, businessDayConvention, compound, maturityDate, issueDate) class(val) <- c("ZeroYield") val } FixedRateBond <- function(bond, rates, schedule, calc, discountCurve, yield, price){ UseMethod("FixedRateBond") } FixedRateBond.default <- function(bond = list(), rates, schedule, calc=list( dayCounter='ActualActual.ISMA', compounding='Compounded', freq='Annual', durationType='Modified'), discountCurve = NULL, yield = NA, price = NA){ val <- 0 # check bond params if (is.null(bond$settlementDays)) bond$settlementDays <- 1 if (is.null(bond$faceAmount)) bond$faceAmount <- 100 if (is.null(bond$dayCounter)) bond$dayCounter <- 'Thirty360' # additional parameters have default values on cpp side (see QuantLib::FixedRateBond first ctor) # paymentConvention # redemption # issueDate # paymentCalendar # exCouponPeriod # exCouponCalendar # exCouponConvention # exCouponEndOfMonth bond <- matchParams(bond) # check schedule params if (is.null(schedule$effectiveDate)){ stop("schedule effective date undefined.") } if (is.null(schedule$maturityDate)){ stop("schedule maturity date undefined.") } if (is.null(schedule$period)) schedule$period <- 'Semiannual' if (is.null(schedule$calendar)) schedule$calendar <- 'TARGET' if (is.null(schedule$businessDayConvention)) schedule$businessDayConvention <- 'Following' if (is.null(schedule$terminationDateConvention)) schedule$terminationDateConvention <- 'Following' if (is.null(schedule$dateGeneration)) schedule$dateGeneration <- 'Backward' if (is.null(schedule$endOfMonth)) schedule$endOfMonth <- 0 schedule <- matchParams(schedule) # check calc params if (is.null(calc$dayCounter)) calc$dayCounter <- 'ActualActual.ISMA' if (is.null(calc$compounding)) calc$compounding <- 'Compounded' if (is.null(calc$freq)) calc$freq <- 'Annual' if (is.null(calc$durationType)) calc$durationType <- 'Simple' if (is.null(calc$accuracy)) calc$accuracy <- 1.0e-8 if (is.null(calc$maxEvaluations)) calc$maxEvaluations <- 100 calc <- matchParams(calc) which.calc <- !c(is.null(discountCurve), is.na(yield), is.na(price)) if (sum(which.calc) != 1) stop("one and only one of discountCurve, yield or price must be defined.") if (!is.null(discountCurve)) { val <- FixedRateWithRebuiltCurve( bond, rates, schedule, calc, c(discountCurve$table$date), discountCurve$table$zeroRates) } else if (!is.na(yield)) { val <- FixedRateWithYield(bond, rates, schedule, calc, yield) } else if (!is.na(price)) { val <- FixedRateWithPrice(bond, rates, schedule, calc, price) } 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 = "UnitedStates/GovernmentBond", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption = 100, issueDate) { val <- fixedRateBondYieldByPriceEngine(settlementDays, price, calendar, faceAmount, businessDayConvention, compound, redemption, dayCounter, period, ## aka frequency maturityDate, issueDate, effectiveDate, rates) 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 = "UnitedStates/GovernmentBond", rates, dayCounter=2, businessDayConvention=0, compound = 0, redemption = 100, issueDate) { val <- fixedRateBondPriceByYieldEngine(settlementDays, yield, calendar, faceAmount, businessDayConvention, compound, redemption, dayCounter, period, maturityDate, issueDate, effectiveDate, rates) class(val) <- c("FixedRateBondPriceByYield") val } FloatingRateBond <- function(bond, gearings, spreads, caps, floors, index, curve, dateparams){ UseMethod("FloatingRateBond") } FloatingRateBond.default <- function(bond, gearings=vector(), spreads=vector(), caps=vector(), floors=vector(), index, curve, dateparams=list(refDate=bond$issueDate-2, settlementDays=1, calendar='UnitedStates/GovernmentBond', 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 <- 'UnitedStates/GovernmentBond' 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 <- floatingWithRebuiltCurveEngine(bond, gearings, spreads, caps, floors, indexparams, c(ibor$table$date), ibor$table$zeroRates, c(curve$table$date), curve$table$zeroRates, dateparams) class(val) <- c("FloatingRateBond", "Bond") val } ConvertibleZeroCouponBond <- function(bondparams, process, dateparams){ UseMethod("ConvertibleZeroCouponBond") } ConvertibleZeroCouponBond.default <- function(bondparams, process, dateparams=list( settlementDays=1, calendar='UnitedStates/GovernmentBond', 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 <- 'UnitedStates/GovernmentBond' 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 <- convertibleZeroBondEngine(bondparams, process, c(dividendYield$table$date), dividendYield$table$zeroRates, c(riskFreeRate$table$date), riskFreeRate$table$zeroRates, dividendSchedule, callabilitySchedule, dateparams) 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='UnitedStates/GovernmentBond', 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 <- 'UnitedStates/GovernmentBond' 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 <- convertibleFixedBondEngine(bondparams, coupon, process, c(dividendYield$table$date), dividendYield$table$zeroRates, c(riskFreeRate$table$date), riskFreeRate$table$zeroRates, dividendSchedule, callabilitySchedule, dateparams) 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='UnitedStates/GovernmentBond', 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 <- 'UnitedStates/GovernmentBond' 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 <- convertibleFloatingBondEngine(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) 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='UnitedStates/GovernmentBond', 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 <- 'UnitedStates/GovernmentBond' 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 <- callableBondEngine(bondparams, hullWhite,coupon, ## c(hw.termStructure$table$date), ## hw.termStructure$table$zeroRates, callSch, dateparams) 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 <- fittedBondCurveEngine(curveparams, lengths, coupons, marketQuotes, dateparams) 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", "Actual365NoLeap", "ActualActual.ISMA", "ActualActual.Bond", "ActualActual.ISDA", "ActualActual.Historical", "ActualActual.AFB", "ActualActual.Euro")) { 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, Actual365NoLeap = 7, ActualActual.ISMA = 8, ActualActual.Bond = 9, ActualActual.ISDA = 10, ActualActual.Historical = 11, ActualActual.AFB = 12, ActualActual.Euro = 13) } daycounter } matchBDC <- function(bdc = c("Following", "ModifiedFollowing", "Preceding", "ModifiedPreceding", "Unadjusted", "HalfMonthModifiedFollowing", "Nearest")) { if (!is.numeric(bdc)){ bdc <- match.arg(bdc) bdc <- switch(bdc, Following = 0, ModifiedFollowing = 1, Preceding = 2, ModifiedPreceding = 3, Unadjusted = 4, HalfMonthModifiedFollowing = 5, Nearest = 6) } 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", "Monthly", "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 } matchFloatFrequency <- function(freq = c( "Annual", "Semiannual", "EveryFourthMonth", "Quarterly", "Bimonthly", "Monthly")) { if (!is.numeric(freq)){ freq <- match.arg(freq) freq <- switch(freq, Annual = 12, Semiannual = 6, EveryFourthMonth = 4, Quarterly = 3, Bimonthly = 2, Monthly = 1) } freq } matchDateGen <- function(dg = c("Backward", "Forward", "Zero", "ThirdWednesday", "Twentieth", "TwentiethIMM", "OldCDS", "CDS")){ if (!is.numeric(dg)){ dg <- match.arg(dg) dg <- switch(dg, Backward = 0, Forward = 1, Zero = 2, ThirdWednesday = 3, Twentieth = 4, TwentiethIMM = 5, OldCDS=6, CDS=7) } dg } matchDurationType <- function(dt = c("Simple", "Macaulay", "Modified")) { if (!is.numeric(dt)){ dt <- match.arg(dt) dt <- switch(dt, Simple = 0, Macaulay = 1, Modified = 2) } dt } matchParams <- function(params) { if (!is.null(params$dayCounter)) { params$dayCounter <- matchDayCounter(params$dayCounter) } if (!is.null(params$compounding)) { params$compounding <- matchCompounding(params$compounding) } if (!is.null(params$period)) { params$period <- matchFrequency(params$period) } if (!is.null(params$freq)) { params$freq <- matchFrequency(params$freq) } if (!is.null(params$fixFreq)) { params$fixFreq <- matchFrequency(params$fixFreq) } if (!is.null(params$floatFreq)) { params$floatFreq <- matchFloatFrequency(params$floatFreq) } if (!is.null(params$businessDayConvention)) { params$businessDayConvention <- matchBDC(params$businessDayConvention) } if (!is.null(params$terminationDateConvention)) { params$terminationDateConvention <- matchBDC(params$terminationDateConvention) } if (!is.null(params$paymentConvention)) { params$paymentConvention <- matchBDC(params$paymentConvention) } if (!is.null(params$exCouponConvention)) { params$exCouponConvention <- matchBDC(params$exCouponConvention) } 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) } if (!is.null(params$durationType)) { params$durationType <- matchDurationType(params$durationType) } 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) } print.FixedRateBond <- 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(" duration : ", format(x$duration, digits=digits), "\n") cat(" settlement date : ", format(x$settlementDate, format="%Y-%m-%d"), "\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/option.R0000644000176200001440000001164113005133672013752 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2002 - 2016 Dirk Eddelbuettel ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . EuropeanOption <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, discreteDividends = NULL, discreteDividendsTimeUntil = NULL) { UseMethod("EuropeanOption") } EuropeanOption.default <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, discreteDividends = NULL, discreteDividendsTimeUntil = NULL) { type <- match.arg(type, c("call", "put")) val <- europeanOptionEngine(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, discreteDividends, discreteDividendsTimeUntil) class(val) <- c("EuropeanOption", "Option") val } AmericanOption <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=149, engine="BaroneAdesiWhaley", discreteDividends = NULL, discreteDividendsTimeUntil = NULL) { UseMethod("AmericanOption") } AmericanOption.default <- function(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps=150, gridPoints=149, engine="BaroneAdesiWhaley", discreteDividends = NULL, discreteDividendsTimeUntil = NULL) { type <- match.arg(type, c("call", "put")) engine <- match.arg(engine, c("BaroneAdesiWhaley", "CrankNicolson")) val <- americanOptionEngine(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, timeSteps, gridPoints, engine, discreteDividends, discreteDividendsTimeUntil) 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 <- binaryOptionEngine(binType, type, excType, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, cashPayoff) 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 <- barrierOptionEngine(barrType, type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility, barrier, rebate) 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/dayCounter.R0000644000176200001440000000250012313406102014541 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2010 - 2011 Dirk Eddelbuettel and Khanh Nguyen ## Copyright (C) 2012 - 2014 Dirk Eddelbuettel ## ## 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/hullWhiteCalibration.R0000644000176200001440000000402112315613340016547 0ustar liggesusers## RQuantLib -- R interface to the QuantLib libraries ## ## Copyright (C) 2010 Dirk Eddelbuettel and Khanh Nguyen ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . hullWhiteCalibrateUsingCap <- function(termStrc, capHelpers, index, evaluationDate) { capData <- capHelpers$data ibor <- index$term val <- calibrateHullWhiteUsingCapsEngine(termStrc$table$date, termStrc$table$zeroRates, capData, ibor$table$date, ibor$table$zeroRates, index$type, evaluationDate) } hullWhiteCalibrateUsingSwap <- function(termStrc, swapHelpers, index, evaluationDate) { swapData <- swapHelpers$data ibor <- index$term val <- calibrateHullWhiteUsingSwapsEngine(termStrc$table$date, termStrc$table$zeroRates, swapData, ibor$table$date, ibor$table$zeroRates, index$type, evaluationDate) } RQuantLib/R/affine.R0000644000176200001440000001571312714226467013711 0ustar liggesusers## RQuantLib function AffineSwaption ## ## Copyright (C) 2005 Dominick Samperi ## Copyright (C) 2007 - 2014 Dirk Eddelbuettel ## Copyright (C) 2016 Terry Leitch and Dirk Eddelbuettel ## ## This file is part of RQuantLib. ## ## RQuantLib 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. ## ## RQuantLib 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 RQuantLib. If not, see . AffineSwaption <- function(params, ts, swaptionMaturities, swapTenors, volMatrix, legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual")) { UseMethod("AffineSwaption") } AffineSwaption.default <- function(params, ts, swaptionMaturities, swapTenors, volMatrix, legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual")) { # Check that params list names if (!is.list(params) || length(params) == 0) { stop("The params parameter must be a non-empty list", call.=FALSE) } if(is.null(params$startDate)){ params$startDate=advance("UnitedStates",params$tradeDate, 1, 3) warning("swaption start date not set, defaulting to 1 year from trade date using US calendar") } if(is.null(params$maturity)){ params$maturity=advance("UnitedStates",params$startDate, 5, 3) warning("swaption maturity not set, defaulting to 5 years from startDate using US calendar") } if(is.null(params$european)){ params$european=TRUE warning("affine swaption european flag not set defaulting to european") } if(is.null(params$payFix)){ params$payFix=TRUE warning("affine swaption payFix flag not set defaulting to pay fix swap") } matYears=as.numeric(params$maturity-params$tradeDate)/365 expYears=as.numeric(params$startDate-params$tradeDate)/365 increment=min(matYears/6,1.0) numObs=floor(matYears/increment)+1 optStart=as.numeric(params$startDate-params$tradeDate)/365 # find closest option to our target to ensure it is in calibration tenor=expiry=vol=vector(length=numObs,mode="numeric") expiryIDX=findInterval(expYears,swaptionMaturities) tenorIDX=findInterval(matYears-expYears,swapTenors) if(tenorIDX >0 & expiryIDX>0){ vol[1]=volMatrix[expiryIDX,tenorIDX] expiry[1]=swaptionMaturities[expiryIDX] tenor[1]=swapTenors[tenorIDX] } else { vol[1]=expiry[1]=tenor[1]=0 } for(i in 2:numObs){ expiryIDX=findInterval(i*increment,swaptionMaturities) tenorIDX=findInterval(matYears-(i-1)*increment,swapTenors) if(tenorIDX >0 & expiryIDX>0){ vol[i]=volMatrix[expiryIDX,tenorIDX] expiry[i]=swaptionMaturities[expiryIDX] tenor[i]=swapTenors[tenorIDX] } else { vol[i]=volMatrix[expiryIDX,tenorIDX+1] expiry[i]=swaptionMaturities[expiryIDX] tenor[i]=swapTenors[tenorIDX+1] } } # remove if search was out of bounds expiry=expiry[expiry>0];tenor=tenor[tenor>0];vol=vol[vol>0] if(length(expiry)<5){ warning("Insufficent vols to fit affine model") return(NULL) } #Take 1st 5 which includes closest to initial date expiry=expiry[1:5];tenor=tenor[1:5];vol=vol[1:5] # 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. if(class(ts)=="DiscountCurve"){ matchlegs<-matchParams(legparams) val <- affineWithRebuiltCurveEngine(params, matchlegs, c(ts$table$date), ts$table$zeroRates, expiry,tenor,vol) } else{ stop("DiscountCurve class term structure required", call.=FALSE) } class(val) <- paste(params$method, "AffineSwaption",sep="") summary(val) val } summary.G2AnalyticAffineSwaption <- function(object,...) { cat('\n\tSummary of pricing results for Affine Swaption\n') cat('\nPrice (in bp) of Affine swaption is ', object$NPV) cat('\nStike is ', format(object$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.HWAnalyticAffineSwaption <- function(object,...) { cat('\n\tSummary of pricing results for Affine Swaption\n') cat('\nPrice (in bp) of Affine swaption is ', object$NPV) 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.HWTreeAffineSwaption <- function(object,...) { cat('\n\tSummary of pricing results for Affine Swaption\n') cat('\nPrice (in bp) of Affine swaption is ', object$NPV) 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.BKTreeAffineSwaption <- function(object,...) { cat('\n\tSummary of pricing results for Affine Swaption\n') cat('\nPrice (in bp) of Affine swaption is ', object$NPV) 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/datasets.R0000644000176200001440000000102612750761663014263 0ustar liggesusers#' Vol Cube Example Data #' #' Data for valuing swaption examples including rates and a lognormal vol cube #' #' @name vcube #' @docType data #' @usage data(vcube) #' @format two data frames: \code{vcube}, a data frame with four columns: \code{Expiry}, \code{Tenor}, #' \code{LogNormalVol}, and \code{Spread} #' @source TBA NULL #' Vol Cube Example Data #' #' Short time series examples #' #' @name tsQuotes #' @docType data #' @format A series of tenors and rates approppriate for calling DiscountCurve #' @source TBA NULL RQuantLib/MD50000644000176200001440000001323713607525142012436 0ustar liggesusers08e1ef2465b146e614cb0fd971238cb3 *ChangeLog cc2c985d6b1ee6b8b774ad71baff029f *DESCRIPTION fd4e5b0b9cfeda5b3034514d07deb7b1 *NAMESPACE e20f180d3c8fa6c4b96362a509edfaab *R/RcppExports.R 5d5efe9f5ae1dda7ab086f659ec05ddf *R/affine.R e0a43a106b8da65a6392c6cdcf2a72cf *R/arrays.R 57a50637f99f34c9e4c7d8310a63978a *R/asian.R 33494316a2cdbe2c872270a650bbcc8f *R/bermudan.R 688fbc14f3e3150e1e524f57b58a07fd *R/bond.R 5359a7169e561feba933e2caea4b6058 *R/calendars.R c946fbb142fc1ad588319ecf5b3b6fba *R/datasets.R a0a4d7aa07a16c88bfcb94caf171b9b3 *R/dayCounter.R b573f804569873ce3c288f1c2c09a5d6 *R/discount.R b79175a852abf36508c1fe7c8be9546b *R/hullWhiteCalibration.R db5f0c220ccb7a54c72f7343a3279457 *R/implied.R 03c5562d493d8c2a9577aa3d3132d56d *R/inline.R 57bb1ee8b9bc6931658c5f4ef95f70e3 *R/mod.R 54ac323ca76afcebd9299156d48ad279 *R/option.R bf6c8d734ef487f50126aa256faecf27 *R/sabr.R 1820845115c19f810eb0ccc279e4cce2 *R/schedule.R 288f6267f18f8b1f59cd0888fcadced7 *R/zzz.R b30ca2ffbd669766645818cd0b1b2b2b *README.md 0b4e9a09b64bef80f5a626b72b29df56 *cleanup 1a19075ececf90a3305feeef786c78dd *configure b3b5bd2cacb0ee22ccd37c1e13af69a5 *configure.ac dc11205a07128f22d0b6133e899ed83e *data/tsQuotes.RData 4b82a9f5fa30a97f379b0f57da401322 *data/vcube.RData fd060754d818864ca897476ff2b58f16 *demo/00Index 62a5aa8589c12d27ae69ba05f8b84d60 *demo/OptionSurfaces.R 8887075c0be0b9a5ed5368d8b7b5333e *demo/ShinyDiscountCurves.R 2adf2228c562c11831db1d7ee0480cc6 *inst/Boost_LICENSE.TXT cb5542d3dc00f3e1cdb6e22611eb359c *inst/NEWS.Rd 6ce07e1e9679d2c63ff4fe0bece5ad05 *inst/QuantLib_LICENSE.TXT f4b079613d0dee5843973b30e0b6aa77 *inst/include/RQuantLib.h 791e66a357ffc678d4be05d136ef6880 *inst/include/RQuantLib_RcppExports.h b44e152e6474102c15d3a93e362061f8 *inst/include/rquantlib_impl.h 253fc3d4ffbb1f23f6af76d93c2f3282 *inst/include/rquantlib_internal.h 001d1eea5707e1b3369e95ee2165ad74 *inst/include/rquantlib_wrappers.h 11c98a9cc1dbd4604c20ad86cb85fff8 *inst/shiny/DiscountCurve/server.R 397d98cb41922fe368e6f0701d36d1f0 *inst/shiny/DiscountCurve/ui.R 078ee9b3bbaadf65afbfceded0d9d7e9 *inst/shiny/SabrSwaption/README.md c56b0b08e1ee51334d5c2b76683ce3ec *inst/shiny/SabrSwaption/server.R f278368b4f4e603e0a936c0c6691fba2 *inst/shiny/SabrSwaption/ui.R ad9146ee33b853d522f948f4923ec75b *inst/shiny/SabrSwaption/volDF2CubeK.R d8edd335ab2b7b0727a002c0ddf5cc39 *inst/shiny/SabrSwaption/volcube.csv ca4e6472c457a1e9ade2b7f87a3a475c *inst/tinytest/cpp/dates.cpp 641daa9e7373fdc1e507e879d655af01 *inst/tinytest/test_businessdayconvention.R 3438bf4439d2f76c5ebb691364406dae *inst/tinytest/test_calendar.R a5e06c136e92019946a502841ecf3b5a *inst/tinytest/test_dates.R aa5786a2297a9d8a764f8c36bd2832fc *inst/tinytest/test_options.R ac7d26d486a1fc334c78c53048231267 *inst/tinytest/test_schedule.R d0df7a3ba48e6d6413af6e8f813faf11 *man/AffineSwaption.Rd e574881bf44bc3323150fb2676ccbd15 *man/AmericanOption.Rd b230fb586d6b02d0749b039eb2357151 *man/AmericanOptionImpliedVolatility.Rd 43e9e78edb4d0019c736fe48fc56f8ae *man/AsianOption.Rd cac2420f20d7a3331d6c959f05076bdc *man/BarrierOption.Rd 5afcba45970e431d42e8c1c8e081f8f1 *man/BermudanSwaption.Rd b5901cf2ec226d511ef9b9bce1907364 *man/BinaryOption.Rd 5b225518ded59a705d75ce69e018f86c *man/BinaryOptionImpliedVolatility.Rd f13cf2b137f36da3d7d899b21590ac02 *man/Bond.Rd 8e030354a5f4d2acf27f639980f1235e *man/BondUtilities.Rd ed1bcf0f8fc66084524fa338fd062941 *man/Calendars.Rd 473109993119589c830f77680da376ef *man/CallableBond.Rd 81751c2296f0621a42cbb3170c041c0c *man/ConvertibleBond.Rd 257863d0ababa438a0295cbe3cd923d8 *man/DiscountCurve.Rd d16b27172f5469df34e4b4dbde35304e *man/Enum.Rd 2da45ba14b5528f32732bad58dfebd9c *man/EuropeanOption.Rd cce9ceb3c8194401944cec9f72cbd62d *man/EuropeanOptionArrays.Rd 62ce2197ced8428b3987aafb290715d6 *man/EuropeanOptionImpliedVolatility.Rd 1216d35992e95d5e8a8173585d64a39b *man/FittedBondCurve.Rd 1e6fea63a541c6ccb8b52daf6a0f4481 *man/FixedRateBond.Rd 6bd8af55dc953ce448c8e60e3f4b3f88 *man/FloatingRateBond.Rd 88869f4c09f5e53a872f6fe2d5210209 *man/ImpliedVolatility.Rd 1bc2affd56ddfc25d6f51a1a875e88ea *man/Option.Rd 6c40287f7c89df7340c927b9ff5bda1f *man/SabrSwaption.Rd b2b1d77fffee3143786590f0e4e0469c *man/Schedule.Rd e869bc6837478de1c47c9c89aba0f36d *man/ZeroCouponBond.Rd c55baa35f3fe3e75db988698813e2cbc *man/getQuantLibCapabilities.Rd b8b0df9181baa1211bd632dcb4990a33 *man/getQuantLibVersion.Rd 0abdd3c24763fc0d991155276b2f7577 *man/tsQuotes.Rd b132afe2925ac2a027e19002d40ed388 *man/vcube.Rd f209270a4cd2342d9fbaded6b0a7e367 *src/Makevars.in a19f73fcb8ff523ff022495e85c3a764 *src/Makevars.win 388e1a25300537b81e4d2031fb1c12c5 *src/RcppExports.cpp e96f635b189e057954f9caee4f963daf *src/affine.cpp 708dbbf8e651b8828b2c3184099668d7 *src/asian.cpp 0cbd4e6d1943c5f1b2727fd0edb22217 *src/barrier_binary.cpp 7f27b1a94b8033fd7a6bfc6692dc38de *src/bermudan.cpp 385d940b17803c6ba6853af087e25f1c *src/bonds.cpp 5ced179d9a10bbda5b8da0b860a40eb9 *src/calendars.cpp 171ad8560f1716f5628509fee7eb1f8e *src/curves.cpp b467ede776a5f35074b1b13011686dbe *src/dates.cpp 99eb924b6326ccef0f2d4e17b28e7790 *src/daycounter.cpp 5cbf1e336e97a65e20fdd61dc27aee44 *src/deprecated/rquantlib.h 131e4777691240ada887bb6d5f6251f1 *src/discount.cpp 70f8bb5e9d6666a6561e084c8f398d9e *src/hullwhite.cpp ca2ad5bb042b4dee35cd49d50ca4d607 *src/implieds.cpp 30fc5d704106520e394d42a520045782 *src/modules.cpp 710193260bf5d5ff7b0e449da72a43b9 *src/sabr.cpp 5c3a8515fe3237dc4b6e0d05e0424ea5 *src/schedule.cpp aec4556256361b6755e886997371ee4d *src/utils.cpp 8c8f305292bfce82ae84fef58cd99ce2 *src/vanilla.cpp a61d2cb65d26a9be41dde42aa2475712 *src/zero.cpp 109f1aa5994f65aec7f0a6ee5cfedfc3 *tests/RQuantlib.R 8ec30eb98b0069708f04d87ef146fed0 *tests/tinytest.R 0e2ae09ae946a03f6e132b9aff0442ad *tools/build_RQuantLib.sh 2c7d9ecefcef479884a8f535560d46a7 *tools/winlibs.R RQuantLib/inst/0000755000176200001440000000000013564352402013074 5ustar liggesusersRQuantLib/inst/include/0000755000176200001440000000000013467001143014512 5ustar liggesusersRQuantLib/inst/include/rquantlib_impl.h0000644000176200001440000000504213443253624017715 0ustar liggesusers // RQuantLib wrapper implmenentation // // Copyright 2014 Dirk Eddelbuettel // // 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_impl_h_ #define _rquantlib_impl_h_ #include "rquantlib_internal.h" // define template specialisations for as and wrap namespace Rcpp { static const unsigned int QLtoJan1970Offset = 25569; // Offset to R / Unix epoch inline unsigned int getQLtoJan1970offset(void) { return QLtoJan1970Offset; } template <> QuantLib::Date as(SEXP dtsexp) { Rcpp::Date dt(dtsexp); return QuantLib::Date(static_cast(dt.getDate()) + QLtoJan1970Offset); } template <> SEXP wrap(const QuantLib::Date &d) { double dt = static_cast(d.serialNumber()); // QL::BigInteger can cast to double return Rcpp::wrap(Rcpp::Date(dt - QLtoJan1970Offset)); } // non-intrusive extension via template specialisation template <> std::vector as(SEXP dtvecsexp) { Rcpp::DateVector dtvec(dtvecsexp); int n = dtvec.size(); std::vector dates(n); for (int i = 0; i= Rcpp_Version(0,12,8) //dates[i] = QuantLib::Date(static_cast(dtvec[i]) + QLtoJan1970Offset); dates[i] = QuantLib::Date(static_cast(Rcpp::Date(dtvec[i]).getDate()) + QLtoJan1970Offset); #else dates[i] = QuantLib::Date(static_cast(dtvec[i].getDate()) + QLtoJan1970Offset); #endif } return dates; } // non-intrusive extension via template specialisation template <> SEXP wrap(const std::vector &dvec) { int n = dvec.size(); Rcpp::DateVector dtvec(n); for (int i = 0; i(dvec[i].serialNumber()); dtvec[i] = Rcpp::Date(dt - QLtoJan1970Offset); } return Rcpp::wrap(dtvec); } } #endif RQuantLib/inst/include/RQuantLib_RcppExports.h0000644000176200001440000013677613333110111021105 0ustar liggesusers// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #ifndef RCPP_RQuantLib_RCPPEXPORTS_H_GEN_ #define RCPP_RQuantLib_RCPPEXPORTS_H_GEN_ #include namespace RQuantLib { using namespace Rcpp; namespace { void validateSignature(const char* sig) { Rcpp::Function require = Rcpp::Environment::base_env()["require"]; require("RQuantLib", Rcpp::Named("quietly") = true); typedef int(*Ptr_validate)(const char*); static Ptr_validate p_validate = (Ptr_validate) R_GetCCallable("RQuantLib", "_RQuantLib_RcppExport_validate"); if (!p_validate(sig)) { throw Rcpp::function_not_exported( "C++ function with signature '" + std::string(sig) + "' not found in RQuantLib"); } } } inline double zeroPriceByYieldEngine(double yield, double faceAmount, double dayCounter, double frequency, double businessDayConvention, double compound, QuantLib::Date maturityDate, QuantLib::Date issueDate) { typedef SEXP(*Ptr_zeroPriceByYieldEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_zeroPriceByYieldEngine p_zeroPriceByYieldEngine = NULL; if (p_zeroPriceByYieldEngine == NULL) { validateSignature("double(*zeroPriceByYieldEngine)(double,double,double,double,double,double,QuantLib::Date,QuantLib::Date)"); p_zeroPriceByYieldEngine = (Ptr_zeroPriceByYieldEngine)R_GetCCallable("RQuantLib", "_RQuantLib_zeroPriceByYieldEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_zeroPriceByYieldEngine(Shield(Rcpp::wrap(yield)), Shield(Rcpp::wrap(faceAmount)), Shield(Rcpp::wrap(dayCounter)), Shield(Rcpp::wrap(frequency)), Shield(Rcpp::wrap(businessDayConvention)), Shield(Rcpp::wrap(compound)), Shield(Rcpp::wrap(maturityDate)), Shield(Rcpp::wrap(issueDate))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline double zeroYieldByPriceEngine(double price, double faceAmount, double dayCounter, double frequency, double businessDayConvention, double compound, QuantLib::Date maturityDate, QuantLib::Date issueDate) { typedef SEXP(*Ptr_zeroYieldByPriceEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_zeroYieldByPriceEngine p_zeroYieldByPriceEngine = NULL; if (p_zeroYieldByPriceEngine == NULL) { validateSignature("double(*zeroYieldByPriceEngine)(double,double,double,double,double,double,QuantLib::Date,QuantLib::Date)"); p_zeroYieldByPriceEngine = (Ptr_zeroYieldByPriceEngine)R_GetCCallable("RQuantLib", "_RQuantLib_zeroYieldByPriceEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_zeroYieldByPriceEngine(Shield(Rcpp::wrap(price)), Shield(Rcpp::wrap(faceAmount)), Shield(Rcpp::wrap(dayCounter)), Shield(Rcpp::wrap(frequency)), Shield(Rcpp::wrap(businessDayConvention)), Shield(Rcpp::wrap(compound)), Shield(Rcpp::wrap(maturityDate)), Shield(Rcpp::wrap(issueDate))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline double fixedRateBondYieldByPriceEngine(double settlementDays, double price, std::string cal, double faceAmount, double businessDayConvention, double compound, double redemption, double dayCounter, double frequency, QuantLib::Date maturityDate, QuantLib::Date issueDate, QuantLib::Date effectiveDate, std::vector rates) { typedef SEXP(*Ptr_fixedRateBondYieldByPriceEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_fixedRateBondYieldByPriceEngine p_fixedRateBondYieldByPriceEngine = NULL; if (p_fixedRateBondYieldByPriceEngine == NULL) { validateSignature("double(*fixedRateBondYieldByPriceEngine)(double,double,std::string,double,double,double,double,double,double,QuantLib::Date,QuantLib::Date,QuantLib::Date,std::vector)"); p_fixedRateBondYieldByPriceEngine = (Ptr_fixedRateBondYieldByPriceEngine)R_GetCCallable("RQuantLib", "_RQuantLib_fixedRateBondYieldByPriceEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_fixedRateBondYieldByPriceEngine(Shield(Rcpp::wrap(settlementDays)), Shield(Rcpp::wrap(price)), Shield(Rcpp::wrap(cal)), Shield(Rcpp::wrap(faceAmount)), Shield(Rcpp::wrap(businessDayConvention)), Shield(Rcpp::wrap(compound)), Shield(Rcpp::wrap(redemption)), Shield(Rcpp::wrap(dayCounter)), Shield(Rcpp::wrap(frequency)), Shield(Rcpp::wrap(maturityDate)), Shield(Rcpp::wrap(issueDate)), Shield(Rcpp::wrap(effectiveDate)), Shield(Rcpp::wrap(rates))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline double fixedRateBondPriceByYieldEngine(double settlementDays, double yield, std::string cal, double faceAmount, double businessDayConvention, double compound, double redemption, double dayCounter, double frequency, QuantLib::Date maturityDate, QuantLib::Date issueDate, QuantLib::Date effectiveDate, std::vector rates) { typedef SEXP(*Ptr_fixedRateBondPriceByYieldEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_fixedRateBondPriceByYieldEngine p_fixedRateBondPriceByYieldEngine = NULL; if (p_fixedRateBondPriceByYieldEngine == NULL) { validateSignature("double(*fixedRateBondPriceByYieldEngine)(double,double,std::string,double,double,double,double,double,double,QuantLib::Date,QuantLib::Date,QuantLib::Date,std::vector)"); p_fixedRateBondPriceByYieldEngine = (Ptr_fixedRateBondPriceByYieldEngine)R_GetCCallable("RQuantLib", "_RQuantLib_fixedRateBondPriceByYieldEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_fixedRateBondPriceByYieldEngine(Shield(Rcpp::wrap(settlementDays)), Shield(Rcpp::wrap(yield)), Shield(Rcpp::wrap(cal)), Shield(Rcpp::wrap(faceAmount)), Shield(Rcpp::wrap(businessDayConvention)), Shield(Rcpp::wrap(compound)), Shield(Rcpp::wrap(redemption)), Shield(Rcpp::wrap(dayCounter)), Shield(Rcpp::wrap(frequency)), Shield(Rcpp::wrap(maturityDate)), Shield(Rcpp::wrap(issueDate)), Shield(Rcpp::wrap(effectiveDate)), Shield(Rcpp::wrap(rates))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FloatBond1(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index, Rcpp::List discountCurve, Rcpp::List dateparams) { typedef SEXP(*Ptr_FloatBond1)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FloatBond1 p_FloatBond1 = NULL; if (p_FloatBond1 == NULL) { validateSignature("Rcpp::List(*FloatBond1)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); p_FloatBond1 = (Ptr_FloatBond1)R_GetCCallable("RQuantLib", "_RQuantLib_FloatBond1"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FloatBond1(Shield(Rcpp::wrap(bond)), Shield(Rcpp::wrap(gearings)), Shield(Rcpp::wrap(caps)), Shield(Rcpp::wrap(spreads)), Shield(Rcpp::wrap(floors)), Shield(Rcpp::wrap(indexparams)), Shield(Rcpp::wrap(index)), Shield(Rcpp::wrap(discountCurve)), Shield(Rcpp::wrap(dateparams))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FloatBond2(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index_params, Rcpp::List index_tsQuotes, Rcpp::List index_times, Rcpp::List discountCurve, Rcpp::List dateparams) { typedef SEXP(*Ptr_FloatBond2)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FloatBond2 p_FloatBond2 = NULL; if (p_FloatBond2 == NULL) { validateSignature("Rcpp::List(*FloatBond2)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); p_FloatBond2 = (Ptr_FloatBond2)R_GetCCallable("RQuantLib", "_RQuantLib_FloatBond2"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FloatBond2(Shield(Rcpp::wrap(bond)), Shield(Rcpp::wrap(gearings)), Shield(Rcpp::wrap(caps)), Shield(Rcpp::wrap(spreads)), Shield(Rcpp::wrap(floors)), Shield(Rcpp::wrap(indexparams)), Shield(Rcpp::wrap(index_params)), Shield(Rcpp::wrap(index_tsQuotes)), Shield(Rcpp::wrap(index_times)), Shield(Rcpp::wrap(discountCurve)), Shield(Rcpp::wrap(dateparams))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FloatBond3(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index, Rcpp::List disc_params, Rcpp::List disc_tsQuotes, Rcpp::List disc_times, Rcpp::List dateparams) { typedef SEXP(*Ptr_FloatBond3)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FloatBond3 p_FloatBond3 = NULL; if (p_FloatBond3 == NULL) { validateSignature("Rcpp::List(*FloatBond3)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); p_FloatBond3 = (Ptr_FloatBond3)R_GetCCallable("RQuantLib", "_RQuantLib_FloatBond3"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FloatBond3(Shield(Rcpp::wrap(bond)), Shield(Rcpp::wrap(gearings)), Shield(Rcpp::wrap(caps)), Shield(Rcpp::wrap(spreads)), Shield(Rcpp::wrap(floors)), Shield(Rcpp::wrap(indexparams)), Shield(Rcpp::wrap(index)), Shield(Rcpp::wrap(disc_params)), Shield(Rcpp::wrap(disc_tsQuotes)), Shield(Rcpp::wrap(disc_times)), Shield(Rcpp::wrap(dateparams))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FloatBond4(Rcpp::List bond, std::vector gearings, std::vector caps, std::vector spreads, std::vector floors, Rcpp::List indexparams, Rcpp::List index_params, Rcpp::List index_tsQuotes, Rcpp::List index_times, Rcpp::List disc_params, Rcpp::List disc_tsQuotes, Rcpp::List disc_times, Rcpp::List dateparams) { typedef SEXP(*Ptr_FloatBond4)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FloatBond4 p_FloatBond4 = NULL; if (p_FloatBond4 == NULL) { validateSignature("Rcpp::List(*FloatBond4)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List,Rcpp::List)"); p_FloatBond4 = (Ptr_FloatBond4)R_GetCCallable("RQuantLib", "_RQuantLib_FloatBond4"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FloatBond4(Shield(Rcpp::wrap(bond)), Shield(Rcpp::wrap(gearings)), Shield(Rcpp::wrap(caps)), Shield(Rcpp::wrap(spreads)), Shield(Rcpp::wrap(floors)), Shield(Rcpp::wrap(indexparams)), Shield(Rcpp::wrap(index_params)), Shield(Rcpp::wrap(index_tsQuotes)), Shield(Rcpp::wrap(index_times)), Shield(Rcpp::wrap(disc_params)), Shield(Rcpp::wrap(disc_tsQuotes)), Shield(Rcpp::wrap(disc_times)), Shield(Rcpp::wrap(dateparams))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List floatingWithRebuiltCurveEngine(Rcpp::List bondparams, std::vector gearings, std::vector spreads, std::vector caps, std::vector floors, Rcpp::List indexparams, std::vector iborDateVec, std::vector iborzeroVec, std::vector dateVec, std::vector zeroVec, Rcpp::List dateparams) { typedef SEXP(*Ptr_floatingWithRebuiltCurveEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_floatingWithRebuiltCurveEngine p_floatingWithRebuiltCurveEngine = NULL; if (p_floatingWithRebuiltCurveEngine == NULL) { validateSignature("Rcpp::List(*floatingWithRebuiltCurveEngine)(Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::List)"); p_floatingWithRebuiltCurveEngine = (Ptr_floatingWithRebuiltCurveEngine)R_GetCCallable("RQuantLib", "_RQuantLib_floatingWithRebuiltCurveEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_floatingWithRebuiltCurveEngine(Shield(Rcpp::wrap(bondparams)), Shield(Rcpp::wrap(gearings)), Shield(Rcpp::wrap(spreads)), Shield(Rcpp::wrap(caps)), Shield(Rcpp::wrap(floors)), Shield(Rcpp::wrap(indexparams)), Shield(Rcpp::wrap(iborDateVec)), Shield(Rcpp::wrap(iborzeroVec)), Shield(Rcpp::wrap(dateVec)), Shield(Rcpp::wrap(zeroVec)), Shield(Rcpp::wrap(dateparams))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FixedRateWithYield(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, double yield) { typedef SEXP(*Ptr_FixedRateWithYield)(SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FixedRateWithYield p_FixedRateWithYield = NULL; if (p_FixedRateWithYield == NULL) { validateSignature("Rcpp::List(*FixedRateWithYield)(Rcpp::List,std::vector,Rcpp::List,Rcpp::List,double)"); p_FixedRateWithYield = (Ptr_FixedRateWithYield)R_GetCCallable("RQuantLib", "_RQuantLib_FixedRateWithYield"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FixedRateWithYield(Shield(Rcpp::wrap(bondparam)), Shield(Rcpp::wrap(ratesVec)), Shield(Rcpp::wrap(scheduleparam)), Shield(Rcpp::wrap(calcparam)), Shield(Rcpp::wrap(yield))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FixedRateWithPrice(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, double price) { typedef SEXP(*Ptr_FixedRateWithPrice)(SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FixedRateWithPrice p_FixedRateWithPrice = NULL; if (p_FixedRateWithPrice == NULL) { validateSignature("Rcpp::List(*FixedRateWithPrice)(Rcpp::List,std::vector,Rcpp::List,Rcpp::List,double)"); p_FixedRateWithPrice = (Ptr_FixedRateWithPrice)R_GetCCallable("RQuantLib", "_RQuantLib_FixedRateWithPrice"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FixedRateWithPrice(Shield(Rcpp::wrap(bondparam)), Shield(Rcpp::wrap(ratesVec)), Shield(Rcpp::wrap(scheduleparam)), Shield(Rcpp::wrap(calcparam)), Shield(Rcpp::wrap(price))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List FixedRateWithRebuiltCurve(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam, Rcpp::List calcparam, std::vector dateVec, std::vector zeroVec) { typedef SEXP(*Ptr_FixedRateWithRebuiltCurve)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_FixedRateWithRebuiltCurve p_FixedRateWithRebuiltCurve = NULL; if (p_FixedRateWithRebuiltCurve == NULL) { validateSignature("Rcpp::List(*FixedRateWithRebuiltCurve)(Rcpp::List,std::vector,Rcpp::List,Rcpp::List,std::vector,std::vector)"); p_FixedRateWithRebuiltCurve = (Ptr_FixedRateWithRebuiltCurve)R_GetCCallable("RQuantLib", "_RQuantLib_FixedRateWithRebuiltCurve"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_FixedRateWithRebuiltCurve(Shield(Rcpp::wrap(bondparam)), Shield(Rcpp::wrap(ratesVec)), Shield(Rcpp::wrap(scheduleparam)), Shield(Rcpp::wrap(calcparam)), Shield(Rcpp::wrap(dateVec)), Shield(Rcpp::wrap(zeroVec))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List ZeroBondWithRebuiltCurve(Rcpp::List bond, std::vector dateVec, std::vector zeroVec, Rcpp::List dateparams) { typedef SEXP(*Ptr_ZeroBondWithRebuiltCurve)(SEXP,SEXP,SEXP,SEXP); static Ptr_ZeroBondWithRebuiltCurve p_ZeroBondWithRebuiltCurve = NULL; if (p_ZeroBondWithRebuiltCurve == NULL) { validateSignature("Rcpp::List(*ZeroBondWithRebuiltCurve)(Rcpp::List,std::vector,std::vector,Rcpp::List)"); p_ZeroBondWithRebuiltCurve = (Ptr_ZeroBondWithRebuiltCurve)R_GetCCallable("RQuantLib", "_RQuantLib_ZeroBondWithRebuiltCurve"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_ZeroBondWithRebuiltCurve(Shield(Rcpp::wrap(bond)), Shield(Rcpp::wrap(dateVec)), Shield(Rcpp::wrap(zeroVec)), Shield(Rcpp::wrap(dateparams))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List convertibleZeroBondEngine(Rcpp::List rparam, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { typedef SEXP(*Ptr_convertibleZeroBondEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_convertibleZeroBondEngine p_convertibleZeroBondEngine = NULL; if (p_convertibleZeroBondEngine == NULL) { validateSignature("Rcpp::List(*convertibleZeroBondEngine)(Rcpp::List,Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::DataFrame,Rcpp::DataFrame,Rcpp::List)"); p_convertibleZeroBondEngine = (Ptr_convertibleZeroBondEngine)R_GetCCallable("RQuantLib", "_RQuantLib_convertibleZeroBondEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_convertibleZeroBondEngine(Shield(Rcpp::wrap(rparam)), Shield(Rcpp::wrap(processParam)), Shield(Rcpp::wrap(dividendYieldDateVec)), Shield(Rcpp::wrap(dividendYieldZeroVec)), Shield(Rcpp::wrap(rffDateVec)), Shield(Rcpp::wrap(rffZeroVec)), Shield(Rcpp::wrap(dividendScheduleFrame)), Shield(Rcpp::wrap(callabilityScheduleFrame)), Shield(Rcpp::wrap(datemisc))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List convertibleFixedBondEngine(Rcpp::List rparam, Rcpp::NumericVector rates, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { typedef SEXP(*Ptr_convertibleFixedBondEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_convertibleFixedBondEngine p_convertibleFixedBondEngine = NULL; if (p_convertibleFixedBondEngine == NULL) { validateSignature("Rcpp::List(*convertibleFixedBondEngine)(Rcpp::List,Rcpp::NumericVector,Rcpp::List,std::vector,std::vector,std::vector,std::vector,Rcpp::DataFrame,Rcpp::DataFrame,Rcpp::List)"); p_convertibleFixedBondEngine = (Ptr_convertibleFixedBondEngine)R_GetCCallable("RQuantLib", "_RQuantLib_convertibleFixedBondEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_convertibleFixedBondEngine(Shield(Rcpp::wrap(rparam)), Shield(Rcpp::wrap(rates)), Shield(Rcpp::wrap(processParam)), Shield(Rcpp::wrap(dividendYieldDateVec)), Shield(Rcpp::wrap(dividendYieldZeroVec)), Shield(Rcpp::wrap(rffDateVec)), Shield(Rcpp::wrap(rffZeroVec)), Shield(Rcpp::wrap(dividendScheduleFrame)), Shield(Rcpp::wrap(callabilityScheduleFrame)), Shield(Rcpp::wrap(datemisc))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List convertibleFloatingBondEngine(Rcpp::List rparam, Rcpp::List processParam, std::vector dividendYieldDateVec, std::vector dividendYieldZeroVec, std::vector rffDateVec, std::vector rffZeroVec, std::vector iborIndexDateVec, std::vector iborIndexZeroVec, Rcpp::List iborparams, std::vector spreads, Rcpp::DataFrame dividendScheduleFrame, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { typedef SEXP(*Ptr_convertibleFloatingBondEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_convertibleFloatingBondEngine p_convertibleFloatingBondEngine = NULL; if (p_convertibleFloatingBondEngine == NULL) { validateSignature("Rcpp::List(*convertibleFloatingBondEngine)(Rcpp::List,Rcpp::List,std::vector,std::vector,std::vector,std::vector,std::vector,std::vector,Rcpp::List,std::vector,Rcpp::DataFrame,Rcpp::DataFrame,Rcpp::List)"); p_convertibleFloatingBondEngine = (Ptr_convertibleFloatingBondEngine)R_GetCCallable("RQuantLib", "_RQuantLib_convertibleFloatingBondEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_convertibleFloatingBondEngine(Shield(Rcpp::wrap(rparam)), Shield(Rcpp::wrap(processParam)), Shield(Rcpp::wrap(dividendYieldDateVec)), Shield(Rcpp::wrap(dividendYieldZeroVec)), Shield(Rcpp::wrap(rffDateVec)), Shield(Rcpp::wrap(rffZeroVec)), Shield(Rcpp::wrap(iborIndexDateVec)), Shield(Rcpp::wrap(iborIndexZeroVec)), Shield(Rcpp::wrap(iborparams)), Shield(Rcpp::wrap(spreads)), Shield(Rcpp::wrap(dividendScheduleFrame)), Shield(Rcpp::wrap(callabilityScheduleFrame)), Shield(Rcpp::wrap(datemisc))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List callableBondEngine(Rcpp::List rparam, Rcpp::List hwparam, Rcpp::NumericVector coupon, Rcpp::DataFrame callabilityScheduleFrame, Rcpp::List datemisc) { typedef SEXP(*Ptr_callableBondEngine)(SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_callableBondEngine p_callableBondEngine = NULL; if (p_callableBondEngine == NULL) { validateSignature("Rcpp::List(*callableBondEngine)(Rcpp::List,Rcpp::List,Rcpp::NumericVector,Rcpp::DataFrame,Rcpp::List)"); p_callableBondEngine = (Ptr_callableBondEngine)R_GetCCallable("RQuantLib", "_RQuantLib_callableBondEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_callableBondEngine(Shield(Rcpp::wrap(rparam)), Shield(Rcpp::wrap(hwparam)), Shield(Rcpp::wrap(coupon)), Shield(Rcpp::wrap(callabilityScheduleFrame)), Shield(Rcpp::wrap(datemisc))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List fittedBondCurveEngine(Rcpp::List curveparam, Rcpp::NumericVector length, Rcpp::NumericVector coupons, Rcpp::NumericVector marketQuotes, Rcpp::List datemisc) { typedef SEXP(*Ptr_fittedBondCurveEngine)(SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_fittedBondCurveEngine p_fittedBondCurveEngine = NULL; if (p_fittedBondCurveEngine == NULL) { validateSignature("Rcpp::List(*fittedBondCurveEngine)(Rcpp::List,Rcpp::NumericVector,Rcpp::NumericVector,Rcpp::NumericVector,Rcpp::List)"); p_fittedBondCurveEngine = (Ptr_fittedBondCurveEngine)R_GetCCallable("RQuantLib", "_RQuantLib_fittedBondCurveEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_fittedBondCurveEngine(Shield(Rcpp::wrap(curveparam)), Shield(Rcpp::wrap(length)), Shield(Rcpp::wrap(coupons)), Shield(Rcpp::wrap(marketQuotes)), Shield(Rcpp::wrap(datemisc))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline QuantLib::Date advanceDate(QuantLib::Date issueDate, int days) { typedef SEXP(*Ptr_advanceDate)(SEXP,SEXP); static Ptr_advanceDate p_advanceDate = NULL; if (p_advanceDate == NULL) { validateSignature("QuantLib::Date(*advanceDate)(QuantLib::Date,int)"); p_advanceDate = (Ptr_advanceDate)R_GetCCallable("RQuantLib", "_RQuantLib_advanceDate"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_advanceDate(Shield(Rcpp::wrap(issueDate)), Shield(Rcpp::wrap(days))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline std::vector dayCount(std::vector startDates, std::vector endDates, std::vector dayCounters) { typedef SEXP(*Ptr_dayCount)(SEXP,SEXP,SEXP); static Ptr_dayCount p_dayCount = NULL; if (p_dayCount == NULL) { validateSignature("std::vector(*dayCount)(std::vector,std::vector,std::vector)"); p_dayCount = (Ptr_dayCount)R_GetCCallable("RQuantLib", "_RQuantLib_dayCount"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_dayCount(Shield(Rcpp::wrap(startDates)), Shield(Rcpp::wrap(endDates)), Shield(Rcpp::wrap(dayCounters))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as >(rcpp_result_gen); } inline std::vector yearFraction(std::vector startDates, std::vector endDates, std::vector dayCounters) { typedef SEXP(*Ptr_yearFraction)(SEXP,SEXP,SEXP); static Ptr_yearFraction p_yearFraction = NULL; if (p_yearFraction == NULL) { validateSignature("std::vector(*yearFraction)(std::vector,std::vector,std::vector)"); p_yearFraction = (Ptr_yearFraction)R_GetCCallable("RQuantLib", "_RQuantLib_yearFraction"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_yearFraction(Shield(Rcpp::wrap(startDates)), Shield(Rcpp::wrap(endDates)), Shield(Rcpp::wrap(dayCounters))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as >(rcpp_result_gen); } inline bool setEvaluationDate(QuantLib::Date evalDate) { typedef SEXP(*Ptr_setEvaluationDate)(SEXP); static Ptr_setEvaluationDate p_setEvaluationDate = NULL; if (p_setEvaluationDate == NULL) { validateSignature("bool(*setEvaluationDate)(QuantLib::Date)"); p_setEvaluationDate = (Ptr_setEvaluationDate)R_GetCCallable("RQuantLib", "_RQuantLib_setEvaluationDate"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_setEvaluationDate(Shield(Rcpp::wrap(evalDate))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline double europeanOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility) { typedef SEXP(*Ptr_europeanOptionImpliedVolatilityEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_europeanOptionImpliedVolatilityEngine p_europeanOptionImpliedVolatilityEngine = NULL; if (p_europeanOptionImpliedVolatilityEngine == NULL) { validateSignature("double(*europeanOptionImpliedVolatilityEngine)(std::string,double,double,double,double,double,double,double)"); p_europeanOptionImpliedVolatilityEngine = (Ptr_europeanOptionImpliedVolatilityEngine)R_GetCCallable("RQuantLib", "_RQuantLib_europeanOptionImpliedVolatilityEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_europeanOptionImpliedVolatilityEngine(Shield(Rcpp::wrap(type)), Shield(Rcpp::wrap(value)), Shield(Rcpp::wrap(underlying)), Shield(Rcpp::wrap(strike)), Shield(Rcpp::wrap(dividendYield)), Shield(Rcpp::wrap(riskFreeRate)), Shield(Rcpp::wrap(maturity)), Shield(Rcpp::wrap(volatility))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline double americanOptionImpliedVolatilityEngine(std::string type, double value, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volguess, int timesteps, int gridpoints) { typedef SEXP(*Ptr_americanOptionImpliedVolatilityEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_americanOptionImpliedVolatilityEngine p_americanOptionImpliedVolatilityEngine = NULL; if (p_americanOptionImpliedVolatilityEngine == NULL) { validateSignature("double(*americanOptionImpliedVolatilityEngine)(std::string,double,double,double,double,double,double,double,int,int)"); p_americanOptionImpliedVolatilityEngine = (Ptr_americanOptionImpliedVolatilityEngine)R_GetCCallable("RQuantLib", "_RQuantLib_americanOptionImpliedVolatilityEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_americanOptionImpliedVolatilityEngine(Shield(Rcpp::wrap(type)), Shield(Rcpp::wrap(value)), Shield(Rcpp::wrap(underlying)), Shield(Rcpp::wrap(strike)), Shield(Rcpp::wrap(dividendYield)), Shield(Rcpp::wrap(riskFreeRate)), Shield(Rcpp::wrap(maturity)), Shield(Rcpp::wrap(volguess)), Shield(Rcpp::wrap(timesteps)), Shield(Rcpp::wrap(gridpoints))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::DateVector CreateSchedule(Rcpp::List params) { typedef SEXP(*Ptr_CreateSchedule)(SEXP); static Ptr_CreateSchedule p_CreateSchedule = NULL; if (p_CreateSchedule == NULL) { validateSignature("Rcpp::DateVector(*CreateSchedule)(Rcpp::List)"); p_CreateSchedule = (Ptr_CreateSchedule)R_GetCCallable("RQuantLib", "_RQuantLib_CreateSchedule"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_CreateSchedule(Shield(Rcpp::wrap(params))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline std::string getQuantLibVersion() { typedef SEXP(*Ptr_getQuantLibVersion)(); static Ptr_getQuantLibVersion p_getQuantLibVersion = NULL; if (p_getQuantLibVersion == NULL) { validateSignature("std::string(*getQuantLibVersion)()"); p_getQuantLibVersion = (Ptr_getQuantLibVersion)R_GetCCallable("RQuantLib", "_RQuantLib_getQuantLibVersion"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_getQuantLibVersion(); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::LogicalVector getQuantLibCapabilities() { typedef SEXP(*Ptr_getQuantLibCapabilities)(); static Ptr_getQuantLibCapabilities p_getQuantLibCapabilities = NULL; if (p_getQuantLibCapabilities == NULL) { validateSignature("Rcpp::LogicalVector(*getQuantLibCapabilities)()"); p_getQuantLibCapabilities = (Ptr_getQuantLibCapabilities)R_GetCCallable("RQuantLib", "_RQuantLib_getQuantLibCapabilities"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_getQuantLibCapabilities(); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List europeanOptionEngine(std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, Rcpp::Nullable discreteDividends, Rcpp::Nullable discreteDividendsTimeUntil) { typedef SEXP(*Ptr_europeanOptionEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_europeanOptionEngine p_europeanOptionEngine = NULL; if (p_europeanOptionEngine == NULL) { validateSignature("Rcpp::List(*europeanOptionEngine)(std::string,double,double,double,double,double,double,Rcpp::Nullable,Rcpp::Nullable)"); p_europeanOptionEngine = (Ptr_europeanOptionEngine)R_GetCCallable("RQuantLib", "_RQuantLib_europeanOptionEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_europeanOptionEngine(Shield(Rcpp::wrap(type)), Shield(Rcpp::wrap(underlying)), Shield(Rcpp::wrap(strike)), Shield(Rcpp::wrap(dividendYield)), Shield(Rcpp::wrap(riskFreeRate)), Shield(Rcpp::wrap(maturity)), Shield(Rcpp::wrap(volatility)), Shield(Rcpp::wrap(discreteDividends)), Shield(Rcpp::wrap(discreteDividendsTimeUntil))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List americanOptionEngine(std::string type, double underlying, double strike, double dividendYield, double riskFreeRate, double maturity, double volatility, int timeSteps, int gridPoints, std::string engine, Rcpp::Nullable discreteDividends, Rcpp::Nullable discreteDividendsTimeUntil) { typedef SEXP(*Ptr_americanOptionEngine)(SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP,SEXP); static Ptr_americanOptionEngine p_americanOptionEngine = NULL; if (p_americanOptionEngine == NULL) { validateSignature("Rcpp::List(*americanOptionEngine)(std::string,double,double,double,double,double,double,int,int,std::string,Rcpp::Nullable,Rcpp::Nullable)"); p_americanOptionEngine = (Ptr_americanOptionEngine)R_GetCCallable("RQuantLib", "_RQuantLib_americanOptionEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_americanOptionEngine(Shield(Rcpp::wrap(type)), Shield(Rcpp::wrap(underlying)), Shield(Rcpp::wrap(strike)), Shield(Rcpp::wrap(dividendYield)), Shield(Rcpp::wrap(riskFreeRate)), Shield(Rcpp::wrap(maturity)), Shield(Rcpp::wrap(volatility)), Shield(Rcpp::wrap(timeSteps)), Shield(Rcpp::wrap(gridPoints)), Shield(Rcpp::wrap(engine)), Shield(Rcpp::wrap(discreteDividends)), Shield(Rcpp::wrap(discreteDividendsTimeUntil))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } inline Rcpp::List europeanOptionArraysEngine(std::string type, Rcpp::NumericMatrix par) { typedef SEXP(*Ptr_europeanOptionArraysEngine)(SEXP,SEXP); static Ptr_europeanOptionArraysEngine p_europeanOptionArraysEngine = NULL; if (p_europeanOptionArraysEngine == NULL) { validateSignature("Rcpp::List(*europeanOptionArraysEngine)(std::string,Rcpp::NumericMatrix)"); p_europeanOptionArraysEngine = (Ptr_europeanOptionArraysEngine)R_GetCCallable("RQuantLib", "_RQuantLib_europeanOptionArraysEngine"); } RObject rcpp_result_gen; { RNGScope RCPP_rngScope_gen; rcpp_result_gen = p_europeanOptionArraysEngine(Shield(Rcpp::wrap(type)), Shield(Rcpp::wrap(par))); } if (rcpp_result_gen.inherits("interrupted-error")) throw Rcpp::internal::InterruptedException(); if (Rcpp::internal::isLongjumpSentinel(rcpp_result_gen)) throw Rcpp::LongjumpException(rcpp_result_gen); if (rcpp_result_gen.inherits("try-error")) throw Rcpp::exception(Rcpp::as(rcpp_result_gen).c_str()); return Rcpp::as(rcpp_result_gen); } } #endif // RCPP_RQuantLib_RCPPEXPORTS_H_GEN_ RQuantLib/inst/include/rquantlib_wrappers.h0000644000176200001440000000225313443253624020620 0ustar liggesusers // RQuantLib wrapper definitions // // Copyright 2014 Dirk Eddelbuettel // // 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_wrappers_h_ #define _rquantlib_wrappers_h_ #include "rquantlib_internal.h" // define template specialisations for as and wrap namespace Rcpp { //template <> QuantLib::Date as(SEXP dtsexp); template T as(SEXP dtsexp); template SEXP wrap(const T& d); template <> std::vector as(SEXP dtvecsexp); template <> SEXP wrap(const std::vector &dvec); } #endif RQuantLib/inst/include/RQuantLib.h0000644000176200001440000000207613443253624016540 0ustar liggesusers // RQuantLib function prototypes and macros // // Copyright 2014 Dirk Eddelbuettel // // 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 "rquantlib_internal.h" // old rquantlib.h #include "rquantlib_wrappers.h" // as<> and wrap #if defined(RQuantLib_Plugin) #include "rquantlib_impl.h" // as<> and wrap implementation #endif #include "RQuantLib_RcppExports.h" #endif // __RQuantLib_h__ RQuantLib/inst/include/rquantlib_internal.h0000644000176200001440000002120113467001143020554 0ustar liggesusers // RQuantLib function prototypes and macros // // Copyright 2002 - 2019 Dirk Eddelbuettel // Copyright 2005 - 2006 Dominick Samperi // // 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 #include //using namespace QuantLib; #include namespace Rcpp { // non-intrusive extension via template specialisation template <> QuantLib::Date as(SEXP dtsexp); // non-intrusive extension via template specialisation template <> SEXP wrap(const QuantLib::Date &d); // non-intrusive extension via template specialisation template <> std::vector as(SEXP dtvecsexp); // non-intrusive extension via template specialisation template <> SEXP wrap(const std::vector &dvec); } #include //#define NULL_RateHelper (QuantLib::ext::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(); QuantLib::ext::shared_ptr getRateHelper(std::string& ticker, QuantLib::Rate r); // original rate helper // modded rate helper to allow variable daycount and frequencies in curve building QuantLib::ext::shared_ptr getRateHelper(std::string& ticker, QuantLib::Rate r, double fixDayCount, double fixFreq, int floatIndex); private: RQLMap db_; }; QuantLib::ext::shared_ptr getTermStructure(std::string& interpWhat, std::string& interpHow, const QuantLib::Date& settleDate, const std::vector >& curveInput, QuantLib::DayCounter& dayCounter, QuantLib::Real tolerance); QuantLib::ext::shared_ptr makeFlatCurve(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& forward, const QuantLib::DayCounter& dc); QuantLib::ext::shared_ptr flatRate(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& forward, const QuantLib::DayCounter& dc); QuantLib::ext::shared_ptr makeFlatVolatility(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& vol, QuantLib::DayCounter dc); QuantLib::ext::shared_ptr flatVol(const QuantLib::Date& today, const QuantLib::ext::shared_ptr& vol, const QuantLib::DayCounter& dc); enum EngineType {Analytic, JR, CRR, EQP, TGEO, TIAN, LR, JOSHI, FiniteDifferences, Integral, PseudoMonteCarlo, QuasiMonteCarlo }; enum optionType { European = 0, American }; QuantLib::ext::shared_ptr makeOption(const QuantLib::ext::shared_ptr& payoff, const QuantLib::ext::shared_ptr& exercise, const QuantLib::ext::shared_ptr& u, const QuantLib::ext::shared_ptr& q, const QuantLib::ext::shared_ptr& r, const QuantLib::ext::shared_ptr& vol, EngineType engineType = Analytic, QuantLib::Size binomialSteps=128, QuantLib::Size samples=100); QuantLib::ext::shared_ptr makeProcess(const QuantLib::ext::shared_ptr& u, const QuantLib::ext::shared_ptr& q, const QuantLib::ext::shared_ptr& r, const QuantLib::ext::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::IborIndex getIborIndex(std::string type); 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); QuantLib::ext::shared_ptr buildTermStructure(Rcpp::List params, Rcpp::List); QuantLib::Schedule getSchedule(Rcpp::List rparam); QuantLib::ext::shared_ptr getFixedRateBond(Rcpp::List bondparam, std::vector ratesVec, Rcpp::List scheduleparam); //QuantLib::ext::shared_ptr getIborIndex(Rcpp::List index, const QuantLib::Date today);////****** ?? //QuantLib::ext::shared_ptr getIborIndex(std:string type);////****** ?? // deprecated std::vector getDoubleVector(SEXP vector); QuantLib::ext::shared_ptr getFlatCurve(Rcpp::List flatcurve); //QuantLib::ext::shared_ptr rebuildCurveFromZeroRates(SEXP dateSexp, SEXP zeroSexp); QuantLib::ext::shared_ptr rebuildCurveFromZeroRates(std::vector dates, std::vector zeros); QuantLib::ext::shared_ptr buildIborIndex(std::string type, const QuantLib::Handle& iborStrc); //QuantLib::Calendar* getCalendar(SEXP calParameters); QuantLib::ext::shared_ptr getCalendar(const std::string &calstr); 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(Rcpp::DataFrame dividendScheduleFrame); QuantLib::CallabilitySchedule getCallabilitySchedule(Rcpp::DataFrame callabilityScheduleFrame); QuantLib::Duration::Type getDurationType(const double n); // dates.cpp QuantLib::Date advanceDate(QuantLib::Date issueDate, int days); #endif RQuantLib/inst/tinytest/0000755000176200001440000000000013564352402014757 5ustar liggesusersRQuantLib/inst/tinytest/test_schedule.R0000644000176200001440000001233413564352402017740 0ustar liggesusers library(RQuantLib) #test.Schedule <- function() { ## these tests are taken from the QuantLib test-suite/schedule.cpp file startDate <- as.Date("2012-1-17") params <- list(effectiveDate=startDate, maturityDate=startDate+7, period = "Daily", businessDayConvention="Preceding") expected <- as.Date(c("2012-1-17", "2012-1-18", "2012-1-19", "2012-1-20", "2012-1-23", "2012-1-24")) expect_equal(Schedule(params), expected, info="Testing schedule with daily frequency...") params <- list(effectiveDate= as.Date("2009-09-30"), maturityDate = as.Date("2012-06-15"), calendar = "Japan", period = "Semiannual", businessDayConvention="Following", terminationDateConvention="ModifiedFollowing", dateGeneration="Forward", endOfMonth=T) expected <- as.Date(c("2009-09-30", "2010-03-31", "2010-09-30", "2011-03-31", "2011-09-30", "2012-03-30", "2012-06-29")) expect_equal(Schedule(params), expected, info="Testing end date for schedule with end-of-month adjustment...") params$terminationDateConvention="Unadjusted" expected[7] <- as.Date("2012-06-15") expect_equal(Schedule(params), expected) params <- list(effectiveDate = as.Date("2013-03-28"), maturityDate = as.Date("2015-03-30"), calendar = "TARGET", period="Annual", businessDayConvention="Unadjusted", terminationDateConvention="Unadjusted", dateGeneration="Forward", endOfMonth=T) expected <- as.Date(c("2013-03-31", "2014-03-31", "2015-03-30")) expect_equal(Schedule(params), expected, info="Testing that no dates are past the end date with EOM adjustment...") params <- list(effectiveDate = as.Date("1996-08-31"), maturityDate = as.Date("1997-09-15"), calendar = "UnitedStates/GovernmentBond", period="Semiannual", businessDayConvention="Unadjusted", terminationDateConvention="Unadjusted", dateGeneration="Forward", endOfMonth=T) expected <- as.Date(c("1996-08-31", "1997-02-28", "1997-08-31", "1997-09-15")) expect_equal(Schedule(params), expected, info=paste("Testing that the last date is not adjusted for EOM", "when termination date convention is unadjusted...")) params <- list(effectiveDate = as.Date("1996-08-22"), maturityDate = as.Date("1997-08-31"), calendar = "UnitedStates/GovernmentBond", period="Semiannual", businessDayConvention="Unadjusted", terminationDateConvention="Unadjusted", dateGeneration="Backward", endOfMonth=T) expected <- as.Date(c("1996-08-22", "1996-08-31", "1997-02-28", "1997-08-31")) expect_equal(Schedule(params), expected, info=paste("Testing that the first date is not adjusted for EOM", "going backward when termination date convention is unadjusted...")) params <- list(effectiveDate = as.Date("1996-08-22"), maturityDate = as.Date("1997-08-31"), calendar = "UnitedStates/GovernmentBond", period="Semiannual", businessDayConvention="Following", terminationDateConvention="Following", dateGeneration="Backward", endOfMonth=T) expected <- as.Date(c("1996-08-30", "1997-02-28", "1997-08-29")) expect_equal(Schedule(params), expected, info=paste("Testing that the first date is not duplicated due to", "EOM convention when going backwards...")) if( compareVersion(getQuantLibVersion(), "1.7.1") >= 0 ) { params <- list(effectiveDate = as.Date("2016-01-13"), maturityDate = as.Date("2016-05-04"), calendar = "TARGET", period = "EveryFourthWeek", businessDayConvention="Following", terminationDateConvention="Following", dateGeneration="Forward") expected <- as.Date(c("2016-01-13", "2016-02-10", "2016-03-09", "2016-04-06", "2016-05-04")) expect_equal(Schedule(params), expected, info="Testing that a four-weeks tenor works...") } #test.CDS <- function() { params <- list(effectiveDate = as.Date("2016-06-21"), maturityDate = as.Date("2021-06-20"), calendar = "UnitedStates/GovernmentBond", period = "Quarterly", businessDayConvention="ModifiedFollowing", terminationDateConvention="Unadjusted", dateGeneration="CDS") ## values come from Bloomberg (last date is wrong, because of a bug in QuantLib) expected <- as.Date(c("2016-06-20", "2016-09-20", "2016-12-20", "2017-03-20", "2017-06-20", "2017-09-20", "2017-12-20", "2018-03-20", "2018-06-20", "2018-09-20", "2018-12-20", "2019-03-20", "2019-06-20", "2019-09-20", "2019-12-20", "2020-03-20", "2020-06-22", "2020-09-21", "2020-12-21", "2021-03-22", "2021-06-20")) expect_equal(Schedule(params), expected, info="Checking schedule of IG26") RQuantLib/inst/tinytest/cpp/0000755000176200001440000000000013564352402015541 5ustar liggesusersRQuantLib/inst/tinytest/cpp/dates.cpp0000644000176200001440000000334313564352402017350 0ustar liggesusers// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // // dates.cpp: RQuantLib date conversion tests // // Copyright (C) 2014 - 2016 Dirk Eddelbuettel // // This file is part of RQuantLib. // // RQuantLib 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. // // RQuantLib 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 RQuantLib. If not, see . // [[Rcpp::depends(RQuantLib)]] #include // [[Rcpp::export]] Rcpp::Date advanceDateRR(Rcpp::Date d, int n) { return d + n; } // [[Rcpp::export]] Rcpp::Date advanceDateQR(QuantLib::Date d, int n) { return Rcpp::wrap(d + n); } // [[Rcpp::export]] QuantLib::Date advanceDateQQ(QuantLib::Date d, int n) { return d + n; } // [[Rcpp::export]] Rcpp::DateVector advanceDatesRR(Rcpp::DateVector d, int n) { Rcpp::DateVector nd(d.size()); for (int i=0; i d, int n) { for (unsigned int i=0; i advanceDatesQQ(std::vector d, int n) { for (unsigned int i=0; i. .onWindows <- .Platform$OS.type == "windows" if (.onWindows) exit_file("Skipping dates test on Windows.") Rcpp::sourceCpp("cpp/dates.cpp") #test.date.conversion <- function() { given <- as.Date("2000-01-01") inc <- 2 expected <- given + inc expect_equal(advanceDateRR(given, inc), expected, info="date conversion from R to R") expect_equal(advanceDateQR(given, inc), expected, info="date conversion from QuantLib to R") expect_equal(advanceDateQQ(given, inc), expected, info="date conversion from QuantLib to QuantLib") #test.datevector.conversion <- function() { given <- as.Date("2000-01-01") + 0:3 inc <- 2 expected <- given + inc expect_equal(advanceDatesRR(given, inc), expected, info="date conversion from R to R") expect_equal(advanceDatesQR(given, inc), expected, info="date conversion from QuantLib to QuantLib") expect_equal(advanceDatesQQ(given, inc), expected, info="date conversion from QuantLib to R") RQuantLib/inst/tinytest/test_options.R0000644000176200001440000007540613564352402017650 0ustar liggesusers library(RQuantLib) ## AsianOption() currently has issue of Windows .onWindows <- .Platform$OS.type == "windows" ## 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 expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) ## Barrier Options #test.barrier <- function() { expect_equal(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) expect_equal(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) expect_equal(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 expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(rc$value, 2.671045684) expect_equal(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), tol=1.0e-5) ## 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 expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) ## European and American option tests with discrete dividends based on Hull's book #test.discreteDividend.Hull <- function() { AO <- AmericanOption # shorthand EO <- EuropeanOption # shorthand ## Reference p. 253 - Hull 5th ed. Exercise 12.8 - From QuantLib tests expect_equal(EO(type="call", underlying=40, strike=40, div=0, riskFree=0.09, maturity=0.5, vol=0.3, discreteDividends = c(0.5, 0.5), discreteDividendsTimeUntil = c(2/12, 5/12))$value, 3.67, tol=1.0e-2) ## Reference p. 256 - Hull 5th ed. Exercise 12.9 using (flawed) Roll, Geske and Whaley formula expect_equal(AO(type="call", underlying=40, strike=40, div=0, riskFree=0.09, maturity=0.5, vol=0.3, engine = "CrankNicolson", discreteDividends = c(0.5, 0.5), discreteDividendsTimeUntil = c(2/12, 5/12))$value, 3.72, tol=1.0e-1) ## Asian option tests #test.asian <- function() { ## see QuantLib's test-suite/asianoptions.cpp AO <- AsianOption # shorthand expect_equal(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) if (.onWindows) exit_file("Skipping Asian options on Windows.") ## data from "Asian Option", Levy, 1997 ## in "Exotic Options: The State of the Art", ## edited by Clewlow, Strickland expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) expect_equal(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) RQuantLib/inst/Boost_LICENSE.TXT0000644000176200001440000000247312271333436015733 0ustar liggesusersBoost 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.TXT0000644000176200001440000001373612303640333016361 0ustar liggesusersQuantLib 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, 2009, 2010, 2011, 2012 Ferdinando Ametrano Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 StatPro Italia srl Copyright (C) 2003, 2004, 2007 Neil Firth Copyright (C) 2003, 2004 Roman Gitlin Copyright (C) 2003, 2005, 2013 Gary Kennedy 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, 2009, 2010, 2011, 2012, 2013, 2014 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, 2009 Piter Dias 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, 2009, 2010 Mark Joshi Copyright (C) 2006, 2007, 2008 Allen Kuo Copyright (C) 2006, 2007, 2008, 2009, 2012 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, 2009, 2010, 2011 Chris Kenyon Copyright (C) 2007 Gang Liang Copyright (C) 2008, 2009 Jose Aparicio Copyright (C) 2008 Yee Man Chan Copyright (C) 2008, 2011 Charles Chongseok Hyun Copyright (C) 2008 Piero Del Boca Copyright (C) 2008 Paul Farrington Copyright (C) 2008 Lorella Fatone Copyright (C) 2008, 2009 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, 2009, 2010, 2011, 2012 Master IMAFA - Polytech'Nice Sophia - Université de Nice Sophia Antipolis Copyright (C) 2008, 2009 Andrea Odetti Copyright (C) 2008 J. Erik Radmall Copyright (C) 2008 Maria Cristina Recchioni Copyright (C) 2008, 2009, 2012 Ralph Schreyer Copyright (C) 2008 Roland Stamm Copyright (C) 2008 Francesco Zirilli Copyright (C) 2009 Nathan Abbott Copyright (C) 2009 Sylvain Bertrand Copyright (C) 2009 Frédéric Degraeve Copyright (C) 2009 Dirk Eddelbuettel Copyright (C) 2009 Bernd Engelmann Copyright (C) 2009, 2010, 2012 Liquidnet Holdings, Inc. Copyright (C) 2009 Bojan Nikolic Copyright (C) 2009, 2010 Dimitri Reiswich Copyright (C) 2009 Sun Xiuxin Copyright (C) 2010 Kakhkhor Abdijalilov Copyright (C) 2010 Hachemi Benyahia Copyright (C) 2010 Manas Bhatt Copyright (C) 2010 DeriveXperts SAS Copyright (C) 2010, 2014 Cavit Hafizoglu Copyright (C) 2010 Michael Heckl Copyright (C) 2010 Slava Mazur Copyright (C) 2010, 2011, 2012, 2013 Andre Miemiec Copyright (C) 2010 Adrian O' Neill Copyright (C) 2010 Robert Philipp Copyright (C) 2010 Alessandro Roveda Copyright (C) 2010 SunTrust Bank Copyright (C) 2011, 2013 Fabien Le Floc'h Copyright (C) 2012, 2013 Grzegorz Andruszkiewicz Copyright (C) 2012, 2013, 2014 Peter Caspers Copyright (C) 2012 Mateusz Kapturski Copyright (C) 2012 Simon Shakeshaft Copyright (C) 2012 Édouard Tallent Copyright (C) 2012 Samuel Tebege Copyright (C) 2013 BGC Partners L.P. Copyright (C) 2013 Cheng Li Copyright (C) 2013 Yue Tian 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. QuantLib includes a set of numbers provided by Stephen Joe and Frances Kuo under a BSD-style license. 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/shiny/0000755000176200001440000000000012744670072014233 5ustar liggesusersRQuantLib/inst/shiny/DiscountCurve/0000755000176200001440000000000012466654326017035 5ustar liggesusersRQuantLib/inst/shiny/DiscountCurve/server.R0000644000176200001440000000444312466654326020473 0ustar liggesusers library(shiny) library(RQuantLib) shinyServer(function(input, output) { ## 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-09-20")) ## 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 ## Removing s2y helps, as kindly pointed out by Luigi Ballabio 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) times <- seq(0,10,.1) ## Reactive expression to generate the requested curves. data <- reactive({ params$interpHow <- input$interpolation curve <- DiscountCurve(params, tsQuotes, times) }) ## Generate a plot of the data. output$plot <- renderPlot({ interp <- input$interpolation crv <- input$curve dat <- data() plot(dat[["times"]], dat[[crv]], type='l', main=paste(interp, crv), ylab=crv, xlab="time in years") }) ## Generate a summary of the data output$summary <- renderPrint({ dat <- data() cat("Return Object Structure\n") str(dat) cat("\n\nSummary of first four elements\n") summary(data.frame(dat[1:4])) }) ## Generate an HTML table view of the data output$table <- renderTable({ data.frame(x=data()[1:4]) }) }) RQuantLib/inst/shiny/DiscountCurve/ui.R0000644000176200001440000000205512466654326017577 0ustar liggesuserslibrary(shiny) shinyUI(fluidPage( ## Application title titlePanel("Simple DiscountCurve Example from RQuantLib"), ## Sidebar with controls to select parameters sidebarLayout( sidebarPanel( radioButtons("interpolation", "Interpolation type:", c("loglinear" = "loglinear", "linear" = "linear", "spline" = "spline")), br(), radioButtons("curve", "Curve type:", c("forwards" = "forwards", "zero rates" = "zerorates", "discounts" = "discounts")) ), ## Show a tabset that includes a plot, summary, and table view mainPanel( tabsetPanel(type = "tabs", tabPanel("Plot", plotOutput("plot")), tabPanel("Summary", verbatimTextOutput("summary")), tabPanel("Table", tableOutput("table")) ) ) ) )) RQuantLib/inst/shiny/SabrSwaption/0000755000176200001440000000000012757140057016646 5ustar liggesusersRQuantLib/inst/shiny/SabrSwaption/volcube.csv0000644000176200001440000005523012744670072021030 0ustar liggesusersExpiry,Tenor,Spread,LogNormalVol 10Y,10Y,-200,0.6897 10Y,10Y,-150,0.4973 10Y,10Y,-100,0.4034 10Y,10Y,-75,0.3703 10Y,10Y,-50,0.3428 10Y,10Y,-25,0.3199 10Y,10Y,0,0.3007 10Y,10Y,25,0.2849 10Y,10Y,50,0.2719 10Y,10Y,75,0.2613 10Y,10Y,100,0.2527 10Y,10Y,150,0.2409 10Y,10Y,200,0.2342 1M,10Y,-200,NA 1M,10Y,-150,1.5201 1M,10Y,-100,0.8195 1M,10Y,-75,0.6487 1M,10Y,-50,0.5274 1M,10Y,-25,0.4435 1M,10Y,-20,0.4306 1M,10Y,-15,0.4190 1M,10Y,-10,0.4087 1M,10Y,-5,0.3997 1M,10Y,0,0.3922 1M,10Y,5,0.3859 1M,10Y,10,0.3810 1M,10Y,15,0.3773 1M,10Y,20,0.3749 1M,10Y,25,0.3734 1M,10Y,50,0.3786 1M,10Y,75,0.3982 1M,10Y,100,0.4237 1M,10Y,150,0.4732 1M,10Y,200,0.5186 1Y,10Y,-200,NA 1Y,10Y,-150,0.9561 1Y,10Y,-100,0.6572 1Y,10Y,-75,0.5768 1Y,10Y,-50,0.5167 1Y,10Y,-25,0.4704 1Y,10Y,0,0.4343 1Y,10Y,25,0.4066 1Y,10Y,50,0.3858 1Y,10Y,75,0.3706 1Y,10Y,100,0.3598 1Y,10Y,150,0.3478 1Y,10Y,200,0.3437 2Y,10Y,-200,2.1527 2Y,10Y,-150,0.8126 2Y,10Y,-100,0.5968 2Y,10Y,-75,0.5326 2Y,10Y,-50,0.4831 2Y,10Y,-25,0.4438 2Y,10Y,0,0.4123 2Y,10Y,25,0.3869 2Y,10Y,50,0.3666 2Y,10Y,75,0.3506 2Y,10Y,100,0.3381 2Y,10Y,150,0.3215 2Y,10Y,200,0.3126 3M,10Y,-200,NA 3M,10Y,-150,1.2754 3M,10Y,-100,0.7706 3M,10Y,-75,0.6444 3M,10Y,-50,0.5518 3M,10Y,-25,0.4839 3M,10Y,-20,0.4730 3M,10Y,-15,0.4630 3M,10Y,-10,0.4537 3M,10Y,-5,0.4454 3M,10Y,0,0.4379 3M,10Y,5,0.4311 3M,10Y,10,0.4252 3M,10Y,15,0.4201 3M,10Y,20,0.4156 3M,10Y,25,0.4118 3M,10Y,50,0.4015 3M,10Y,75,0.4016 3M,10Y,100,0.4075 3M,10Y,150,0.4264 3M,10Y,200,0.4467 3Y,10Y,-200,1.2763 3Y,10Y,-150,0.7217 3Y,10Y,-100,0.5521 3Y,10Y,-75,0.4980 3Y,10Y,-50,0.4554 3Y,10Y,-25,0.4210 3Y,10Y,0,0.3928 3Y,10Y,25,0.3699 3Y,10Y,50,0.3511 3Y,10Y,75,0.3358 3Y,10Y,100,0.3237 3Y,10Y,150,0.3065 3Y,10Y,200,0.2965 4Y,10Y,-200,1.0370 4Y,10Y,-150,0.6589 4Y,10Y,-100,0.5163 4Y,10Y,-75,0.4691 4Y,10Y,-50,0.4310 4Y,10Y,-25,0.4000 4Y,10Y,0,0.3743 4Y,10Y,25,0.3532 4Y,10Y,50,0.3357 4Y,10Y,75,0.3214 4Y,10Y,100,0.3098 4Y,10Y,150,0.2932 4Y,10Y,200,0.2831 5Y,10Y,-200,0.9182 5Y,10Y,-150,0.6181 5Y,10Y,-100,0.4915 5Y,10Y,-75,0.4486 5Y,10Y,-50,0.4135 5Y,10Y,-25,0.3846 5Y,10Y,0,0.3606 5Y,10Y,25,0.3408 5Y,10Y,50,0.3244 5Y,10Y,75,0.3110 5Y,10Y,100,0.3001 5Y,10Y,150,0.2844 5Y,10Y,200,0.2749 6M,10Y,-200,NA 6M,10Y,-150,1.1043 6M,10Y,-100,0.7136 6M,10Y,-75,0.6130 6M,10Y,-50,0.5387 6M,10Y,-25,0.4832 6M,10Y,0,0.4428 6M,10Y,25,0.4150 6M,10Y,50,0.3976 6M,10Y,75,0.3880 6M,10Y,100,0.3838 6M,10Y,150,0.3847 6M,10Y,200,0.3910 6Y,10Y,-200,0.8326 6Y,10Y,-150,0.5803 6Y,10Y,-100,0.4661 6Y,10Y,-75,0.4267 6Y,10Y,-50,0.3942 6Y,10Y,-25,0.3672 6Y,10Y,0,0.3447 6Y,10Y,25,0.3261 6Y,10Y,50,0.3107 6Y,10Y,75,0.2981 6Y,10Y,100,0.2879 6Y,10Y,150,0.2732 6Y,10Y,200,0.2645 7Y,10Y,-200,0.7789 7Y,10Y,-150,0.5530 7Y,10Y,-100,0.4466 7Y,10Y,-75,0.4094 7Y,10Y,-50,0.3787 7Y,10Y,-25,0.3531 7Y,10Y,0,0.3317 7Y,10Y,25,0.3140 7Y,10Y,50,0.2994 7Y,10Y,75,0.2875 7Y,10Y,100,0.2778 7Y,10Y,150,0.2641 7Y,10Y,200,0.2560 8Y,10Y,-200,0.7418 8Y,10Y,-150,0.5313 8Y,10Y,-100,0.4301 8Y,10Y,-75,0.3945 8Y,10Y,-50,0.3651 8Y,10Y,-25,0.3405 8Y,10Y,0,0.3201 8Y,10Y,25,0.3032 8Y,10Y,50,0.2891 8Y,10Y,75,0.2776 8Y,10Y,100,0.2684 8Y,10Y,150,0.2554 8Y,10Y,200,0.2479 9Y,10Y,-200,0.7122 9Y,10Y,-150,0.5128 9Y,10Y,-100,0.4158 9Y,10Y,-75,0.3815 9Y,10Y,-50,0.3532 9Y,10Y,-25,0.3295 9Y,10Y,0,0.3098 9Y,10Y,25,0.2935 9Y,10Y,50,0.2800 9Y,10Y,75,0.2689 9Y,10Y,100,0.2601 9Y,10Y,150,0.2478 9Y,10Y,200,0.2407 10Y,15Y,-200,0.6438 10Y,15Y,-150,0.4650 10Y,15Y,-100,0.3758 10Y,15Y,-75,0.3441 10Y,15Y,-50,0.3178 10Y,15Y,-25,0.2958 10Y,15Y,0,0.2775 10Y,15Y,25,0.2626 10Y,15Y,50,0.2503 10Y,15Y,75,0.2405 10Y,15Y,100,0.2329 10Y,15Y,150,0.2228 10Y,15Y,200,0.2179 1M,15Y,-200,NA 1M,15Y,-150,1.0595 1M,15Y,-100,0.6597 1M,15Y,-75,0.5378 1M,15Y,-50,0.4454 1M,15Y,-25,0.3782 1M,15Y,-20,0.3675 1M,15Y,-15,0.3578 1M,15Y,-10,0.3492 1M,15Y,-5,0.3417 1M,15Y,0,0.3352 1M,15Y,5,0.3299 1M,15Y,10,0.3256 1M,15Y,15,0.3224 1M,15Y,20,0.3202 1M,15Y,25,0.3189 1M,15Y,50,0.3234 1M,15Y,75,0.3407 1M,15Y,100,0.3637 1M,15Y,150,0.4089 1M,15Y,200,0.4506 1Y,15Y,-200,1.4169 1Y,15Y,-150,0.7512 1Y,15Y,-100,0.5573 1Y,15Y,-75,0.4964 1Y,15Y,-50,0.4488 1Y,15Y,-25,0.4109 1Y,15Y,0,0.3809 1Y,15Y,25,0.3576 1Y,15Y,50,0.3400 1Y,15Y,75,0.3274 1Y,15Y,100,0.3186 1Y,15Y,150,0.3097 1Y,15Y,200,0.3076 2Y,15Y,-200,1.0972 2Y,15Y,-150,0.6758 2Y,15Y,-100,0.5177 2Y,15Y,-75,0.4665 2Y,15Y,-50,0.4258 2Y,15Y,-25,0.3929 2Y,15Y,0,0.3660 2Y,15Y,25,0.3443 2Y,15Y,50,0.3270 2Y,15Y,75,0.3134 2Y,15Y,100,0.3030 2Y,15Y,150,0.2898 2Y,15Y,200,0.2833 3M,15Y,-200,2.7078 3M,15Y,-150,0.9321 3M,15Y,-100,0.6341 3M,15Y,-75,0.5416 3M,15Y,-50,0.4699 3M,15Y,-25,0.4154 3M,15Y,-20,0.4064 3M,15Y,-15,0.3982 3M,15Y,-10,0.3905 3M,15Y,-5,0.3837 3M,15Y,0,0.3775 3M,15Y,5,0.3719 3M,15Y,10,0.3670 3M,15Y,15,0.3628 3M,15Y,20,0.3591 3M,15Y,25,0.3560 3M,15Y,50,0.3482 3M,15Y,75,0.3497 3M,15Y,100,0.3565 3M,15Y,150,0.3763 3M,15Y,200,0.3974 3Y,15Y,-200,0.9383 3Y,15Y,-150,0.6228 3Y,15Y,-100,0.4880 3Y,15Y,-75,0.4426 3Y,15Y,-50,0.4062 3Y,15Y,-25,0.3763 3Y,15Y,0,0.3518 3Y,15Y,25,0.3316 3Y,15Y,50,0.3152 3Y,15Y,75,0.3020 3Y,15Y,100,0.2917 3Y,15Y,150,0.2777 3Y,15Y,200,0.2702 4Y,15Y,-200,0.8387 4Y,15Y,-150,0.5798 4Y,15Y,-100,0.4612 4Y,15Y,-75,0.4201 4Y,15Y,-50,0.3864 4Y,15Y,-25,0.3588 4Y,15Y,0,0.3358 4Y,15Y,25,0.3169 4Y,15Y,50,0.3013 4Y,15Y,75,0.2887 4Y,15Y,100,0.2787 4Y,15Y,150,0.2649 4Y,15Y,200,0.2572 5Y,15Y,-200,0.7816 5Y,15Y,-150,0.5525 5Y,15Y,-100,0.4430 5Y,15Y,-75,0.4045 5Y,15Y,-50,0.3728 5Y,15Y,-25,0.3464 5Y,15Y,0,0.3246 5Y,15Y,25,0.3066 5Y,15Y,50,0.2917 5Y,15Y,75,0.2797 5Y,15Y,100,0.2702 5Y,15Y,150,0.2571 5Y,15Y,200,0.2499 6M,15Y,-200,1.9107 6M,15Y,-150,0.8340 6M,15Y,-100,0.5954 6M,15Y,-75,0.5210 6M,15Y,-50,0.4632 6M,15Y,-25,0.4184 6M,15Y,0,0.3851 6M,15Y,25,0.3621 6M,15Y,50,0.3478 6M,15Y,75,0.3404 6M,15Y,100,0.3379 6M,15Y,150,0.3408 6M,15Y,200,0.3484 6Y,15Y,-200,0.7338 6Y,15Y,-150,0.5267 6Y,15Y,-100,0.4247 6Y,15Y,-75,0.3885 6Y,15Y,-50,0.3585 6Y,15Y,-25,0.3333 6Y,15Y,0,0.3125 6Y,15Y,25,0.2952 6Y,15Y,50,0.2811 6Y,15Y,75,0.2697 6Y,15Y,100,0.2606 6Y,15Y,150,0.2482 6Y,15Y,200,0.2416 7Y,15Y,-200,0.7015 7Y,15Y,-150,0.5072 7Y,15Y,-100,0.4102 7Y,15Y,-75,0.3757 7Y,15Y,-50,0.3469 7Y,15Y,-25,0.3227 7Y,15Y,0,0.3027 7Y,15Y,25,0.2861 7Y,15Y,50,0.2725 7Y,15Y,75,0.2616 7Y,15Y,100,0.2529 7Y,15Y,150,0.2413 7Y,15Y,200,0.2351 8Y,15Y,-200,0.6812 8Y,15Y,-150,0.4927 8Y,15Y,-100,0.3983 8Y,15Y,-75,0.3646 8Y,15Y,-50,0.3366 8Y,15Y,-25,0.3133 8Y,15Y,0,0.2938 8Y,15Y,25,0.2779 8Y,15Y,50,0.2649 8Y,15Y,75,0.2544 8Y,15Y,100,0.2462 8Y,15Y,150,0.2354 8Y,15Y,200,0.2300 9Y,15Y,-200,0.6609 9Y,15Y,-150,0.4783 9Y,15Y,-100,0.3867 9Y,15Y,-75,0.3541 9Y,15Y,-50,0.3271 9Y,15Y,-25,0.3045 9Y,15Y,0,0.2857 9Y,15Y,25,0.2702 9Y,15Y,50,0.2577 9Y,15Y,75,0.2475 9Y,15Y,100,0.2397 9Y,15Y,150,0.2292 9Y,15Y,200,0.2240 10Y,1Y,-200,0.9112 10Y,1Y,-150,0.5967 10Y,1Y,-100,0.4741 10Y,1Y,-75,0.4335 10Y,1Y,-50,0.4004 10Y,1Y,-25,0.3729 10Y,1Y,0,0.3501 10Y,1Y,25,0.3310 10Y,1Y,50,0.3148 10Y,1Y,75,0.3013 10Y,1Y,100,0.2899 10Y,1Y,150,0.2729 10Y,1Y,200,0.2616 1M,1Y,-200,NA 1M,1Y,-150,NA 1M,1Y,-100,NA 1M,1Y,-75,1.4547 1M,1Y,-50,0.7412 1M,1Y,-25,0.5216 1M,1Y,-20,0.4943 1M,1Y,-15,0.4717 1M,1Y,-10,0.4533 1M,1Y,-5,0.4391 1M,1Y,0,0.4285 1M,1Y,5,0.4213 1M,1Y,10,0.4166 1M,1Y,15,0.4142 1M,1Y,20,0.4139 1M,1Y,25,0.4154 1M,1Y,50,0.4401 1M,1Y,75,0.4710 1M,1Y,100,0.5020 1M,1Y,150,0.5437 1M,1Y,200,0.5704 1Y,1Y,-200,NA 1Y,1Y,-150,NA 1Y,1Y,-100,2.1187 1Y,1Y,-75,1.0539 1Y,1Y,-50,0.7994 1Y,1Y,-25,0.6664 1Y,1Y,-20,0.6470 1Y,1Y,-15,0.6289 1Y,1Y,-10,0.6124 1Y,1Y,-5,0.5975 1Y,1Y,0,0.5835 1Y,1Y,5,0.5707 1Y,1Y,10,0.5589 1Y,1Y,15,0.5479 1Y,1Y,20,0.5378 1Y,1Y,25,0.5285 1Y,1Y,50,0.4917 1Y,1Y,75,0.4674 1Y,1Y,100,0.4513 1Y,1Y,150,0.4345 1Y,1Y,200,0.4285 2Y,1Y,-200,NA 2Y,1Y,-150,NA 2Y,1Y,-100,1.2829 2Y,1Y,-75,0.9560 2Y,1Y,-50,0.7924 2Y,1Y,-25,0.6878 2Y,1Y,-20,0.6712 2Y,1Y,-15,0.6556 2Y,1Y,-10,0.6410 2Y,1Y,-5,0.6272 2Y,1Y,0,0.6143 2Y,1Y,5,0.6020 2Y,1Y,10,0.5906 2Y,1Y,15,0.5798 2Y,1Y,20,0.5694 2Y,1Y,25,0.5597 2Y,1Y,50,0.5181 2Y,1Y,75,0.4861 2Y,1Y,100,0.4613 2Y,1Y,150,0.4274 2Y,1Y,200,0.4076 3M,1Y,-200,NA 3M,1Y,-150,NA 3M,1Y,-100,NA 3M,1Y,-75,1.4071 3M,1Y,-50,0.8456 3M,1Y,-25,0.6451 3M,1Y,-20,0.6197 3M,1Y,-15,0.5978 3M,1Y,-10,0.5786 3M,1Y,-5,0.5623 3M,1Y,0,0.5483 3M,1Y,5,0.5366 3M,1Y,10,0.5268 3M,1Y,15,0.5188 3M,1Y,20,0.5123 3M,1Y,25,0.5071 3M,1Y,50,0.4972 3M,1Y,75,0.5031 3M,1Y,100,0.5159 3M,1Y,150,0.5455 3M,1Y,200,0.5703 3Y,1Y,-200,NA 3Y,1Y,-150,NA 3Y,1Y,-100,1.0590 3Y,1Y,-75,0.8624 3Y,1Y,-50,0.7429 3Y,1Y,-25,0.6593 3Y,1Y,0,0.5972 3Y,1Y,25,0.5491 3Y,1Y,50,0.5111 3Y,1Y,75,0.4806 3Y,1Y,100,0.4561 3Y,1Y,150,0.4204 3Y,1Y,200,0.3973 4Y,1Y,-200,NA 4Y,1Y,-150,1.7981 4Y,1Y,-100,0.8690 4Y,1Y,-75,0.7429 4Y,1Y,-50,0.6568 4Y,1Y,-25,0.5927 4Y,1Y,0,0.5431 4Y,1Y,25,0.5037 4Y,1Y,50,0.4717 4Y,1Y,75,0.4456 4Y,1Y,100,0.4242 4Y,1Y,150,0.3923 4Y,1Y,200,0.3709 5Y,1Y,-200,NA 5Y,1Y,-150,1.1238 5Y,1Y,-100,0.7352 5Y,1Y,-75,0.6463 5Y,1Y,-50,0.5812 5Y,1Y,-25,0.5305 5Y,1Y,0,0.4901 5Y,1Y,25,0.4574 5Y,1Y,50,0.4305 5Y,1Y,75,0.4082 5Y,1Y,100,0.3898 5Y,1Y,150,0.3619 5Y,1Y,200,0.3431 6M,1Y,-200,NA 6M,1Y,-150,NA 6M,1Y,-100,NA 6M,1Y,-75,1.1688 6M,1Y,-50,0.7929 6M,1Y,-25,0.6289 6M,1Y,-20,0.6067 6M,1Y,-15,0.5868 6M,1Y,-10,0.5694 6M,1Y,-5,0.5538 6M,1Y,0,0.5402 6M,1Y,5,0.5280 6M,1Y,10,0.5173 6M,1Y,15,0.5081 6M,1Y,20,0.5001 6M,1Y,25,0.4930 6M,1Y,50,0.4712 6M,1Y,75,0.4633 6M,1Y,100,0.4629 6M,1Y,150,0.4711 6M,1Y,200,0.4833 6Y,1Y,-200,NA 6Y,1Y,-150,0.8859 6Y,1Y,-100,0.6396 6Y,1Y,-75,0.5718 6Y,1Y,-50,0.5200 6Y,1Y,-25,0.4786 6Y,1Y,0,0.4449 6Y,1Y,25,0.4172 6Y,1Y,50,0.3943 6Y,1Y,75,0.3751 6Y,1Y,100,0.3591 6Y,1Y,150,0.3348 6Y,1Y,200,0.3183 7Y,1Y,-200,2.1998 7Y,1Y,-150,0.7689 7Y,1Y,-100,0.5805 7Y,1Y,-75,0.5241 7Y,1Y,-50,0.4797 7Y,1Y,-25,0.4437 7Y,1Y,0,0.4142 7Y,1Y,25,0.3895 7Y,1Y,50,0.3691 7Y,1Y,75,0.3519 7Y,1Y,100,0.3375 7Y,1Y,150,0.3157 7Y,1Y,200,0.3010 8Y,1Y,-200,1.2528 8Y,1Y,-150,0.6938 8Y,1Y,-100,0.5358 8Y,1Y,-75,0.4864 8Y,1Y,-50,0.4467 8Y,1Y,-25,0.4144 8Y,1Y,0,0.3876 8Y,1Y,25,0.3652 8Y,1Y,50,0.3466 8Y,1Y,75,0.3309 8Y,1Y,100,0.3178 8Y,1Y,150,0.2981 8Y,1Y,200,0.2849 9Y,1Y,-200,1.0338 9Y,1Y,-150,0.6393 9Y,1Y,-100,0.5021 9Y,1Y,-75,0.4575 9Y,1Y,-50,0.4217 9Y,1Y,-25,0.3920 9Y,1Y,0,0.3675 9Y,1Y,25,0.3468 9Y,1Y,50,0.3296 9Y,1Y,75,0.3150 9Y,1Y,100,0.3029 9Y,1Y,150,0.2846 9Y,1Y,200,0.2725 10Y,20Y,-200,0.6282 10Y,20Y,-150,0.4504 10Y,20Y,-100,0.3621 10Y,20Y,-75,0.3308 10Y,20Y,-50,0.3049 10Y,20Y,-25,0.2832 10Y,20Y,0,0.2653 10Y,20Y,25,0.2507 10Y,20Y,50,0.2388 10Y,20Y,75,0.2294 10Y,20Y,100,0.2223 10Y,20Y,150,0.2131 10Y,20Y,200,0.2089 1M,20Y,-200,1.7578 1M,20Y,-150,0.9182 1M,20Y,-100,0.5991 1M,20Y,-75,0.4941 1M,20Y,-50,0.4118 1M,20Y,-25,0.3504 1M,20Y,-20,0.3405 1M,20Y,-15,0.3315 1M,20Y,-10,0.3233 1M,20Y,-5,0.3162 1M,20Y,0,0.3100 1M,20Y,5,0.3048 1M,20Y,10,0.3006 1M,20Y,15,0.2975 1M,20Y,20,0.2952 1M,20Y,25,0.2939 1M,20Y,50,0.2978 1M,20Y,75,0.3145 1M,20Y,100,0.3368 1M,20Y,150,0.3808 1M,20Y,200,0.4209 1Y,20Y,-200,1.0880 1Y,20Y,-150,0.6779 1Y,20Y,-100,0.5152 1Y,20Y,-75,0.4611 1Y,20Y,-50,0.4179 1Y,20Y,-25,0.3830 1Y,20Y,0,0.3552 1Y,20Y,25,0.3335 1Y,20Y,50,0.3171 1Y,20Y,75,0.3053 1Y,20Y,100,0.2973 1Y,20Y,150,0.2897 1Y,20Y,200,0.2886 2Y,20Y,-200,0.9368 2Y,20Y,-150,0.6213 2Y,20Y,-100,0.4826 2Y,20Y,-75,0.4360 2Y,20Y,-50,0.3986 2Y,20Y,-25,0.3680 2Y,20Y,0,0.3430 2Y,20Y,25,0.3227 2Y,20Y,50,0.3065 2Y,20Y,75,0.2940 2Y,20Y,100,0.2845 2Y,20Y,150,0.2728 2Y,20Y,200,0.2676 3M,20Y,-200,1.5135 3M,20Y,-150,0.8222 3M,20Y,-100,0.5804 3M,20Y,-75,0.4999 3M,20Y,-50,0.4359 3M,20Y,-25,0.3864 3M,20Y,-20,0.3782 3M,20Y,-15,0.3707 3M,20Y,-10,0.3637 3M,20Y,-5,0.3573 3M,20Y,0,0.3515 3M,20Y,5,0.3463 3M,20Y,10,0.3417 3M,20Y,15,0.3378 3M,20Y,20,0.3343 3M,20Y,25,0.3315 3M,20Y,50,0.3242 3M,20Y,75,0.3259 3M,20Y,100,0.3328 3M,20Y,150,0.3529 3M,20Y,200,0.3745 3Y,20Y,-200,0.8374 3Y,20Y,-150,0.5788 3Y,20Y,-100,0.4575 3Y,20Y,-75,0.4154 3Y,20Y,-50,0.3814 3Y,20Y,-25,0.3535 3Y,20Y,0,0.3304 3Y,20Y,25,0.3115 3Y,20Y,50,0.2961 3Y,20Y,75,0.2839 3Y,20Y,100,0.2745 3Y,20Y,150,0.2621 3Y,20Y,200,0.2559 4Y,20Y,-200,0.7681 4Y,20Y,-150,0.5432 4Y,20Y,-100,0.4342 4Y,20Y,-75,0.3956 4Y,20Y,-50,0.3640 4Y,20Y,-25,0.3378 4Y,20Y,0,0.3162 4Y,20Y,25,0.2984 4Y,20Y,50,0.2838 4Y,20Y,75,0.2722 4Y,20Y,100,0.2630 4Y,20Y,150,0.2510 4Y,20Y,200,0.2447 5Y,20Y,-200,0.7311 5Y,20Y,-150,0.5223 5Y,20Y,-100,0.4191 5Y,20Y,-75,0.3823 5Y,20Y,-50,0.3519 5Y,20Y,-25,0.3269 5Y,20Y,0,0.3060 5Y,20Y,25,0.2889 5Y,20Y,50,0.2750 5Y,20Y,75,0.2638 5Y,20Y,100,0.2552 5Y,20Y,150,0.2438 5Y,20Y,200,0.2380 6M,20Y,-200,1.2817 6M,20Y,-150,0.7434 6M,20Y,-100,0.5478 6M,20Y,-75,0.4828 6M,20Y,-50,0.4311 6M,20Y,-25,0.3905 6M,20Y,0,0.3598 6M,20Y,25,0.3384 6M,20Y,50,0.3252 6M,20Y,75,0.3185 6M,20Y,100,0.3164 6M,20Y,150,0.3200 6M,20Y,200,0.3281 6Y,20Y,-200,0.7000 6Y,20Y,-150,0.5036 6Y,20Y,-100,0.4050 6Y,20Y,-75,0.3698 6Y,20Y,-50,0.3406 6Y,20Y,-25,0.3164 6Y,20Y,0,0.2964 6Y,20Y,25,0.2799 6Y,20Y,50,0.2665 6Y,20Y,75,0.2557 6Y,20Y,100,0.2475 6Y,20Y,150,0.2366 6Y,20Y,200,0.2313 7Y,20Y,-200,0.6771 7Y,20Y,-150,0.4885 7Y,20Y,-100,0.3933 7Y,20Y,-75,0.3594 7Y,20Y,-50,0.3312 7Y,20Y,-25,0.3077 7Y,20Y,0,0.2883 7Y,20Y,25,0.2724 7Y,20Y,50,0.2594 7Y,20Y,75,0.2492 7Y,20Y,100,0.2412 7Y,20Y,150,0.2309 7Y,20Y,200,0.2258 8Y,20Y,-200,0.6607 8Y,20Y,-150,0.4760 8Y,20Y,-100,0.3829 8Y,20Y,-75,0.3498 8Y,20Y,-50,0.3223 8Y,20Y,-25,0.2995 8Y,20Y,0,0.2807 8Y,20Y,25,0.2651 8Y,20Y,50,0.2527 8Y,20Y,75,0.2428 8Y,20Y,100,0.2351 8Y,20Y,150,0.2255 8Y,20Y,200,0.2210 9Y,20Y,-200,0.6429 9Y,20Y,-150,0.4625 9Y,20Y,-100,0.3722 9Y,20Y,-75,0.3401 9Y,20Y,-50,0.3135 9Y,20Y,-25,0.2913 9Y,20Y,0,0.2729 9Y,20Y,25,0.2579 9Y,20Y,50,0.2458 9Y,20Y,75,0.2362 9Y,20Y,100,0.2288 9Y,20Y,150,0.2195 9Y,20Y,200,0.2151 10Y,2Y,-200,0.8560 10Y,2Y,-150,0.5773 10Y,2Y,-100,0.4615 10Y,2Y,-75,0.4226 10Y,2Y,-50,0.3908 10Y,2Y,-25,0.3643 10Y,2Y,0,0.3424 10Y,2Y,25,0.3238 10Y,2Y,50,0.3084 10Y,2Y,75,0.2954 10Y,2Y,100,0.2847 10Y,2Y,150,0.2688 10Y,2Y,200,0.2585 1M,2Y,-200,NA 1M,2Y,-150,NA 1M,2Y,-100,NA 1M,2Y,-75,1.1581 1M,2Y,-50,0.7831 1M,2Y,-25,0.6093 1M,2Y,-20,0.5863 1M,2Y,-15,0.5665 1M,2Y,-10,0.5497 1M,2Y,-5,0.5359 1M,2Y,0,0.5246 1M,2Y,5,0.5153 1M,2Y,10,0.5084 1M,2Y,15,0.5028 1M,2Y,20,0.4991 1M,2Y,25,0.4964 1M,2Y,50,0.5005 1M,2Y,75,0.5188 1M,2Y,100,0.5391 1M,2Y,150,0.5748 1M,2Y,200,0.6021 1Y,2Y,-200,NA 1Y,2Y,-150,NA 1Y,2Y,-100,1.4312 1Y,2Y,-75,0.9778 1Y,2Y,-50,0.7853 1Y,2Y,-25,0.6717 1Y,2Y,-20,0.6541 1Y,2Y,-15,0.6380 1Y,2Y,-10,0.6228 1Y,2Y,-5,0.6089 1Y,2Y,0,0.5959 1Y,2Y,5,0.5839 1Y,2Y,10,0.5725 1Y,2Y,15,0.5620 1Y,2Y,20,0.5522 1Y,2Y,25,0.5431 1Y,2Y,50,0.5057 1Y,2Y,75,0.4795 1Y,2Y,100,0.4613 1Y,2Y,150,0.4401 1Y,2Y,200,0.4310 2Y,2Y,-200,NA 2Y,2Y,-150,NA 2Y,2Y,-100,1.0852 2Y,2Y,-75,0.8630 2Y,2Y,-50,0.7339 2Y,2Y,-25,0.6466 2Y,2Y,-20,0.6323 2Y,2Y,-15,0.6190 2Y,2Y,-10,0.6063 2Y,2Y,-5,0.5944 2Y,2Y,0,0.5830 2Y,2Y,5,0.5724 2Y,2Y,10,0.5623 2Y,2Y,15,0.5529 2Y,2Y,20,0.5437 2Y,2Y,25,0.5352 2Y,2Y,50,0.4980 2Y,2Y,75,0.4693 2Y,2Y,100,0.4467 2Y,2Y,150,0.4157 2Y,2Y,200,0.3974 3M,2Y,-200,NA 3M,2Y,-150,NA 3M,2Y,-100,NA 3M,2Y,-75,1.1906 3M,2Y,-50,0.8598 3M,2Y,-25,0.6965 3M,2Y,-20,0.6737 3M,2Y,-15,0.6534 3M,2Y,-10,0.6355 3M,2Y,-5,0.6196 3M,2Y,0,0.6054 3M,2Y,5,0.5929 3M,2Y,10,0.5821 3M,2Y,15,0.5726 3M,2Y,20,0.5646 3M,2Y,25,0.5576 3M,2Y,50,0.5369 3M,2Y,75,0.5321 3M,2Y,100,0.5359 3M,2Y,150,0.5541 3M,2Y,200,0.5749 3Y,2Y,-200,NA 3Y,2Y,-150,2.7138 3Y,2Y,-100,0.9112 3Y,2Y,-75,0.7689 3Y,2Y,-50,0.6741 3Y,2Y,-25,0.6049 3Y,2Y,0,0.5523 3Y,2Y,25,0.5108 3Y,2Y,50,0.4777 3Y,2Y,75,0.4511 3Y,2Y,100,0.4296 3Y,2Y,150,0.3985 3Y,2Y,200,0.3788 4Y,2Y,-200,NA 4Y,2Y,-150,1.2480 4Y,2Y,-100,0.7712 4Y,2Y,-75,0.6728 4Y,2Y,-50,0.6018 4Y,2Y,-25,0.5475 4Y,2Y,0,0.5047 4Y,2Y,25,0.4703 4Y,2Y,50,0.4421 4Y,2Y,75,0.4190 4Y,2Y,100,0.4001 4Y,2Y,150,0.3718 4Y,2Y,200,0.3531 5Y,2Y,-200,NA 5Y,2Y,-150,0.9631 5Y,2Y,-100,0.6754 5Y,2Y,-75,0.6003 5Y,2Y,-50,0.5433 5Y,2Y,-25,0.4983 5Y,2Y,0,0.4620 5Y,2Y,25,0.4323 5Y,2Y,50,0.4078 5Y,2Y,75,0.3875 5Y,2Y,100,0.3706 5Y,2Y,150,0.3453 5Y,2Y,200,0.3285 6M,2Y,-200,NA 6M,2Y,-150,NA 6M,2Y,-100,2.1063 6M,2Y,-75,1.0959 6M,2Y,-50,0.8281 6M,2Y,-25,0.6862 6M,2Y,-20,0.6655 6M,2Y,-15,0.6469 6M,2Y,-10,0.6297 6M,2Y,-5,0.6143 6M,2Y,0,0.6005 6M,2Y,5,0.5880 6M,2Y,10,0.5766 6M,2Y,15,0.5662 6M,2Y,20,0.5570 6M,2Y,25,0.5487 6M,2Y,50,0.5188 6M,2Y,75,0.5028 6M,2Y,100,0.4955 6M,2Y,150,0.4943 6M,2Y,200,0.5012 6Y,2Y,-200,NA 6Y,2Y,-150,0.8025 6Y,2Y,-100,0.5993 6Y,2Y,-75,0.5398 6Y,2Y,-50,0.4930 6Y,2Y,-25,0.4554 6Y,2Y,0,0.4246 6Y,2Y,25,0.3990 6Y,2Y,50,0.3778 6Y,2Y,75,0.3600 6Y,2Y,100,0.3453 6Y,2Y,150,0.3229 6Y,2Y,200,0.3080 7Y,2Y,-200,1.3475 7Y,2Y,-150,0.7196 7Y,2Y,-100,0.5537 7Y,2Y,-75,0.5021 7Y,2Y,-50,0.4609 7Y,2Y,-25,0.4274 7Y,2Y,0,0.3996 7Y,2Y,25,0.3767 7Y,2Y,50,0.3574 7Y,2Y,75,0.3412 7Y,2Y,100,0.3277 7Y,2Y,150,0.3074 7Y,2Y,200,0.2938 8Y,2Y,-200,1.0788 8Y,2Y,-150,0.6571 8Y,2Y,-100,0.5144 8Y,2Y,-75,0.4684 8Y,2Y,-50,0.4313 8Y,2Y,-25,0.4008 8Y,2Y,0,0.3756 8Y,2Y,25,0.3545 8Y,2Y,50,0.3369 8Y,2Y,75,0.3220 8Y,2Y,100,0.3097 8Y,2Y,150,0.2912 8Y,2Y,200,0.2791 9Y,2Y,-200,0.9438 9Y,2Y,-150,0.6123 9Y,2Y,-100,0.4852 9Y,2Y,-75,0.4433 9Y,2Y,-50,0.4092 9Y,2Y,-25,0.3810 9Y,2Y,0,0.3576 9Y,2Y,25,0.3378 9Y,2Y,50,0.3215 9Y,2Y,75,0.3077 9Y,2Y,100,0.2962 9Y,2Y,150,0.2791 9Y,2Y,200,0.2680 10Y,30Y,-200,0.6565 10Y,30Y,-150,0.4572 10Y,30Y,-100,0.3638 10Y,30Y,-75,0.3312 10Y,30Y,-50,0.3044 10Y,30Y,-25,0.2822 10Y,30Y,0,0.2637 10Y,30Y,25,0.2488 10Y,30Y,50,0.2367 10Y,30Y,75,0.2274 10Y,30Y,100,0.2202 10Y,30Y,150,0.2112 10Y,30Y,200,0.2072 1M,30Y,-200,1.4241 1M,30Y,-150,0.8312 1M,30Y,-100,0.5566 1M,30Y,-75,0.4622 1M,30Y,-50,0.3866 1M,30Y,-25,0.3294 1M,30Y,-20,0.3201 1M,30Y,-15,0.3117 1M,30Y,-10,0.3039 1M,30Y,-5,0.2971 1M,30Y,0,0.2912 1M,30Y,5,0.2862 1M,30Y,10,0.2822 1M,30Y,15,0.2791 1M,30Y,20,0.2769 1M,30Y,25,0.2755 1M,30Y,50,0.2793 1M,30Y,75,0.2954 1M,30Y,100,0.3169 1M,30Y,150,0.3586 1M,30Y,200,0.3965 1Y,30Y,-200,0.9574 1Y,30Y,-150,0.6327 1Y,30Y,-100,0.4865 1Y,30Y,-75,0.4363 1Y,30Y,-50,0.3957 1Y,30Y,-25,0.3628 1Y,30Y,0,0.3362 1Y,30Y,25,0.3154 1Y,30Y,50,0.2998 1Y,30Y,75,0.2886 1Y,30Y,100,0.2812 1Y,30Y,150,0.2744 1Y,30Y,200,0.2740 2Y,30Y,-200,0.8640 2Y,30Y,-150,0.5894 2Y,30Y,-100,0.4602 2Y,30Y,-75,0.4161 2Y,30Y,-50,0.3803 2Y,30Y,-25,0.3509 2Y,30Y,0,0.3268 2Y,30Y,25,0.3073 2Y,30Y,50,0.2917 2Y,30Y,75,0.2797 2Y,30Y,100,0.2708 2Y,30Y,150,0.2600 2Y,30Y,200,0.2556 3M,30Y,-200,1.2563 3M,30Y,-150,0.7574 3M,30Y,-100,0.5436 3M,30Y,-75,0.4699 3M,30Y,-50,0.4106 3M,30Y,-25,0.3642 3M,30Y,-20,0.3565 3M,30Y,-15,0.3493 3M,30Y,-10,0.3428 3M,30Y,-5,0.3367 3M,30Y,0,0.3313 3M,30Y,5,0.3264 3M,30Y,10,0.3221 3M,30Y,15,0.3183 3M,30Y,20,0.3152 3M,30Y,25,0.3125 3M,30Y,50,0.3061 3M,30Y,75,0.3083 3M,30Y,100,0.3157 3M,30Y,150,0.3366 3M,30Y,200,0.3588 3Y,30Y,-200,0.7977 3Y,30Y,-150,0.5577 3Y,30Y,-100,0.4407 3Y,30Y,-75,0.4001 3Y,30Y,-50,0.3669 3Y,30Y,-25,0.3396 3Y,30Y,0,0.3171 3Y,30Y,25,0.2986 3Y,30Y,50,0.2838 3Y,30Y,75,0.2721 3Y,30Y,100,0.2632 3Y,30Y,150,0.2518 3Y,30Y,200,0.2464 4Y,30Y,-200,0.7491 4Y,30Y,-150,0.5299 4Y,30Y,-100,0.4224 4Y,30Y,-75,0.3843 4Y,30Y,-50,0.3529 4Y,30Y,-25,0.3270 4Y,30Y,0,0.3056 4Y,30Y,25,0.2880 4Y,30Y,50,0.2738 4Y,30Y,75,0.2626 4Y,30Y,100,0.2539 4Y,30Y,150,0.2427 4Y,30Y,200,0.2373 5Y,30Y,-200,0.7236 5Y,30Y,-150,0.5137 5Y,30Y,-100,0.4104 5Y,30Y,-75,0.3738 5Y,30Y,-50,0.3433 5Y,30Y,-25,0.3183 5Y,30Y,0,0.2975 5Y,30Y,25,0.2804 5Y,30Y,50,0.2666 5Y,30Y,75,0.2557 5Y,30Y,100,0.2472 5Y,30Y,150,0.2363 5Y,30Y,200,0.2310 6M,30Y,-200,1.0927 6M,30Y,-150,0.6891 6M,30Y,-100,0.5150 6M,30Y,-75,0.4551 6M,30Y,-50,0.4071 6M,30Y,-25,0.3689 6M,30Y,0,0.3400 6M,30Y,25,0.3198 6M,30Y,50,0.3074 6M,30Y,75,0.3013 6M,30Y,100,0.2998 6M,30Y,150,0.3041 6M,30Y,200,0.3127 6Y,30Y,-200,0.7012 6Y,30Y,-150,0.4982 6Y,30Y,-100,0.3984 6Y,30Y,-75,0.3630 6Y,30Y,-50,0.3336 6Y,30Y,-25,0.3093 6Y,30Y,0,0.2892 6Y,30Y,25,0.2727 6Y,30Y,50,0.2594 6Y,30Y,75,0.2489 6Y,30Y,100,0.2408 6Y,30Y,150,0.2304 6Y,30Y,200,0.2255 7Y,30Y,-200,0.6871 7Y,30Y,-150,0.4873 7Y,30Y,-100,0.3895 7Y,30Y,-75,0.3550 7Y,30Y,-50,0.3262 7Y,30Y,-25,0.3026 7Y,30Y,0,0.2829 7Y,30Y,25,0.2668 7Y,30Y,50,0.2539 7Y,30Y,75,0.2436 7Y,30Y,100,0.2358 7Y,30Y,150,0.2259 7Y,30Y,200,0.2212 8Y,30Y,-200,0.6784 8Y,30Y,-150,0.4782 8Y,30Y,-100,0.3815 8Y,30Y,-75,0.3475 8Y,30Y,-50,0.3192 8Y,30Y,-25,0.2959 8Y,30Y,0,0.2766 8Y,30Y,25,0.2609 8Y,30Y,50,0.2483 8Y,30Y,75,0.2383 8Y,30Y,100,0.2309 8Y,30Y,150,0.2215 8Y,30Y,200,0.2173 9Y,30Y,-200,0.6655 9Y,30Y,-150,0.4669 9Y,30Y,-100,0.3721 9Y,30Y,-75,0.3389 9Y,30Y,-50,0.3114 9Y,30Y,-25,0.2886 9Y,30Y,0,0.2699 9Y,30Y,25,0.2546 9Y,30Y,50,0.2423 9Y,30Y,75,0.2327 9Y,30Y,100,0.2254 9Y,30Y,150,0.2162 9Y,30Y,200,0.2122 10Y,5Y,-200,0.7596 10Y,5Y,-150,0.5355 10Y,5Y,-100,0.4327 10Y,5Y,-75,0.3971 10Y,5Y,-50,0.3679 10Y,5Y,-25,0.3436 10Y,5Y,0,0.3233 10Y,5Y,25,0.3063 10Y,5Y,50,0.2922 10Y,5Y,75,0.2805 10Y,5Y,100,0.2709 10Y,5Y,150,0.2571 10Y,5Y,200,0.2486 1M,5Y,-200,NA 1M,5Y,-150,NA 1M,5Y,-100,1.3245 1M,5Y,-75,0.9421 1M,5Y,-50,0.7337 1M,5Y,-25,0.6056 1M,5Y,-20,0.5869 1M,5Y,-15,0.5700 1M,5Y,-10,0.5553 1M,5Y,-5,0.5424 1M,5Y,0,0.5316 1M,5Y,5,0.5224 1M,5Y,10,0.5150 1M,5Y,15,0.5091 1M,5Y,20,0.5045 1M,5Y,25,0.5012 1M,5Y,50,0.4992 1M,5Y,75,0.5131 1M,5Y,100,0.5334 1M,5Y,150,0.5737 1M,5Y,200,0.6072 1Y,5Y,-200,NA 1Y,5Y,-150,NA 1Y,5Y,-100,0.9357 1Y,5Y,-75,0.7732 1Y,5Y,-50,0.6694 1Y,5Y,-25,0.5964 1Y,5Y,0,0.5424 1Y,5Y,25,0.5017 1Y,5Y,50,0.4712 1Y,5Y,75,0.4486 1Y,5Y,100,0.4320 1Y,5Y,150,0.4113 1Y,5Y,200,0.4015 2Y,5Y,-200,NA 2Y,5Y,-150,1.3330 2Y,5Y,-100,0.7802 2Y,5Y,-75,0.6723 2Y,5Y,-50,0.5960 2Y,5Y,-25,0.5389 2Y,5Y,0,0.4946 2Y,5Y,25,0.4598 2Y,5Y,50,0.4320 2Y,5Y,75,0.4102 2Y,5Y,100,0.3929 2Y,5Y,150,0.3693 2Y,5Y,200,0.3554 3M,5Y,-200,NA 3M,5Y,-150,NA 3M,5Y,-100,1.2131 3M,5Y,-75,0.9225 3M,5Y,-50,0.7535 3M,5Y,-25,0.6440 3M,5Y,-20,0.6272 3M,5Y,-15,0.6119 3M,5Y,-10,0.5980 3M,5Y,-5,0.5855 3M,5Y,0,0.5743 3M,5Y,5,0.5641 3M,5Y,10,0.5552 3M,5Y,15,0.5473 3M,5Y,20,0.5404 3M,5Y,25,0.5346 3M,5Y,50,0.5160 3M,5Y,75,0.5107 3M,5Y,100,0.5129 3M,5Y,150,0.5271 3M,5Y,200,0.5442 3Y,5Y,-200,NA 3Y,5Y,-150,0.9940 3Y,5Y,-100,0.6815 3Y,5Y,-75,0.6017 3Y,5Y,-50,0.5419 3Y,5Y,-25,0.4954 3Y,5Y,0,0.4583 3Y,5Y,25,0.4284 3Y,5Y,50,0.4041 3Y,5Y,75,0.3844 3Y,5Y,100,0.3686 3Y,5Y,150,0.3459 3Y,5Y,200,0.3320 4Y,5Y,-200,NA 4Y,5Y,-150,0.8346 4Y,5Y,-100,0.6137 4Y,5Y,-75,0.5501 4Y,5Y,-50,0.5004 4Y,5Y,-25,0.4609 4Y,5Y,0,0.4290 4Y,5Y,25,0.4028 4Y,5Y,50,0.3812 4Y,5Y,75,0.3635 4Y,5Y,100,0.3492 4Y,5Y,150,0.3281 4Y,5Y,200,0.3148 5Y,5Y,-200,1.4151 5Y,5Y,-150,0.7405 5Y,5Y,-100,0.5665 5Y,5Y,-75,0.5124 5Y,5Y,-50,0.4694 5Y,5Y,-25,0.4343 5Y,5Y,0,0.4057 5Y,5Y,25,0.3821 5Y,5Y,50,0.3625 5Y,5Y,75,0.3462 5Y,5Y,100,0.3328 5Y,5Y,150,0.3130 5Y,5Y,200,0.3003 6M,5Y,-200,NA 6M,5Y,-150,NA 6M,5Y,-100,1.0846 6M,5Y,-75,0.8579 6M,5Y,-50,0.7219 6M,5Y,-25,0.6307 6M,5Y,0,0.5678 6M,5Y,25,0.5252 6M,5Y,50,0.4975 6M,5Y,75,0.4807 6M,5Y,100,0.4712 6M,5Y,150,0.4649 6M,5Y,200,0.4671 6Y,5Y,-200,1.0999 6Y,5Y,-150,0.6737 6Y,5Y,-100,0.5272 6Y,5Y,-75,0.4797 6Y,5Y,-50,0.4413 6Y,5Y,-25,0.4099 6Y,5Y,0,0.3839 6Y,5Y,25,0.3624 6Y,5Y,50,0.3445 6Y,5Y,75,0.3297 6Y,5Y,100,0.3175 6Y,5Y,150,0.2995 6Y,5Y,200,0.2880 7Y,5Y,-200,0.9539 7Y,5Y,-150,0.6262 7Y,5Y,-100,0.4971 7Y,5Y,-75,0.4541 7Y,5Y,-50,0.4193 7Y,5Y,-25,0.3904 7Y,5Y,0,0.3665 7Y,5Y,25,0.3466 7Y,5Y,50,0.3300 7Y,5Y,75,0.3163 7Y,5Y,100,0.3050 7Y,5Y,150,0.2884 7Y,5Y,200,0.2778 8Y,5Y,-200,0.8663 8Y,5Y,-150,0.5891 8Y,5Y,-100,0.4716 8Y,5Y,-75,0.4316 8Y,5Y,-50,0.3992 8Y,5Y,-25,0.3721 8Y,5Y,0,0.3497 8Y,5Y,25,0.3311 8Y,5Y,50,0.3155 8Y,5Y,75,0.3025 8Y,5Y,100,0.2920 8Y,5Y,150,0.2764 8Y,5Y,200,0.2667 9Y,5Y,-200,0.8055 9Y,5Y,-150,0.5599 9Y,5Y,-100,0.4507 9Y,5Y,-75,0.4132 9Y,5Y,-50,0.3825 9Y,5Y,-25,0.3570 9Y,5Y,0,0.3358 9Y,5Y,25,0.3180 9Y,5Y,50,0.3032 9Y,5Y,75,0.2910 9Y,5Y,100,0.2810 9Y,5Y,150,0.2664 9Y,5Y,200,0.2573RQuantLib/inst/shiny/SabrSwaption/README.md0000755000176200001440000000000612744670072020125 0ustar liggesusers# cftcRQuantLib/inst/shiny/SabrSwaption/volDF2CubeK.R0000644000176200001440000000501312757140057020776 0ustar liggesusersvolDF2CubeK <- function(params, tbl, source = "CME") { strikes <- levels(tbl$Spread)<-c(-200,-150,-100,-75,-50,-25,0,25,50,75,100,150,200) matYears <- as.numeric(params$maturity-params$tradeDate)/365 expYears <- as.numeric(params$expiryDate-params$tradeDate)/365 expLvl <- c( "1M","3M","6M","1Y","2Y","3Y","4Y", "5Y", "6Y", "7Y", "8Y", "9Y","10Y") tbl$Expiry <- factor(tbl$Expiry, levels <- expLvl) expiries <- c(1/12,.25,.5,1,2,3,4,5,6,7,8,9,10) tenorLvl <- c( "1Y", "2Y", "5Y", "10Y","15Y","20Y","30Y") tbl$Tenor <- factor(tbl$Tenor, levels = tenorLvl) tenors <- c(1,2,5,10,15,20,30) tenorIDX <- max(findInterval(matYears-expYears,tenors),1) tenorIDX <- min(tenorIDX,length(tenors)-3) expiryIDX <- findInterval(expYears,expiries) expiryIDX <- min(expiryIDX,length(expiries)-3) strikeIDX <- 1 expire <- expLvl[expiryIDX] tenor <- tenorLvl[tenorIDX] for(strike in levels(tbl$Spread)){ if(!is.na(tbl[tbl$Expiry==expire & tbl$Spread==strike &tbl$Tenor==tenor,]$LogNormalVol))break; strikeIDX <- strikeIDX+1 } strikes <- strikes[strikeIDX:length(strikes)] expLvl <- expLvl[expiryIDX:length(expLvl)] expiries <- expiries[expiryIDX:length(expiries)] tenorLvl <- tenorLvl[tenorIDX:length(tenorLvl)] tenors <- tenors[tenorIDX:length(tenors)] tbl <- tbl[tbl$Expiry%in%expLvl,] tbl <- tbl[tbl$Tenor%in%tenorLvl,] tbl <- tbl[tbl$Spread%in%strikes,] tbl <- tbl[with(tbl,order(Expiry,Tenor,Spread)),] tbl3 <- tbl[tbl$Spread==0,] # atm vol matrix atmMat=acast(tbl3,Expiry~Tenor,value.var = "LogNormalVol") #atmMat=matrix(data=NA,nrow=length(expLvl),ncol=length(tenorLvl),dimnames=list(expLvl,tenorLvl)) # for(i in 1:length(expLvl)){ # for(j in 1:length(tenorLvl)){ # atmMat[i,j]=tbl[tbl$Expiry==expLvl[i]& tbl$Tenor==tenorLvl[j] & tbl$Spread==0,]$LogNormalVol # } # } smirk=matrix(ncol=length(strikes),nrow=length(expLvl)*length(tenorLvl)) tmp3=acast(tbl,Expiry~Tenor~Spread,value.var="LogNormalVol") k=0 for(i in 1:length(expLvl)){ for(j in 1:length(tenorLvl)){ k=k+1 #for(n in 1:length(strikes)){ smirk[k,]=tmp3[i,j,]-tmp3[i,j,"0"] #smirk[k,n]=tbl[tbl$Expiry==expLvl[i]& tbl$Tenor==tenorLvl[j] & tbl$Spread==strikes[n],]$LogNormalVol - # tbl[tbl$Expiry==expLvl[i]& tbl$Tenor==tenorLvl[j] & tbl$Spread==0,]$LogNormalVol #} } } smirk <- na.spline(smirk,method="natural") tmp <- list(atmVol=atmMat,tenors=tenors,expiries=expiries,smirk=smirk,strikes=strikes/10000) class(tmp) <- "volcube" return(tmp) }RQuantLib/inst/shiny/SabrSwaption/server.R0000644000176200001440000001300612757140057020277 0ustar liggesusers # This is the server logic for a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(rhandsontable) library(lubridate) library(reshape2) library(zoo) library(data.table) data(vcube) data(tsQuotes) library(shiny) assignInNamespace("volDF2CubeK",source("volDF2CubeK.R"),"RQuantLib") # tsQuotes <- list( # d1w =0.004, # d1y=.0091, # s2y=.0115, # s3y=.0138, # s4y =.011349, # s5y =0.012375, # s6y =.0134, # s7y=.01446, # s10y =0.016829, # s15y =0.01944, # s30y=.02178, # s50y=.02205) tsQuoteUp01=lapply(tsQuotes,"+",.0001) tsQuoteDn01=lapply(tsQuotes,"-",.0001) setEvaluationDate(as.Date("2016-4-30")) params <- list(tradeDate=as.Date('2016-4-28'), settleDate=as.Date('2016-4-30'), payFixed=TRUE, #european=F, dt=.25, interpWhat="discount", interpHow="loglinear") legparams=list(dayCounter="Thirty360", fixFreq="Annual", floatFreq="Semiannual") times<-times <- seq(0,49.5,.25) dcurve <- DiscountCurve(params, tsQuotes, times=times,legparams) dcurveUp01 <- DiscountCurve(params, tsQuoteUp01, times=times,legparams) dcurveDn01 <- DiscountCurve(params, tsQuoteDn01, times=times,legparams) expiriesY=c(1/12,.25,.5,1,2,3,4,5,6,7,8,9,10) expiriesM=c(1,3,6,0,0,0,0,0,0,0,0,0,0) expLvl=c("1M","3M","6M","1Y" , "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y","10Y") tenorLvl=c("1Y" , "2Y", "5Y", "10Y","15Y","20Y","30Y") tenors=c(1,2,5,10,15,20,30) shinyServer(function(input, output) { inputVol<-vcube output$table<- renderRHandsontable({ tbl2=inputVol tbl2$Expiry<-factor(tbl2$Expiry,level=expLvl) tbl2$Tenor=factor(tbl2$Tenor,level=tenorLvl) tbl2=subset(tbl2,Expiry %in% input$expiries) tbl2=subset(tbl2,Tenor %in% input$tenors) tbl2=tbl2[with(tbl2,order(Expiry,Tenor,-Spread))] tbl2[,"payer"]<- -.0000001 tbl2[,"payerDV01"]<- -.0000001 tbl2[,"payerCnvx"]<- -.0000001 tbl2[,"rcv"]<- -.0000001 tbl2[,"rcvDV01"]<- -.0000001 tbl2[,"rcvCnvx"]<- -.0000001 tbl2[,"payerVega"]<- -.0000001 tbl2[,"rcvVega"]<- -.0000001 tbl2[,"sabrVol"]<- -.0000001 tbl2[,"strike"]<- -.00000001 for(expire in input$expiries){ for(tenor in input$tenors){ expIDX=match(expire,expLvl) expiry=params$settleDate; if(expIDX>3){ year(expiry)=year(expiry)+expiriesY[expIDX] } else{ expiry=expiry%m+% months(expiriesM[expIDX]) } tenorIDX=match(tenor,tenorLvl) tenorVal=expiry; params$european=!input$bermudan year(tenorVal)=year(tenorVal)+tenors[tenorIDX] params$expiryDate=expiry if(params$european){params$startDate=expiry;}else{params$startDate=params$settleDate} params$maturity=tenorVal params$strike=.03 tmp2<-SabrSwaption(params, dcurve, inputVol,legparams, vega=T) fwd1=tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==0,]$Strike fwdDiff=fwd1-tmp2$atmRate for(spread in unique(tbl2$Spread)){ params$strike=tmp2$atmRate+spread/10000 if(params$strike>0){ tmp<-SabrSwaption(params, dcurve, inputVol,legparams,tsUp01=dcurveUp01,tsDn01=dcurveDn01,vega=T) tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,rcv:=signif(tmp$rcv,digits=4)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,payer:=signif(tmp$pay,digits=4)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,rcvDV01:=signif(tmp$rcvDV01,digits=6)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,rcvCnvx:=signif(tmp$rcvCnvx,digits=6)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,payerDV01:=signif(tmp$payDV01,digits=6)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,payerCnvx:=signif(tmp$payCnvx,digits=6)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,rcvVega:=signif(tmp$rcvVega,digits=4)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,payerVega:=signif(tmp$payVega,digits=4)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,sabrVol:=signif(tmp$sigma,digits=3)] tbl2[tbl2$Expiry==expire & tbl2$Tenor== tenor & tbl2$Spread==spread,strike:=signif(params$strike,digits=4)] } } } } tbl2=tbl2[,c("Expiry","Tenor","Spread","strike","LogNormalVol","sabrVol","payer","payerDV01","payerCnvx","payerVega","rcv","rcvDV01","rcvCnvx","rcvVega"),with=F] numRow=length(tbl2) rhandsontable(tbl2,readOnly = F,rowHeaders=NULL,selectCallback = TRUE,halign="htCenter")%>% hot_col("strike", format = "0.0000") %>% hot_col("LogNormalVol", format = "0.00") %>% hot_col("sabrVol", format = "0.00") %>% hot_col("payer", format = "0.0000") %>% hot_col("payerDV01", format = "0.000000") %>% hot_col("payerCnvx", format = "0.000000") %>% hot_col("payerVega", format = "0.0000") %>% hot_col("rcv", format = "0.000")%>% hot_col("rcvDV01", format = "0.00000")%>% hot_col("rcvCnvx", format = "0.00000")%>% hot_col("rcvVega", format = "0.0000") }) }) RQuantLib/inst/shiny/SabrSwaption/ui.R0000644000176200001440000000226012744670072017407 0ustar liggesusers # This is the user-interface definition of a Shiny web application. # You can find out more about building applications with Shiny here: # # http://shiny.rstudio.com # library(shiny) shinyUI(fluidPage( # Application title titlePanel("SABR Vol Cube Tool"), checkboxGroupInput("expiries", label = h3("Option Expiries"), inline=T, choices=list("1M"="1M","3M"="3M","6M"="6M","1Y"="1Y" , "2Y"="2Y", "3Y"="3Y", "4Y"="4Y", "5Y"="5Y", "6Y"="6Y", "7Y"="7Y", "8Y"="8Y", "9Y"="9Y","10Y"="10Y"), # selected = c("1M","3M","6M","1Y" , "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y","10Y")), selected = c( "3Y", "4Y","5Y")), checkboxGroupInput("tenors", label = h3("Swap Tenors"), inline=T, choices=list("1Y"="1Y" , "2Y"="2Y", "5Y"="5Y","10Y"="10Y","15Y"="15Y","20Y"="20Y","30Y"="30Y"), #selected = c("1Y" , "2Y", "5Y", "10Y","15Y","20Y","30Y")), selected = c( "5Y")), checkboxInput("bermudan", label = "Bermudan Exercise?", value = F), # Show a plot of the generated distribution mainPanel( rHandsontableOutput(outputId="table") ) )) RQuantLib/inst/NEWS.Rd0000644000176200001440000002536213564333065014153 0ustar liggesusers\name{NEWS} \title{News for Package \pkg{RQuantLib}} \newcommand{\ghpr}{\href{https://github.com/eddelbuettel/rquantlib/pull/#1}{##1}} \newcommand{\ghit}{\href{https://github.com/eddelbuettel/rquantlib/issues/#1}{##1}} \newcommand{\ghrp}{\href{https://github.com/#1}{##1}} \section{Changes in \pkg{RQuantLib} version 0.4.11 (20xx-yy-zz)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item The 'Null' calendar without weekends or holidays is now recognized. } } } \section{Changes in \pkg{RQuantLib} version 0.4.10 (2019-08-07)}{ \itemize{ \item Changes in \pkg{RQuantLib} build system: \itemize{ \item The \code{src/Makevars.win} and \code{tools/winlibs.R} file get QuantLib 1.16 for either toolchain (Jeroes in \ghpr{136}). \item The custom Docker container now downloads QuantLib from Debian unstable to get release 1.16 (from yesterday, no less) } } } \section{Changes in \pkg{RQuantLib} version 0.4.9 (2019-05-15)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item Completed switch to \code{QuantLib::ext} namespace wrappers for either \code{shared_ptr} use started in 0.4.8. } } } \section{Changes in \pkg{RQuantLib} version 0.4.8 (2019-03-17)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item Source code supports Boost \code{shared_ptr} and C+11 \code{shared_ptr} via \code{QuantLib::ext} namespace like upstream. } \item Changes in \pkg{RQuantLib} build system: \itemize{ \item The \code{configure.ac} file no longer upsets \code{R CMD check}; the change does not actually change \code{configure}. } } } \section{Changes in \pkg{RQuantLib} version 0.4.7 (2018-12-10)}{ \itemize{ \item Changes in \pkg{RQuantLib} tests: \itemize{ \item Thanks to the updated \ghrp{rwinlib/quantlib} Windows library provided by Josh, all tests that previously exhibited issues have been re-enabled (Dirk in \ghpr{126}). } \item Changes in \pkg{RQuantLib} documentation: \itemize{ \item The \code{CallableBonds} example now sets an evaluation date (\ghit{124}). \item Thanks to the updated \ghrp{rwinlib/quantlib} Windows library provided by Josh, examples that were set to \code{dontrun} are re-activated (Dirk in \ghpr{126}). \code{AffineSwaption} remains the sole holdout. } \item Changes in \pkg{RQuantLib} build system: \itemize{ \item The \code{src/Makevars.win} file was updated to reflect the new layout used by the upstream build. \item The \code{-DBOOST_NO_AUTO_PTR} compilation flag is now set. } } } \section{Changes in \pkg{RQuantLib} version 0.4.6 (2018-11-25)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item The code was updated for release 1.14 of QuantLib. \item The code was updated for Boost 1.67 or later (\ghpr{120} fixing \ghit{119}, Debian bug report #911957) to support \item Fewer examples and tests are running on Windows. \item Corrected bond function documentation to use \code{dayCounter} instead of \code{accruedDayCounter}. \item Two new functions \code{addHolidays} and \code{removeHolidays} enable custom local holiday management (\ghit{115}). \item Corrected bond function documentation to use \code{dayCounter} instead of \code{accruedDayCounter}. \item Travis CI now uses a custom Docker container, also added a deployment container building on the testing container. } } } \section{Changes in \pkg{RQuantLib} version 0.4.5 (2018-08-10)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item The old \code{rquantlib.h} header is deprecated and moved to a subdirectory. (Some OS confuse it with \code{RQuantLib.h} which Rcpp Attributes like to be the same name as the package.) (Dirk in \ghpr{100} addressing \ghit{99}). \item The files in \code{src/} now include \code{rquantlib_internal.h} directly. \item Several \sQuote{unused variable} warnings have been taken care of. \item The Windows build has been updated, and now uses an external QuantLib library from 'rwinlib' (Jeroen Ooms in \ghpr{105}). \item Three curve-building example are no longer running by default as win32 has seen some numerical issues. \item Two \code{Rcpp::compileAttributes} generated files have been updated. } } } \section{Changes in \pkg{RQuantLib} version 0.4.4 (2017-11-07)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item Equity options can now be analyzed via discrete dividends through two vectors of dividend dates and values (Francois Cocquemas in \ghpr{73} fixing \ghit{72}) \item Some package and dependency information was updated in files \code{DESCRIPTION} and \code{NAMESPACE}. \item The new \code{Date(time)Vector} classes introduced with Rcpp 0.12.8 are now used when available. \item Minor corrections were applied to \code{BKTree}, to vanilla options for the case of intraday time stamps, to the \code{SabrSwaption} documentation, and to bond utilities for the most recent QuantLib release. } } } \section{Changes in \pkg{RQuantLib} version 0.4.3 (2016-08-19)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item Discount curve creation has been made more general by allowing additional arguments for day counter and fixed and floating frequency (contributed by Terry Leitch in \ghpr{31}, plus some work by Dirk in \ghpr{32}). \item Swap leg parameters are now in combined variable and allow textual description (Terry Leitch in \ghpr{34} and \ghpr{35}) \item BermudanSwaption has been modfied to take option expiration and swap tenors in order to enable more general swaption structure pricing; a more general search for the swaptions was developed to accomodate this. Also, a DiscountCurve is allowed as an alternative to market quotes to reduce computation time for a portfolio on a given valuation date (Terry Leitch in \ghpr{42} closing issue \ghpr{41}). \item A new AffineSwaption model was added with similar interface to BermudanSwaption but allowing for valuation of a European exercise swaption utlizing the same affine methods available in BermudanSwaption. AffineSwaption will also value a Bermudan swaption, but does not take rate market quotes to build a term structure and a DiscountCurve object is required (Terry Leitch in \ghpr{43}). \item Swap tenors can now be defined up to 100 years (Terry Leitch in \ghpr{48} fising issue \ghit{46}). \item Additional (shorter term) swap tenors are now defined (Guillaume Horel in \ghpr{49}, \ghpr{54}, \ghpr{55}). \item New SABR swaption pricer (Terry Leitch in \ghpr{60} and \ghpr{64}, small follow-up by Dirk in \ghpr{65}). \item Use of Travis CI has been updated and switch to maintained fork of deprecated mainline. } } } \section{Changes in \pkg{RQuantLib} version 0.4.2 (2015-12-30)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item Intra-day times are now available if QuantLib 1.7 or later is used, and has been configured with \code{--enable-intraday} \item New helper functions \code{getQuantLibVersion()} and \code{getQuantLibCapabilties()} \item New package startup code detects and warns about outdated QuantLib versions, or missing intra-day capability, unless not interactive. \item The missing \code{Monthly} parameter has been added to \code{matchFrequency} (fixing issue ticket \ghit{19}) } } } \section{Changes in \pkg{RQuantLib} version 0.4.1 (2015-09-11)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item A simple \CRANpkg{shiny} application is now included in the directory \code{shiny/DiscountCurve/} and accessible via the new demo function \code{ShinyDiscountCurve}. \item The option surface plotting example in \code{arrays.R} now checks for \CRANpkg{rgl} by using \code{requireNamespace}. \item The files \code{NAMESPACE} and \code{DESCRIPTION} have been updated to reflect all the suggestions of \code{R CMD check}. \item The Travis CI tests now use binary Debian packages for all package dependencies making the tests a little faster. } } } \section{Changes in \pkg{RQuantLib} version 0.4.0 (2014-12-01)}{ \itemize{ \item Changes in \pkg{RQuantLib} code: \itemize{ \item All function interfaces have been rewritten using \CRANpkg{Rcpp} Attributes. No \code{SEXP} remain in the function signatures. This make the code shorter, more readable and more easily extensible. \item The header files have been reorganized so that plugin use is possible. An \code{impl.h} files is imported once for each compilation unit: for RQuantLib from the file \code{src/dates.cpp} directory, from a sourced file via a \code{#define} set by the plugin wrapper. \item \code{as<>()} and \code{wrap()} converters have added for QuantLib Date types. \item Plugin support has been added, allowing more ad-hoc use via Rcpp Attributes. \item Several Fixed Income functions have been added, and/or rewritten to better match the QuantLib signatures; this was done mostly by Michele Salvadore. \item Several Date and Calendar functions have been added. \item Calendar support has been greatly expanded thanks to Danilo Dias da Silva. \item Exported curve objects are now more parsimonious and advance entries in the \code{table} object roughly one business month at a time. \item The \code{DiscountCurve} and \code{Bond} curve construction has been fixed via a corrected evaluation date and omitted the two-year swap rate, as suggested by Luigi Ballabio. \item The \code{NAMESPACE} file has a tighter rule for export of \code{*.default} functions, as suggested by Bill Dunlap \item Builds now use OpenMP where available. \item The package now depends on QuantLib 1.4.0 or later. } \item Changes in \pkg{RQuantLib} tests: \itemize{ \item New unit tests for dates have been added. \item C++ code for the unit tests has also been converted to \CRANpkg{Rcpp} Attributes use; a helper function \code{unitTestSetup()} has been added. \item Continuous Integration via Travis is now enabled from the GitHub repo. } \item Changes in \pkg{RQuantLib} documentation: \itemize{ \item This NEWS file has been added. Better late than never, as they say. } } } RQuantLib/cleanup0000755000176200001440000000050313607470337013500 0ustar liggesusers#!/bin/sh Rscript -e 'library(Rcpp); compileAttributes(".")' rm -rf 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/configure0000755000176200001440000035220413607470337014042 0ustar liggesusers#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for RQuantlib 0.4.11. # # # Copyright (C) 1992-1996, 1998-2012 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. as_myself= 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 # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # 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. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} 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 test -x / || 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 : export CONFIG_SHELL # 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. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 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_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_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; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # 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 -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' 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 as_test_x='test -x' as_executable_p=as_fn_executable_p # 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.4.11' PACKAGE_STRING='RQuantlib 0.4.11' PACKAGE_BUGREPORT='' PACKAGE_URL='' ac_subst_vars='LTLIBOBJS LIBOBJS QUANTLIB 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 runstatedir 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' runstatedir='${localstatedir}/run' 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 ;; -runstatedir | --runstatedir | --runstatedi | --runstated \ | --runstate | --runstat | --runsta | --runst | --runs \ | --run | --ru | --r) ac_prev=runstatedir ;; -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ | --run=* | --ru=* | --r=*) runstatedir=$ac_optarg ;; -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 runstatedir 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 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.4.11 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] --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] --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.4.11:";; 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.4.11 generated by GNU Autoconf 2.69 Copyright (C) 2012 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; ${as_lineno_stack:+:} 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; ${as_lineno_stack:+:} 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.4.11, which was generated by GNU Autoconf 2.69. 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 # Set CXX and CXXFLAGS based on the R configuration (with thanks to KH) : ${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` # 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 ${ac_cv_prog_CXX+:} false; 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 as_fn_executable_p "$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 ${ac_cv_prog_ac_ct_CXX+:} false; 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 as_fn_executable_p "$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 ${ac_cv_objext+:} false; 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 ${ac_cv_cxx_compiler_gnu+:} false; 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 ${ac_cv_prog_cxx_g+:} false; 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 ${ac_cv_prog_CXXCPP+:} false; 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 ${ac_cv_prog_CXX+:} false; 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 as_fn_executable_p "$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 ${ac_cv_prog_ac_ct_CXX+:} false; 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 as_fn_executable_p "$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 ${ac_cv_cxx_compiler_gnu+:} false; 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 ${ac_cv_prog_cxx_g+:} false; 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.*|4.9.*|5.*|6.*|7.*|8.*|9.*|10.*) 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 ${ac_cv_prog_R+:} false; 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 as_fn_executable_p "$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 ## We no longer need to set LDFLAGS for Rcpp 0.11.0 or later, ## and hence no longer need to check for Rscipt ## ## ## 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 # 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 ${ac_cv_prog_QUANTLIB+:} false; 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 as_fn_executable_p "$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.*|1.0.*|1.1.*|1.2.*|1.3.*|1.4.*|1.5.*|1.6.*|1.7.*|1.8*|1.9.*|1.10.*|1.11.*|1.12.*|1.13.*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: RQuantLib requires QuantLib (>= 1.14)." >&5 $as_echo "$as_me: WARNING: RQuantLib requires QuantLib (>= 1.14)." >&2;} as_fn_error $? "Please upgrade to a current 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 if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi 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. as_myself= 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 -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' 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 # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # 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.4.11, which was generated by GNU Autoconf 2.69. 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.4.11 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 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= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_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 -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # 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 {' >"$ac_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 >>"\$ac_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 >>"\$ac_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 < "$ac_tmp/subs1.awk" > "$ac_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="$ac_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 >"$ac_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 "$ac_tmp/subs.awk" \ >$ac_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' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_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 "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_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: ***