MA: Simple Moving Average

Description Usage Arguments Value Author(s) References Examples

Description

The function computes a moving average of a vector.

Usage

1
MA(y, order, pad = NULL)

Arguments

y

a numeric vector

order

An integer. The order of the moving average. The function is defined such that order one returns y (see Examples).

pad

Defaults to NULL. If not NULL, all elements of the returned moving average with position smaller than order are replaced by the value of pad. Sensible values may be NA or 0.

Value

Returns a vector of length length(y).

Author(s)

Enrico Schumann

References

Gilli, M., Maringer, D. and Schumann, E. (2011) Numerical Methods and Optimization in Finance. Elsevier. http://www.elsevierdirect.com/product.jsp?isbn=9780123756626

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
MA(1:10, 3)
MA(1:10, 3, pad = NA)

y <- seq(1, 4, by = 0.3)
z <- MA(y, 1)
all(y == z)      ### (typically) FALSE
all.equal(y, z)  ### should be TRUE

## 'Relative strength index'
rsi <- function(y, t) {
    y <- diff(y)
    ups   <- y + abs(y)
    downs <- y - abs(y)
    RS <- -MA(ups, t) / MA(downs, t)
    RS/(1 + RS)
}
x <- cumprod(c(100, 1 + rnorm(100, sd = 0.01)))
par(mfrow = c(2,1))
plot(x, type = "l")
plot(rsi(x, 14), ylim = c(0,1), type = "l")

Example output

 [1] 0.3333333 1.0000000 2.0000000 3.0000000 4.0000000 5.0000000 6.0000000
 [8] 7.0000000 8.0000000 9.0000000
 [1] NA NA  2  3  4  5  6  7  8  9
[1] FALSE
[1] TRUE

NMOF documentation built on May 2, 2019, 6:39 p.m.