Duck typing with quantmod

February 4, 2011

(This article was first published on Cartesian Faith » R, and kindly contributed to R-bloggers)

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.

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


To leave a comment for the author, please follow the link and comment on his blog: Cartesian Faith » R. offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: ,

Comments are closed.