c++ - 通过 Rcpp 从 R 调用 QuantLib

标签 c++ r rcpp quantlib

预备步骤

QuantLibBoost 一起安装并按照 these 构建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:\DevTools\QuantLib-1.3\lib,如果从 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 常见问题解答,了解“我可以在 Visual Studio 中使用 R 和 Rcpp 吗”的一般问题(tl;dr:不,你不能)。

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

然后您可以根据自己的喜好扩展 RQuantLib。

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

编辑:正如 promise 的那样,我试了一下。使用当前的 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 上对您来说失败了,请确保

  • 已安装 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;
}

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

关于c++ - 通过 Rcpp 从 R 调用 QuantLib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22414198/

相关文章:

c++ - 是否允许为自定义数字类型专门化数学常量?

c++ - 在 OpenGL 中渲染 .obj 文件最终会丢失顶点

c++ - 检查 NULL 时要忽略多少位?

r - 如何将两个变量写入一个文本文件?

debugging - R等同于MATLAB的“出错时停止”

c++ - 迭代 MappedSparseMatrix 特征中的非零元素

c++ - 我们可以使用()代替{}作为函数范围吗?

r - 在 R 中使用 colnames ifelse 命令

c++ - 在 Windows 上使用与 Rtools 和 Rcpp 包含的版本不同的 gcc 版本

Rcpp 和默认 C++ 编译器