movingDynamic

First introduced in version: 3.00.6

Syntax

movingDynamic(func, funcArgs, window, [maxWindow], [minPeriods])

Details

Constructs variable-length moving windows over funcArgs using the row-specific lengths in window, and applies the aggregate function func to each window. Each window ends at the current element.

If maxWindow is specified, the effective window length at row i is min(window[i], maxWindow); otherwise, it is window[i]. A NULL is returned when the number of non-NULL observations in a window is less than minPeriods.

Unlike moving, movingDynamic requires window to be a positive integer vector and does not support DURATION values. minPeriods can be greater than an element of window or maxWindow, in which case rows that do not meet the minimum observation count return NULL.

Note: movingDynamic is currently not supported in streaming engines.

Parameters

func is an aggregate function.

Note: A user-defined aggregate function must be defined with the defg keyword. For details, see Tutorial: User Defined Aggregate Functions.

funcArgs are the arguments of func. They can be vectors, dictionaries, or matrices. If func takes multiple arguments, pass them as a tuple, and all arguments must have the same length.

window is a positive integer vector specifying the moving window length for each row. It must have the same length as funcArgs and cannot contain NULL or non-positive values.

maxWindow (optional) is a positive integer scalar that limits the effective window length. If window[i] > maxWindow, maxWindow is used as the window length for row i.

minPeriods (optional) is a positive integer scalar indicating the minimum number of non-NULL observations required in a window to produce a result. The default is the effective window length of the current row. It can be greater than the effective window length.

Returns

The result has the same length as funcArgs. For vector or dictionary input, it typically returns a vector. For matrix input, it calculates each column and returns a matrix. If func returns a tuple, the result is a tuple whose elements contain the corresponding calculation results.

Examples

Example 1. Calculate a moving sum using the row-specific lengths in window.

movingDynamic(func=sum, funcArgs=1..5, window=[1, 2, 3, 2, 4])
// output: [1,3,6,7,14]

Example 2. Set maxWindow to 3 to cap larger windows at 3, and set minPeriods to 1 so that one valid observation is sufficient to produce a result.

w = [1, 5, 2, 100, 4]
movingDynamic(func=sum, funcArgs=1..5, window=w, maxWindow=3, minPeriods=1)
// output: [1,3,5,9,12]

Example 3. Compare the default minPeriods with an explicit value of 1.

movingDynamic(func=avg, funcArgs=1..5, window=[3, 3, 3, 3, 3])
// output: [,,2,3,4]

movingDynamic(func=avg, funcArgs=1..5, window=[3, 3, 3, 3, 3], minPeriods=1)
// output: [1,1.5,2,3,4]

Related functions: moving, movingValid