[R-SIG-Finance] creation of add_stoch

Gordon Erlebacher gordon.erlebach at gmail.com
Sun Apr 22 20:21:47 CEST 2012


Here is a function add_stoch that works, although it is heavy coding given
that one is adding a subframe which is a single line plot. Also, there
should be no need to call add_stoch more than once for efficiency. Finally,
the add_xxx() collection of routines  presumes that the underlying function
xxx() returns a single series, which is why I need to create the inner
function stoch1.

Surely there must be a simpler approach. I attach the code (I do not know
whether attachments work.)



add_stoch = function (nFastK = 10, nFastD=3, nSlowD=3, maType, bounded=T,
smooth=1, on = 1, ...)
{
stoch1 = function (HLC, nFastK = 10, nFastD=3, nSlowD=3, maType, bounded=T,
smooth=1, ...)
{
return(stoch(HLC, nFastK, nFastD, nSlowD, maType, bounded, smooth,
...)['2012'][,2])
}

    lenv <- new.env()
    lenv$add_stoch <- function(x, nFastK = 10, nFastD=3, nSlowD=3,
maType=SMA, bounded=T, smooth=1, ...) {
        xdata <- x$Env$xdata
        xsubset <- x$Env$xsubset
        sto <- stoch1(Cl(xdata),
nFastK=nFastK,nFastD=nFastD,nSlowD=nSlowD,maType=SMA, bounded=bounded,
smooth=smooth)[xsubset]
        lines(1:NROW(xdata[xsubset]), sto, ...)
    }
    mapply(function(name, value) {
        assign(name, value, envir = lenv)
    }, names(list(nFastK=nFastK,nFastD=nFastD,nSlowD=nSlowD,maType=SMA,
bounded=bounded, smooth=smooth, ...)),
list(nFastK=nFastK,nFastD=nFastD,nSlowD=nSlowD,maType=SMA, bounded=bounded,
smooth=smooth, ...))
    exp <- parse(text = gsub("list", "add_stoch",
as.expression(substitute(list(x = current.chob(),
        nFastK=nFastK,nFastD=nFastD,nSlowD=nSlowD,maType=SMA,
bounded=bounded, smooth=smooth, ...)))), srcfile = NULL)
    plot_object <- current.chob()
    lenv$xdata <-
stoch1(Cl(plot_object$Env$xdata),nFastK=nFastK,nFastD=nFastD,nSlowD=nSlowD,maType=SMA,
bounded=bounded, smooth=smooth)
    plot_object$set_frame(sign(on) * abs(on) + 1L)
    plot_object$add(exp, env = c(lenv, plot_object$Env), expr = TRUE)
    plot_object
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20120422/48319f33/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: add_stoch.r
Type: application/octet-stream
Size: 1646 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20120422/48319f33/attachment.obj>


More information about the R-SIG-Finance mailing list