Automatic stationary conversion 1

Automatic stationary conversion

def make_stationary(data: pd.Series, alpha: float = 0.05, max_diff_order: int = 10) -> dict:
    # Test to see if the time series is already stationary
    if adfuller(data)[1] < alpha:
        return {
            'differencing_order': 0,
            'time_series': np.array(data)
    # A list to store P-Values
    p_values = []
    # Test for differencing orders from 1 to max_diff_order (included)
    for i in range(1, max_diff_order + 1):
        # Perform ADF test
        result = adfuller(data.diff(i).dropna())
        # Append P-value
        p_values.append((i, result[1]))
    # Keep only those where P-value is lower than significance level
    significant = [p for p in p_values if p[1] < alpha]
    # Sort by the differencing order
    significant = sorted(significant, key=lambda x: x[0])
    # Get the differencing order
    diff_order = significant[0][0]
    # Make the time series stationary
    stationary_series = data.diff(diff_order).dropna()
    return {
        'differencing_order': diff_order,
        'time_series': np.array(stationary_series)

Here is what the above code is Doing:
1. First, we check if the time series is already stationary. If it is, we return it as it is.
2. If it's not, we perform the ADF test for differencing orders from 1 to max_diff_order.
3. We keep only those where the P-value is lower than the significance level.
4. We sort the results by the differencing order.
5. We get the differencing order.
6. We make the time series stationary.

Similar Posts