import numpy as np
from collections import deque
[docs]def shift(darray, k, axis=0):
"""
Utility function to shift a numpy array
Inputs
------
darray: a numpy array
the array to be shifted.
k: integer
number of shift
axis: non-negative integer
axis to perform shift operation
Outputs
-------
shifted numpy array, fill the unknown values with nan
"""
if k == 0:
return darray
elif k < 0:
shift_array = np.roll(darray, k, axis=axis)
shift_array[k:] = np.nan
return shift_array
else:
shift_array = np.roll(darray, k, axis=axis)
shift_array[:k] = np.nan
return shift_array
[docs]class LagFeatureProcessor(object):
def __init__(self, data, order, delay):
self._data = data
self._lags = deque(range(delay, delay + order))
[docs] def generate_lag_features(self, data_new=None):
features = [shift(self._data, l) for l in self._lags]
if data_new is not None:
features[0] = data_new
return np.array(features).T
[docs] def update(self, data_new=None):
self._lags.pop()
self._lags.appendleft(self._lags[0] - 1)
return self.generate_lag_features(data_new=data_new)