【问题标题】:Calling QuantLib from R through Rcpp通过 Rcpp 从 R 调用 QuantLib
【发布时间】:2014-03-14 19:34:31
【问题描述】:

初步步骤

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 中,如果从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;
}

【问题讨论】:

    标签: c++ r rcpp quantlib


    【解决方案1】:

    有关“我可以在 Visual Studio 中使用 R 和 Rcpp”的一般问题,请参阅 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 中,这“正常工作”:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2015-05-04
      • 2014-06-25
      相关资源
      最近更新 更多