通过Rcpp从R调用QuantLib

Calling QuantLib from R through Rcpp

本文关键字:调用 QuantLib Rcpp 通过      更新时间:2023-10-16

初步步骤

QuantLibBoost一起安装,并按照这些说明在Microsoft Visual C++2010中构建;测试代码继续进行,没有出现任何问题。

将R与以下示例代码一起使用,可以得到预期的结果:

install.packages("Rcpp")
library(Rcpp)
cppFunction('
  int add(int x, int y, int z) {
    int sum = x + y + z;
    return sum;
  }'
)
add(1, 2, 3)
# > add(1, 2, 3)
# [1] 6

关于使用单独的C++文件,下面的例子是

#include <Rcpp.h>
using namespace Rcpp;
// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar)
// For more on using Rcpp click the Help button on the editor toolbar
// [[Rcpp::export]]
int timesTwo(int x) {
   return x * 2;
}

R中的结果是

> timesTwo(7)
[1] 14

我想一切都很好。

我的问题

如果我的设置是正确的,我的问题是:假设我的QuantLib-vc100-mt-gd.lib对象文件库在C:DevToolsQuantLib-1.3lib中,如果从R调用,我应该怎么做才能使下面的代码正常工作?

#include <ql/quantlib.hpp>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double timesTwo(double x) {
  QuantLib::Calendar myCal = QuantLib::UnitedKingdom();
  QuantLib::Date newYearsEve(31, QuantLib::Dec, 2008);
  QuantLib::Rate zc3mQuote = x;
  return zc3mQuote * 2;
}

请参阅Rcpp常见问题解答,了解"我可以将R和Rcpp与Visual Studio一起使用吗?"(太长了,读不下去了:不,不能(。

但在Rcpp出现之前,就已经有了RQuantLib,而且它仍然存在。下载它的源代码,从牛津的"extrass"网站下载quantlib-1.4.zip,然后用它重建RQuantLib。它使用Rcpp。

然后,您可以随心所欲地扩展RQuantLib。

最新的RQuantLib也有一个类似于RcppArmadillo和RcppEigen的插件,所以你可以构建像你发布的那样的快速小测试文件。我将在周末尝试用一个证明存在的例子来跟进。

编辑正如承诺的那样,我尝试了一下。使用当前的RQuantLib(0.3.12(和Rcpp(0.11.1,今天发布,但0.11.0应该可以工作(,并且您的文件保存在/tmp/lisaann.cpp中,这"刚刚工作":

R> library(Rcpp)
R> sourceCpp("/tmp/lisaann.cpp")
R> timesTwo(1.23)
[1] 2.46
R> 

如果在Windows上失败,请确保有

  • 已安装R工具
  • 供R使用的预构建QuantLib(请参阅我最近的博客文章(
  • 设置src/Makevars.win期望的环境变量

否则,只需在虚拟机中使用Ubuntu、Debian或任何其他正常的操作系统。

Edit 2:不过,一个重要的部分是将[[ Rcpp::depends() ]]属性添加到代码中。这是我使用的文件:

#include <ql/quantlib.hpp>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::depends(RQuantLib)]]
// [[Rcpp::export]]
double timesTwo(double x) {
  QuantLib::Calendar myCal = QuantLib::UnitedKingdom();
  QuantLib::Date newYearsEve(31, QuantLib::Dec, 2008);
  QuantLib::Rate zc3mQuote = x;
  return zc3mQuote * 2;
}

它与您的不同之处仅在于对此处使用的插件的(重要!(引用。