从R到Rcpp调用QuantLib

时间:2014-03-14 19:34:31

标签: c++ r rcpp quantlib

预备步骤

QuantLibBoost一起安装,并在Microsoft Visual C ++ 2010中遵循these指令构建;测试代码继续没有问题。

将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:\DevTools\QuantLib-1.3\lib中,如果从{{{{}}调用,我该怎么做才能使下面的代码正常工作1}}?

R

1 个答案:

答案 0 :(得分:2)

请参阅Rcpp常见问题解答一般性问题&#39;我可以在Visual Studio中使用R和Rcpp吗? (tl;博士:不,你不能)。

但是在Rcpp之前已经存在RQuantLib,它仍然存在。下载其源代码,从the 'extras' site in Oxford下载quantlib-1.4.zip,然后用它重建RQuantLib。其中使用Rcpp。

然后,您可以将RQuantLib扩展到您心中的内容。

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

编辑正如所承诺的,我放弃了。使用当前的RQuantLib(0.3.12)和Rcpp(0.11.1,今天发布,但0.11.0应该可以工作),你的文件保存在/tmp/lisaann.cpp这个&#34;只是工作&#34;:

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

如果在Windows上失败,请确保

  • 已安装Rtools
  • 由R使用的预构建QuantLib(请参阅my recent blog post
  • 设置了src/Makevars.win期望
  • 的环境变量

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

编辑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;
}

与你的不同之处仅在于(重要!)对这里使用的插件的引用。