Ejemplo n.º 1
0
RcppExport SEXP holidayList(SEXP calSexp, SEXP params) {

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        Rcpp::List rparam(params);
        int iw = Rcpp::as<int>(rparam["includeWeekends"]);
        std::vector<QuantLib::Date> 
            holidays = QuantLib::Calendar::holidayList(*pcal,
                                                       QuantLib::Date(dateFromR(Rcpp::as<Rcpp::Date>( rparam["from"]))), 
                                                       QuantLib::Date(dateFromR(Rcpp::as<Rcpp::Date>( rparam["to"] ))), 
                                                       iw == 1 ? true : false);                

        if (holidays.size() > 0) {
            Rcpp::DateVector dv( holidays.size() );
            for (unsigned int i = 0; i< holidays.size(); i++){
                dv[i] = Rcpp::Date(holidays[i].month(), holidays[i].dayOfMonth(), holidays[i].year());
            }
            return Rcpp::wrap(dv);
        } else {
            return R_NilValue;
        }

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Ejemplo n.º 2
0
RcppExport SEXP businessDaysBetween(SEXP calSexp, SEXP params,
                                       SEXP from, SEXP to){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        Rcpp::List rparam(params);
        double ifirst = Rcpp::as<double>(rparam["includeFirst"]);
        double ilast = Rcpp::as<double>(rparam["includeLast"]);

        Rcpp::DateVector dates1  = Rcpp::DateVector(from);
        Rcpp::DateVector dates2  = Rcpp::DateVector(to);

        int n = dates1.size();
        std::vector<double> between(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day1( dateFromR(dates1[i]) );
            QuantLib::Date day2( dateFromR(dates2[i]) );
            between[i] = pcal->businessDaysBetween(day1, day2,
                                                   (ifirst == 1) ? true: false,
                                                   (ilast == 1) ? true: false);
        }
        
        return Rcpp::wrap(between);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Ejemplo n.º 3
0
RcppExport SEXP advance2(SEXP calSexp, SEXP param, SEXP dateSexp){

    try {
        boost::shared_ptr<QuantLib::Calendar> pcal( getCalendar(Rcpp::as<std::string>(calSexp)) );
        Rcpp::List rparam(param);        
        QuantLib::BusinessDayConvention bdc = getBusinessDayConvention( Rcpp::as<double>(rparam["bdc"]) );
        double emr = Rcpp::as<double>(rparam["emr"]);
        double period = Rcpp::as<double>(rparam["period"]);

        Rcpp::DateVector dates  = Rcpp::DateVector(dateSexp);
        int n = dates.size();
        std::vector<QuantLib::Date> advance(n);

        for (int i=0; i<n; i++) {
            QuantLib::Date day( dateFromR(dates[i]) );
            advance[i] = pcal->advance(day, QuantLib::Period(getFrequency(period)), 
                                       bdc, (emr == 1)?true:false );
            dates[i] =  Rcpp::Date(advance[i].month(), 
                                   advance[i].dayOfMonth(), 
                                   advance[i].year());
        }

        return Rcpp::wrap(dates);

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}
Ejemplo n.º 4
0
// test for list(foo = c(1L,2L)
RcppExport SEXP test_rlist_ref_var_context1(SEXP params) {
  BEGIN_RCPP; 
  Rcpp::List rparam(params);  
  rstan::io::rlist_ref_var_context  rlist_(rparam); 

  Rprintf("Test1 started.\n-------\n"); 

  // test for list(foo = c(1L,2L)
  EXPECT_TRUE(rlist_.contains_i("foo"));
  EXPECT_TRUE(rlist_.contains_r("foo"));

  EXPECT_EQ(2U,rlist_.vals_i("foo").size());

  EXPECT_EQ(1,rlist_.vals_i("foo")[0]);
  EXPECT_EQ(2,rlist_.vals_i("foo")[1]);
  EXPECT_FLOAT_EQ(1.0,rlist_.vals_r("foo")[0]);
  EXPECT_FLOAT_EQ(2.0,rlist_.vals_r("foo")[1]);

  EXPECT_TRUE(rlist_.remove("foo"));
  EXPECT_FALSE(rlist_.remove("foo"));

  EXPECT_FALSE(rlist_.contains_i("foo"));
  EXPECT_FALSE(rlist_.contains_r("foo"));
  return Rcpp::wrap(int(0)); 
  Rprintf("Test1 ended.\n-------\n"); 
  END_RCPP; 
} 
Ejemplo n.º 5
0
RcppExport SEXP test_rlist_ref_var_context3(SEXP params) {
  BEGIN_RCPP;
  Rcpp::List rparam(params);  
  rstan::io::rlist_ref_var_context  rlist_(rparam); 
  Rprintf("Test3 started.\n-------\n"); 
  EXPECT_TRUE(rlist_.contains_i("foo"));
  EXPECT_TRUE(rlist_.contains_r("foo"));
  EXPECT_TRUE(rlist_.contains_r("bar"));
  EXPECT_FALSE(rlist_.contains_r("baz"));
  EXPECT_FALSE(rlist_.contains_i("bingz"));

  EXPECT_EQ(2U,rlist_.vals_i("foo").size());
  EXPECT_EQ(1U,rlist_.vals_r("bar").size());
  EXPECT_EQ(1,rlist_.vals_i("foo")[0]);
  EXPECT_EQ(2,rlist_.vals_i("foo")[1]);
  EXPECT_FLOAT_EQ(1.0,rlist_.vals_r("foo")[0]);
  EXPECT_FLOAT_EQ(2.0,rlist_.vals_r("foo")[1]);
  EXPECT_FLOAT_EQ(1.0,rlist_.vals_r("bar")[0]);
  EXPECT_EQ(6U,rlist_.vals_r("bing").size());
  EXPECT_FLOAT_EQ(2.0,rlist_.vals_r("bing")[2]);

  EXPECT_EQ(2U, rlist_.dims_r("bing").size());
  EXPECT_EQ(2U, rlist_.dims_r("bing")[0]);
  EXPECT_EQ(3U, rlist_.dims_r("bing")[1]);

  EXPECT_TRUE(rlist_.remove("bing"));
  EXPECT_FALSE(rlist_.remove("bing"));
  Rprintf("Test3 ended.\n-------\n"); 
  return Rcpp::wrap(int(0)); 
  END_RCPP;
} 
Ejemplo n.º 6
0
RcppExport SEXP cfamounts(SEXP params){
       
    SEXP rl=R_NilValue;
    char* exceptionMesg=NULL;
    try{
        RcppParams rparam(params); 

        QuantLib::Date maturity(dateFromR(rparam.getDateValue("Maturity")));
        QuantLib::Date settle(dateFromR(rparam.getDateValue("Settle")));
        QuantLib::Date issue(dateFromR(rparam.getDateValue("IssueDate")));

        double rate = rparam.getDoubleValue("CouponRate");
        std::vector<double> rateVec(1, rate);
        double faceAmount = rparam.getDoubleValue("Face");
        double period = rparam.getDoubleValue("Period");
        double basis = rparam.getDoubleValue("Basis");
        DayCounter dayCounter = getDayCounter(basis);
        Frequency freq = getFrequency(period);
        Period p(freq);
        double EMR = rparam.getDoubleValue("EMR");
        Calendar calendar=UnitedStates(UnitedStates::GovernmentBond);
        
        
        Schedule sch(settle, maturity, p, calendar, 
                     Unadjusted, Unadjusted, DateGeneration::Backward, 
                     (EMR == 1)? true : false);

        FixedRateBond bond(1, faceAmount, sch, rateVec, dayCounter, Following,
                           100, issue);

        //cashflow
        int numCol = 2;
        std::vector<std::string> colNames(numCol);
        colNames[0] = "Date";
        colNames[1] = "Amount";
        RcppFrame frame(colNames);
        
        Leg bondCashFlow = bond.cashflows();
        for (unsigned int i = 0; i< bondCashFlow.size(); i++){
            std::vector<ColDatum> row(numCol);
            Date d = bondCashFlow[i]->date();
            row[0].setDateValue(RcppDate(d.month(), d.dayOfMonth(), d.year()));
            row[1].setDoubleValue(bondCashFlow[i]->amount());
            frame.addRow(row);
        }
                     
        RcppResultSet rs;
        rs.add("cashFlow", frame);
        rl = rs.getReturnList();

    } catch(std::exception& ex) {
        exceptionMesg = copyMessageToR(ex.what());
    } catch(...) {
        exceptionMesg = copyMessageToR("unknown reason");
    }   
    if(exceptionMesg != NULL)
        Rf_error(exceptionMesg);    
    return rl;
}
Ejemplo n.º 7
0
RcppExport SEXP cfdates(SEXP params){
    SEXP rl = R_NilValue;
    char* exceptionMesg = NULL;
    try {
        RcppParams rparam(params);
        
        double basis = rparam.getDoubleValue("dayCounter");
        DayCounter dayCounter = getDayCounter(basis);
        double p = rparam.getDoubleValue("period");        
        Frequency freq = getFrequency(p);
        Period period(freq);
        double emr = rparam.getDoubleValue("emr");

        bool endOfMonth = false;
        if (emr == 1) endOfMonth = true;

        QuantLib::Date d1(dateFromR(rparam.getDateValue("settle")));        
        QuantLib::Date d2(dateFromR(rparam.getDateValue("maturity")));
        Calendar calendar=UnitedStates(UnitedStates::GovernmentBond); 
        
        Schedule sch(d1, d2, period, calendar, Unadjusted,
                     Unadjusted, DateGeneration::Backward, endOfMonth);

        //cfdates
        int numCol = 1;
        std::vector<std::string> colNames(numCol);
        colNames[0] = "Date";        
        RcppFrame frame(colNames);
        
        std::vector<QuantLib::Date> dates = sch.dates();
        for (unsigned int i = 0; i< dates.size(); i++){
            std::vector<ColDatum> row(numCol);
            Date d = dates[i];
            row[0].setDateValue(RcppDate(d.month(), d.dayOfMonth(), d.year()));           
            frame.addRow(row);
        }
        RcppResultSet rs;
        rs.add("", frame);
        rl = rs.getReturnList();
    } 
    catch(std::exception& ex) {
        exceptionMesg = copyMessageToR(ex.what());
    } catch(...) {
        exceptionMesg = copyMessageToR("unknown reason");
    }
    if(exceptionMesg != NULL)
        Rf_error(exceptionMesg);
    
    return rl;
}
Ejemplo n.º 8
0
RcppExport SEXP AsianOption(SEXP optionParameters){

    try{
        Rcpp::List rparam(optionParameters);

        std::string avgType = Rcpp::as<std::string>(rparam["averageType"]);
        std::string type = Rcpp::as<std::string>(rparam["type"]);
        double underlying = Rcpp::as<double>(rparam["underlying"]);
        double strike = Rcpp::as<double>(rparam["strike"]);
        QuantLib::Spread dividendYield = Rcpp::as<double>(rparam["dividendYield"]);
        QuantLib::Rate riskFreeRate = Rcpp::as<double>(rparam["riskFreeRate"]);
        QuantLib::Time maturity = Rcpp::as<double>(rparam["maturity"]);
        //        int length = int(maturity*360 + 0.5); // FIXME: this could be better
        double volatility = Rcpp::as<double>(rparam["volatility"]);

        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;

        boost::shared_ptr<QuantLib::SimpleQuote> spot(new QuantLib::SimpleQuote(underlying));
        boost::shared_ptr<QuantLib::SimpleQuote> qRate(new QuantLib::SimpleQuote(dividendYield));
        boost::shared_ptr<QuantLib::YieldTermStructure> qTS = flatRate(today, qRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> rRate(new QuantLib::SimpleQuote(riskFreeRate));
        boost::shared_ptr<QuantLib::YieldTermStructure> rTS = flatRate(today, rRate, dc);
        boost::shared_ptr<QuantLib::SimpleQuote> vol(new QuantLib::SimpleQuote(volatility));
        boost::shared_ptr<QuantLib::BlackVolTermStructure> volTS = flatVol(today, vol, dc);
        
        boost::shared_ptr<QuantLib::BlackScholesMertonProcess>
            stochProcess(new
                         QuantLib::BlackScholesMertonProcess(QuantLib::Handle<QuantLib::Quote>(spot),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(qTS),
                                                             QuantLib::Handle<QuantLib::YieldTermStructure>(rTS),
                                                             QuantLib::Handle<QuantLib::BlackVolTermStructure>(volTS)));

        boost::shared_ptr<QuantLib::StrikedTypePayoff> payoff(new QuantLib::PlainVanillaPayoff(optionType,strike));

      

        QuantLib::Average::Type averageType = QuantLib::Average::Geometric;
        Rcpp::List rl = R_NilValue;
   
        if (avgType=="geometric"){
            averageType = QuantLib::Average::Geometric;
            boost::shared_ptr<QuantLib::PricingEngine> 
                engine(new
                       QuantLib::AnalyticContinuousGeometricAveragePriceAsianEngine(stochProcess));
            
            QuantLib::Date exDate = today + int(maturity * 360 + 0.5);
            boost::shared_ptr<QuantLib::Exercise> exercise(new QuantLib::EuropeanExercise(exDate));
            QuantLib::ContinuousAveragingAsianOption option(averageType, 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(),
                                    Rcpp::Named("parameters") = optionParameters);
            
        } else if (avgType=="arithmetic"){
            averageType = QuantLib::Average::Arithmetic;

            boost::shared_ptr<QuantLib::PricingEngine> engine =
                QuantLib::MakeMCDiscreteArithmeticAPEngine<QuantLib::LowDiscrepancy>(stochProcess)
                .withSamples(2047)
                .withControlVariate();
            
            //boost::shared_ptr<PricingEngine> engine =
            //    MakeMCDiscreteArithmeticASEngine<LowDiscrepancy>(stochProcess)
            //    .withSeed(3456789)
            //    .withSamples(1023);
            
            QuantLib::Size fixings = Rcpp::as<double>(rparam["fixings"]);
            QuantLib::Time length = Rcpp::as<double>(rparam["length"]);
            QuantLib::Time first = Rcpp::as<double>(rparam["first"]);
            QuantLib::Time dt = length / (fixings - 1);

            std::vector<QuantLib::Time> timeIncrements(fixings);
            std::vector<QuantLib::Date> fixingDates(fixings);
            timeIncrements[0] = first;
            fixingDates[0] = today + QuantLib::Integer(timeIncrements[0] * 360 + 0.5);
            for (QuantLib::Size i=1; i<fixings; i++) {
                timeIncrements[i] = i*dt + first;
                fixingDates[i] = today + QuantLib::Integer(timeIncrements[i]*360+0.5);
            }
            QuantLib::Real runningSum = 0.0;
            QuantLib::Size pastFixing = 0;

            boost::shared_ptr<QuantLib::Exercise> 
                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_NaN,
                                    Rcpp::Named("gamma") = R_NaN,
                                    Rcpp::Named("vega") = R_NaN,
                                    Rcpp::Named("theta") = R_NaN,
                                    Rcpp::Named("rho") = R_NaN,
                                    Rcpp::Named("divRho") = R_NaN,
                                    Rcpp::Named("parameters") = optionParameters);
        } else {
            throw std::range_error("Unknown average type " + type);
        }      
    
        return rl;

    } catch(std::exception &ex) { 
        forward_exception_to_r(ex); 
    } catch(...) { 
        ::Rf_error("c++ exception (unknown reason)"); 
    }

    return R_NilValue;
}