Estimating or specifying parameters in state space models¶
In this notebook we show how to fix specific values of certain parameters in statsmodels’ state space models while estimating others.
In general, state space models allow users to:
- Estimate all parameters by maximum likelihood
- Fix some parameters and estimate the rest
- Fix all parameters (so that no parameters are estimated)
[1]:
%matplotlib inline
from importlib import reload
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from pandas_datareader.data import DataReader
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-983aed9929fa> in <module>
7 import matplotlib.pyplot as plt
8
----> 9 from pandas_datareader.data import DataReader
ModuleNotFoundError: No module named 'pandas_datareader'
To illustrate, we will use the Consumer Price Index for Apparel, which has a time-varying level and a strong seasonal component.
[2]:
endog = DataReader('CPIAPPNS', 'fred', start='1980').asfreq('MS')
endog.plot(figsize=(15, 3));
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-8944cbfb1743> in <module>
----> 1 endog = DataReader('CPIAPPNS', 'fred', start='1980').asfreq('MS')
2 endog.plot(figsize=(15, 3));
NameError: name 'DataReader' is not defined
It is well known (e.g. Harvey and Jaeger [1993]) that the HP filter output can be generated by an unobserved components model given certain restrictions on the parameters.
The unobserved components model is:
For the trend to match the output of the HP filter, the parameters must be set as follows:
where \(\lambda\) is the parameter of the associated HP filter. For the monthly data that we use here, it is usually recommended that \(\lambda = 129600\).
[3]:
# Run the HP filter with lambda = 129600
hp_cycle, hp_trend = sm.tsa.filters.hpfilter(endog, lamb=129600)
# The unobserved components model above is the local linear trend, or "lltrend", specification
mod = sm.tsa.UnobservedComponents(endog, 'lltrend')
print(mod.param_names)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-4c4165c3968c> in <module>
1 # Run the HP filter with lambda = 129600
----> 2 hp_cycle, hp_trend = sm.tsa.filters.hpfilter(endog, lamb=129600)
3
4 # The unobserved components model above is the local linear trend, or "lltrend", specification
5 mod = sm.tsa.UnobservedComponents(endog, 'lltrend')
NameError: name 'endog' is not defined
The parameters of the unobserved components model (UCM) are written as:
- \(\sigma_\varepsilon^2 = \text{sigma2.irregular}\)
- \(\sigma_\eta^2 = \text{sigma2.level}\)
- \(\sigma_\zeta^2 = \text{sigma2.trend}\)
To satisfy the above restrictions, we will set \((\sigma_\varepsilon^2, \sigma_\eta^2, \sigma_\zeta^2) = (1, 0, 1 / 129600)\).
Since we are fixing all parameters here, we do not need to use the fit
method at all, since that method is used to perform maximum likelihood estimation. Instead, we can directly run the Kalman filter and smoother at our chosen parameters using the smooth
method.
[4]:
res = mod.smooth([1., 0, 1. / 129600])
print(res.summary())
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-a8b11d53583c> in <module>
----> 1 res = mod.smooth([1., 0, 1. / 129600])
2 print(res.summary())
NameError: name 'mod' is not defined
The estimate that corresponds to the HP filter’s trend estimate is given by the smoothed estimate of the level
(which is \(\mu_t\) in the notation above):
[5]:
ucm_trend = pd.Series(res.level.smoothed, index=endog.index)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-de3b6e6ecfc4> in <module>
----> 1 ucm_trend = pd.Series(res.level.smoothed, index=endog.index)
NameError: name 'res' is not defined
It is easy to see that the estimate of the smoothed level from the UCM is equal to the output of the HP filter:
[6]:
fig, ax = plt.subplots(figsize=(15, 3))
ax.plot(hp_trend, label='HP estimate')
ax.plot(ucm_trend, label='UCM estimate')
ax.legend();
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-dfacf97b486a> in <module>
1 fig, ax = plt.subplots(figsize=(15, 3))
2
----> 3 ax.plot(hp_trend, label='HP estimate')
4 ax.plot(ucm_trend, label='UCM estimate')
5 ax.legend();
NameError: name 'hp_trend' is not defined

Adding a seasonal component¶
However, unobserved components models are more flexible than the HP filter. For example, the data shown above is clearly seasonal, but with time-varying seasonal effects (the seasonality is much weaker at the beginning than at the end). One of the benefits of the unobserved components framework is that we can add a stochastic seasonal component. In this case, we will estimate the variance of the seasonal component by maximum likelihood while still including the restriction on the parameters implied above so that the trend corresponds to the HP filter concept.
Adding the stochastic seasonal component adds one new parameter, sigma2.seasonal
.
[7]:
# Construct a local linear trend model with a stochastic seasonal component of period 1 year
mod = sm.tsa.UnobservedComponents(endog, 'lltrend', seasonal=12, stochastic_seasonal=True)
print(mod.param_names)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-ea7932f15b93> in <module>
1 # Construct a local linear trend model with a stochastic seasonal component of period 1 year
----> 2 mod = sm.tsa.UnobservedComponents(endog, 'lltrend', seasonal=12, stochastic_seasonal=True)
3 print(mod.param_names)
NameError: name 'endog' is not defined
In this case, we will continue to restrict the first three parameters as described above, but we want to estimate the value of sigma2.seasonal
by maximum likelihood. Therefore, we will use the fit
method along with the fix_params
context manager.
The fix_params
method takes a dictionary of parameters names and associated values. Within the generated context, those parameters will be used in all cases. In the case of the fit
method, only the parameters that were not fixed will be estimated.
[8]:
# Here we restrict the first three parameters to specific values
with mod.fix_params({'sigma2.irregular': 1, 'sigma2.level': 0, 'sigma2.trend': 1. / 129600}):
# Now we fit any remaining parameters, which in this case
# is just `sigma2.seasonal`
res_restricted = mod.fit()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-714b440e7eff> in <module>
1 # Here we restrict the first three parameters to specific values
----> 2 with mod.fix_params({'sigma2.irregular': 1, 'sigma2.level': 0, 'sigma2.trend': 1. / 129600}):
3 # Now we fit any remaining parameters, which in this case
4 # is just `sigma2.seasonal`
5 res_restricted = mod.fit()
NameError: name 'mod' is not defined
Alternatively, we could have simply used the fit_constrained
method, which also accepts a dictionary of constraints:
[9]:
res_restricted = mod.fit_constrained({'sigma2.irregular': 1, 'sigma2.level': 0, 'sigma2.trend': 1. / 129600})
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-7a7451ec4103> in <module>
----> 1 res_restricted = mod.fit_constrained({'sigma2.irregular': 1, 'sigma2.level': 0, 'sigma2.trend': 1. / 129600})
NameError: name 'mod' is not defined
The summary output includes all parameters, but indicates that the first three were fixed (and so were not estimated).
[10]:
print(res_restricted.summary())
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-3f7c77154d23> in <module>
----> 1 print(res_restricted.summary())
NameError: name 'res_restricted' is not defined
For comparison, we construct the unrestricted maximum likelihood estimates (MLE). In this case, the estimate of the level will no longer correspond to the HP filter concept.
[11]:
res_unrestricted = mod.fit()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-d05346356dbc> in <module>
----> 1 res_unrestricted = mod.fit()
NameError: name 'mod' is not defined
Finally, we can retrieve the smoothed estimates of the trend and seasonal components.
[12]:
# Construct the smoothed level estimates
unrestricted_trend = pd.Series(res_unrestricted.level.smoothed, index=endog.index)
restricted_trend = pd.Series(res_restricted.level.smoothed, index=endog.index)
# Construct the smoothed estimates of the seasonal pattern
unrestricted_seasonal = pd.Series(res_unrestricted.seasonal.smoothed, index=endog.index)
restricted_seasonal = pd.Series(res_restricted.seasonal.smoothed, index=endog.index)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-b29fafe9c456> in <module>
1 # Construct the smoothed level estimates
----> 2 unrestricted_trend = pd.Series(res_unrestricted.level.smoothed, index=endog.index)
3 restricted_trend = pd.Series(res_restricted.level.smoothed, index=endog.index)
4
5 # Construct the smoothed estimates of the seasonal pattern
NameError: name 'res_unrestricted' is not defined
Comparing the estimated level, it is clear that the seasonal UCM with fixed parameters still produces a trend that corresponds very closely (although no longer exactly) to the HP filter output.
Meanwhile, the estimated level from the model with no parameter restrictions (the MLE model) is much less smooth than these.
[13]:
fig, ax = plt.subplots(figsize=(15, 3))
ax.plot(unrestricted_trend, label='MLE, with seasonal')
ax.plot(restricted_trend, label='Fixed parameters, with seasonal')
ax.plot(hp_trend, label='HP filter, no seasonal')
ax.legend();
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-13-27e6f043919f> in <module>
1 fig, ax = plt.subplots(figsize=(15, 3))
2
----> 3 ax.plot(unrestricted_trend, label='MLE, with seasonal')
4 ax.plot(restricted_trend, label='Fixed parameters, with seasonal')
5 ax.plot(hp_trend, label='HP filter, no seasonal')
NameError: name 'unrestricted_trend' is not defined

Finally, the UCM with the parameter restrictions is still able to pick up the time-varying seasonal component quite well.
[14]:
fig, ax = plt.subplots(figsize=(15, 3))
ax.plot(unrestricted_seasonal, label='MLE')
ax.plot(restricted_seasonal, label='Fixed parameters')
ax.legend();
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-65c890b91eb7> in <module>
1 fig, ax = plt.subplots(figsize=(15, 3))
2
----> 3 ax.plot(unrestricted_seasonal, label='MLE')
4 ax.plot(restricted_seasonal, label='Fixed parameters')
5 ax.legend();
NameError: name 'unrestricted_seasonal' is not defined
