Search code examples
rstatisticsdata-miningxtsquantmod

R data mining syntax


I am trying to run the code provided with Data Mining With R book. It basically takes the quotes data for SP500 index(GSPC) and builds a prediction function (T.ind) to predict the quotes for next n days.

library(DMwR)
#load S&P500 Dataset
data(GSPC)

# Create a Prediction function T based on which Buy / Sell / Hold decision
# will be taken. target variation margin is 2.5%
T.ind <- function(quotes,tgt.margin=0.025,n.days=10) {
  v <- apply(HLC(quotes),1,mean)
  r <- matrix(NA,ncol=n.days,nrow=NROW(quotes))

  for(x in 1:n.days) {
    r[,x] <- Next(Delt(v,k=x),x)
  }

  x <- apply(r,1,function(x) sum(x[x > tgt.margin | x < -tgt.margin]))

  if (is.xts(quotes))
    xts(x,time(quotes))
  else
    x
}

#Plot candle chart for 3 months of Index with Avg. price and Parameter T.
candleChart(last(GSPC,'3 months'),theme='white',TA=NULL)

addAvgPrice <- newTA(FUN=avgPrice,col=1,legend='AvgPrice')
addT.ind <- newTA(FUN=T.ind,col='red',legend='tgtRet')
addT.ind()

My question is how T.ind is called from newTA() function call. How are the values of quotes from selected period passed on to the T.ind function. Please let me know.


Solution

  • It's quite a bit like lattice or ggolot2 plots but without the "+" signs. However, the operation that is equivalent to "feature addition" is being delivered via side-effects. The plot is not just a 2D display but is also an object in the workspace. When you call addT.ind() its effects are being applied to the currently active chart object that has the data gathered by HLC() in the context of having implicit access to the results of candleChart()'s product.