Site icon R-bloggers

Duck typing with quantmod

[This article was first published on Cartesian Faith » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This is a short example of using duck typing in a guard statement in the futile.paradigm. We are implementing a simple function to calculate the daily volatility of the returns with the help of quantmod.

vol.symbol %when% (has.Cl(symbol))
vol.symbol <- function(symbol, window)
{
  r <- Delt(Cl(symbol))
  v <- rollapply(r, window, function(x) sd(x, na.rm=TRUE), align='right')
}

A working example is below. The function is called whenever the symbol object satisfies the has.Cl assertion. Quantmod comes with the has.Cl function to check if a particular symbol contains a series representing the closing price. This is necessary since all names in the symbol object are prefixed by the literal string symbol. Hence the close series for GLD is GLD.Close. This makes direct access a bit cumbersome but since accessor and inspection functions are provided it isn’t so bad.

getSymbols("GLD")
v <- vol(GLD,30)

Getting back to the point, to accomplish the same task in any of the class systems in R would require conditional statements in the body of the method, since only the class of the arguments can be tested. In S3, the function would be implemented like this:

vol <- function(symbol, window) UseMethod("vol")
vol.xts <- function(symbol, window)
{
  if (! has.Cl(symbol)) stop("No close series in symbol")
  r <- Delt(Cl(symbol))
  v <- rollapply(r, window, function(x) sd(x, na.rm=TRUE), align='right')
}

While this example is trivial, it illustrates two important concepts:

  1. The fine granularity that guards provide for function dispatching
  2. The removal of control flow in functions, leaving only the essential logic

On a larger scale, these improvements add up yielding cleaner code that is easier to maintain and modify.

Required Packages

require(futile.paradigm)
require(quantmod)

To leave a comment for the author, please follow the link and comment on their blog: Cartesian Faith » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.