使用狀態空間方法進行時間序列分析 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 : obs_intercept \((k\_endog \times nobs)\)

H : obs_cov \((k\_endog \times k\_endog \times nobs)\)

T : 轉換 \((k\_states \times k\_states \times nobs)\)

c : state_intercept \((k\_states \times nobs)\)

R : 選擇 \((k\_states \times k\_posdef \times nobs)\)

Q : 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)

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)

VARMAX 類別是多元狀態空間模型的一個範例。

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

具有外生迴歸變數的向量自迴歸移動平均模型

varmax.VARMAXResults(model, params, ...[, ...])

用於保存擬合 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()

DynamicFactor 類別適用於觀測變數數量較少的模型

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

動態因子模型

dynamic_factor.DynamicFactorResults(model, ...)

用於保存擬合 DynamicFactor 模型結果的類別。

關於使用 DynamicFactor 模型的範例,請參閱 動態因子範例筆記本

線性指數平滑模型

ExponentialSmoothing 類別是使用狀態空間方法實現的線性指數平滑模型。

注意:此模型位於 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.ExponentialSmoothing)與位於 sm.tsa.ExponentialSmoothing 的模型類別之間存在若干差異。

  • 此模型類別僅支援線性指數平滑模型,而 sm.tsa.ExponentialSmoothing 也支援乘法模型。

  • 此模型類別將指數平滑模型放入狀態空間形式,然後應用卡爾曼濾波器來估計狀態,而 sm.tsa.ExponentialSmoothing 則基於指數平滑遞迴。在某些情況下,這可能意味著使用此模型類別估計參數會比使用 sm.tsa.ExponentialSmoothing 稍微慢一些。

  • 此模型類別可以根據高斯誤差的假設產生預測的信賴區間,而 sm.tsa.ExponentialSmoothing 則不支援信賴區間。

  • 此模型類別支援從目標函數中集中初始值,當需要估計的初始狀態很多時(例如,當季節性週期很大時),這可以提高效能。

  • 此模型類別支援狀態空間模型可用的許多進階功能,例如診斷和固定參數。

注意:此類別基於「多重誤差來源」(MSOE) 狀態空間公式,而非「單一誤差來源」(SSOE) 公式。

自訂狀態空間模型

狀態空間模型的真正強大之處在於允許建立和估計自訂模型。通常是透過擴展以下兩個類別來完成,這兩個類別捆綁了所有狀態空間表示、卡爾曼濾波和最大概似擬合功能,用於估計和結果輸出。

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

用於最大概似估計的狀態空間模型

mlemodel.MLEResults(model, params, results)

用於保存擬合狀態空間模型結果的類別。

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 - 與係數的 z 統計量相關的 p 值。 請注意,假設係數具有常態分佈。

  • llf - 在估計參數下評估的對數概似函數值。

  • sse, mse, 和 mae - 誤差平方和、均方誤差和平均絕對誤差。

  • 資訊準則,包括:aicaiccbichquc

  • 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, ...[, ...])

資料修訂和消息對感興趣變數估計值的影響

其他選項和工具

所有狀態空間模型都有以下選項和工具

固定某些參數並估計其餘參數

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(model)

凍結狀態空間模型

KalmanFilter 類別是提供篩選功能的 Representation 的子類別。一旦建構狀態空間表示矩陣,就可以呼叫 filter 方法,產生 FilterResults 實例;FilterResultsFrozenRepresentation 的子類別。

FilterResults 類別不僅保存狀態空間模型的凍結表示(設計、轉換等矩陣,以及模型維度等),還保存篩選輸出,包括 filtered state 和對數概似(請參閱類別文件以取得可用結果的完整列表)。它還提供了一個 predict 方法,允許樣本內預測或樣本外預測。類似的方法 predict 提供額外的預測或預測結果,包括信賴區間。

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(model)

將卡爾曼平滑器和/或濾波器套用至狀態空間模型的結果。

SimulationSmoother 類別是 KalmanSmoother 的子類別,進一步提供模擬和平滑模擬功能。可以呼叫 simulation_smoother 方法,產生 SimulationSmoothResults 實例。

SimulationSmoothResults 類別具有 simulate 方法,允許執行平滑模擬以從狀態向量的聯合後驗中提取樣本。這對於透過吉布斯取樣對狀態空間模型進行貝氏估計非常有用。

simulation_smoother.SimulationSmoother(...)

具有卡爾曼濾波器和平滑器以及模擬平滑器之時間序列過程的狀態空間表示。

simulation_smoother.SimulationSmoothResults(...)

將卡爾曼平滑器和/或濾波器套用至狀態空間模型的結果。

cfa_simulation_smoother.CFASimulationSmoother(model)

「喬列斯基因數演算法」(CFA) 模擬平滑器

狀態空間工具

有多種用於狀態空間建模或 SARIMAX 類別使用的工具

tools.companion_matrix(polynomial)

建立伴隨矩陣

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

沿著第零軸簡單地或按季節性差分一個序列。

tools.is_invertible(polynomial[, threshold])

判斷多項式是否可逆。

tools.constrain_stationary_univariate(...)

將最佳化器使用的無約束參數轉換為似然估計中使用的約束參數

tools.unconstrain_stationary_univariate(...)

將似然估計中使用的約束參數轉換為最佳化器使用的無約束參數

tools.constrain_stationary_multivariate(...)

將最佳化器使用的無約束參數轉換為向量自迴歸的似然估計中使用的約束參數。

tools.unconstrain_stationary_multivariate(...)

將似然估計中使用的約束參數轉換為最佳化器使用的無約束參數

tools.validate_matrix_shape(name, shape, ...)

驗證可能隨時間變化的矩陣形狀,或引發例外。

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

驗證可能隨時間變化的向量形狀,或引發例外。


上次更新:2024 年 10 月 03 日