Skip to content
statsmodels logo
statsmodels v0.13.2 Trends and cycles in unemployment
Type to start searching
    statsmodels
    • Examples
    statsmodels
    • Installing statsmodels
    • Getting started
    • User Guide
    • Examples
      • Linear Regression Models
      • Plotting
      • Discrete Choice Models
      • Nonparametric Statistics
      • Generalized Linear Models
      • Robust Regression
      • Generalized Estimating Equations
      • Statistics
      • Time Series Analysis
      • State space models
        • SARIMAX: Introduction
        • SARIMAX and ARIMA: Frequently Asked Questions (FAQ)
        • VARMAX models
        • Dynamic factors and coincident indices
        • Detrending, Stylized Facts and the Business Cycle
        • Trends and cycles in unemployment
          • Trends and cycles in unemployment
            • Hodrick-Prescott (HP) filter
            • Unobserved components and ARIMA model (UC-ARIMA)
            • Unobserved components with stochastic cycle (UC)
            • Graphical comparison
          • Show Source
        • State space modeling: Local Linear Trends
        • Autoregressive Moving Average (ARMA): Sunspots data
        • Seasonality in time series data
        • Estimating or specifying parameters in state space models
        • TVP-VAR, MCMC, and sparse simulation smoothing
        • Forecasting, updating datasets, and the “news”
        • Custom statespace models
        • ETS models
      • State space models - Technical notes
      • Forecasting
      • Multivariate Methods
      • User Notes
    • API Reference
    • About statsmodels
    • Developer Page
    • Release Notes
    • Trends and cycles in unemployment
      • Hodrick-Prescott (HP) filter
      • Unobserved components and ARIMA model (UC-ARIMA)
      • Unobserved components with stochastic cycle (UC)
      • Graphical comparison
    • Show Source

    Trends and cycles in unemployment¶

    Here we consider three methods for separating a trend and cycle in economic data. Supposing we have a time series \(y_t\), the basic idea is to decompose it into these two components:

    \[y_t = \mu_t + \eta_t\]

    where \(\mu_t\) represents the trend or level and \(\eta_t\) represents the cyclical component. In this case, we consider a stochastic trend, so that \(\mu_t\) is a random variable and not a deterministic function of time. Two of methods fall under the heading of “unobserved components” models, and the third is the popular Hodrick-Prescott (HP) filter. Consistent with e.g. Harvey and Jaeger (1993), we find that these models all produce similar decompositions.

    This notebook demonstrates applying these models to separate trend from cycle in the U.S. unemployment rate.

    [1]:
    
    %matplotlib inline
    
    [2]:
    
    import numpy as np
    import pandas as pd
    import statsmodels.api as sm
    import matplotlib.pyplot as plt
    
    [3]:
    
    from pandas_datareader.data import DataReader
    endog = DataReader('UNRATE', 'fred', start='1954-01-01')
    endog.index.freq = endog.index.inferred_freq
    

    Hodrick-Prescott (HP) filter¶

    The first method is the Hodrick-Prescott filter, which can be applied to a data series in a very straightforward method. Here we specify the parameter \(\lambda=129600\) because the unemployment rate is observed monthly.

    [4]:
    
    hp_cycle, hp_trend = sm.tsa.filters.hpfilter(endog, lamb=129600)
    

    Unobserved components and ARIMA model (UC-ARIMA)¶

    The next method is an unobserved components model, where the trend is modeled as a random walk and the cycle is modeled with an ARIMA model - in particular, here we use an AR(4) model. The process for the time series can be written as:

    \[\begin{split}\begin{align} y_t & = \mu_t + \eta_t \\ \mu_{t+1} & = \mu_t + \epsilon_{t+1} \\ \phi(L) \eta_t & = \nu_t \end{align}\end{split}\]

    where \(\phi(L)\) is the AR(4) lag polynomial and \(\epsilon_t\) and \(\nu_t\) are white noise.

    [5]:
    
    mod_ucarima = sm.tsa.UnobservedComponents(endog, 'rwalk', autoregressive=4)
    # Here the powell method is used, since it achieves a
    # higher loglikelihood than the default L-BFGS method
    res_ucarima = mod_ucarima.fit(method='powell', disp=False)
    print(res_ucarima.summary())
    
                            Unobserved Components Results
    ==============================================================================
    Dep. Variable:                 UNRATE   No. Observations:                  817
    Model:                    random walk   Log Likelihood                -457.238
                                  + AR(4)   AIC                            926.475
    Date:                Tue, 08 Feb 2022   BIC                            954.702
    Time:                        18:17:05   HQIC                           937.309
    Sample:                    01-01-1954
                             - 01-01-2022
    Covariance Type:                  opg
    ================================================================================
                       coef    std err          z      P>|z|      [0.025      0.975]
    --------------------------------------------------------------------------------
    sigma2.level     0.0801      0.167      0.481      0.631      -0.246       0.406
    sigma2.ar        0.0977      0.169      0.577      0.564      -0.234       0.429
    ar.L1            1.0644      0.116      9.201      0.000       0.838       1.291
    ar.L2           -0.1832      0.330     -0.554      0.579      -0.831       0.465
    ar.L3            0.0914      0.199      0.460      0.646      -0.298       0.481
    ar.L4           -0.0208      0.083     -0.251      0.802      -0.183       0.142
    ===================================================================================
    Ljung-Box (L1) (Q):                   0.01   Jarque-Bera (JB):           5953680.15
    Prob(Q):                              0.94   Prob(JB):                         0.00
    Heteroskedasticity (H):               9.36   Skew:                            17.09
    Prob(H) (two-sided):                  0.00   Kurtosis:                       420.06
    ===================================================================================
    
    Warnings:
    [1] Covariance matrix calculated using the outer product of gradients (complex-step).
    

    Unobserved components with stochastic cycle (UC)¶

    The final method is also an unobserved components model, but where the cycle is modeled explicitly.

    \[\begin{split}\begin{align} y_t & = \mu_t + \eta_t \\ \mu_{t+1} & = \mu_t + \epsilon_{t+1} \\ \eta_{t+1} & = \eta_t \cos \lambda_\eta + \eta_t^* \sin \lambda_\eta + \tilde \omega_t \qquad & \tilde \omega_t \sim N(0, \sigma_{\tilde \omega}^2) \\ \eta_{t+1}^* & = -\eta_t \sin \lambda_\eta + \eta_t^* \cos \lambda_\eta + \tilde \omega_t^* & \tilde \omega_t^* \sim N(0, \sigma_{\tilde \omega}^2) \end{align}\end{split}\]
    [6]:
    
    mod_uc = sm.tsa.UnobservedComponents(
        endog, 'rwalk',
        cycle=True, stochastic_cycle=True, damped_cycle=True,
    )
    # Here the powell method gets close to the optimum
    res_uc = mod_uc.fit(method='powell', disp=False)
    # but to get to the highest loglikelihood we do a
    # second round using the L-BFGS method.
    res_uc = mod_uc.fit(res_uc.params, disp=False)
    print(res_uc.summary())
    
                                Unobserved Components Results
    =====================================================================================
    Dep. Variable:                        UNRATE   No. Observations:                  817
    Model:                           random walk   Log Likelihood                -460.271
                       + damped stochastic cycle   AIC                            928.543
    Date:                       Tue, 08 Feb 2022   BIC                            947.351
    Time:                               18:17:05   HQIC                           935.762
    Sample:                           01-01-1954
                                    - 01-01-2022
    Covariance Type:                         opg
    ===================================================================================
                          coef    std err          z      P>|z|      [0.025      0.975]
    -----------------------------------------------------------------------------------
    sigma2.level        0.1814      0.004     42.478      0.000       0.173       0.190
    sigma2.cycle     3.591e-11      0.003   1.43e-08      1.000      -0.005       0.005
    frequency.cycle     0.3491    576.349      0.001      1.000   -1129.274    1129.972
    damping.cycle       0.1095     36.168      0.003      0.998     -70.778      70.997
    ===================================================================================
    Ljung-Box (L1) (Q):                   1.51   Jarque-Bera (JB):           6001916.38
    Prob(Q):                              0.22   Prob(JB):                         0.00
    Heteroskedasticity (H):               9.94   Skew:                            17.09
    Prob(H) (two-sided):                  0.00   Kurtosis:                       422.28
    ===================================================================================
    
    Warnings:
    [1] Covariance matrix calculated using the outer product of gradients (complex-step).
    

    Graphical comparison¶

    The output of each of these models is an estimate of the trend component \(\mu_t\) and an estimate of the cyclical component \(\eta_t\). Qualitatively the estimates of trend and cycle are very similar, although the trend component from the HP filter is somewhat more variable than those from the unobserved components models. This means that relatively mode of the movement in the unemployment rate is attributed to changes in the underlying trend rather than to temporary cyclical movements.

    [7]:
    
    fig, axes = plt.subplots(2, figsize=(13,5));
    axes[0].set(title='Level/trend component')
    axes[0].plot(endog.index, res_uc.level.smoothed, label='UC')
    axes[0].plot(endog.index, res_ucarima.level.smoothed, label='UC-ARIMA(2,0)')
    axes[0].plot(hp_trend, label='HP Filter')
    axes[0].legend(loc='upper left')
    axes[0].grid()
    
    axes[1].set(title='Cycle component')
    axes[1].plot(endog.index, res_uc.cycle.smoothed, label='UC')
    axes[1].plot(endog.index, res_ucarima.autoregressive.smoothed, label='UC-ARIMA(2,0)')
    axes[1].plot(hp_cycle, label='HP Filter')
    axes[1].legend(loc='upper left')
    axes[1].grid()
    
    fig.tight_layout();
    
    ../../../_images/examples_notebooks_generated_statespace_cycles_11_0.png
    Previous Detrending, Stylized Facts and the Business Cycle
    Next State space modeling: Local Linear Trends
    © Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
    Last updated on Feb 08, 2022.
    Created using Sphinx 4.4.0. and Material for Sphinx