Rolling and rolling exponential averages (rolling
)#
Functions:
|
Convert an array to one with rolling windows. |
|
Moving average of central moments array. |
|
Moving average of central moments generated by values. |
|
Moving average of central moments array. |
|
Moving average of central moments generated by values. |
- cmomy.rolling.construct_rolling_window_array(x, window, *, axis=MISSING, dim=MISSING, center=False, stride=1, fill_value=nan, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, window_dim=None, keep_attrs=None, **kwargs)[source]#
Convert an array to one with rolling windows.
- Parameters:
center (
bool
) – IfTrue
, center windows.stride (
int
) – Size of strides in rolling window.fill_value (scalar) – Fill value for missing values.
mom_ndim (
{1, 2}
, optional) – Ifmom_ndim
is notNone
, then wrap axis relative tomom_ndim
. For Example, with mom_ndim=``2``,axis = -1
will be transformed toaxis = -3
. Ifmom_dims
is passed and data is anxarray
object, infermom_n=ndim
frommom_dims
.mom_axes (
int
ortuple
ofint
, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...)
. If specified andmom_ndim
is None, setmom_ndim
tolen(mom_axes)
. Note that ifmom_axes
is specified, negative values are relative to the end of the array. This is also the case foraxes
ifmom_axes
is specified.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. If specified, infermom_ndim
frommom_dims
. If also passmom_ndim
, check thatmom_dims
is consistent withmom_dims
. If not specified, defaults todata.dims[-mom_ndim:]
. This is primarily used ifdata
is aDataset
, or ifmom_dims
are not the last dimensions.mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.window_dim (
str
orSequence
ofstr
, optional) – Names of output window dimension(s). Default torolling_dim : hashable Dimension to reduce/sample along.
wheredim : hashable Dimension to reduce/sample along.
is replaced bydim
names.keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
**kwargs (Any) – Extra arguments to
xarray.DataArray.rolling()
orxarray.Dataset.rolling()
.
- Returns:
output (array) – Array of shape
(window, *shape)
.
Notes
This function uses different syntax compared to
xarray.DataArray.rolling()
. Instead of mappings forcenter
, etc, here you pass scalar or sequence values corresponding to axis/dim. Corresponding mappings are created from, for examplecenter=dict(zip(dim, center))
.Examples
>>> x = np.arange(5).astype(float) >>> construct_rolling_window_array(x, window=4, axis=0) array([[nan, nan, nan, 0., 1.], [nan, nan, 0., 1., 2.], [nan, 0., 1., 2., 3.], [ 0., 1., 2., 3., 4.]])
>>> dx = xr.DataArray(x) >>> construct_rolling_window_array(dx, window=4, center=True, dim="dim_0") <xarray.DataArray (rolling_dim_0: 4, dim_0: 5)> Size: 160B array([[nan, nan, 0., 1., 2.], [nan, 0., 1., 2., 3.], [ 0., 1., 2., 3., 4.], [ 1., 2., 3., 4., nan]]) Dimensions without coordinates: rolling_dim_0, dim_0
- cmomy.rolling.rolling_data(data, *, window, axis=MISSING, dim=MISSING, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, min_periods=None, center=False, zero_missing_weights=True, out=None, dtype=None, casting='same_kind', order=None, parallel=None, axes_to_end=False, keep_attrs=None, apply_ufunc_kwargs=None)[source]#
Moving average of central moments array.
- Parameters:
data (array-like or
DataArray
orDataset
)window (
int
) – Size of moving window.axis (
int
) – Axis to reduce/sample along.dim (hashable) – Dimension to reduce/sample along.
mom_ndim (
{1, 2}
, optional) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
). If not specified and data is anxarray
object attempt to infermom_ndim
frommom_dims
. Otherwise, default tomom_ndim = 1
.mom_axes (
int
ortuple
ofint
, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...)
. If specified andmom_ndim
is None, setmom_ndim
tolen(mom_axes)
. Note that ifmom_axes
is specified, negative values are relative to the end of the array. This is also the case foraxes
ifmom_axes
is specified.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. If specified, infermom_ndim
frommom_dims
. If also passmom_ndim
, check thatmom_dims
is consistent withmom_dims
. If not specified, defaults todata.dims[-mom_ndim:]
. This is primarily used ifdata
is aDataset
, or ifmom_dims
are not the last dimensions.mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.min_periods (
int
, optional) – Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window.center (
bool
, defaultFalse
) – IfTrue
, set the labels at the center of the window.zero_missing_weights (
bool
, defaultTrue
) – IfTrue
, set missing weights (np.nan
) to0
.out (
ndarray
) – Optional output array. If specified, output will be a reference to this array. Note that if the output if method returns aDataset
, then this option is ignored.casting (
{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
, optional) –Controls what kind of data casting may occur.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ (default) means any data conversions may be done.
order (
{"C", "F", "A", "K"}
, optional) – Order argument. Seenumpy.asarray()
.parallel (
bool
, optional) – IfTrue
, use parallel numbanumba.njit
ornumba.guvectorized
code if possible. IfNone
, use a heuristic to determine if should attempt to use parallel method.axes_to_end (
bool
) – IfTrue
, place sampled dimension (if exists in output) and moment dimensions at end of output. Otherwise, place sampled dimension (if exists in output) at same position as inputaxis
and moment dimensions at same position as input (if input does not contain moment dimensions, place them at end of array).keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.
- Returns:
out (
ndarray
orDataArray
orDataset
) – Moving average data, of same shape and type asdata
.
- cmomy.rolling.rolling_vals(x, *y, mom, window, axis=MISSING, dim=MISSING, weight=None, mom_dims=None, mom_params=None, min_periods=None, center=False, zero_missing_weights=True, out=None, dtype=None, casting='same_kind', order=None, parallel=None, axes_to_end=True, keep_attrs=None, apply_ufunc_kwargs=None)[source]#
Moving average of central moments generated by values.
- Parameters:
x (array-like or
DataArray
orDataset
) – Values to reduce.*y (array-like or
DataArray
orDataset
) – Additional values (needed iflen(mom)==2
).y
has same type restrictions and broadcasting rules asweight
.mom (
int
ortuple
ofint
) – Order or moments. If integer or length one tuple, then moments are for a single variable. If length 2 tuple, then comoments of two variableswindow (
int
) – Size of moving window.axis (
int
) – Axis to reduce/sample along.dim (hashable) – Dimension to reduce/sample along.
weight (array-like or
DataArray
orDataset
) –Optional weight. The type of
weight
must be “less than” the type ofx
.x
isDataset
:weight
can be aDataset
,DataArray
, or array-likex
is array-like:weight
can be array-like
In the case that
weight
is array-like, it must broadcast tox
using usual broadcasting rules (seenumpy.broadcast_to()
), with the following exceptions: Ifweight
is a 1d array of lengthx.shape[axis]]
, it will be formatted to broadcast along the other dimensions ofx
. For example, ifx
has shape(10, 2, 3)
andweight
has shape(10,)
, thenweight
will be converted to the broadcastable shape(10, 1, 1)
. Ifweight
is a scalar, it will be broadcast tox.shape
.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. Defaults to("mom_0",)
formom_ndim==1
and(mom_0, mom_1)
formom_ndim==2
mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.min_periods (
int
, optional) – Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window.center (
bool
, defaultFalse
) – IfTrue
, set the labels at the center of the window.zero_missing_weights (
bool
, defaultTrue
) – IfTrue
, set missing weights (np.nan
) to0
.out (
ndarray
) – Optional output array. If specified, output will be a reference to this array. Note that if the output if method returns aDataset
, then this option is ignored.casting (
{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
, optional) –Controls what kind of data casting may occur.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ (default) means any data conversions may be done.
order (
{"C", "F"}
, optional) – Order argument. Seenumpy.zeros()
.parallel (
bool
, optional) – IfTrue
, use parallel numbanumba.njit
ornumba.guvectorized
code if possible. IfNone
, use a heuristic to determine if should attempt to use parallel method.axes_to_end (
bool
) – IfTrue
, place sampled dimension (if exists in output) and moment dimensions at end of output. Otherwise, place sampled dimension (if exists in output) at same position as inputaxis
and moment dimensions at same position as input (if input does not contain moment dimensions, place them at end of array).keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.
- Returns:
out (
ndarray
orDataArray
) – Central moments array of same type asx
.out.shape = shape + (mom0, ...)
whereshape = np.broadcast_shapes(*(a.shape for a in (x_, *y_, weight_)))
andx_
,y_
andweight_
are the input arrays withaxis
moved to the last axis. That is, the last dimensions are the moving average axisaxis
and the moments dimensions.
See also
- cmomy.rolling.rolling_exp_data(data, alpha, *, axis=MISSING, dim=MISSING, mom_ndim=None, mom_axes=None, mom_dims=None, mom_params=None, min_periods=None, alpha_axis=MISSING, adjust=True, zero_missing_weights=True, out=None, dtype=None, casting='same_kind', order=None, parallel=None, axes_to_end=False, keep_attrs=None, apply_ufunc_kwargs=None)[source]#
Moving average of central moments array.
- Parameters:
data (array-like)
alpha (array-like) – alpha values.
axis (
int
) – Axis to reduce/sample along.dim (hashable) – Dimension to reduce/sample along.
mom_ndim (
{1, 2}
, optional) – Value indicates if moments (mom_ndim = 1
) or comoments (mom_ndim=2
). If not specified and data is anxarray
object attempt to infermom_ndim
frommom_dims
. Otherwise, default tomom_ndim = 1
.mom_axes (
int
ortuple
ofint
, optional) – Location of the moment dimensions. Default to(-mom_ndim, -mom_ndim+1, ...)
. If specified andmom_ndim
is None, setmom_ndim
tolen(mom_axes)
. Note that ifmom_axes
is specified, negative values are relative to the end of the array. This is also the case foraxes
ifmom_axes
is specified.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. If specified, infermom_ndim
frommom_dims
. If also passmom_ndim
, check thatmom_dims
is consistent withmom_dims
. If not specified, defaults todata.dims[-mom_ndim:]
. This is primarily used ifdata
is aDataset
, or ifmom_dims
are not the last dimensions.mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.min_periods (
int
, optional) – Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window.alpha_axis (
int
) – Axis ofalpha
corresponding toaxis
fordata
.adjust (
bool
, defaultTrue
) – Same asadjust
parameter ofpandas.DataFrame.ewm()
zero_missing_weights (
bool
, defaultTrue
) – IfTrue
, set missing weights (np.nan
) to0
.out (
ndarray
) – Optional output array. If specified, output will be a reference to this array. Note that if the output if method returns aDataset
, then this option is ignored.casting (
{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
, optional) –Controls what kind of data casting may occur.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ (default) means any data conversions may be done.
order (
{"C", "F", "A", "K"}
, optional) – Order argument. Seenumpy.asarray()
.parallel (
bool
, optional) – IfTrue
, use parallel numbanumba.njit
ornumba.guvectorized
code if possible. IfNone
, use a heuristic to determine if should attempt to use parallel method.axes_to_end (
bool
) – IfTrue
, place sampled dimension (if exists in output) and moment dimensions at end of output. Otherwise, place sampled dimension (if exists in output) at same position as inputaxis
and moment dimensions at same position as input (if input does not contain moment dimensions, place them at end of array).keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.
- Returns:
out (
ndarray
orDataArray
) – Exponential moving average of same shape and type ofdata
.
- cmomy.rolling.rolling_exp_vals(x, *y, alpha, mom, axis=MISSING, dim=MISSING, weight=None, mom_dims=None, mom_params=None, min_periods=None, adjust=True, zero_missing_weights=True, out=None, dtype=None, casting='same_kind', order=None, parallel=None, axes_to_end=True, keep_attrs=None, apply_ufunc_kwargs=None)[source]#
Moving average of central moments generated by values.
- Parameters:
x (array-like or
DataArray
orDataset
) – Values to reduce.*y (array-like or
DataArray
orDataset
) – Additional values (needed iflen(mom)==2
).y
has same type restrictions and broadcasting rules asweight
.alpha (array-like) – alpha values.
mom (
int
ortuple
ofint
) – Order or moments. If integer or length one tuple, then moments are for a single variable. If length 2 tuple, then comoments of two variablesaxis (
int
) – Axis to reduce/sample along.dim (hashable) – Dimension to reduce/sample along.
weight (array-like or
DataArray
orDataset
) –Optional weight. The type of
weight
must be “less than” the type ofx
.x
isDataset
:weight
can be aDataset
,DataArray
, or array-likex
is array-like:weight
can be array-like
In the case that
weight
is array-like, it must broadcast tox
using usual broadcasting rules (seenumpy.broadcast_to()
), with the following exceptions: Ifweight
is a 1d array of lengthx.shape[axis]]
, it will be formatted to broadcast along the other dimensions ofx
. For example, ifx
has shape(10, 2, 3)
andweight
has shape(10,)
, thenweight
will be converted to the broadcastable shape(10, 1, 1)
. Ifweight
is a scalar, it will be broadcast tox.shape
.mom_dims (hashable or
tuple
of hashable) – Name of moment dimensions. Defaults to("mom_0",)
formom_ndim==1
and(mom_0, mom_1)
formom_ndim==2
mom_params (
cmomy.MomParams
orcmomy.MomParamsDict
ordict
, optional) – Moment parameters. You can set moment parametersaxes
anddims
using this option. For example, passingmom_params={"dim": ("a", "b")}
is equivalent to passingmom_dims=("a", "b")
. You can also pass as acmomy.MomParams
object withmom_params=cmomy.MomParams(dims=("a", "b"))
.min_periods (
int
, optional) – Minimum number of observations in window required to have a value (otherwise result is NA). The default, None, is equivalent to setting min_periods equal to the size of the window.adjust (
bool
, defaultTrue
) – Same asadjust
parameter ofpandas.DataFrame.ewm()
zero_missing_weights (
bool
, defaultTrue
) – IfTrue
, set missing weights (np.nan
) to0
.out (
ndarray
) – Optional output array. If specified, output will be a reference to this array. Note that if the output if method returns aDataset
, then this option is ignored.casting (
{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}
, optional) –Controls what kind of data casting may occur.
’no’ means the data types should not be cast at all.
’equiv’ means only byte-order changes are allowed.
’safe’ means only casts which can preserve values are allowed.
’same_kind’ means only safe casts or casts within a kind, like float64 to float32, are allowed.
’unsafe’ (default) means any data conversions may be done.
order (
{"C", "F"}
, optional) – Order argument. Seenumpy.zeros()
.parallel (
bool
, optional) – IfTrue
, use parallel numbanumba.njit
ornumba.guvectorized
code if possible. IfNone
, use a heuristic to determine if should attempt to use parallel method.axes_to_end (
bool
) – IfTrue
, place sampled dimension (if exists in output) and moment dimensions at end of output. Otherwise, place sampled dimension (if exists in output) at same position as inputaxis
and moment dimensions at same position as input (if input does not contain moment dimensions, place them at end of array).keep_attrs (
{"drop", "identical", "no_conflicts", "drop_conflicts", "override"}
orbool
, optional) –‘drop’ or False: empty attrs on returned xarray object.
’identical’: all attrs must be the same on every object.
’no_conflicts’: attrs from all objects are combined, any that have the same name must also have the same value.
’drop_conflicts’: attrs from all objects are combined, any that have the same name but different values are dropped.
’override’ or True: skip comparing and copy attrs from the first object to the result.
apply_ufunc_kwargs (dict-like) – Extra parameters to
xarray.apply_ufunc()
. One useful option ison_missing_core_dim
, which can take the value"copy"
(the default),"raise"
, or"drop"
and controls what to do with variables of aDataset
missing core dimensions. Other options arejoin
,dataset_join
,dataset_fill_value
, anddask_gufunc_kwargs
. Unlisted options are handled internally.
- Returns:
out (
ndarray
orDataArray
) – Central moments array of same type asx
.out.shape = shape + (mom0, ...)
whereshape = np.broadcast_shapes(*(a.shape for a in (x_, *y_, weight_)))
andx_
,y_
andweight_
are the input arrays withaxis
moved to the last axis. That is, the last dimensions are the moving average axisaxis
and the moments dimensions.
See also