.packageName <- "RQuantLib"
RcppVersion <- function() {
  licenseFile <- file(system.file(".","Rcpp-license.txt",package="RQuantLib"),"r")
  writeLines(readLines(licenseFile))
}
## RQuantLib -- R interface to the QuantLib libraries
##
## Copyright 2002 Dirk Eddelbuettel <edd@debian.org>
##
## $Id: arrays.R,v 1.2 2002/11/15 01:49:28 edd Exp $
##
## This file is part of the RQuantLib library for GNU R.
## It is made available under the terms of the GNU General Public
## License, version 2, or at your option, any later version,
## incorporated herein by reference.
##
## This program is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public
## License along with this program; if not, write to the Free
## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
## MA 02111-1307, USA

EuropeanOptionArrays <- function(type, underlying, strike, dividendYield,
                                 riskFreeRate, maturity, volatility) {
  n.underlying <- length(underlying)
  n.strike <- length(strike)
  n.dividendYield <- length(dividendYield)
  n.riskFreeRate <- length(riskFreeRate)
  n.maturity <- length(maturity)
  n.volatility <- length(volatility)

  res <- numeric(n.underlying * n.strike * n.dividendYield * n.riskFreeRate *
                 n.maturity * n.volatility)
  dim(res) <- c(n.underlying, n.strike, n.dividendYield, n.riskFreeRate,
                 n.maturity, n.volatility)
  dimnames(res) <- list(paste("s",underlying,sep="="),
                        paste("k",strike,sep="="),
                        paste("y",dividendYield,sep="="),
                        paste("r",riskFreeRate,sep="="),
                        paste("t",maturity,sep="="),
                        paste("v",volatility,sep="="))
  value <- delta <- gamma <- vega <- theta <- rho <- divRho <- res
  for (s in 1:n.underlying)
    for (k in 1:n.strike)
      for (y in 1:n.dividendYield)
        for (r in 1:n.riskFreeRate)
          for (t in 1:n.maturity)
            for (v in 1:n.volatility) {
              val <- .Call("QL_EuropeanOption",
                           list(type=as.character(type),
                                underlying=as.double(underlying[s]),
                                strike=as.double(strike[k]),
                                dividendYield=as.double(dividendYield[y]),
                                riskFreeRate=as.double(riskFreeRate[r]),
                                maturity=as.double(maturity[t]),
                                volatility=as.double(volatility[v])),
                           PACKAGE="RQuantLib")
              value[s,k,y,r,t,v] <- val$value
              delta[s,k,y,r,t,v] <- val$delta
              gamma[s,k,y,r,t,v] <- val$gamma
              vega[s,k,y,r,t,v] <- val$vega
              theta[s,k,y,r,t,v] <- val$theta
              rho[s,k,y,r,t,v] <- val$rho
              divRho[s,k,y,r,t,v] <- val$divRho
            }
  value <- drop(value)
  delta <- drop(delta)
  gamma <- drop(gamma)
  vega <- drop(vega)
  theta <- drop(theta)
  rho <- drop(rho)
  divRho <- drop(divRho)
  invisible(list(value=value, delta=delta, gamma=gamma, vega=vega,
                 theta=theta, rho=rho, divRho=divRho,
                 parameters=list(type=type, underlying=underlying,
                   strike=strike, dividendYield=dividendYield,
                   riskFreeRate=riskFreeRate, maturity=maturity,
                   volatility=volatility)))
}

## RQuantLib function DiscountCurve
##
## Copyright (C) 2005  Dominick Samperi
##
## $Id: bermudan.R,v 1.1 2005/10/12 03:42:03 edd Exp $
##
## This program is part of the RQuantLib library for R (GNU S).
## It is made available under the terms of the GNU General Public
## License, version 2, or at your option, any later version.
##
## This program is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.

BermudanSwaption <- function(params, tsQuotes, swaptionMaturities,
                             swapTenors, volMatrix) {
    UseMethod("BermudanSwaption")
}

BermudanSwaption.default <- function(params, tsQuotes, swaptionMaturities,
                                     swapTenors, volMatrix) {

  # Check that params list names
  if(!is.list(params) || length(params) == 0) {
    stop("The params parameter must be a non-empty list");
  }

  # Check that the term structure quotes are properly formatted.
  if(!is.list(tsQuotes) || length(tsQuotes) == 0) {
    stop("Term structure quotes must be a non-empty list");
  }
  if(length(tsQuotes) != length(names(tsQuotes))) {
    stop("Term structure quotes must include labels");
  }
  if(!is.numeric(unlist(tsQuotes))) {
    stop("Term structure quotes must have numeric values")
  }
  
  # Check for correct matrix/vector types
  if(!is.matrix(volMatrix)
     || !is.vector(swaptionMaturities)
     || !is.vector(swapTenors)) {
    stop("Swaption vol must be a matrix, maturities/tenors must be vectors")
  }

  # Check that matrix/vectors have compatible dimensions
  if(prod(dim(volMatrix)) != length(swaptionMaturities)*length(swapTenors)) {
    stop("Dimensions of swaption vol matrix not compatible with maturity/tenor vectors")
  }

  # Finally ready to make the call...
  # We could coerce types here and pass as.integer(round(swapTenors)),
  # temp <- as.double(volMatrix), dim(temp) < dim(a) [and pass temp instead
  # of volMatrix]. But this is taken care of in the C/C++ code.
  val <- .Call("QL_BermudanSwaption",
               params, tsQuotes,
               swaptionMaturities,
               swapTenors,
               volMatrix,
               PACKAGE="RQuantLib")
  class(val) <- c(params$method, "BermudanSwaption")
  val
}

summary.G2Analytic <- function(object,...) {
  cat('\n\tSummary of pricing results for Bermudan Swaption\n')
  cat('\nPrice (in bp) of Bermudan swaption is ', object$price)
  cat('\nStike is ', format(object$params$strike,digits=6))
  cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')')
  cat('\nModel used is: G2/Jamshidian using analytic formulas')
  cat('\nCalibrated model parameters are:')
  cat('\na = ', format(object$a,digits=4))
  cat('\nb = ', format(object$b,digits=4))
  cat('\nsigma = ', format(object$sigma,digits=4))
  cat('\neta = ', format(object$eta,digits=4))
  cat('\nrho = ', format(object$rho,digits=4))
  cat('\n\n')
}

summary.HWAnalytic <- function(object,...) {
  cat('\n\tSummary of pricing results for Bermudan Swaption\n')
  cat('\nPrice (in bp) of Bermudan swaption is ', object$price)
  cat('\nStike is ', format(object$params$strike,digits=6))
  cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')')
  cat('\nModel used is: Hull-White using analytic formulas')
  cat('\nCalibrated model parameters are:')
  cat('\na = ', format(object$a,digits=4))
  cat('\nsigma = ', format(object$sigma,digits=4))
  cat('\n\n')
}

summary.HWTree <- function(object,...) {
  cat('\n\tSummary of pricing results for Bermudan Swaption\n')
  cat('\nPrice (in bp) of Bermudan swaption is ', object$price)
  cat('\nStike is ', format(object$params$strike,digits=6))
  cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')')
  cat('\nModel used is: Hull-White using a tree')
  cat('\nCalibrated model parameters are:')
  cat('\na = ', format(object$a,digits=4))
  cat('\nsigma = ', format(object$sigma,digits=4))
  cat('\n\n')
}

summary.BKTree <- function(object,...) {
  cat('\n\tSummary of pricing results for Bermudan Swaption\n')
  cat('\nPrice (in bp) of Bermudan swaption is ', object$price)
  cat('\nStike is ', format(object$params$strike,digits=6))
  cat(' (ATM strike is ', format(object$ATMStrike,digits=6), ')')
  cat('\nModel used is: Black-Karasinski using a tree')
  cat('\nCalibrated model parameters are:')
  cat('\na = ', format(object$a,digits=4))
  cat('\nsigma = ', format(object$sigma,digits=4))
  cat('\n\n')
}
## RQuantLib function DiscountCurve
##
## Copyright (C) 2005  Dominick Samperi
##
## $Id: discount.R,v 1.2 2005/11/01 04:34:33 dsamperi Exp $
##
## This program is part of the RQuantLib library for R (GNU S).
## It is made available under the terms of the GNU General Public
## License, version 2, or at your option, any later version.
##
## This program is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.

DiscountCurve <- function(params, tsQuotes, times) {
  UseMethod("DiscountCurve")
}

DiscountCurve.default <- function(params, tsQuotes, times) {

  # Check that params is properly formatted.
  if(!is.list(params) || length(params) == 0) {
    stop("The params parameter must be a non-empty list");
  }

  # Check that the term structure quotes are properly formatted.
  if(!is.list(tsQuotes) || length(tsQuotes) == 0) {
    stop("Term structure quotes must be a non-empty list")
  }
  if(length(tsQuotes) != length(names(tsQuotes))) {
    stop("Term structure quotes must include labels")
  }
  if(!is.numeric(unlist(tsQuotes))) {
    stop("Term structure quotes must have numeric values")
  }
  
  # Check the times vector
  if(!is.numeric(times) || length(times) == 0)
    stop("The times parameter must be a non-emptry numeric vector")
    
  # Finally ready to make the call...
  val <- .Call("QL_DiscountCurve", params, tsQuotes, times,
               PACKAGE="RQuantLib")
  class(val) <- c("DiscountCurve")
  val
}

plot.DiscountCurve <- function(x,setpar=TRUE,dolegend=TRUE,...) {
  if(setpar) {
      savepar <- par(mfrow=c(3,1))
  }
  if(names(tsQuotes)[1] == "flat") {
    # Don't want to plot noise when we look at a flat yield curve
    plot(c(x$times[1],x$times[length(x$times)]), c(0,.5),type='n',
         main='forwards', xlab='time',ylab='forward rate')
    lines(x$times, x$forwards, type='l')
    if(dolegend) {
      legend('center','center','flat',bty='n',text.col='red')
    }
    plot(c(x$times[1],x$times[length(x$times)]), c(0,.5),type='n',
         main='zero rates', xlab='time',ylab='zero rate')
    lines(x$times, x$zerorates, type='l')
    if(dolegend) {
      legend('center','center','flat',bty='n',text.col='red')
    }
  }
  else {
    plot(x$times, x$forwards, type='l',
         main='forwards',xlab='time',ylab='fwd rate')
    if(dolegend) {
      legend('center','center',paste(x$params$interpHow, 'discount'),bty='n',
             text.col='red')
    }
    plot(x$times, x$zerorates, type='l',
         main='zero rates',xlab='time',ylab='zero rate')
    if(dolegend) {
      legend('center','center',paste(x$params$interpHow, 'discount'),bty='n',
             text.col='red')
    }
  }
  plot(x$times, x$discounts, type='l',
       main='discounts',xlab='time',ylab='discount')
  if(dolegend) {
    if(names(tsQuotes)[1] == "flat") {
      legend('center','center','flat',bty='n',text.col='red')
    }
    else {
      legend('center','center',paste(x$params$interpHow, 'discount'),bty='n',
             text.col='red')
    }
  }
  if(setpar) {
      par(savepar)
  }
}
## RQuantLib -- R interface to the QuantLib libraries
##
## Copyright 2002 - 2005 Dirk Eddelbuettel <edd@debian.org>
##
## $Id: implied.R,v 1.8 2005/10/12 03:20:39 edd Exp $
##
## This file is part of the RQuantLib library for GNU R.
## It is made available under the terms of the GNU General Public
## License, version 2, or at your option, any later version,
## incorporated herein by reference.
##
## This program is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public
## License along with this program; if not, write to the Free
## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
## MA 02111-1307, USA

## also dumps core (0.3.7)
## no longer under 0.3.9 and 0.3.10 with g++ 3.4/4.0
EuropeanOptionImpliedVolatility <-
  function(type, value, underlying, strike, dividendYield,
           riskFreeRate, maturity, volatility) {
  UseMethod("EuropeanOptionImpliedVolatility")
}

EuropeanOptionImpliedVolatility.default <-
  function(type, value, underlying, strike, dividendYield,
            riskFreeRate, maturity, volatility) {
  val <- .Call("QL_EuropeanOptionImpliedVolatility",
               list(type=as.character(type),
		    value=as.double(value),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),
                    volatility=as.double(volatility)),
               PACKAGE="RQuantLib")
  class(val) <- c("EuropeanOptionImpliedVolatility","ImpliedVolatility")
  val
}

# also dumps core (0.3.7)
## no longer under 0.3.9 and 0.3.10 with g++ 3.4/4.0
AmericanOptionImpliedVolatility <-
  function(type, value, underlying, strike, dividendYield, riskFreeRate,
           maturity, volatility, timeSteps=150, gridPoints=151) {
  UseMethod("AmericanOptionImpliedVolatility")
}

AmericanOptionImpliedVolatility.default <-
  function(type, value, underlying, strike, dividendYield, riskFreeRate,
            maturity, volatility, timeSteps=150, gridPoints=151) {
  val <- .Call("QL_AmericanOptionImpliedVolatility",
               list(type=as.character(type),
		    value=as.double(value),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),


                    volatility=as.double(volatility),
                    timeSteps=as.integer(timeSteps),
                    gridPoints=as.integer(gridPoints)),
               PACKAGE="RQuantLib")
  class(val) <- c("AmericanOptionImpliedVolatility","ImpliedVolatility")
  val
}

# dumps core :-/
BinaryOptionImpliedVolatility <-
  function(type, value, underlying, strike, dividendYield, riskFreeRate,
           maturity, volatility, cashPayoff=1) {
  UseMethod("BinaryOptionImpliedVolatility")
}

BinaryOptionImpliedVolatility.default <-
  function(type, value, underlying, strike, dividendYield, riskFreeRate,
            maturity, volatility, cashPayoff=1) {
  val <- .Call("QL_BinaryOptionImpliedVolatility",
               list(type=as.character(type),
		    value=as.double(value),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),
                    volatility=as.double(volatility),
                    cashPayoff=as.double(cashPayoff)),
               PACKAGE="RQuantLib")
  class(val) <- c("BinaryOptionImpliedVolatility","ImpliedVolatility")
  val
}

print.ImpliedVolatility <- function(x, digits=3, ...) {
  impvol <- x[[1]]
  cat("Implied Volatility for", class(x)[1], "is", round(impvol, digits), "\n")
  invisible(x)
}

summary.ImpliedVolatility <- function(object, digits=3, ...) {
  impvol <- object[[1]]
  cat("Implied Volatility for", class(object)[1], "is", round(impvol, digits), "\n")
  cat("with parameters\n")
  print(unlist(object[[2]]))
  invisible(object)
}
## RQuantLib -- R interface to the QuantLib libraries
##
## Copyright 2002, 2005 Dirk Eddelbuettel <edd@debian.org>
##
## $Id: option.R,v 1.5 2005/08/07 02:05:27 edd Exp edd $
##
## This file is part of the RQuantLib library for GNU R.
## It is made available under the terms of the GNU General Public
## License, version 2, or at your option, any later version,
## incorporated herein by reference.
##
## This program is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public
## License along with this program; if not, write to the Free
## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
## MA 02111-1307, USA

EuropeanOption <- function(type, underlying, strike, dividendYield,
                           riskFreeRate, maturity, volatility) {
  UseMethod("EuropeanOption")
}

EuropeanOption.default <- function(type, underlying, strike, dividendYield,
                                   riskFreeRate, maturity, volatility) {
  val <- .Call("QL_EuropeanOption",
               list(type=as.character(type),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),
                    volatility=as.double(volatility)),
               PACKAGE="RQuantLib")
  class(val) <- c("EuropeanOption", "Option")
  val
}

AmericanOption <- function(type, underlying, strike, dividendYield,
                           riskFreeRate, maturity, volatility,
                           timeSteps=150, gridPoints=151) {
  UseMethod("AmericanOption")
}

AmericanOption.default <- function(type, underlying, strike, dividendYield,
                                   riskFreeRate, maturity, volatility,
                                   timeSteps=150, gridPoints=151) {
  val <- .Call("QL_AmericanOption",
               list(type=as.character(type),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),
                    volatility=as.double(volatility),
                    timeSteps=as.integer(timeSteps),
                    gridPoints=as.integer(gridPoints)),
               PACKAGE="RQuantLib")
  class(val) <- c("AmericanOption","Option")
  val[[2]] <- NA
  val[[3]] <- NA
  val[[4]] <- NA
  val[[5]] <- NA
  val[[6]] <- NA
  val[[7]] <- NA 
  val
}

BinaryOption <- function(type, underlying, strike, dividendYield,
                         riskFreeRate, maturity, volatility,
                         cashPayoff) {
  UseMethod("BinaryOption")
}

BinaryOption.default <- function(type, underlying, strike, dividendYield,
                                 riskFreeRate, maturity, volatility,
                                 cashPayoff) {
  val <- .Call("QL_BinaryOption",
               list(type=as.character(type),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),
                    volatility=as.double(volatility),
                    cashPayoff=as.double(cashPayoff)),
               PACKAGE="RQuantLib")
  class(val) <- c("BinaryOption", "Option")
  val
}

BarrierOption <- function(barrType, type, underlying, strike,
                          dividendYield, riskFreeRate, maturity,
                          volatility, barrier, rebate=0.0) {
  UseMethod("BarrierOption")
}

BarrierOption.default <- function(barrType, type, underlying, strike,
                                  dividendYield, riskFreeRate, maturity,
                                  volatility, barrier, rebate=0.0) {
  val <- .Call("QL_BarrierOption",
               list(barrType=as.character(barrType),
                    type=as.character(type),
                    underlying=as.double(underlying),
                    strike=as.double(strike),
                    dividendYield=as.double(dividendYield),
                    riskFreeRate=as.double(riskFreeRate),
                    maturity=as.double(maturity),
                    volatility=as.double(volatility),
                    barrier=as.double(barrier),
                    rebate=as.double(rebate)),
               PACKAGE="RQuantLib")
  class(val) <- c("BarrierOption", "Option")
  val[[2]] <- NA
  val[[3]] <- NA
  val[[4]] <- NA
  val[[5]] <- NA
  val[[6]] <- NA
  val[[7]] <- NA 
  val
}

plot.Option <- function(x, ...) {
  warning("No plotting available for class", class(x)[1],"\n")
  invisible(x)
}

print.Option <- function(x, digits=4, ...) {
  cat("Concise summary of valuation for", class(x)[1], "\n")
  print(round(unlist(x[1:7]), digits))
  invisible(x)
}

summary.Option <- function(object, digits=4, ...) {
  cat("Detailed summary of valuation for", class(object)[1], "\n")
  print(round(unlist(object[1:7]), digits))
  cat("with parameters\n")
  print(unlist(object[["parameters"]]))
  invisible(object)
}




## RQuantLib -- R interface to the QuantLib libraries
##
## Copyright 2002 Dirk Eddelbuettel <edd@debian.org>
##
## $Id: zzz.R,v 1.3 2005/10/05 03:03:54 edd Exp $
##
## This file is part of the RQuantLib library for GNU R.
## It is made available under the terms of the GNU General Public
## License, version 2, or at your option, any later version,
## incorporated herein by reference.
##
## This program is distributed in the hope that it will be
## useful, but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public
## License along with this program; if not, write to the Free
## Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
## MA 02111-1307, USA

.First.lib <- function(lib, pkg) {
  #cat("This is a pre-release. The interface might change...\n")
  library.dynam("RQuantLib", pkg, lib )
}

