状态空间方法的时间序列分析 statespace

statsmodels.tsa.statespace 包含用于时间序列分析的状态空间方法的类和函数。

一般状态空间模型形式如下

\[\begin{split}y_t & = Z_t \alpha_t + d_t + \varepsilon_t \\ \alpha_{t+1} & = T_t \alpha_t + c_t + R_t \eta_t \\\end{split}\]

其中 \(y_t\) 表示时间 \(t\) 的观测向量, \(\alpha_t\) 表示时间 \(t\) 的(未观测到的)状态向量,并且不规则分量定义为

\[\begin{split}\varepsilon_t \sim N(0, H_t) \\ \eta_t \sim N(0, Q_t) \\\end{split}\]

剩余的变量(\(Z_t, d_t, H_t, T_t, c_t, R_t, Q_t\))在方程中是描述过程的矩阵。它们的变量名称和维度如下

Z : 设计 \((k\_endog \times k\_states \times nobs)\)

d : 观测截距 \((k\_endog \times nobs)\)

H : 观测协方差 \((k\_endog \times k\_endog \times nobs)\)

T : 转移 \((k\_states \times k\_states \times nobs)\)

c : 状态截距 \((k\_states \times nobs)\)

R : 选择 \((k\_states \times k\_posdef \times nobs)\)

问:state_cov \((k\_posdef \times k\_posdef \times nobs)\)

如果其中一个矩阵是时间不变的(例如,\(Z_t = Z_{t+1} ~ \forall ~ t\)),则其最后一个维度的大小可能是\(1\),而不是大小nobs

这种通用形式封装了许多最流行的线性时间序列模型(见下文),并且非常灵活,允许在有缺失观测值的情况下进行估计、预测、脉冲响应函数等。

示例:AR(2) 模型

自回归模型是将模型置于状态空间形式的一个很好的入门示例。回想一下,AR(2)模型通常写为:

\[y_t = \phi_1 y_{t-1} + \phi_2 y_{t-2} + \epsilon_t, \quad \epsilon_t \sim N(0, \sigma^2)\]

这可以以下列方式放入状态空间形式中:

\[\begin{split}y_t & = \begin{bmatrix} 1 & 0 \end{bmatrix} \alpha_t \\ \alpha_{t+1} & = \begin{bmatrix} \phi_1 & \phi_2 \\ 1 & 0 \end{bmatrix} \alpha_t + \begin{bmatrix} 1 \\ 0 \end{bmatrix} \eta_t\end{split}\]

哪里

\[Z_t \equiv Z = \begin{bmatrix} 1 & 0 \end{bmatrix}\]

\[\begin{split}T_t \equiv T & = \begin{bmatrix} \phi_1 & \phi_2 \\ 1 & 0 \end{bmatrix} \\ R_t \equiv R & = \begin{bmatrix} 1 \\ 0 \end{bmatrix} \\ \eta_t \equiv \epsilon_{t+1} & \sim N(0, \sigma^2)\end{split}\]

这个模型中有三个未知参数: \(\phi_1, \phi_2, \sigma^2\)

模型与估计

以下是通过statsmodels.tsa.statespace.api可以访问的主要估计类及其结果类。

带有外生回归量的季节性自回归积分移动平均 (SARIMAX)

The SARIMAX 类是使用状态空间后端创建的完全成熟模型的示例。SARIMAX 可以非常类似于 tsa 模型使用,但通过添加对加性和乘性季节效应以及任意趋势多项式的估计,适用于更广泛范围的模型。

sarimax.SARIMAX(endog[, exog, order, ...])

带有外生回归量的季节性自回归综合移动平均模型

sarimax.SARIMAXResults(model, params, ...[, ...])

用于保存拟合SARIMAX模型结果的类。

有关此模型的使用示例,请参阅 SARIMAX 示例笔记本 或下面的非常简短的代码片段:

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# We could fit an AR(2) model, described above
mod_ar2 = sm.tsa.SARIMAX(endog, order=(2,0,0))
# Note that mod_ar2 is an instance of the SARIMAX class

# Fit the model via maximum likelihood
res_ar2 = mod_ar2.fit()
# Note that res_ar2 is an instance of the SARIMAXResults class

# Show the summary of results
print(res_ar2.summary())

# We could also fit a more complicated model with seasonal components.
# As an example, here is an SARIMA(1,1,1) x (0,1,1,4):
mod_sarimax = sm.tsa.SARIMAX(endog, order=(1,1,1),
                             seasonal_order=(0,1,1,4))
res_sarimax = mod_sarimax.fit()

# Show the summary of results
print(res_sarimax.summary())

结果对象具有许多您期望从其他 statsmodels 结果对象中获得的属性和方法,包括标准误差、z 统计量以及预测/预测。

在幕后,SARIMAX 模型根据模型规范创建设计和转移矩阵(有时还包括其他一些矩阵)。

未观测到的成分

UnobservedComponents是状态空间模型的另一个示例。

structural.UnobservedComponents(endog[, ...])

单变量未观测成分时间序列模型

structural.UnobservedComponentsResults(...)

用于保存拟合未观测成分模型结果的类。

有关此模型的使用示例,请参阅示例笔记本或使用未观测成分模型将时间序列分解为趋势和周期的笔记本,或以下非常简短的代码片段:

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# Fit a local level model
mod_ll = sm.tsa.UnobservedComponents(endog, 'local level')
# Note that mod_ll is an instance of the UnobservedComponents class

# Fit the model via maximum likelihood
res_ll = mod_ll.fit()
# Note that res_ll is an instance of the UnobservedComponentsResults class

# Show the summary of results
print(res_ll.summary())

# Show a plot of the estimated level and trend component series
fig_ll = res_ll.plot_components()

# We could further add a damped stochastic cycle as follows
mod_cycle = sm.tsa.UnobservedComponents(endog, 'local level', cycle=True,
                                        damped_cycle=True,
                                        stochastic_cycle=True)
res_cycle = mod_cycle.fit()

# Show the summary of results
print(res_cycle.summary())

# Show a plot of the estimated level, trend, and cycle component series
fig_cycle = res_cycle.plot_components()

带有外生回归变量的向量自回归移动平均模型 (VARMAX)

The VARMAX 类是多元状态空间模型的一个示例。

varmax.VARMAX(endog[, exog, order, trend, ...])

带有外生回归量的向量自回归移动平均模型

varmax.VARMAXResults(模型, 参数, ...[, ...])

用于保存拟合 VARMAX 模型结果的类。

有关此模型的使用示例,请参阅VARMAX 示例笔记本或下面的非常简短的代码片段:

# Load the statsmodels api
import statsmodels.api as sm

# Load your (multivariate) dataset
endog = pd.read_csv('your/dataset/here.csv')

# Fit a local level model
mod_var1 = sm.tsa.VARMAX(endog, order=(1,0))
# Note that mod_var1 is an instance of the VARMAX class

# Fit the model via maximum likelihood
res_var1 = mod_var1.fit()
# Note that res_var1 is an instance of the VARMAXResults class

# Show the summary of results
print(res_var1.summary())

# Construct impulse responses
irfs = res_ll.impulse_responses(steps=10)

动态因子模型

Statsmodels 有两个类支持动态因子模型: DynamicFactorMQDynamicFactor。每个模型都有其优势,但 通常推荐使用 DynamicFactorMQ 类。这是因为它是使用期望最大化(EM)算法来拟合 参数的,该算法更稳健,并且可以处理包含数百个观测序列的情况。此外,它 允许自定义哪些变量加载在哪些因子上。然而,它还不支持包含外生变量,而 DynamicFactor 则支持该功能。

dynamic_factor_mq.DynamicFactorMQ(endog[, ...])

使用EM算法的动态因子模型;适用于月度/季度数据。

dynamic_factor_mq.DynamicFactorMQResults(...)

拟合动态因子模型的结果

关于DynamicFactorMQ类的示例,请参见下面的非常简短的代码片段:

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# Create a dynamic factor model
mod_dfm = sm.tsa.DynamicFactorMQ(endog, k_factors=1, factor_order=2)
# Note that mod_dfm is an instance of the DynamicFactorMQ class

# Fit the model via maximum likelihood, using the EM algorithm
res_dfm = mod_dfm.fit()
# Note that res_dfm is an instance of the DynamicFactorMQResults class

# Show the summary of results
print(res_ll.summary())

# Show a plot of the r^2 values from regressions of
# individual estimated factors on endogenous variables.
fig_dfm = res_ll.plot_coefficients_of_determination()

The DynamicFactor 类适用于具有较少观测变量的模型

dynamic_factor.DynamicFactor(endog, ...[, ...])

动态因子模型

dynamic_factor.DynamicFactorResults(model, ...)

用于保存拟合动态因子模型结果的类。

有关使用DynamicFactor模型的示例,请参阅 动态因子示例笔记本

线性指数平滑模型

类是使用状态空间方法实现线性指数平滑模型的实现。

注意:此模型可在 sm.tsa.statespace.ExponentialSmoothing 中找到; 它与 sm.tsa.ExponentialSmoothing 中的模型不同。 有关这些类之间差异的详细信息,请参见下文。

exponential_smoothing.ExponentialSmoothing(endog)

线性指数平滑模型

exponential_smoothing.ExponentialSmoothingResults(...)

拟合线性指数平滑模型的结果

以下是一个非常简短的代码片段:

# Load the statsmodels api
import statsmodels.api as sm

# Load your dataset
endog = pd.read_csv('your/dataset/here.csv')

# Simple exponential smoothing, denoted (A,N,N)
mod_ses = sm.tsa.statespace.ExponentialSmoothing(endog)
res_ses = mod_ses.fit()

# Holt's linear method, denoted (A,A,N)
mod_h = sm.tsa.statespace.ExponentialSmoothing(endog, trend=True)
res_h = mod_h.fit()

# Damped trend model, denoted (A,Ad,N)
mod_dt = sm.tsa.statespace.ExponentialSmoothing(endog, trend=True,
                                                damped_trend=True)
res_dt = mod_dt.fit()

# Holt-Winters' trend and seasonality method, denoted (A,A,A)
# (assuming that `endog` has a seasonal periodicity of 4, for example if it
# is quarterly data).
mod_hw = sm.tsa.statespace.ExponentialSmoothing(endog, trend=True,
                                                seasonal=4)
res_hw = mod_hw.fit()

Statsmodels 指数平滑模型类之间的区别

这个模型类与sm.tsa.statespace.ExponentialSmoothingsm.tsa.ExponentialSmoothing中的模型类有几个不同之处。

  • 此模型类仅支持线性指数平滑模型,而sm.tsa.ExponentialSmoothing还支持乘法模型。

  • 该模型类将指数平滑模型转换为状态空间形式,然后应用卡尔曼滤波器来估计状态,而 sm.tsa.ExponentialSmoothing 基于指数平滑递归。 在某些情况下,这意味着使用该模型类估计参数可能会比使用 sm.tsa.ExponentialSmoothing 稍慢。

  • 该模型类可以基于高斯误差的假设,为预测生成置信区间,而 sm.tsa.ExponentialSmoothing 不支持置信区间。

  • 此模型类支持从目标函数中集中初始值,这可以在有许多初始状态需要估计时(例如当季节周期性较大时)提高性能。

  • 此模型类支持状态空间模型可用的许多高级功能,例如诊断和固定参数。

注意:此类基于“多源误差”(MSOE)状态空间公式,而不是“单源误差”(SSOE)公式。

自定义状态空间模型

状态空间模型的真正强大之处在于允许创建和估计自定义模型。通常这是通过扩展以下两个类来实现的,这两个类将状态空间表示、卡尔曼滤波和最大似然拟合功能捆绑在一起,用于估计和结果输出。

mlemodel.MLEModel(endog, k_states[, exog, ...])

最大似然估计的状态空间模型

mlemodel.MLEResults(模型, 参数, 结果)

用于保存状态空间模型拟合结果的类。

mlemodel.PredictionResults(model, ...[, ...])

来自MLE模型的预测结果

有关展示创建和估计自定义状态空间模型的基本示例,请参阅局部线性趋势示例笔记本。 对于更复杂的示例,请参阅SARIMAXSARIMAXResults类的源代码,这些类是通过扩展MLEModelMLEResults构建的。

在简单的情况下,可以使用 MLEModel 类完全构建模型。例如,上面的 AR(2) 模型可以通过以下代码构建和估计:

import numpy as np
from scipy.signal import lfilter
import statsmodels.api as sm

# True model parameters
nobs = int(1e3)
true_phi = np.r_[0.5, -0.2]
true_sigma = 1**0.5

# Simulate a time series
np.random.seed(1234)
disturbances = np.random.normal(0, true_sigma, size=(nobs,))
endog = lfilter([1], np.r_[1, -true_phi], disturbances)

# Construct the model
class AR2(sm.tsa.statespace.MLEModel):
    def __init__(self, endog):
        # Initialize the state space model
        super(AR2, self).__init__(endog, k_states=2, k_posdef=1,
                                  initialization='stationary')

        # Setup the fixed components of the state space representation
        self['design'] = [1, 0]
        self['transition'] = [[0, 0],
                                  [1, 0]]
        self['selection', 0, 0] = 1

    # Describe how parameters enter the model
    def update(self, params, transformed=True, **kwargs):
        params = super(AR2, self).update(params, transformed, **kwargs)

        self['transition', 0, :] = params[:2]
        self['state_cov', 0, 0] = params[2]

    # Specify start parameters and parameter names
    @property
    def start_params(self):
        return [0,0,1]  # these are very simple

# Create and fit the model
mod = AR2(endog)
res = mod.fit()
print(res.summary())

这将生成以下摘要表:

                           Statespace Model Results
==============================================================================
Dep. Variable:                      y   No. Observations:                 1000
Model:                            AR2   Log Likelihood               -1389.437
Date:                Wed, 26 Oct 2016   AIC                           2784.874
Time:                        00:42:03   BIC                           2799.598
Sample:                             0   HQIC                          2790.470
                               - 1000
Covariance Type:                  opg
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
param.0        0.4395      0.030     14.730      0.000       0.381       0.498
param.1       -0.2055      0.032     -6.523      0.000      -0.267      -0.144
param.2        0.9425      0.042     22.413      0.000       0.860       1.025
===================================================================================
Ljung-Box (Q):                       24.25   Jarque-Bera (JB):                 0.22
Prob(Q):                              0.98   Prob(JB):                         0.90
Heteroskedasticity (H):               1.05   Skew:                            -0.04
Prob(H) (two-sided):                  0.66   Kurtosis:                         3.02
===================================================================================

Warnings:
[1] Covariance matrix calculated using the outer product of gradients (complex-step).

结果对象具有许多您期望从其他 statsmodels 结果对象中获得的属性和方法,包括标准误差、z 统计量以及预测/预测。

更高级的使用方式是可能的,包括指定参数转换,以及为参数指定名称以获得更详细的信息输出摘要。

使用概述

所有状态空间模型都遵循典型的Statsmodels模式:

  1. 使用输入数据集构建一个模型实例

  2. 将参数应用于模型(例如,使用fit)以构建一个结果实例

  3. 与结果实例进行交互,以检查估计的参数,探索残差诊断,并生成预测、模拟或脉冲响应。

此模式的示例如下:

# Load in the example macroeconomic dataset
dta = sm.datasets.macrodata.load_pandas().data
# Make sure we have an index with an associated frequency, so that
# we can refer to time periods with date strings or timestamps
dta.index = pd.date_range('1959Q1', '2009Q3', freq='QS')

# Step 1: construct an SARIMAX model for US inflation data
model = sm.tsa.SARIMAX(dta.infl, order=(4, 0, 0), trend='c')

# Step 2: fit the model's parameters by maximum likelihood
results = model.fit()

# Step 3: explore / use results

# - Print a table summarizing estimation results
print(results.summary())

# - Print only the estimated parameters
print(results.params)

# - Create diagnostic figures based on standardized residuals:
#   (1) time series graph
#   (2) histogram
#   (3) Q-Q plot
#   (4) correlogram
results.plot_diagnostics()

# - Examine diagnostic hypothesis tests
# Jarque-Bera: [test_statistic, pvalue, skewness, kurtosis]
print(results.test_normality(method='jarquebera'))
# Goldfeld-Quandt type test: [test_statistic, pvalue]
print(results.test_heteroskedasticity(method='breakvar'))
# Ljung-Box test: [test_statistic, pvalue] for each lag
print(results.test_serial_correlation(method='ljungbox'))

# - Forecast the next 4 values
print(results.forecast(4))

# - Forecast until 2020Q4
print(results.forecast('2020Q4'))

# - Plot in-sample dynamic prediction starting in 2005Q1
#   and out-of-sample forecasts until 2010Q4 along with
#   90% confidence intervals
predict_results = results.get_prediction(start='2005Q1', end='2010Q4', dynamic=True)
predict_df = predict_results.summary_frame(alpha=0.10)
fig, ax = plt.subplots()
predict_df['mean'].plot(ax=ax)
ax.fill_between(predict_df.index, predict_df['mean_ci_lower'],
                predict_df['mean_ci_upper'], alpha=0.2)

# - Simulate two years of new data after the end of the sample
print(results.simulate(8, anchor='end'))

# - Impulse responses for two years
print(results.impulse_responses(8))

估计/滤波/平滑的基本方法和属性

状态空间模型中最常用的方法是:

  • fit - 通过最大似然估计参数并返回一个结果对象(此对象还将已经在估计的参数上执行了卡尔曼滤波和平滑)。这是最常用的方法。

  • smooth - 返回一个结果对象 与给定参数向量相关联,在执行卡尔曼滤波和平滑后

  • loglike - 使用给定的参数向量计算数据的似然值

状态空间模型的一些有用属性包括:

  • param_names - 模型使用的参数名称

  • state_names - (未观测)状态向量的元素名称

  • start_params - 用于数值最大似然优化的初始参数估计值

其他使用较少的方法包括:

  • filter - 返回一个结果对象,该对象与在仅执行卡尔曼滤波(但不进行平滑)后给定的参数向量相关联

  • simulation_smoother - 返回一个可以执行模拟平滑的对象

输出和后估计方法及属性

常用的方法包括:

  • summary - 构建一个表格,展示模型拟合统计量、估计参数和其他摘要输出

  • predict - 计算样本内预测和样本外预测(仅点估计)

  • get_prediction - 计算样本内预测和样本外预测,包括置信区间

  • forecast - 计算样本外预测(仅点估计)(这是一个围绕predict的便捷包装器)

  • get_forecast - 计算样本外预测,包括置信区间(这是一个围绕 get_prediction 的便捷包装器)

  • simulate - 根据状态空间模型模拟新数据

  • impulse_responses - 从状态空间模型计算脉冲响应

常用的属性包括:

  • params - 估计的参数

  • bse - 估计参数的标准误差

  • pvalues - 与估计参数相关的p值

  • llf - 数据在估计参数处的对数似然值

  • sse, mse, 和 mae - 平方误差之和, 均方误差,和平均绝对误差

  • 信息准则,包括:aic, aicc, bic, 和 hquc

  • fittedvalues - 模型的拟合值(注意这些是单步预测)

  • resid - 模型的残差(注意这些是单步预测误差)

未观测状态的估计和协方差

计算未观测状态向量的估计值对于基于观测数据的条件估计可能是有用的。这些估计值可以在结果对象中找到,states,其中包含以下元素:

  • states.filtered - 过滤后的(单边)状态向量估计。时间t的状态向量估计是基于截至并包括时间t的观测数据得出的。

  • states.smoothed - 平滑(双向)的状态向量估计。时间t的状态向量估计基于样本中的所有观测数据。

  • states.filtered_cov - 状态向量的滤波(单边)协方差

  • states.smoothed_cov - 状态向量的平滑(双向)协方差

这些元素中的每一个都是 Pandas DataFrame 对象。

例如,在通过UnobservedComponents组件类估计的“局部水平 + 季节性”模型中,我们可以得到随时间变化的序列的潜在水平和季节性波动的估计。

fig, axes = plt.subplots(3, 1, figsize=(8, 8))

# Retrieve monthly retail sales for clothing
from pandas_datareader.data import DataReader
clothing = DataReader('MRTSSM4481USN', 'fred', start='1992').asfreq('MS')['MRTSSM4481USN']

# Construct a local level + seasonal model
model = sm.tsa.UnobservedComponents(clothing, 'llevel', seasonal=12)
results = model.fit()

# Plot the data, the level, and seasonal
clothing.plot(ax=axes[0])
results.states.smoothed['level'].plot(ax=axes[1])
results.states.smoothed['seasonal'].plot(ax=axes[2])

残差诊断

在估计任何状态空间模型后,无论是内置的还是自定义的,都有三种诊断测试可用来帮助评估模型是否符合基础统计假设。这些测试包括:

一些标准的回归残差图可用于相同的目的。这些可以通过使用命令 plot_diagnostics来生成。

将估计的参数应用于更新或不同的数据集

有三种方法可以将结果对象中的估计参数应用于更新或不同的数据集:

  • append - 获取一个新的结果对象,其中包含附加到当前样本末尾的额外观测值(因此新的结果对象包含当前样本和附加的观测值)

  • extend - 获取一个新的结果对象,用于在当前样本结束后的额外观测数据(因此新的结果对象仅包含新的观测数据,但不包含当前样本)

  • apply - 检索一个全新的结果对象 用于与原始数据完全不同的数据集

对时间序列数据进行的一次交叉验证练习涉及基于训练样本(时间 t 的观测值)拟合模型的参数,然后使用测试样本(观测值 t+1t+2,…)评估模型的拟合情况。这可以通过使用 applyextend 方便地完成。在下面的示例中,我们使用 extend 方法。

# Load in the example macroeconomic dataset
dta = sm.datasets.macrodata.load_pandas().data
# Make sure we have an index with an associated frequency, so that
# we can refer to time periods with date strings or timestamps
dta.index = pd.date_range('1959Q1', '2009Q3', freq='QS')

# Separate inflation data into a training and test dataset
training_endog = dta['infl'].iloc[:-1]
test_endog = dta['infl'].iloc[-1:]

# Fit an SARIMAX model for inflation
training_model = sm.tsa.SARIMAX(training_endog, order=(4, 0, 0))
training_results = training_model.fit()

# Extend the results to the test observations
test_results = training_results.extend(test_endog)

# Print the sum of squared errors in the test sample,
# based on parameters computed using only the training sample
print(test_results.sse)

了解数据修订的影响

状态空间模型结果展示了一个news方法,可以用来理解数据修订(新闻)对模型参数的影响。

news.NewsResults(news_results, model, ...[, ...])

数据修订和新闻对感兴趣变量估计的影响

附加选项和工具

所有状态空间模型都有以下选项和工具:

固定一些参数并估计其余参数

The fit_constrained 方法允许将某些参数固定为已知值,然后通过最大似然估计其余参数。一个例子是:

# Construct a model
model = sm.tsa.SARIMAX(endog, order=(1, 0, 0))

# To find out the parameter names, use:
print(model.param_names)

# Fit the model with a fixed value for the AR(1) coefficient:
results = model.fit_constrained({'ar.L1': 0.5})

或者,您可以使用 fix_params 上下文管理器:

# Construct a model
model = sm.tsa.SARIMAX(endog, order=(1, 0, 0))

# Fit the model with a fixed value for the AR(1) coefficient using the
# context manager
with model.fix_params({'ar.L1': 0.5}):
    results = model.fit()

低内存选项

当观测数据集非常大和/或模型的状态向量是高维的(例如在考虑长期季节效应时),默认的内存需求可能会过大。为此,fitfiltersmooth方法接受一个可选的low_memory=True参数,这可以显著减少内存需求并加快模型拟合速度。

请注意,当使用low_memory=True时,并非所有结果对象都可用。然而,残差诊断、样本内(非动态)预测和样本外预测仍然可用。

低级状态空间表示和卡尔曼滤波

虽然自定义模型的创建几乎总是通过扩展MLEModelMLEResults来完成,但了解这些类背后的超结构可能会有所帮助。

最大似然估计需要评估模型的似然函数,而对于状态空间形式的模型,似然函数的评估是作为运行卡尔曼滤波器的副产品进行的。

MLEModel中使用了两个类来简化状态空间模型和卡尔曼滤波的指定:RepresentationKalmanFilter

Representation 是定义状态空间模型表示的部分。简单来说,它保存了状态空间矩阵(designobs_intercept 等;参见上面的状态空间模型介绍)并允许对它们进行操作。

FrozenRepresentation 是最基本的结果类型类,因为它在任何给定时间对状态空间表示进行“快照”。有关可用属性的完整列表,请参阅类文档。

representation.Representation(k_endog, k_states)

时间序列过程的状态空间表示

representation.FrozenRepresentation(模型)

冻结的状态空间模型

KalmanFilter 类是 Representation 的一个子类,提供了过滤功能。一旦状态空间表示矩阵被构造,可以调用 filter 方法,生成一个 FilterResults 实例;FilterResultsFrozenRepresentation 的一个子类。

FilterResults 类不仅保存了状态空间模型(设计、转移等矩阵,以及模型维度等)的冻结表示,还保存了滤波输出,包括滤波状态和对数似然(参见类文档以获取可用结果的完整列表)。它还提供了一个预测方法,允许样本内预测或样本外预测。类似的方法预测提供了额外的预测或预测结果,包括置信区间。

kalman_filter.KalmanFilter(k_endog, k_states)

时间序列过程的状态空间表示,使用卡尔曼滤波器

kalman_filter.FilterResults(model)

应用于状态空间模型的卡尔曼滤波结果。

kalman_filter.PredictionResults(results, ...)

样本内和样本外预测结果通常用于状态空间模型

KalmanSmoother 类是 KalmanFilter 的子类,提供了平滑功能。一旦状态空间表示矩阵已经构建,可以调用 filter 方法,生成一个 SmootherResults 实例;SmootherResultsFilterResults 的子类。

SmootherResults 类包含了 FilterResults 的所有输出,但还包括平滑输出,包括 smoothed state 和 对数似然(参见类文档以获取可用结果的完整列表)。而“过滤”输出在时间 t 指的是基于截至时间 t 的观测值的估计,“平滑”输出指的是基于数据集中所有观测值的估计。

kalman_smoother.KalmanSmoother(k_endog, k_states)

时间序列过程的状态空间表示,带有卡尔曼滤波器和平滑器。

kalman_smoother.SmootherResults(模型)

对状态空间模型应用卡尔曼平滑器和/或滤波器的结果。

SimulationSmoother 类是 KalmanSmoother 的子类,进一步提供了模拟和模拟平滑功能。可以调用 simulation_smoother 方法,生成一个 SimulationSmoothResults 实例。

SimulationSmoothResults 有一个 simulate 方法,允许执行模拟平滑以从状态向量的联合后验中抽取样本。这对于通过吉布斯采样进行状态空间模型的贝叶斯估计非常有用。

simulation_smoother.SimulationSmoother(...)

时间序列过程的状态空间表示,带有卡尔曼滤波和平滑器,以及带有模拟平滑器。

simulation_smoother.SimulationSmoothResults(...)

对状态空间模型应用卡尔曼平滑器和/或滤波器的结果。

cfa_simulation_smoother.CFASimulationSmoother(模型)

“Cholesky 因子算法”(CFA)模拟平滑器

状态空间工具

有多种工具用于状态空间建模或由SARIMAX类使用:

tools.companion_matrix(多项式)

创建一个伴随矩阵

tools.diff(series[, k_diff, ...])

沿第零轴简单和/或季节性地差分一个序列。

tools.is_invertible(多项式[, 阈值])

确定一个多项式是否可逆。

tools.constrain_stationary_univariate(...)

将优化器使用的无约束参数转换为似然评估中使用的约束参数

tools.unconstrain_stationary_univariate(...)

将似然评估中使用的约束参数转换为优化器使用的无约束参数

tools.constrain_stationary_multivariate(...)

将优化器使用的无约束参数转换为向量自回归似然评估中使用的约束参数。

tools.unconstrain_stationary_multivariate(...)

将似然评估中使用的约束参数转换为优化器使用的无约束参数

tools.validate_matrix_shape(名称, 形状, ...)

验证一个可能随时间变化的矩阵的形状,或者引发异常

tools.validate_vector_shape(name, shape, ...)

验证可能随时间变化的向量的形状,或引发异常


Last update: Oct 16, 2024