INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Ratio of values that are more than r*std(x) (so r sigma) away from the mean of x. :param x: the time series to calculate the feature of :type x: iterable :return: the value of this feature :return type: float
def ratio_beyond_r_sigma(x, r): """ Ratio of values that are more than r*std(x) (so r sigma) away from the mean of x. :param x: the time series to calculate the feature of :type x: iterable :return: the value of this feature :return type: float """ if not isinstance(x, (np.ndarray, pd.S...
Boolean variable denoting if the standard dev of x is higher than 'r' times the range = difference between max and min of x. Hence it checks if .. math:: std(x) > r * (max(X)-min(X)) According to a rule of the thumb, the standard deviation should be a forth of the range of the values. :p...
def large_standard_deviation(x, r): """ Boolean variable denoting if the standard dev of x is higher than 'r' times the range = difference between max and min of x. Hence it checks if .. math:: std(x) > r * (max(X)-min(X)) According to a rule of the thumb, the standard deviation shoul...
Boolean variable denoting if the distribution of x *looks symmetric*. This is the case if .. math:: | mean(X)-median(X)| < r * (max(X)-min(X)) :param x: the time series to calculate the feature of :type x: numpy.ndarray :param r: the percentage of the range to compare with :type r: float ...
def symmetry_looking(x, param): """ Boolean variable denoting if the distribution of x *looks symmetric*. This is the case if .. math:: | mean(X)-median(X)| < r * (max(X)-min(X)) :param x: the time series to calculate the feature of :type x: numpy.ndarray :param r: the percentage of t...
Checks if the maximum value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool
def has_duplicate_max(x): """ Checks if the maximum value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool """ if not isinstance(x, (np.ndarray, pd.Series)): x = np....
Checks if the minimal value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool
def has_duplicate_min(x): """ Checks if the minimal value of x is observed more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool """ if not isinstance(x, (np.ndarray, pd.Series)): x = np....
Checks if any value in x occurs more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool
def has_duplicate(x): """ Checks if any value in x occurs more than once :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: bool """ if not isinstance(x, (np.ndarray, pd.Series)): x = np.asarray(x) re...
r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sigma^{2}} \sum_{t=1}^{n-l}(X_{t}-\mu )(X_...
def agg_autocorrelation(x, param): r""" Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as .. math:: R(l) = \frac{1}{(n-l)\sig...
Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and :math:`x_{t-k}`, adjusted for the intermediate variables :math:`\\lbrace x_{t-1...
def partial_autocorrelation(x, param): """ Calculates the value of the partial autocorrelation function at the given lag. The lag `k` partial autocorrelation of a time series :math:`\\lbrace x_t, t = 1 \\ldots T \\rbrace` equals the partial correlation of :math:`x_t` and :math:`x_{t-k}`, adjusted for th...
The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time series sample. This feature calculator returns the value of the respective test statistic. See the statsmodels implementation for references and more details. :param x: the time series to calculate ...
def augmented_dickey_fuller(x, param): """ The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time series sample. This feature calculator returns the value of the respective test statistic. See the statsmodels implementation for references and more de...
Returns the absolute energy of the time series which is the sum over the squared values .. math:: E = \\sum_{i=1,\ldots, n} x_i^2 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def abs_energy(x): """ Returns the absolute energy of the time series which is the sum over the squared values .. math:: E = \\sum_{i=1,\ldots, n} x_i^2 :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: fl...
This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubric:: References | [1] Batista, Gustavo EAPA, et al (2014). ...
def cid_ce(x, normalize): """ This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks, valleys etc.). It calculates the value of .. math:: \\sqrt{ \\sum_{i=0}^{n-2lag} ( x_{i} - x_{i+1})^2 } .. rubric:: References | [1] Bat...
Returns the mean value of a central approximation of the second derivative .. math:: \\frac{1}{n} \\sum_{i=1,\ldots, n-1} \\frac{1}{2} (x_{i+2} - 2 \\cdot x_{i+1} + x_i) :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :retur...
def mean_second_derivative_central(x): """ Returns the mean value of a central approximation of the second derivative .. math:: \\frac{1}{n} \\sum_{i=1,\ldots, n-1} \\frac{1}{2} (x_{i+2} - 2 \\cdot x_{i+1} + x_i) :param x: the time series to calculate the feature of :type x: numpy.ndarra...
Returns the sample skewness of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G1). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def skewness(x): """ Returns the sample skewness of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G1). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ if not isin...
Returns the kurtosis of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G2). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def kurtosis(x): """ Returns the kurtosis of x (calculated with the adjusted Fisher-Pearson standardized moment coefficient G2). :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ if not isinstance(...
Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def longest_strike_below_mean(x): """ Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ if not isinstan...
Returns the number of values in x that are higher than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def count_above_mean(x): """ Returns the number of values in x that are higher than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ m = np.mean(x) return np.where(x > m)[0].size
Returns the number of values in x that are lower than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def count_below_mean(x): """ Returns the number of values in x that are lower than the mean of x :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ m = np.mean(x) return np.where(x < m)[0].size
Returns the relative last location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def last_location_of_maximum(x): """ Returns the relative last location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float ...
Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def first_location_of_maximum(x): """ Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def last_location_of_minimum(x): """ Returns the last location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the first location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def first_location_of_minimum(x): """ Returns the first location of the minimal value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
Returns the percentage of unique values, that are present in the time series more than once. len(different values occurring more than once) / len(different values) This means the percentage is normalized to the number of unique values, in contrast to the percentage_of_reoccurring_values_to_all_val...
def percentage_of_reoccurring_datapoints_to_all_datapoints(x): """ Returns the percentage of unique values, that are present in the time series more than once. len(different values occurring more than once) / len(different values) This means the percentage is normalized to the number of unique...
Returns the ratio of unique values, that are present in the time series more than once. # of data points occurring more than once / # of all data points This means the ratio is normalized to the number of data points in the time series, in contrast to the percentage_of_reoccurring_datapoints_to_al...
def percentage_of_reoccurring_values_to_all_values(x): """ Returns the ratio of unique values, that are present in the time series more than once. # of data points occurring more than once / # of all data points This means the ratio is normalized to the number of data points in the time series...
Returns the sum of all values, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def sum_of_reoccurring_values(x): """ Returns the sum of all values, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ unique, counts = np.unique...
Returns the sum of all data points, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
def sum_of_reoccurring_data_points(x): """ Returns the sum of all data points, that are present in the time series more than once. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ unique, counts =...
Returns a factor which is 1 if all values in the time series occur only once, and below one if this is not the case. In principle, it just returns # unique values / # values :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature ...
def ratio_value_number_to_time_series_length(x): """ Returns a factor which is 1 if all values in the time series occur only once, and below one if this is not the case. In principle, it just returns # unique values / # values :param x: the time series to calculate the feature of :type...
Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}, \\qquad k = 0, \\ldots , n-1. The resulting coefficien...
def fft_coefficient(x, param): """ Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}, \\qquad k = 0, \...
Returns the spectral centroid (mean), variance, skew, and kurtosis of the absolute fourier transform spectrum. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param param: contains dictionaries {"aggtype": s} where s str and in ["centroid", "variance", "skew", "kurtosi...
def fft_aggregated(x, param): """ Returns the spectral centroid (mean), variance, skew, and kurtosis of the absolute fourier transform spectrum. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param param: contains dictionaries {"aggtype": s} where s str and in ["centr...
Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as a subsequence of x where a value occurs, which is bigger than its n neighbours to the left and to the right. Hence in the sequence >>> x = [3, 0, 0, 4, 0, 0, 13] 4 is a peak of support 1 and 2...
def number_peaks(x, n): """ Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as a subsequence of x where a value occurs, which is bigger than its n neighbours to the left and to the right. Hence in the sequence >>> x = [3, 0, 0, 4, 0, 0, 13]...
Those apply features calculate the relative index i where q% of the mass of the time series x lie left of i. For example for q = 50% this feature calculator will return the mass center of the time series :param x: the time series to calculate the feature of :type x: numpy.ndarray :param param: contains...
def index_mass_quantile(x, param): """ Those apply features calculate the relative index i where q% of the mass of the time series x lie left of i. For example for q = 50% this feature calculator will return the mass center of the time series :param x: the time series to calculate the feature of :t...
This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal-to-Noise-Ratio (SNR) :param x: the time series t...
def number_cwt_peaks(x, n): """ This feature calculator searches for different peaks in x. To do so, x is smoothed by a ricker wavelet and for widths ranging from 1 to n. This feature calculator returns the number of peaks that occur at enough width scales and with sufficiently high Signal-to-Noise-Rati...
Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters control which of the characteristics are ...
def linear_trend(x, param): """ Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters c...
Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is defined by .. math:: \\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2}) where :math:`a` is the width parameter of the wavelet function. This...
def cwt_coefficients(x, param): """ Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the "Mexican hat wavelet" which is defined by .. math:: \\frac{2}{\\sqrt{3a} \\pi^{\\frac{1}{4}}} (1 - \\frac{x^2}{a^2}) exp(-\\frac{x^2}{2a^2}) where :math:`a` is the width ...
This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so, the time series is first shifted from the time domain to the frequency domain. The feature calculators returns the power spectrum of the different frequencies. :param x: the time ser...
def spkt_welch_density(x, param): """ This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so, the time series is first shifted from the time domain to the frequency domain. The feature calculators returns the power spectrum of the diff...
This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the configurations from param which should contain t...
def ar_coefficient(x, param): """ This feature calculator fits the unconditional maximum likelihood of an autoregressive AR(k) process. The k parameter is the maximum lag of the process .. math:: X_{t}=\\varphi_0 +\\sum _{{i=1}}^{k}\\varphi_{i}X_{{t-i}}+\\varepsilon_{t} For the config...
First fixes a corridor given by the quantiles ql and qh of the distribution of x. Then calculates the average, absolute value of consecutive changes of the series x inside this corridor. Think about selecting a corridor on the y-Axis and only calculating the mean of the absolute change of the time series i...
def change_quantiles(x, ql, qh, isabs, f_agg): """ First fixes a corridor given by the quantiles ql and qh of the distribution of x. Then calculates the average, absolute value of consecutive changes of the series x inside this corridor. Think about selecting a corridor on the y-Axis and only calcu...
This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2 which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2] where :math:`\\mathbb{E}` is the mean and :math:`L` is the...
def time_reversal_asymmetry_statistic(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} - x_{i + lag} \cdot x_{i}^2 which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) - L(X) \cdot X^2] ...
This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was prop...
def c3(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is t...
First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. :param x: the time series to calculate the fe...
def binned_entropy(x, max_bins): """ First bins the values of x into max_bins equidistant bins. Then calculates the value of .. math:: - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)} where :math:`p_k` is the percentage of samples in bin :math:`k`. ...
Calculate and return sample entropy of x. .. rubric:: References | [1] http://en.wikipedia.org/wiki/Sample_Entropy | [2] https://www.ncbi.nlm.nih.gov/pubmed/10843903?dopt=Abstract :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this featur...
def sample_entropy(x): """ Calculate and return sample entropy of x. .. rubric:: References | [1] http://en.wikipedia.org/wiki/Sample_Entropy | [2] https://www.ncbi.nlm.nih.gov/pubmed/10843903?dopt=Abstract :param x: the time series to calculate the feature of :type x: numpy.ndarray ...
Calculates the autocorrelation of the specified lag, according to the formula [1] .. math:: \\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t}-\\mu )(X_{t+l}-\\mu) where :math:`n` is the length of the time series :math:`X_i`, :math:`\sigma^2` its variance and :math:`\mu` its mean. `l` denotes the...
def autocorrelation(x, lag): """ Calculates the autocorrelation of the specified lag, according to the formula [1] .. math:: \\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t}-\\mu )(X_{t+l}-\\mu) where :math:`n` is the length of the time series :math:`X_i`, :math:`\sigma^2` its variance and ...
Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param q: the quantile to calculate :type q: float :return: the value of this feature :return type: float
def quantile(x, q): """ Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param q: the quantile to calculate :type q: float :return: the value of this feature ...
Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value is lower than m and the next is greater, or vice-versa. If you set m to zero, you will get the number of zero crossings. :param x: the time series to calculate the feature of :type x: nump...
def number_crossing_m(x, m): """ Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value is lower than m and the next is greater, or vice-versa. If you set m to zero, you will get the number of zero crossings. :param x: the time series to c...
Count occurrences of `value` in time series x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param value: the value to be counted :type value: int or float :return: the count :rtype: int
def value_count(x, value): """ Count occurrences of `value` in time series x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param value: the value to be counted :type value: int or float :return: the count :rtype: int """ if not isinstance(x, (np....
Count observed values within the interval [min, max). :param x: the time series to calculate the feature of :type x: numpy.ndarray :param min: the inclusive lower bound of the range :type min: int or float :param max: the exclusive upper bound of the range :type max: int or float :return: t...
def range_count(x, min, max): """ Count observed values within the interval [min, max). :param x: the time series to calculate the feature of :type x: numpy.ndarray :param min: the inclusive lower bound of the range :type min: int or float :param max: the exclusive upper bound of the range ...
Implements a vectorized Approximate entropy algorithm. https://en.wikipedia.org/wiki/Approximate_entropy For short time-series this method is highly dependent on the parameters, but should be stable for N > 2000, see: Yentes et al. (2012) - *The Appropriate Use of Approximate Entropy ...
def approximate_entropy(x, m, r): """ Implements a vectorized Approximate entropy algorithm. https://en.wikipedia.org/wiki/Approximate_entropy For short time-series this method is highly dependent on the parameters, but should be stable for N > 2000, see: Yentes et al. (2012) - ...
Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) as described by [1]. For short time-series this method is highly dependent on the parameters. .. rubric:: References | [1...
def friedrich_coefficients(x, param): """ Coefficients of polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot{x}(t) = h(x(t)) + \mathcal{N}(0,R) as described by [1]. For short time-series this method is highly dependent on the ...
Largest fixed point of dynamics :math:argmax_x {h(x)=0}` estimated from polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot(x)(t) = h(x(t)) + R \mathcal(N)(0,1) as described by Friedrich et al. (2000): Physics Letters A 271, p. 21...
def max_langevin_fixed_point(x, r, m): """ Largest fixed point of dynamics :math:argmax_x {h(x)=0}` estimated from polynomial :math:`h(x)`, which has been fitted to the deterministic dynamics of Langevin model .. math:: \dot(x)(t) = h(x(t)) + R \mathcal(N)(0,1) as described by Fr...
Calculates a linear least-squares regression for values of the time series that were aggregated over chunks versus the sequence from 0 up to the number of chunks minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model. The parameters attr contro...
def agg_linear_trend(x, param): """ Calculates a linear least-squares regression for values of the time series that were aggregated over chunks versus the sequence from 0 up to the number of chunks minus one. This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fi...
Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment number (starting at zero) to return a feature on. ...
def energy_ratio_by_chunks(x, param): """ Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment numbe...
Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parameters control which of the characteristics are ret...
def linear_trend_timewise(x, param): """ Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to length of the time series minus one. This feature uses the index of the time series to fit the model, which must be of a datetime dtype. The parame...
Extract the information, which of the features are relevent using the given target. For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh` function. All columns in the input data sample are treated as feature. The index of all rows in X must be ...
def fit(self, X, y): """ Extract the information, which of the features are relevent using the given target. For more information, please see the :func:`~tsfresh.festure_selection.festure_selector.check_fs_sig_bh` function. All columns in the input data sample are treated as feature. Th...
Delete all features, which were not relevant in the fit phase. :param X: data sample with all features, which will be reduced to only those that are relevant :type X: pandas.DataSeries or numpy.array :return: same data sample as X, but with only the relevant features :rtype: pandas.Dat...
def transform(self, X): """ Delete all features, which were not relevant in the fit phase. :param X: data sample with all features, which will be reduced to only those that are relevant :type X: pandas.DataSeries or numpy.array :return: same data sample as X, but with only the ...
Download human activity recognition dataset from UCI ML Repository and store it at /tsfresh/notebooks/data. Examples ======== >>> from tsfresh.examples import har_dataset >>> har_dataset.download_har_dataset()
def download_har_dataset(): """ Download human activity recognition dataset from UCI ML Repository and store it at /tsfresh/notebooks/data. Examples ======== >>> from tsfresh.examples import har_dataset >>> har_dataset.download_har_dataset() """ zipurl = 'https://github.com/MaxBen...
Add the features calculated using the timeseries_container and add them to the corresponding rows in the input pandas.DataFrame X. To save some computing time, you should only include those time serieses in the container, that you need. You can set the timeseries container with the method :func...
def transform(self, X): """ Add the features calculated using the timeseries_container and add them to the corresponding rows in the input pandas.DataFrame X. To save some computing time, you should only include those time serieses in the container, that you need. You can set th...
Use the given timeseries from :func:`~set_timeseries_container` and calculate features from it and add them to the data sample X (which can contain other manually-designed features). Then determine which of the features of X are relevant for the given target y. Store those relevant features int...
def fit(self, X, y): """ Use the given timeseries from :func:`~set_timeseries_container` and calculate features from it and add them to the data sample X (which can contain other manually-designed features). Then determine which of the features of X are relevant for the given target y. ...
After the fit step, it is known which features are relevant, Only extract those from the time series handed in with the function :func:`~set_timeseries_container`. If filter_only_tsfresh_features is False, also delete the irrelevant, already present features in the data frame. :param X: the da...
def transform(self, X): """ After the fit step, it is known which features are relevant, Only extract those from the time series handed in with the function :func:`~set_timeseries_container`. If filter_only_tsfresh_features is False, also delete the irrelevant, already present features ...
given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise.
def _preprocess(df): """ given a DataFrame where records are stored row-wise, rearrange it such that records are stored column-wise. """ df = df.stack() df.index.rename(["id", "time"], inplace=True) # .reset_index() df.name = "value" df = df.reset_index() return df
Calculate the relevance table for the features contained in feature matrix `X` with respect to target vector `y`. The relevance table is calculated for the intended machine learning task `ml_task`. To accomplish this for each feature from the input pandas.DataFrame an univariate feature significance test i...
def calculate_relevance_table(X, y, ml_task='auto', n_jobs=defaults.N_PROCESSES, chunksize=defaults.CHUNKSIZE, test_for_binary_target_binary_feature=defaults.TEST_FOR_BINARY_TARGET_BINARY_FEATURE, test_for_binary_target_real_feature=defaults.TEST_FOR_BINARY_TARGET_REAL_FEATURE, ...
Infer the machine learning task to select for. The result will be either `'regression'` or `'classification'`. If the target vector only consists of integer typed values or objects, we assume the task is `'classification'`. Else `'regression'`. :param y: The target vector y. :type y: pandas.Series ...
def infer_ml_task(y): """ Infer the machine learning task to select for. The result will be either `'regression'` or `'classification'`. If the target vector only consists of integer typed values or objects, we assume the task is `'classification'`. Else `'regression'`. :param y: The target vec...
Create a combined relevance table out of a list of relevance tables, aggregating the p-values and the relevances. :param relevance_tables: A list of relevance tables :type relevance_tables: List[pd.DataFrame] :return: The combined relevance table :rtype: pandas.DataFrame
def combine_relevance_tables(relevance_tables): """ Create a combined relevance table out of a list of relevance tables, aggregating the p-values and the relevances. :param relevance_tables: A list of relevance tables :type relevance_tables: List[pd.DataFrame] :return: The combined relevance ta...
For a given feature, determine if it is real, binary or constant. Here binary means that only two unique values occur in the feature. :param feature_column: The feature column :type feature_column: pandas.Series :return: 'constant', 'binary' or 'real'
def get_feature_type(feature_column): """ For a given feature, determine if it is real, binary or constant. Here binary means that only two unique values occur in the feature. :param feature_column: The feature column :type feature_column: pandas.Series :return: 'constant', 'binary' or 'real' ...
Extract features from * a :class:`pandas.DataFrame` containing the different time series or * a dictionary of :class:`pandas.DataFrame` each containing one type of time series In both cases a :class:`pandas.DataFrame` with the calculated features will be returned. For a list of all the calculat...
def extract_features(timeseries_container, default_fc_parameters=None, kind_to_fc_parameters=None, column_id=None, column_sort=None, column_kind=None, column_value=None, chunksize=defaults.CHUNKSIZE, n_jobs=defaults.N_PROCESSES, show_wa...
Converts the dataframe df in into a list of individual time seriess. E.g. the DataFrame ==== ====== ========= id kind val ==== ====== ========= 1 a -0.21761 1 a -0.613667 1 a -2.07339 2 b -0.576254 ...
def generate_data_chunk_format(df, column_id, column_kind, column_value): """Converts the dataframe df in into a list of individual time seriess. E.g. the DataFrame ==== ====== ========= id kind val ==== ====== ========= 1 a -0.21761 1 a ...
Wrapper around the _do_extraction_on_chunk, which calls it on all chunks in the data frame. A chunk is a subset of the data, with a given kind and id - so a single time series. The data is separated out into those single time series and the _do_extraction_on_chunk is called on each of them. The results are...
def _do_extraction(df, column_id, column_value, column_kind, default_fc_parameters, kind_to_fc_parameters, n_jobs, chunk_size, disable_progressbar, distributor): """ Wrapper around the _do_extraction_on_chunk, which calls it on all chunks in the data frame. A chunk is a...
Main function of this module: use the feature calculators defined in the default_fc_parameters or kind_to_fc_parameters parameters and extract all features on the chunk. The chunk consists of the chunk id, the chunk kind and the data (as a Series), which is then converted to a numpy array - so a single...
def _do_extraction_on_chunk(chunk, default_fc_parameters, kind_to_fc_parameters): """ Main function of this module: use the feature calculators defined in the default_fc_parameters or kind_to_fc_parameters parameters and extract all features on the chunk. The chunk consists of the chunk id, the chu...
Helper function to extract the configuration of a certain function from the column name. The column name parts (split by "__") should be passed to this function. It will skip the kind name and the function name and only use the parameter parts. These parts will be split up on "_" into the parameter name and...
def get_config_from_string(parts): """ Helper function to extract the configuration of a certain function from the column name. The column name parts (split by "__") should be passed to this function. It will skip the kind name and the function name and only use the parameter parts. These parts will be ...
Helper function to convert parameters to a valid string, that can be used in a column name. Does the opposite which is used in the from_columns function. The parameters are sorted by their name and written out in the form <param name>_<param value>__<param name>_<param value>__ ... If a <param_val...
def convert_to_output_format(param): """ Helper function to convert parameters to a valid string, that can be used in a column name. Does the opposite which is used in the from_columns function. The parameters are sorted by their name and written out in the form <param name>_<param value>__<par...
Helper function to stop the profiling process and write out the profiled data into the given filename. Before this, sort the stats by the passed sorting. :param profiler: An already started profiler (probably by start_profiling). :type profiler: cProfile.Profile :param filename: The name of the output ...
def end_profiling(profiler, filename, sorting=None): """ Helper function to stop the profiling process and write out the profiled data into the given filename. Before this, sort the stats by the passed sorting. :param profiler: An already started profiler (probably by start_profiling). :type profil...
Compute the min, max and median for all columns in the DataFrame. For more information, please see the :func:`~tsfresh.utilities.dataframe_functions.get_range_values_per_column` function. :param X: DataFrame to calculate min, max and median values on :type X: pandas.DataFrame ...
def fit(self, X, y=None): """ Compute the min, max and median for all columns in the DataFrame. For more information, please see the :func:`~tsfresh.utilities.dataframe_functions.get_range_values_per_column` function. :param X: DataFrame to calculate min, max and median ...
Column-wise replace all ``NaNs``, ``-inf`` and ``+inf`` in the DataFrame `X` with average/extreme values from the provided dictionaries. :param X: DataFrame to impute :type X: pandas.DataFrame :return: imputed DataFrame :rtype: pandas.DataFrame :...
def transform(self, X): """ Column-wise replace all ``NaNs``, ``-inf`` and ``+inf`` in the DataFrame `X` with average/extreme values from the provided dictionaries. :param X: DataFrame to impute :type X: pandas.DataFrame :return: imputed DataFram...
Download the Robot Execution Failures LP1 Data Set[#1] from the UCI Machine Learning Repository [#2] and store it locally. :return: Examples ======== >>> from tsfresh.examples import download_robot_execution_failures >>> download_robot_execution_failures()
def download_robot_execution_failures(): """ Download the Robot Execution Failures LP1 Data Set[#1] from the UCI Machine Learning Repository [#2] and store it locally. :return: Examples ======== >>> from tsfresh.examples import download_robot_execution_failures >>> download_robot_exec...
Load the Robot Execution Failures LP1 Data Set[1]. The Time series are passed as a flat DataFrame. Examples ======== >>> from tsfresh.examples import load_robot_execution_failures >>> df, y = load_robot_execution_failures() >>> print(df.shape) (1320, 8) :param multiclass: If True, ret...
def load_robot_execution_failures(multiclass=False): """ Load the Robot Execution Failures LP1 Data Set[1]. The Time series are passed as a flat DataFrame. Examples ======== >>> from tsfresh.examples import load_robot_execution_failures >>> df, y = load_robot_execution_failures() >>> p...
High level convenience function to extract time series features from `timeseries_container`. Then return feature matrix `X` possibly augmented with relevant features with respect to target vector `y`. For more details see the documentation of :func:`~tsfresh.feature_extraction.extraction.extract_features` and ...
def extract_relevant_features(timeseries_container, y, X=None, default_fc_parameters=None, kind_to_fc_parameters=None, column_id=None, column_sort=None, column_kind=None, column_value=None, show_warni...
Return list of control parameters :param n: number of samples :type n: int :param kappa_3: inverse bifurcation point :type kappa_3: float :param ratio: ratio (default 0.5) of samples before and beyond drift-bifurcation :type ratio: float :param rel_increase: relative increase from bifu...
def sample_tau(n=10, kappa_3=0.3, ratio=0.5, rel_increase=0.15): """ Return list of control parameters :param n: number of samples :type n: int :param kappa_3: inverse bifurcation point :type kappa_3: float :param ratio: ratio (default 0.5) of samples before and beyond drift-bifurcatio...
Simulates n time-series with l time steps each for the m-dimensional velocity of a dissipative soliton classification=True: target 0 means tau<=1/0.3, Dissipative Soliton with Brownian motion (purely noise driven) target 1 means tau> 1/0.3, Dissipative Soliton with Active Brownian motion (intrinsiv velocit...
def load_driftbif(n, l, m=2, classification=True, kappa_3=0.3, seed=False): """ Simulates n time-series with l time steps each for the m-dimensional velocity of a dissipative soliton classification=True: target 0 means tau<=1/0.3, Dissipative Soliton with Brownian motion (purely noise driven) targe...
Helper function to check for ``NaN`` in the data frame and raise a ``ValueError`` if there is one. :param df: the pandas DataFrame to test for NaNs :type df: pandas.DataFrame :param columns: a list of columns to test for NaNs. If left empty, all columns of the DataFrame will be tested. :type columns: l...
def check_for_nans_in_columns(df, columns=None): """ Helper function to check for ``NaN`` in the data frame and raise a ``ValueError`` if there is one. :param df: the pandas DataFrame to test for NaNs :type df: pandas.DataFrame :param columns: a list of columns to test for NaNs. If left empty, all ...
Columnwise replaces all ``NaNs`` and ``infs`` from the DataFrame `df_impute` with average/extreme values from the same columns. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by * ``-inf`` -> ``min`` * ``+inf`` -> ``max`` * ``NaN`` -> ``median`` I...
def impute(df_impute): """ Columnwise replaces all ``NaNs`` and ``infs`` from the DataFrame `df_impute` with average/extreme values from the same columns. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by * ``-inf`` -> ``min`` * ``+inf`` -> ``max`` ...
Replaces all ``NaNs``, ``-infs`` and ``+infs`` from the DataFrame `df_impute` with 0s. The `df_impute` will be modified in place. All its columns will be into converted into dtype ``np.float64``. :param df_impute: DataFrame to impute :type df_impute: pandas.DataFrame :return df_impute: imputed DataFra...
def impute_dataframe_zero(df_impute): """ Replaces all ``NaNs``, ``-infs`` and ``+infs`` from the DataFrame `df_impute` with 0s. The `df_impute` will be modified in place. All its columns will be into converted into dtype ``np.float64``. :param df_impute: DataFrame to impute :type df_impute: pandas...
Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values from the provided dictionaries. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` is replaced by * ``-inf`` -> by value in col_to_min * ``+inf`` -> by valu...
def impute_dataframe_range(df_impute, col_to_max, col_to_min, col_to_median): """ Columnwise replaces all ``NaNs``, ``-inf`` and ``+inf`` from the DataFrame `df_impute` with average/extreme values from the provided dictionaries. This is done as follows: Each occurring ``inf`` or ``NaN`` in `df_impute` ...
Retrieves the finite max, min and mean values per column in the DataFrame `df` and stores them in three dictionaries. Those dictionaries `col_to_max`, `col_to_min`, `col_to_median` map the columnname to the maximal, minimal or median value of that column. If a column does not contain any finite values at a...
def get_range_values_per_column(df): """ Retrieves the finite max, min and mean values per column in the DataFrame `df` and stores them in three dictionaries. Those dictionaries `col_to_max`, `col_to_min`, `col_to_median` map the columnname to the maximal, minimal or median value of that column. If...
Restrict df_or_dict to those ids contained in index. :param df_or_dict: a pandas DataFrame or a dictionary. :type df_or_dict: pandas.DataFrame or dict :param column_id: it must be present in the pandas DataFrame or in all DataFrames in the dictionary. It is not allowed to have NaN values in this co...
def restrict_input_to_index(df_or_dict, column_id, index): """ Restrict df_or_dict to those ids contained in index. :param df_or_dict: a pandas DataFrame or a dictionary. :type df_or_dict: pandas.DataFrame or dict :param column_id: it must be present in the pandas DataFrame or in all DataFrames in ...
Aggregates all ids in column_id from the time series container ` :param df_or_dict: a pandas DataFrame or a dictionary. :type df_or_dict: pandas.DataFrame or dict :param column_id: it must be present in the pandas DataFrame or in all DataFrames in the dictionary. It is not allowed to have NaN value...
def get_ids(df_or_dict, column_id): """ Aggregates all ids in column_id from the time series container ` :param df_or_dict: a pandas DataFrame or a dictionary. :type df_or_dict: pandas.DataFrame or dict :param column_id: it must be present in the pandas DataFrame or in all DataFrames in the diction...
Try to transform any given input to the internal representation of time series, which is a flat DataFrame (the first format from see :ref:`data-formats-label`). This function can transform pandas DataFrames in different formats or dictionaries into the internal format that we use. It should not be called b...
def _normalize_input_to_internal_representation(timeseries_container, column_id, column_sort, column_kind, column_value): """ Try to transform any given input to the internal representation of time series, which is a flat DataFrame (the first format from see :ref:`data-formats-label`). This function ca...
This method creates sub windows of the time series. It rolls the (sorted) data frames for each kind and each id separately in the "time" domain (which is represented by the sort order of the sort column given by `column_sort`). For each rolling step, a new id is created by the scheme "id={id}, shift={shift}", ...
def roll_time_series(df_or_dict, column_id, column_sort, column_kind, rolling_direction, max_timeshift=None): """ This method creates sub windows of the time series. It rolls the (sorted) data frames for each kind and each id separately in the "time" domain (which is represented by the sort order of the sor...
Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series forecasting task. The returned df will contain, for every time stamp in x, the last max_timeshift data points as a new time series, such can be used to fit a time series forecasting model. ...
def make_forecasting_frame(x, kind, max_timeshift, rolling_direction): """ Takes a singular time series x and constructs a DataFrame df and target vector y that can be used for a time series forecasting task. The returned df will contain, for every time stamp in x, the last max_timeshift data points as...
Connect to a running TWS or IB gateway application. After the connection is made the client is fully synchronized and ready to serve requests. This method is blocking. Args: host: Host name or IP address. port: Port number. clientId: ID number to use...
def connect( self, host: str = '127.0.0.1', port: int = 7497, clientId: int = 1, timeout: float = 2): """ Connect to a running TWS or IB gateway application. After the connection is made the client is fully synchronized and ready to serve requests. This m...
Disconnect from a TWS or IB gateway application. This will clear all session state.
def disconnect(self): """ Disconnect from a TWS or IB gateway application. This will clear all session state. """ if not self.client.isConnected(): return stats = self.client.connectionStats() self._logger.info( f'Disconnecting from {self.c...
Wait on any new update to arrive from the network. Args: timeout: Maximum time in seconds to wait. If 0 then no timeout is used. .. note:: A loop with ``waitOnUpdate`` should not be used to harvest tick data from tickers, since some ticks can go miss...
def waitOnUpdate(self, timeout: float = 0) -> bool: """ Wait on any new update to arrive from the network. Args: timeout: Maximum time in seconds to wait. If 0 then no timeout is used. .. note:: A loop with ``waitOnUpdate`` should not be used to ...
List of account values for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name.
def accountValues(self, account: str = '') -> List[AccountValue]: """ List of account values for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name. """ if account: return [v f...
Iterate until condition is met, with optional timeout in seconds. The yielded value is that of the condition or False when timed out. Args: condition: Predicate function that is tested after every network update. timeout: Maximum time in seconds to wait. ...
def loopUntil( self, condition=None, timeout: float = 0) -> Iterator[object]: """ Iterate until condition is met, with optional timeout in seconds. The yielded value is that of the condition or False when timed out. Args: condition: Predicate function that is tes...
List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for this account name.
def accountSummary(self, account: str = '') -> List[AccountValue]: """ List of account values for the given account, or of all accounts if account is left blank. This method is blocking on first run, non-blocking after that. Args: account: If specified, filter for t...
List of portfolio items of the default account.
def portfolio(self) -> List[PortfolioItem]: """ List of portfolio items of the default account. """ account = self.wrapper.accounts[0] return [v for v in self.wrapper.portfolio[account].values()]
List of positions for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name.
def positions(self, account: str = '') -> List[Position]: """ List of positions for the given account, or of all accounts if account is left blank. Args: account: If specified, filter for this account name. """ if account: return list(self.wrapper...
List of subscribed :class:`.PnL` objects (profit and loss), optionally filtered by account and/or modelCode. The :class:`.PnL` objects are kept live updated. Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account mode...
def pnl(self, account='', modelCode='') -> List[PnL]: """ List of subscribed :class:`.PnL` objects (profit and loss), optionally filtered by account and/or modelCode. The :class:`.PnL` objects are kept live updated. Args: account: If specified, filter for this accou...
List of subscribed :class:`.PnLSingle` objects (profit and loss for single positions). The :class:`.PnLSingle` objects are kept live updated. Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model. c...
def pnlSingle( self, account: str = '', modelCode: str = '', conId: int = 0) -> List[PnLSingle]: """ List of subscribed :class:`.PnLSingle` objects (profit and loss for single positions). The :class:`.PnLSingle` objects are kept live updated. Args: ...
Unsubscribe from market depth data. Args: contract: The exact contract object that was used to subscribe with.
def cancelMktDepth(self, contract: Contract, isSmartDepth=False): """ Unsubscribe from market depth data. Args: contract: The exact contract object that was used to subscribe with. """ ticker = self.ticker(contract) reqId = self.wrapper.endTic...
Place the trades in the same One Cancels All (OCA) group. https://interactivebrokers.github.io/tws-api/oca.html Args: orders: The orders that are to be placed together.
def oneCancelsAll( orders: List[Order], ocaGroup: str, ocaType: int) -> List[Order]: """ Place the trades in the same One Cancels All (OCA) group. https://interactivebrokers.github.io/tws-api/oca.html Args: orders: The orders that are to be placed together. ...
Get historical news headline. https://interactivebrokers.github.io/tws-api/news.html This method is blocking. Args: conId: Search news articles for contract with this conId. providerCodes: A '+'-separated list of provider codes, like 'BZ+FLY'. ...
def reqHistoricalNews( self, conId: int, providerCodes: str, startDateTime: Union[str, datetime.date], endDateTime: Union[str, datetime.date], totalResults: int, historicalNewsOptions: List[TagValue] = None) -> HistoricalNews: """ Get historica...
It is recommended to use :meth:`.accountValues` instead. Request account values of multiple accounts and keep updated. This method is blocking. Args: account: If specified, filter for this account name. modelCode: If specified, filter for this account model.
def reqAccountUpdatesMulti( self, account: str = '', modelCode: str = ''): """ It is recommended to use :meth:`.accountValues` instead. Request account values of multiple accounts and keep updated. This method is blocking. Args: account: If specified, f...