[R] Moving standard deviation?

Diethelm Wuertz wuertz at itp.phys.ethz.ch
Tue Dec 14 12:47:16 CET 2004


# Another possibility;

# Have a look on Rmetrics: www.rmetrics.org


# Rmetrics package "fSeries"  has functions to perform rolling analysis:

# FUNCTION:                 DESCRIPTION:
#  rollFun                   Compute Rolling Function Value
#   rollMean                  Compute Rolling Mean
#   rollVar                   Compute Rolling Variance
#   rollMin                   Compute Rolling Minimum
#   rollMax                   Compute Rolling Maximum

# e.g.

rollFun =
function(x, n, FUN, ...)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Compute rolling function value

    # FUNCTION:
   
    # Transform:
    x = as.vector(x)
   
    # Roll FUN:
    start = 1
    end = length(x)-n+1
    m = x[start:end]
    for (i in 2:n) {
        start = start + 1
        end = end + 1
        m = cbind(m, x[start:end])}
   
    # Result:
    ans = apply(m, MARGIN = 1, FUN = FUN, ...)
   
    # Return value:
    ans
}


and for the variance:


rollVar  =
function(x, n = 9, trim = TRUE, unbiased = TRUE, na.rm = FALSE)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Compute rolling variance

    # FUNCTION:
   
    # Transform:
    x = as.vector(x)
   
    # Roll Var:
    if (na.rm) x = as.vector(na.omit(x))
    rvar = rollFun(x = x, n = n, FUN = var)
    if (!unbiased) rvar = (rvar * (n-1))/n
    if (!trim) rvar = c(rep(NA, (n-1)), rvar)
   
    # Return Value:
    rvar
}


# Additional Arguments:

# trim, unbiased and  na.rm

# try for a vector
x = rnorm(100)
sqrt(rollVar(x, n = 9))
sqrt(rollVar(x, n = 9, trim = FALSE))

# It also works for R's time series objects "ts"
# (for any object which can be transformed in a
#      vector by the function as.vector)
# x.ts = as.ts(x)
sqrt(rollVar(x.ts, 9))
sqrt(rollVar(x.ts, 9, trim = FALSE))

# It works for any function ...
# Try also:
rollFun(x, n=9, FUN=sd)


I have also written functions for the rolling analysis of Rmetrics' S4
timeSeries objects, performing the analysis on equidistant time scales
daily business time scales or any other more complex intraday time
scales for time series data collected from financial markets  in
different time zones and with different DST rules, (not on the running
 index).

Functions for the rolling analysis of financial market data are not 
difficult
to write using Rmetrics timeSeries and Financial Center concepts.
They will be published in one of the next Rmetrics releases.


Regards Diethelm Wuertz




Martin Maechler wrote:

>>>>>>"bogdan" == bogdan romocea <br44114 at yahoo.com>
>>>>>>    on Mon, 13 Dec 2004 12:26:46 -0800 (PST) writes:
>>>>>>            
>>>>>>
>
>    bogdan> A simple for loop does the job. Why not write your own function?
>
>     movsd <- function(series,lag)
>     {
>     movingsd <- vector(mode="numeric")
>     for (i in lag:length(series))
>	     {
>	     movingsd[i] <- sd(series[(i-lag+1):i])
>	     }
>     assign("movingsd",movingsd,.GlobalEnv)
>     }
>
>    bogdan> This is very efficient: it takes (much) less time to write from
>    bogdan> scratch than to look for an existing function.
>
>yes, it's fine, but the assign() line is really something so
>much not-recommendable `` I can't let go through '' :
>
>Your  movsd() provides a function with ``side effect'' : it
>"suddenly" creates a global variable 'movingsd' {overwriting
>another one, if there was one} instead of doing
>the most natural thing for an S (or R) function:  *return* it's
>computation:
>
>So, please, use instead something like
>
>     movsd <- function(series,lag)
>     {
>	msd <- vector(mode="numeric")
>	for (i in lag:length(series))
>	{
>		msd[i] <- sd(series[(i-lag+1):i])
>	}
>	msd
>     }
>
>and then things like
>
>    sy1.3 <- movsd(y1, 3)
>    sy1.5 <- movsd(y1, 5)
>    sy2.5 <- movsd(y2, 5)
>
>etc.
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>
>  
>




More information about the R-help mailing list