Wednesday, April 24, 2013

Using R-squared technical indicator in quantmod

R-squared is a technical indicator used by traders to ascertain the strength of the dominant market trend. It is useful when combined with direction indicators such as the stochastic oscillator or the SMI and it can be an alternative to other trending indicators such as Chande Momentum Oscillator. Further information on the composition and usage of R-squared can be found f.ex. in BlastChart.

Currently, the quantmod library for R does not include any built-in function to add the R-squared oscillator. However, the package TTR to which quantmod relies upon for the technical indicators has recently (v.0.22.0) released a function, named rollSFM, which can be used to provide the respective values. The following code enables this:

First , we define a function that calculates the rolling R-squared (x is assumed to be an xts or matrix object, the interval is set by default to 60):

library(TTR)
#---------------------------------------------------------#
# Function: R2                                            # 
# Version: 1.0.0                                          #
# Date: 24/04/13                                          #
# Author: Athanasios Tsakonas                             #
# Inputs:                                                 #
#    x: xts or matrix object                              #
#    interval: integer                                    #
#---------------------------------------------------------#
R2 <- function(x, interval = 60) {
  roll <- rollSFM(c(1:dim(x)[1]),x[,4],interval)
  return(roll$r.squared)
}


Then, we can plot a chartSeries and add this technical indicator using the addTA function.
In the following example, we apply the above to the Yahoo! stock time series.

library(quantmod)
getSymbols("YHOO")
chartSeries(YHOO,type='bars', TA=c(addSMI()), subset='last 6 months')
addTA(R2(YHOO), col='green', type="l")

The result is shown in the following screen.

No comments:

Post a Comment