
    M/PhC                       d Z ddlZddlZddlZddlmZ ddlm	Z	 ddl
mc mZ ddlmZ ddlmZmZmZ ddlmZmZ ddlmZ dd	lmZmZ ddlmc mc mZ dd
l m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z- e#e"e!e$dZ.e(e'e&e)dZ/d Z0d Z1d Z2d Z3 G d d          Z4 G d dej5                  Z6 G d d          Z7 G d de7          Z8 G d dej9                  Z: G d dej;                  Z< ej=        e<e:           dS )z=
Markov switching models

Author: Chad Fulton
License: BSD-3
    N)	logsumexp)
PandasData)cache_readonly)aicbichqic)approx_fprime_csapprox_hess_cs)EstimationWarning)Bunchpinv_extended)chamilton_filter_logdhamilton_filter_logshamilton_filter_logzhamilton_filter_log)ckim_smoother_logdkim_smoother_logskim_smoother_logzkim_smoother_log)find_best_blas_typeprepare_exog
_safe_cond)sdczc           	      ~   t          j        |           } | j        dk    rt          j        | d          }n| j        dk    r&t          j        | t	          |           ddf          }nO| j        dk    r/t          j        | | j        d         d| j        d         f          }n| j        dk    r| }nt          t           j        t          j        |j        d         |j        d         df          |j	        f         j	        }t          j        t          j
        |t          |d          z
            | j                  }|S )5
    Note that this is not a vectorized function
    r   )   r   r   r         axis)nparrayndimreshapelenshapeNotImplementedErrorc_zerosTexpr   )xytmp	evaluateds       q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/regime_switching/markov_switching.py	_logisticr5   2   s
    	Av{{Jq)$$	
1Jq3q661a.))	
1Jq171:q!'!*566	
1!!
%!'"+qwqz1566;
<
>C
26!i!&<&<&<"<==qwGGI    c                    t          |           j        dk    rdz  z
  S j        dk    rt          j        dz  z
            }n$j        dk    rfdt	          j        d                   D             }j        d         j        d         j        d         f}t          j        |                              |                              d          }nfdt	          j        d                   D             }j        d         j        d         j        d         j        d         f}t          j        |                              |                              d          }t	          j        d                   D ]A}t	          |          D ]/}|df          |df         z  |||df<   |||df         |||df<   0B|S )	r   r   r    r   c                 l    g | ]0}t          j        d d |f         d d |f         dz  z
            1S Nr    r%   diag).0tr2   s     r4   
<listcomp>z&_partials_logistic.<locals>.<listcomp>Z   sT     2 2 2 GC1IAAAqD	1455 2 2 2r6   )r   r    r   c                 `    g | ])fd t          j        d                   D             *S )c           	      p    g | ]2}t          j        d d |f         d d |f         dz  z
            3S r9   r:   )r<   r=   jr2   s     r4   r>   z1_partials_logistic.<locals>.<listcomp>.<listcomp>`   sX     3 3 3 WSAq\C1aL!O;<< 3 3 3r6   r    )ranger*   )r<   rA   r2   s    @r4   r>   z&_partials_logistic.<locals>.<listcomp>`   s^     2 2 23 3 3 3 3#CIaL113 3 3 2 2 2r6   )r    r!   r   r   .)	r5   r'   r%   r;   rB   r*   concatenater(   	transpose)r0   partialsr*   irA   r2   s        @r4   _partials_logisticrG   L   s    A,,C x1}}S!V|	Q73a<((	Q2 2 2 2"39Q<002 2 2	!cilCIaL8>(++33E::DDYOO2 2 2 2"39Q<002 2 2 	!cilCIaL#)A,F>(++33E::DD  39Q<   6 6q 	6 	6A#&q#v;,QV"<HQ3Y"*1a9"5HQ3Y	6 Or6   c                    t          |           }|j        d         }|j        dz
  }|j        }|j        d         d||z   fvp%|j        dd         ||fk    p|j        d         |k    }|rt	          d          t          j        |           } t          j        t          j        |d                    }t          j        ||f|          }	t          j        |f|dz   z  |fz   |          }
t          j        |f|          }t          j        |f|dz   z  |dz   fz   |          }| |	dddf<   t          j	        |           }||f}d}t          |          D ];}|j        d         dk    r|}t          j        |d	|f         |d
|z  z             |z   }<||d<   |j        d         dk    r|d	|df         }t          ||||
|f          \  }}}t          |         } ||||||                    ||dz   z  |          ||
                    ||dz   z  |          |                    ||dz   z  |dz                        |
}|}t          j        |
          }
t          j        |          }|d	ddf         }	t          d|	j        dz
            D ]}t          j        |	d          }	|	|
||d	ddf         ||d	ddf         fS )a  
    Hamilton filter in log space using Cython inner loop.

    Parameters
    ----------
    initial_probabilities : ndarray
        Array of initial probabilities, shaped (k_regimes,) giving the
        distribution of the regime process at time t = -order where order
        is a nonnegative integer.
    regime_transition : ndarray
        Matrix of regime transition probabilities, shaped either
        (k_regimes, k_regimes, 1) or if there are time-varying transition
        probabilities (k_regimes, k_regimes, nobs + order).  Entry [i, j,
        t] contains the probability of moving from j at time t-1 to i at
        time t, so each matrix regime_transition[:, :, t] should be left
        stochastic.  The first order entries and initial_probabilities are
        used to produce the initial joint distribution of dimension order +
        1 at time t=0.
    conditional_loglikelihoods : ndarray
        Array of loglikelihoods conditional on the last `order+1` regimes,
        shaped (k_regimes,)*(order + 1) + (nobs,).

    Returns
    -------
    filtered_marginal_probabilities : ndarray
        Array containing Pr[S_t=s_t | Y_t] - the probability of being in each
        regime conditional on time t information. Shaped (k_regimes, nobs).
    predicted_joint_probabilities : ndarray
        Array containing Pr[S_t=s_t, ..., S_{t-order}=s_{t-order} | Y_{t-1}] -
        the joint probability of the current and previous `order` periods
        being in each combination of regimes conditional on time t-1
        information. Shaped (k_regimes,) * (order + 1) + (nobs,).
    joint_loglikelihoods : ndarray
        Array of loglikelihoods condition on time t information,
        shaped (nobs,).
    filtered_joint_probabilities : ndarray
        Array containing Pr[S_t=s_t, ..., S_{t-order}=s_{t-order} | Y_{t}] -
        the joint probability of the current and previous `order` periods
        being in each combination of regimes conditional on time t
        information. Shaped (k_regimes,) * (order + 1) + (nobs,).
    r"   r    r   Nr   z'Arguments do not have compatible shapes#B;dtype.r   .r   r#   )r)   r*   r'   rK   
ValueErrorr%   logmaximumr-   copyrB   r(   r   prefix_hamilton_filter_log_mapr/   sum)initial_probabilitiesregime_transitionconditional_loglikelihoodsmodel_order	k_regimesnobsorderrK   incompatible_shapesfiltered_marginal_probabilitiespredicted_joint_probabilitiesjoint_loglikelihoodsfiltered_joint_probabilitiesr2   r*   transition_trF   prefix_func!predicted_joint_probabilities_log filtered_joint_probabilities_logs                         r4   cy_hamilton_filter_logrg   n   s   Z )**I%+B/D&+a/E&,E 	#Atk/A+BB 	<"2A2&9i*@@	<%+A.);   DBCCC F#899rz*;UCCDD
 	)T"%000 $ %'H		"dW,E%; %; %;! 8TGU33 $&8		"dQh[0$? $? $?  -B#AAAqD)
''
(
(C	"EL5\\ 1 1"2&**Lj*3+<=)+ +-01+. ( r"Q&&-c;<<.?@ +57K%'C,E F FFE1 *&1DDy%!2	#	+	+Ia,@$	G	G		&	.	.y57/CT	J	J	%	-	-i%'.BDF	K	K	M M M )F%'C$ %'F+H$I$I!#%6*F#G#G  'C37&K#15:Q>?? 6 6*,&+"+6 +6 +6'' ,-J ">sABBw"G-,S!""W57 7r6   c                    |j         d         }|j         d         }|j        dz
  }|j        }t          j        |f|dz   z  |fz   |          }| j         d         ||z   k    r| d|df         } t          j        t          j        | d                    } t          | ||f          \  }}}	t          |         }
 |
|||| |	                    ||dz   z  |          |	                    ||dz   z  |          |	                    ||dz   z  |                     t          j
        |          }|}t          d|j        dz
            D ]}t          j        |d	
          }||fS )a  
    Kim smoother in log space using Cython inner loop.

    Parameters
    ----------
    regime_transition : ndarray
        Matrix of regime transition probabilities, shaped either
        (k_regimes, k_regimes, 1) or if there are time-varying transition
        probabilities (k_regimes, k_regimes, nobs).
    predicted_joint_probabilities : ndarray
        Array containing Pr[S_t=s_t, ..., S_{t-order}=s_{t-order} | Y_{t-1}] -
        the joint probability of the current and previous `order` periods
        being in each combination of regimes conditional on time t-1
        information. Shaped (k_regimes,) * (order + 1) + (nobs,).
    filtered_joint_probabilities : ndarray
        Array containing Pr[S_t=s_t, ..., S_{t-order}=s_{t-order} | Y_{t}] -
        the joint probability of the current and previous `order` periods
        being in each combination of regimes conditional on time t
        information. Shaped (k_regimes,) * (order + 1) + (nobs,).

    Returns
    -------
    smoothed_joint_probabilities : ndarray
        Array containing Pr[S_t=s_t, ..., S_{t-order}=s_{t-order} | Y_T] -
        the joint probability of the current and previous `order` periods
        being in each combination of regimes conditional on all information.
        Shaped (k_regimes,) * (order + 1) + (nobs,).
    smoothed_marginal_probabilities : ndarray
        Array containing Pr[S_t=s_t | Y_T] - the probability of being in each
        regime conditional on all information. Shaped (k_regimes, nobs).
    r   r"   r    r   rJ   .NrI   rN   r#   )r*   r'   rK   r%   r-   rP   rQ   r   prefix_kim_smoother_log_mapr(   r/   rB   rT   )rV   r^   r`   rY   rZ   r[   rK   smoothed_joint_probabilitiesrb   rc   rd   smoothed_marginal_probabilitiesrF   s                r4   cy_kim_smoother_logrl      s   F -215I'-b1D(-1E(.E $&8		"dW,E$; $; $;  r"dUl22-c566k: rz*;UCCDD +8$,& ' 'FE1 'v.DDy%!2	&	.	.y57/CT	J	J	%	-	-i%'.BD	I	I	%	-	-i%'.BD	I	IK K K $&6*F#G#G  'C#15:Q>?? 6 6*,&+"+6 +6 +6'' ()HHHr6   c                   $    e Zd ZdZd Zd Zd ZdS )MarkovSwitchingParamsa=
  
    Class to hold parameters in Markov switching models

    Parameters
    ----------
    k_regimes : int
        The number of regimes between which parameters may switch.

    Notes
    -----

    The purpose is to allow selecting parameter indexes / slices based on
    parameter type, regime number, or both.

    Parameters are lexicographically ordered in the following way:

    1. Named type string (e.g. "autoregressive")
    2. Number (e.g. the first autoregressive parameter, then the second)
    3. Regime (if applicable)

    Parameter blocks are set using dictionary setter notation where the key
    is the named type string and the value is a list of boolean values
    indicating whether a given parameter is switching or not.

    For example, consider the following code:

        parameters = MarkovSwitchingParams(k_regimes=2)
        parameters['regime_transition'] = [1,1]
        parameters['exog'] = [0, 1]

    This implies the model has 7 parameters: 4 "regime_transition"-related
    parameters (2 parameters that each switch according to regimes) and 3
    "exog"-related parameters (1 parameter that does not switch, and one 1 that
    does).

    The order of parameters is then:

    1. The first "regime_transition" parameter, regime 0
    2. The first "regime_transition" parameter, regime 1
    3. The second "regime_transition" parameter, regime 1
    4. The second "regime_transition" parameter, regime 1
    5. The first "exog" parameter
    6. The second "exog" parameter, regime 0
    7. The second "exog" parameter, regime 1

    Retrieving indexes / slices is done through dictionary getter notation.
    There are three options for the dictionary key:

    - Regime number (zero-indexed)
    - Named type string (e.g. "autoregressive")
    - Regime number and named type string

    In the above example, consider the following getters:

    >>> parameters[0]
    array([0, 2, 4, 6])
    >>> parameters[1]
    array([1, 3, 5, 6])
    >>> parameters['exog']
    slice(4, 7, None)
    >>> parameters[0, 'exog']
    [4, 6]
    >>> parameters[1, 'exog']
    [4, 7]

    Notice that in the last two examples, both lists of indexes include 4.
    That's because that is the index of the the non-switching first "exog"
    parameter, which should be selected regardless of the regime.

    In addition to the getter, the `k_parameters` attribute is an dict
    with the named type strings as the keys. It can be used to get the total
    number of parameters of each type:

    >>> parameters.k_parameters['regime_transition']
    4
    >>> parameters.k_parameters['exog']
    3
    c                    || _         d| _        i | _        i | _        i | _        d t          | j                   D             | _        d t          | j                   D             | _        d t          | j                   D             | _        d S )Nr   c                     g | ]}i S  rq   r<   rF   s     r4   r>   z2MarkovSwitchingParams.__init__.<locals>.<listcomp>  s%     ./ ./ ./B./ ./ ./r6   c                     g | ]}i S rq   rq   rr   s     r4   r>   z2MarkovSwitchingParams.__init__.<locals>.<listcomp>  s%     %/ %/ %/B%/ %/ %/r6   c                     g | ]}g S rq   rq   rr   s     r4   r>   z2MarkovSwitchingParams.__init__.<locals>.<listcomp>  s    ???AR???r6   )	rY   k_paramsk_parameters	switchingslices_purposerB   relative_index_regime_purposeindex_regime_purposeindex_regime)selfrY   s     r4   __init__zMarkovSwitchingParams.__init__  s    " ./ ./dn--./ ./ ./*%/ %/dn--%/ %/ %/!??t~)>)>???r6   c                 f   t          |          }|t          u r| j        |         S |t          u r| j        |         S |t
          u rt          |          dk    st          d          t          |d                   t          u r;t          |d                   t          u r| j        |d                  |d                  S t          |d                   t          u r;t          |d                   t          u r| j        |d                  |d                  S t          d          t          d          )Nr    Invalid indexr   r   )	typestrrx   intr{   tupler)   
IndexErrorrz   )r|   key_types      r4   __getitem__z!MarkovSwitchingParams.__getitem__  s   S		 C<<&s++c\\$S))e^^s88q== 111CF||s""tCF||s':':0Q8Q@@c!f$$c!f)<)<0Q8Q@@ 111_---r6   c                    t          |          }|t          u r9t          j        |t          d          }| j        }|j        t          j        |          | j        dz
  z  z   | j	        |<   | xj        | j	        |         z  c_        || j
        |<   t          j        || j                 | j        |<   t          | j                  D ]"}g | j        |         |<   g | j        |         |<   #d}t          |j                  D ]}||         }t          | j                  D ]T}|s'| j        |         |                             |           +| j        |         |                             ||z              U||sdn| j        z  }t          | j                  D ]}d}g }	| j        |                                         D ]a\  }
}t          j        |         |z                                   }|| j        |         |
<   |	                    |           || j	        |
         z  }bt          j        |	                              t,                    | j        |<   d S t1          d          )Nr   )rK   ndminr   r   )r   r   r%   r&   boolru   sizerT   rY   rv   rw   s_rx   rB   ry   rz   appenditemsr_tolistrC   astyper   r{   r   )r|   r   valuer   ru   rA   offsetrF   rw   indiceskvs               r4   __setitem__z!MarkovSwitchingParams.__setitem__  s   S		C<<HU$a888E}H
RVE]]dnq.@AA c"MMT.s33MM"'DN3')uXdm-C'DD$4>** 7 7=?215c:46)!,S11F5:&& A A!!H	t~.. ( (A$ (:1=cBII"$ $ $ $ :1=cBII"QJ( ( ( (9@!!$.@4>** K K >qAGGII 3 3DAqqF*2244A67D-a03NN1%%%d/22FF')~g'>'>'E'Ec'J'J!!$$K K _---r6   N)__name__
__module____qualname____doc__r}   r   r   rq   r6   r4   rn   rn   4  sQ        M M\@ @ @. . .*(. (. (. (. (.r6   rn   c                   l    e Zd ZdZ	 	 d/ fd	Zed             Zd Zd0d	Zd1d
Z	d1dZ
d1dZ	 	 d2dZd Zd Zd1dZ	 	 	 d3dZ	 d1dZed             Z	 	 d4dZ	 	 	 d3dZd5dZd5dZd5dZd5dZd5dZ	 	 	 	 d6 fd#	Z	 	 	 d7d&Zd' Zd( Z	 	 d8d)Zed*             Zed+             Z d, Z!d- Z"d. Z# xZ$S )9MarkovSwitchingaU  
    First-order k-regime Markov switching model

    Parameters
    ----------
    endog : array_like
        The endogenous variable.
    k_regimes : int
        The number of regimes.
    order : int, optional
        The order of the model describes the dependence of the likelihood on
        previous regimes. This depends on the model in question and should be
        set appropriately by subclasses.
    exog_tvtp : array_like, optional
        Array of exogenous or lagged variables to use in calculating
        time-varying transition probabilities (TVTP). TVTP is only used if this
        variable is provided. If an intercept is desired, a column of ones must
        be explicitly included in this array.

    Notes
    -----
    This model is new and API stability is not guaranteed, although changes
    will be made in a backwards compatible way if possible.

    References
    ----------
    Kim, Chang-Jin, and Charles R. Nelson. 1999.
    "State-Space Models with Regime Switching:
    Classical and Gibbs-Sampling Approaches with Applications".
    MIT Press Books. The MIT Press.
    r   Nnonec	                    || _         |d u| _        || _        t          |          \  | _        | _        t                                          |||||           | j        j	        d         | _
        | j        j        dk    r%| j        j	        d         dk    rt          d          | j         dk     rt          d          | j        *| j        j	        d         | j
        k    st          d          t          | j                   | _        | j         dz
  }	| j        r
|	| j        z  }	dg|	z  | j        d<   d	| _        d | _        d S )
N)datesfreqmissingr   r   z%Must have univariate endogenous data.r    z7Markov switching models must have at least two regimes.zxTime-varying transition probabilities exogenous array must have the same number of observations as the endogenous array.rV   steady-state)rY   tvtpr[   r   k_tvtp	exog_tvtpsuperr}   endogr*   rZ   r'   rO   rn   
parameters_initialization_initial_probabilities)r|   r   rY   r[   r   exogr   r   r   k_transition	__class__s             r4   r}   zMarkovSwitching.__init__  sg    #T)	
 '39&=&=#T^ 	4u4 	 	
 	
 	

 J$Q'	 :?Q4:#3A#6#:#:DEEE>A ) * * *&$Q'4944 9 : : :
 0??~)9 	(DK'L01s\/A+,  .&*###r6   c                     | j         j        S )z9
        (int) Number of parameters in the model
        )r   ru   r|   s    r4   ru   zMarkovSwitching.k_params  s    
 ''r6   c                 N    | j         rt          d          d| _        d| _        dS )z
        Set initialization of regime probabilities to be steady-state values

        Notes
        -----
        Only valid if there are not time-varying transition probabilities.
        zYCannot use steady-state initialization when the regime transition matrix is time-varying.r   N)r   rO   r   r   r   s    r4   initialize_steady_statez'MarkovSwitching.initialize_steady_state$  sB     9 	O N O O O  .&*###r6   :0yE>c                    d| _         t          j        |d          }|j        | j        fk    st          d          t          j        t          j        |          dz
            |k     st          d          || _        dS )zP
        Set initialization of regime probabilities to use known values
        knownr   r   z=Initial probabilities must be a vector of shape (k_regimes,).z-Initial probabilities vector must sum to one.N)	r   r%   r&   r*   rY   rO   absrT   r   )r|   probabilitiestols      r4   initialize_knownz MarkovSwitching.initialize_known3  s      'a888"t~&777 . / / /vbf]++a/00366LMMM&3###r6   c                 R   t          j        |d          }| j        dk    r||                     |          }|j        dk    r|d         }|j        d         }t           j        t          j        |          |z
  j        t          j	        |          f         j        }	 t           j
                            |          dddf         }nI# t           j
        j        $ r t          d	          w xY w| j        d
k    r| j        }nt          d          t          j        |d          }|S )z0
        Retrieve initial probabilities
        r   r   r   Nr!   rM   r   r"   z4Steady-state probabilities could not be constructed.r   z'Invalid initialization method selected.rI   )r%   r&   r   regime_transition_matrixr'   r*   r,   eyer.   oneslinalgpinvLinAlgErrorRuntimeErrorr   rQ   )r|   paramsrV   mAr   s         r4   rU   z%MarkovSwitching.initial_probabilities@  s3    &***>11 ($($A$A&$I$I! %**$5f$=!!'*Arvayy#447CDFA4 "	q 1 1!!!R% 89( 4 4 4" $3 4 4 44 !W,, 7MMHIII 
=%88s   )C	 	$C-c           	      "   || j         }t          |          }t          j        | j        | j        |ft          j        t          j        |j                            }t          | j                  D ]b}|| j	        |df                  }t          j
        |t          j        || j        dz
  | j        f          j                  j        |d d|d d f<   ct          j        t          j        || j        df          |d dd d d d f         j        f         j        }t          j        |d dd d d d f         t!          |d          z
            |d dd d d d f<   dt          j        |d dd d d d f         d          z
  |dd d d d f<   |S )NrJ   rV   r   r"   r   r#   )r   r)   r%   r-   rY   promote_typesfloat64rK   rB   r   dotr(   r   r.   r,   r/   r   rT   )r|   r   r   rZ   r   rF   coeffsr2   s           r4   _regime_transition_matrix_tvtpz.MarkovSwitching._regime_transition_matrix_tvtp\  s   I9~~#%8^T^T2"2:v|<<$> $> $> 
 t~&& 	I 	IADOA/B,BCDF24&
6DN1$4dk#BCCE3G 3GGH %SbS!QQQY//
 eBHdDNA677,SbS!!!QQQY79: ;;< 	.0f$SbS!!!QQQY/)Ca2H2H2HH/J /J "aaa+
 /QQQ	:CCCC 	!QQQ* ('r6   c                    t          j        |d          }| j        st          j        | j        | j        dft          j        t           j        |j                            }t          j        || j	        d                  | j        dz
  | j        f          |dddddf<   dt          j
        |dddddf         d          z
  |ddddf<   n|                     ||          }|S )	a  
        Construct the left-stochastic transition matrix

        Notes
        -----
        This matrix will either be shaped (k_regimes, k_regimes, 1) or if there
        are time-varying transition probabilities, it will be shaped
        (k_regimes, k_regimes, nobs).

        The (i,j)th element of this matrix is the probability of transitioning
        from regime j to regime i; thus the previous regime is represented in a
        column and the next regime is represented by a row.

        It is left-stochastic, meaning that each column sums to one (because
        it is certain that from one regime (j) you will transition to *some
        other regime*).
        r   r   rJ   rV   Nr"   r   r#   )r%   r&   r   r-   rY   r   r   rK   r(   r   rT   r   )r|   r   r   r   s       r4   r   z(MarkovSwitching.regime_transition_matrixx  s   $ &***y 	H')x3&rz6<@@(B (B (B$ 35*t':;<!4>234 34$SbS!!!QY/ BF3CRCAI>QGGGG %RAX.. 33FIFF % ('r6   Fc                 n   || j         d         }|                     ||          \  }}}}|dk    rt          |                     |          }t	          j        |          }	|	j        dz
  |k    r||dk    r|                     |d          }
|
j        }nI|dk    r| 	                    |d          }
|
j
        }n$|dk    r| 	                    |d          }
|
j        }||z  }t          |j        dz
  t          |          z
            D ]}t	          j        |d	
          }n|	}||||z   dz            S )a
  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        params : ndarray
            Parameters at which to form predictions
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.
        probabilities : str or array_like, optional
            Specifies the weighting probabilities used in constructing the
            prediction as a weighted average. If a string, can be 'predicted',
            'filtered', or 'smoothed'. Otherwise can be an array of
            probabilities to use. Default is smoothed.
        conditional : bool or int, optional
            Whether or not to return predictions conditional on current or
            past regimes. If False, returns a single vector of weighted
            predictions. If True or 1, returns predictions conditional on the
            current regime. For larger integers, returns predictions
            conditional on the current regime and some number of past regimes.

        Returns
        -------
        predict : ndarray
            Array of out of in-sample predictions and / or out-of-sample
            forecasts.
        Nr   r   smoothedT)
return_rawfiltered	predictedrN   r#   )_index_get_prediction_indexr+   predict_conditionalr%   squeezer'   smoothrj   filterr`   r^   rB   r   rT   )r|   r   startendr   conditionalout_of_sampleprediction_indexpredictsqueezedresultsrF   s               r4   r   zMarkovSwitching.predict  sw   L =KNE &&uc22 	4sM#3 1%% **622:g&& =1{**$(C(C++f+>> ' D*,,++f+>> ' D+--++f+>> ' E .G7<!+c+.>.>>?? 3 3&r2223 GuS=014455r6   c                     t           )a  
        In-sample prediction, conditional on the current, and possibly past,
        regimes

        Parameters
        ----------
        params : array_like
            Array of parameters at which to perform prediction.

        Returns
        -------
        predict : array_like
            Array of predictions conditional on current, and possibly past,
            regimes
        r+   r|   r   s     r4   r   z#MarkovSwitching.predict_conditional  s
      "!r6   c                     t           )z
        Compute likelihoods conditional on the current period's regime (and
        the last self.order periods' regimes if self.order > 0).

        Must be implemented in subclasses.
        r   r   s     r4   _conditional_loglikelihoodsz+MarkovSwitching._conditional_loglikelihoods  s
     "!r6   c                     ||                      |          }|                     ||          }|                     |          }|||ft          |||| j                  z   S N)r   rU   r   rg   r[   )r|   r   rV   rU   rW   s        r4   _filterzMarkovSwitching._filter  s    $ $ = =f E E $ : :%!' !' &*%E%Ef%M%M" #$9+-&)+<.
< << 	=r6   Tc                 L   t          j        |d          }|s|                     |          }| j        | j        _        g d}t          | t          di t          t          || 	                    |                                        }	| 
                    ||	|||||          S )a  
        Apply the Hamilton filter

        Parameters
        ----------
        params : array_like
            Array of parameters at which to perform filtering.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        cov_type : str, optional
            See `fit` for a description of covariance matrix types
            for results object.
        cov_kwds : dict or None, optional
            See `fit` for a description of required keywords for alternative
            covariance estimators
        return_raw : bool,optional
            Whether or not to return only the raw Hamilton filter output or a
            full results object. Default is to return a full results object.
        results_class : type, optional
            A results class to instantiate rather than
            `MarkovSwitchingResults`. Usually only used internally by
            subclasses.
        results_wrapper_class : type, optional
            A results wrapper class to instantiate rather than
            `MarkovSwitchingResults`. Usually only used internally by
            subclasses.

        Returns
        -------
        MarkovSwitchingResults
        r   r   	rV   rU   rW   r]   r^   r_   r`   re   rf   rq   )r%   r&   transform_paramsparam_namesdataHamiltonFilterResultsr   dictzipr   _wrap_results)
r|   r   transformedcov_typecov_kwdsr   results_classresults_wrapper_classnamesresults
             r4   r   zMarkovSwitching.filter  s    D &*** 	3**622F !% 0	5 5 5 '%AA$s5$,,v*>*>??@@AAC C !!&&*h"*M"79 9 	9r6   c                 R    ||                      |          }t          |||          S r   )r   rl   )r|   r   re   rf   rV   s        r4   _smoothzMarkovSwitching._smoothK  s>     $ $ = =f E E ##4#D#CE E 	Er6   c                 "    dt           t          fiS )Nfit)MarkovSwitchingResultsMarkovSwitchingResultsWrapperr   s    r4   _res_classeszMarkovSwitching._res_classesV  s    .0MNOOr6   c                     |sPi }|||d<   |||d<   || j         d         d         }|| j         d         d         } || ||fi |}	 ||	          }|S )Nr   r   r   r   r   )r   )
r|   r   r   r   r   r   r   wrapper_classresult_kwargsress
             r4   r   zMarkovSwitching._wrap_resultsZ  s     	(M#,4j)#,4j)$ $ 1% 8 ;$ $ 1% 8 ;-ffFFFFC"]3''Fr6   c                    t          j        |d          }|s|                     |          }| j        | j        _        g d}t          di t          t          ||                     |                              }	| 	                    ||	j
        |	j                  }
|
d         |	d<   |
d         |	d<   t          | |	          }	|                     ||	|||||          S )a  
        Apply the Kim smoother and Hamilton filter

        Parameters
        ----------
        params : array_like
            Array of parameters at which to perform filtering.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        cov_type : str, optional
            See `fit` for a description of covariance matrix types
            for results object.
        cov_kwds : dict or None, optional
            See `fit` for a description of required keywords for alternative
            covariance estimators
        return_raw : bool,optional
            Whether or not to return only the raw Hamilton filter output or a
            full results object. Default is to return a full results object.
        results_class : type, optional
            A results class to instantiate rather than
            `MarkovSwitchingResults`. Usually only used internally by
            subclasses.
        results_wrapper_class : type, optional
            A results wrapper class to instantiate rather than
            `MarkovSwitchingResults`. Usually only used internally by
            subclasses.

        Returns
        -------
        MarkovSwitchingResults
        r   r   r   r   rj   rk   rq   )r%   r&   r   r   r   r   r   r   r   r   re   rf   KimSmootherResultsr   )r|   r   r   r   r   r   r   r   r   r   outs              r4   r   zMarkovSwitching.smoothm  s   D &*** 	3**622F !% 0	
5 5 5 @@c%f)=)=>>??@@ ll66#K!BD D14Q-.47F01#D&11 !!&&*h"*M"79 9 	9r6   c                     t          j        |d          }|s|                     |          }|                     |          }|d         S )aL  
        Loglikelihood evaluation for each period

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        r   r      )r%   r&   r   r   )r|   r   r   r   s       r4   
loglikeobszMarkovSwitching.loglikeobs  sN     &*** 	3**622F,,v&&qzr6   c                 R    t          j        |                     ||                    S )a<  
        Loglikelihood evaluation

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        )r%   rT   r  r|   r   r   s      r4   loglikezMarkovSwitching.loglike  s"     vdoofk::;;;r6   c                 ^    t          j        |d          }t          || j        |f          S )aA  
        Compute the score function at params.

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the score
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        r   r   args)r%   r&   r	   r  r
  s      r4   scorezMarkovSwitching.score  s1     &***K>JJJJr6   c                 ^    t          j        |d          }t          || j        |f          S )aR  
        Compute the score per observation, evaluated at params

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the score
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        r   r   r  )r%   r&   r	   r  r
  s      r4   	score_obszMarkovSwitching.score_obs  s1     &***{nMMMMr6   c                 X    t          j        |d          }t          || j                  S )ar  
        Hessian matrix of the likelihood function, evaluated at the given
        parameters

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the Hessian
            function.
        transformed : bool, optional
            Whether or not `params` is already transformed. Default is True.
        r   r   )r%   r&   r
   r  r
  s      r4   hessianzMarkovSwitching.hessian  s*     &***fdl333r6   approxbfgsd   r   r        ?c                    |
| j         }d}nt          j        |d          }|dk    r|                     |||||          }d}|r#| j        s|                     |||dd          }d}|r|                     |          }d} t                      j        |f||||||	dd	|}|
r| 	                    |j
                  }n=|                     |j
        d
||          }||_        |j        |_        |j        |_        |S )a  
        Fits the model by maximum likelihood via Hamilton filter.

        Parameters
        ----------
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            If None, the default is given by Model.start_params.
        transformed : bool, optional
            Whether or not `start_params` is already transformed. Default is
            True.
        cov_type : str, optional
            The type of covariance matrix estimator to use. Can be one of
            'approx', 'opg', 'robust', or 'none'. Default is 'approx'.
        cov_kwds : dict or None, optional
            Keywords for alternative covariance estimators
        method : str, optional
            The `method` determines which solver from `scipy.optimize`
            is used, and it can be chosen from among the following strings:

            - 'newton' for Newton-Raphson, 'nm' for Nelder-Mead
            - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
            - 'lbfgs' for limited-memory BFGS with optional box constraints
            - 'powell' for modified Powell's method
            - 'cg' for conjugate gradient
            - 'ncg' for Newton-conjugate gradient
            - 'basinhopping' for global basin-hopping solver

            The explicit arguments in `fit` are passed to the solver,
            with the exception of the basin-hopping solver. Each
            solver has several optional arguments that are not the same across
            solvers. See the notes section below (or scipy.optimize) for the
            available arguments and for the list of explicit arguments that the
            basin-hopping solver supports.
        maxiter : int, optional
            The maximum number of iterations to perform.
        full_output : bool, optional
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
        disp : bool, optional
            Set to True to print convergence messages.
        callback : callable callback(xk), optional
            Called after each iteration, as callback(xk), where xk is the
            current parameter vector.
        return_params : bool, optional
            Whether or not to return only the array of maximizing parameters.
            Default is False.
        em_iter : int, optional
            Number of initial EM iteration steps used to improve starting
            parameters.
        search_reps : int, optional
            Number of randomly drawn search parameters that are drawn around
            `start_params` to try and improve starting parameters. Default is
            0.
        search_iter : int, optional
            Number of initial EM iteration steps used to improve each of the
            search parameter repetitions.
        search_scale : float or array, optional.
            Scale of variates for random start parameter search.
        **kwargs
            Additional keyword arguments to pass to the optimizer.

        Returns
        -------
        MarkovSwitchingResults
        NTr   r   r   )start_paramsr   em_iterscale)r   maxiter	tolerancereturn_params)F)methodfargsr  full_outputdispcallbackskip_hessianFr   r   r   )r  r%   r&   _start_params_searchr   _fit_emuntransform_paramsr   r   r   r   r   mlefitmle_retvalsmle_settings)r|   r  r   r   r   r  r  r!  r"  r#  r  r  search_repssearch_itersearch_scalekwargsr   r)  r   r   s                      r4   r   zMarkovSwitching.fit  su   P ,LKK8L:::L ??44,'" 5 $ $L K  	49 	<<+0716: ( < <L K 	A22<@@L \ :&#(%,)4"&*.: :
 39: :  		6**6=99FF [[E*2X ! G GF #FM!'!3F"("5Fr6   2   ư>c	                    |
| j         }d}nt          j        |d          }|s|                     |          }g }
|g}d}d}||k     r|dk     s||k    r|                     |d                   }|
                    |d         j                   |                    |d                    |dk    r8d|
d         |
d         z
  z  t          j        |
d         |
d         z             z  }|dz  }||k     r|dk     ||k    |r	|d         }nw|                     |d         d||	          }|rDt          di t          j        |          t          j        |
          |d
}t          di ||d}nd}d}||_
        ||_        |S )a  
        Fits the model using the Expectation-Maximization (EM) algorithm

        Parameters
        ----------
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            If None, the default is given by `start_params`.
        transformed : bool, optional
            Whether or not `start_params` is already transformed. Default is
            True.
        cov_type : str, optional
            The type of covariance matrix estimator to use. Can be one of
            'approx', 'opg', 'robust', or 'none'. Default is 'none'.
        cov_kwds : dict or None, optional
            Keywords for alternative covariance estimators
        maxiter : int, optional
            The maximum number of iterations to perform.
        tolerance : float, optional
            The iteration stops when the difference between subsequent
            loglikelihood values is less than this tolerance.
        full_output : bool, optional
            Set to True to have all available output in the Results object's
            mle_retvals attribute. This includes all intermediate values for
            parameters and loglikelihood values
        return_params : bool, optional
            Whether or not to return only the array of maximizing parameters.
            Default is False.
        **kwargs
            Additional keyword arguments to pass to the optimizer.

        Notes
        -----
        This is a private method for finding good starting parameters for MLE
        by scoring. It has not been tested for a thoroughly correct EM
        implementation in all cases. It does not support TVTP transition
        probabilities.

        Returns
        -------
        MarkovSwitchingResults
        NTr   r   r   r    r"   rN   r%  )r   llfiter)r  r  rq   )r  r%   r&   r   _em_iterationr   r3  r   r   r   r*  r+  )r|   r  r   r   r   r  r  r!  r  r/  r3  r   rF   deltar  r   
em_retvalsem_settingss                     r4   r'  zMarkovSwitching._fit_emz  s   \ ,LKK8L:::L 	?00>>L 'kkq1uu):):$$VBZ00CJJs1vz"""MM#a&!!!1uuSWs2w./"&R3r79J2K2KKFA 'kkq1uu):):  	.BZFF [[*2X ! G GF  #" 2 20@0@-/Xc]]./&1 &1 2 2
 $ < <I29'; '; < < "
"!+F"-Fr6   c                    t          j        |j        t          j        t           j        |j                            }|                     |dd          }| j        r"|| j        d                  || j        d         <   nD| 	                    |          }t          | j                  D ]}||         || j        |df         <   ||fS )z
        EM iteration

        Notes
        -----
        The EM iteration in this base class only performs the EM step for
        non-TVTP transition probabilities.
        rJ   T)r   r   rV   )r%   r-   r*   r   r   rK   r   r   r   _em_regime_transitionrB   rY   )r|   params0params1r   rV   rF   s         r4   r5  zMarkovSwitching._em_iteration  s     (7=!#!1"*gm!L!LN N N W$4HH 9 	*(;<= DO$7899 !% : :6 B B4>** * *%a( +>(>?@@ wr6   c                 j   |j         }t          |j        dz
            D ]}t          j        |d          }|}t          | j        d                   }t          j        | j        |f          }t          | j                  D ]}t          | j        dz
            D ]C}t          j        |||f                   t          j        |j	        |                   z  |||f<   Dt          j        ||                   dz
  }|dk    r0t          j        dt                     ||xx         d|z   dz   z  cc<   |S )z=
        EM step for regime transition probabilities
        r!   rN   )r   rV   r   r   z|Invalid regime transition probabilities estimated in EM iteration; probabilities have been re-scaled to continue estimation.r1  )rj   rB   r'   r%   rT   r)   r   r-   rY   rk   warningswarnr   )	r|   r   r2   rF   rj   r   rV   rA   r6  s	            r4   r:  z%MarkovSwitching._em_regime_transition  s\    1sx!|$$ 	" 	"A&b//CC'*$ 4?+ABCCHdnl%CDDt~&& 	9 	9A4>A-.. G GF71=>>F6A!DEEF "!Q$'' F,Q/0014Eqyy H 01 1 1 "!$$$E	D(88$$$  r6   c                    |
| j         }d}nt          j        |d          }|r|                     |          }t          j        |d          }|j        dk    rt          j        | j                  |z  }|j        | j        k    st          d          t          j        || j        f          }t          | j                  D ]4}||         t          j
                            dd|          z  |dd|f<   5|                     |d	
          }|}	t          |          D ]}t          j                    5  t          j        d           	 |                     |||         z   d	|d          }
|                     |
          }||k    r|}|                     |
          }	n# t"          $ r Y nw xY wddd           n# 1 swxY w Y   |                     |	          S )a  
        Search for starting parameters as random permutations of a vector

        Parameters
        ----------
        reps : int
            Number of random permutations to try.
        start_params : ndarray, optional
            Starting parameter vector. If not given, class-level start
            parameters are used.
        transformed : bool, optional
            If `start_params` was provided, whether or not those parameters
            are already transformed. Default is True.
        em_iter : int, optional
            Number of EM iterations to apply to each random permutation.
        scale : array or float, optional
            Scale of variates for random start parameter search. Can be given
            as an array of length equal to the number of parameters or as a
            single scalar.

        Notes
        -----
        This is a private method for finding good starting parameters for MLE
        by scoring, where the defaults have been set heuristically.
        NTr   r   zkScale of variates for random start parameter search must be given for each parameter or as a single scalar.g      g      ?)r   Fr   ignore)r   r  r  )r  r%   r&   r(  r   r   ru   rO   r-   rB   randomuniformr  r>  catch_warningssimplefilterr'  	Exceptionr   )r|   repsr  r   r  r  variatesrF   r3  r   proposed_paramsproposed_llfs               r4   r&  z$MarkovSwitching._start_params_search  sT   6 ,LKK8L:::L  	A22<@@L a(((:??GDM**U2EzT]** A B B B
 8T4=122t}%% 	P 	PA"1X	(9(9$$(9(O(OOHQQQTNNll<Ul;;t 	 	A(**  %h///
&*ll$x{2 't '3 '= '=O $(<<#@#@L#c))*!%!8!8!I!I    D                $$V,,,s7   7F>AF"!F>"
F/,F>.F//F>>G	G	c                     t          j        | j        t           j                  }| j        rd|| j        d         <   nd| j        z  || j        d         <   |S )zP
        (array) Starting parameters for maximum likelihood estimation.
        rJ   g        rV   r  )r%   r-   ru   r   r   r   rY   r   s     r4   r  zMarkovSwitching.start_params\  s\    
 $-rz::: 9 	O;=F4?#6788;=;NF4?#678r6   c                 @    t          j         j        t                    } j        r2 fdt           j        dz
            D             | j        d         <   n1 fdt           j        dz
            D             | j        d         <   |                                S )z
        (list of str) List of human readable parameter names (for parameters
        actually included in the model).
        rJ   c                 |    g | ]8}t          j                  D ]!}t          j                  D ]
}d |||fz  "9S )zp[%d->%d].tvtp%d)rB   r   rY   )r<   rF   r   rA   r|   s       r4   r>   z/MarkovSwitching.param_names.<locals>.<listcomp>v  s     A A At{++A A t~..	A A  #aAY.A A A A Ar6   r   rV   c                 L    g | ] }t          j                  D ]	}d ||fz  
!S )z	p[%d->%d])rB   rY   )r<   rF   rA   r|   s      r4   r>   z/MarkovSwitching.param_names.<locals>.<listcomp>}  s\     A0 A0 A0t~..A0 A0  q!f$A0 A0 A0 A0r6   )	r%   r-   ru   objectr   rB   rY   r   r   )r|   r   s   ` r4   r   zMarkovSwitching.param_namesk  s     ht}F;;; 9 	0A A A At~a/00A A AK(;<==A0 A0 A0 A0t~a/00A0 A0 A0K(;<=
 !!###r6   c                    t          j        |d          }|                    t          j        t           j        |j                            }| j        r"|| j        d                  || j        d         <   ntt          | j	                  D ]_}|| j        |df                  }t           j
        d|f         }t          j        |t          |          z
            || j        |df         <   `|S )ac  
        Transform unconstrained parameters used by the optimizer to constrained
        parameters used in likelihood evaluation

        Parameters
        ----------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer, to be
            transformed.

        Returns
        -------
        constrained : array_like
            Array of constrained parameters which may be used in likelihood
            evaluation.

        Notes
        -----
        In the base class, this only transforms the transition-probability-
        related parameters.
        TrR   rV   r   )r%   r&   r   r   r   rK   r   r   rB   rY   r   r/   r   )r|   unconstrainedconstrainedrF   tmp1tmp2s         r4   r   z MarkovSwitching.transform_params  s    , h}4888!((RZ):;;= = 9 
	,do.ABC (;<==
 4>** , ,$T_Q8K5K%LMuQW~GIv9T??*H, H,DOA/B,BCDD
 r6   c                 n   t          j        |j        |j                  }t          j        |          }t          j        |          }t          t          |                    D ]O}||         t          j        d|z   ||         z
            z
  t          j        d||         z  dz
            z   ||<   P|S )zl
        Function to allow using a numerical root-finder to reverse the
        logistic transform.
        rJ   r   )	r%   r-   r*   rK   r/   rT   rB   r)   rP   )r|   rS  rT  residr/   sum_exprF   s          r4   _untransform_logisticz%MarkovSwitching._untransform_logistic  s    
 ,M4GHHHf]##&++s=))** 	8 	8A%a(q7{SV3445q;q>1A5667E!HH r6   c                 h   t          j        |d          }|                    t          j        t           j        |j                            }| j        r"|| j        d                  || j        d         <   nt          | j	                  D ]}| j        |df         }| j	        dk    r%t          j
        d||         z  dz
             ||<   Addlm}  || j        t          j        ||         j        |j                  ||         f	          }|d
         st!          d          |d         ||<   |S )aL  
        Transform constrained parameters used in likelihood evaluation
        to unconstrained parameters used by the optimizer

        Parameters
        ----------
        constrained : array_like
            Array of constrained parameters used in likelihood evaluation, to
            be transformed.

        Returns
        -------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer.

        Notes
        -----
        In the base class, this only untransforms the transition-probability-
        related parameters.
        TrR  rV   r    r  r   r   )rootr  successz!Could not untransform parameters.r0   )r%   r&   r   r   r   rK   r   r   rB   rY   rP   scipy.optimizer\  rZ  r-   r*   rO   )r|   rT  rS  rF   r   r\  r  s          r4   r(  z"MarkovSwitching.untransform_params  sb   * 4888%,,RZ)<==? ? 9 	0DO,?@A $/*=>?? 4>** 0 0OA':$:;>Q&&(*rKN/BQ/F(G(G'GM!$$333333$t9!xa(8(>(5(; =  =%0^$57 7 7C y> N()LMMM'*3xM!$$ r6   )r   NNNNr   )r   r   NNNF)TNNFNN)NNNNT)NTr  Nr  r  r   r   NFr  r   r  r  )NTr   Nr0  r1  TF)NTr  r  )%r   r   r   r   r}   propertyru   r   r   rU   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r   r'  r5  r:  r&  r  r   r   rZ  r(  __classcell__r   s   @r4   r   r     s3        @ HL06*+ *+ *+ *+ *+ *+X ( ( X(+ + +4 4 4 4   8( ( ( (8 (  (  (  (D CG!H6 H6 H6 H6T" " "$" " "= = = =$ HL/3%)89 89 89 89v EI	E 	E 	E 	E P P XP BFGK   & HL/3%)@9 @9 @9 @9D   *< < < <K K K K N N N N 4 4 4 4" AIKLGH(*u u u u u un EKGK#Z Z Z Zx  8 !  !  !D IM.0F- F- F- F-P   X $ $ X$0) ) )V  / / / / / / /r6   r   c                   D    e Zd ZdZd Zed             Zed             ZdS )r   a  
    Results from applying the Hamilton filter to a state space model.

    Parameters
    ----------
    model : Representation
        A Statespace representation

    Attributes
    ----------
    nobs : int
        Number of observations.
    k_endog : int
        The dimension of the observation series.
    k_regimes : int
        The number of unobserved regimes.
    regime_transition : ndarray
        The regime transition matrix.
    initialization : str
        Initialization method for regime probabilities.
    initial_probabilities : ndarray
        Initial regime probabilities
    conditional_loglikelihoods : ndarray
        The loglikelihood values at each time period, conditional on regime.
    predicted_joint_probabilities : ndarray
        Predicted joint probabilities at each time period.
    filtered_marginal_probabilities : ndarray
        Filtered marginal probabilities at each time period.
    filtered_joint_probabilities : ndarray
        Filtered joint probabilities at each time period.
    joint_loglikelihoods : ndarray
        The likelihood values at each time period.
    llf_obs : ndarray
        The loglikelihood values at each time period.
    c           	         || _         |j        | _        |j        | _        |j        | _        g d}|D ]!}t	          | |t          ||                     "|j        | _        | j        | _	        t          j        | j	                  | _        | j        j        d         dk    r&| j        dk    r| j        d| j        d f         | _        d | _        d S )N)rV   rU   rW   r^   r]   r`   r_   r"   r   r   .)modelrZ   r[   rY   setattrgetattrr   initializationr_   llf_obsr%   rT   r3  rV   r*   !_predicted_marginal_probabilities)r|   rf  r   
attributesnames        r4   r}   zHamiltonFilterResults.__init__  s    
J	[
. . .
  	7 	7DD$ 5 56666#306$,'' !'+a//DJNN%)%;C<L%MD" 26...r6   c                     | j         K| j        | _         t          | j         j        dz
            D ]"}t	          j        | j         d          | _         #| j         S )Nr    rN   r#   )rk  r^   rB   r'   r%   rT   )r|   rF   s     r4    predicted_marginal_probabilitiesz6HamiltonFilterResults.predicted_marginal_probabilities/  sm    192 24AFJKK E E9;::E :E :E6655r6   c                 "   t          j        | j                  }t          j        |          }t          j        |dk    d          }dd||          z
  z  || <   t           j        ||<   t           j        ||dk    <   |                                S )zO
        (array) Expected duration of a regime, possibly time-varying.
        r   r#   )r%   diagonalrV   
zeros_likeanynaninfr   )r|   r;   expected_durations
degenerates       r4   rv  z(HamiltonFilterResults.expected_durations9  s     {4122]400VDAIA...
 +,q43D/D*EJ;' *,:&(*419%!))+++r6   N)r   r   r   r   r}   ra  ro  rv  rq   r6   r4   r   r     sd        " "F6 6 68 6 6 X6 , , X, , ,r6   r   c                   "     e Zd ZdZ fdZ xZS )r  a  
    Results from applying the Kim smoother to a Markov switching model.

    Parameters
    ----------
    model : MarkovSwitchingModel
        The model object.
    result : dict
        A dictionary containing two keys: 'smoothd_joint_probabilities' and
        'smoothed_marginal_probabilities'.

    Attributes
    ----------
    nobs : int
        Number of observations.
    k_endog : int
        The dimension of the observation series.
    k_states : int
        The dimension of the unobserved state process.
    c           	          t                                          ||           ddg}|D ]!}t          | |t          ||                     "d S )Nrj   rk   )r   r}   rg  rh  )r|   rf  r   rl  rm  r   s        r4   r}   zKimSmootherResults.__init__f  sd    '''479
  	7 	7DD$ 5 56666	7 	7r6   )r   r   r   r   r}   rb  rc  s   @r4   r  r  Q  sB         (7 7 7 7 7 7 7 7 7r6   r  c                   8   e Zd ZdZdZddZddZed             Zed             Z	ed	             Z
ed
             Zed             Zed             Zed             Zed             Zed             Zed             Zed             Z	 	 ddZddZ	 	 ddZdS )r   a  
    Class to hold results from fitting a Markov switching model

    Parameters
    ----------
    model : MarkovSwitching instance
        The fitted model instance
    params : ndarray
        Fitted parameters
    filter_results : HamiltonFilterResults or KimSmootherResults instance
        The underlying filter and, optionally, smoother output
    cov_type : str
        The type of covariance matrix estimator to use. Can be one of 'approx',
        'opg', 'robust', or 'none'.

    Attributes
    ----------
    model : Model instance
        A reference to the model that was fit.
    filter_results : HamiltonFilterResults or KimSmootherResults instance
        The underlying filter and, optionally, smoother output
    nobs : float
        The number of observations used to fit the model.
    params : ndarray
        The parameters of the model.
    scale : float
        This is currently set to 1.0 and not used by the model or its results.
    FopgNc           	         |j         | _         t          j                            | ||d d           || _        t          |t                    r|| _        nd | _        |j        | _        |j	        | _	        |j
        | _
        t          | d          si | _        || _        i | _        |i }|                    dd          | _        |                    dd          | _        	 d | _         | j        d|dd| ng# t(          j        j        $ rP d	| _        t/          | j                  }t)          j        ||f          t(          j        z  | _        d
| j        d<   Y nw xY wg d}|D ]&}	t9          | |	t;          | j        |	                     'ddg}|D ]?}	| j        %t9          | |	t;          | j        |	                     .t9          | |	d            @| j        j        | _        | j         j        | _         | j        | j!        j        | _!        t          | j         tD                    r| j         j#        }
| j$        j%        dk    r tM          j'        | j$        |
          | _$        tM          j'        | j        |
          | _        tM          j'        | j         |
          | _         | j        $tM          j'        | j!        |
          | _!        d S d S d S )Nr  normalized_cov_paramsr  r   approx_complex_stepTapprox_centeredF)r   use_selfr   zHCovariance matrix could not be calculated: singular. information matrix.r   )	rV   rU   rW   ro  r^   r]   r`   r_   rv  rj   rk   r   )indexrq   )(r   tsbaseTimeSeriesModelResultsr}   filter_results
isinstancer  smoother_resultsrZ   r[   rY   hasattrr   r   _cachepop_cov_approx_complex_step_cov_approx_centered_rank_get_robustcov_resultsr%   r   r   r)   r   r-   rt  cov_params_defaultrg  rh  ro  r.   r]   rk   r   
row_labelsrv  r'   pd	DataFrame)r|   rf  r   r   r   r   r/  ru   rl  rm  r  s              r4   r}   zMarkovSwitchingResults.__init__  s]   J	%..tUFEI57 	/ 	9 	9 	9
 &g122 	)$+D!!$(D! J	[
 tZ(( 	DM   HLL.55 	%$,LL1BE$J$J!
	(DJ'D' 4D 4 4*24 4 4 4y$ 	( 	( 	(DJ4;''H&(h(/C&D&Drv&MD#' M*%%%		(D D D
  	D 	DDD$(;T B BCCCC479
 	* 	*D$0dGD,A4$H$HIIIIdD)))) 13 	- 02 	, ,46 0 di,, 	GI(E&+a//*,,+5+: +: +:'46L5U5D 5D 5DD135<4E4C 4C 4CD0$079|88G 8G 8G444	G 	G 10s    C8 8A!EEc                    ddl m} |                    dd          }|r| }nt          ||_	        i |_
        d}t          | j                  }|dk    r,t          j        d          |_        d|_        d|j
        d	<   nn|d
k    rU|d         |_	        |d         |_        |d         |j
        d	<   t          j                            |j                  |_        n|dk    rJt          j        ||f          t          j        z  |_        t          j        |_        |d         |j
        d	<   n| j	        dk    r1|j        |_        |d                             |          |j
        d	<   n| j	        dk    r1|j        |_        |d                             |          |j
        d	<   nK| j	        dk    r1|j        |_        |d                             |          |j
        d	<   nt          d          |S )Nr   )descriptionsr  Fr}  zcomplex-step)r   r   zNo parameters estimated.descriptioncustomcustom_cov_typecustom_cov_paramscustom_descriptionr   r  )approx_typer{  OPGrobustzInvalid covariance matrix type.)statsmodels.base.covtyper  r  r+   r   rf  r   r~  r  r   r   r)   r%   r-   r  r  r   matrix_rankrt  cov_params_approxformatcov_params_opgcov_params_robust)r|   r   r/  r  r  r  approx_type_strru   s           r4   r  z-MarkovSwitchingResults._get_robustcov_results  s   999999::j%00 	"CC%%  ( t{##q==%'Xf%5%5C"CI*DCL''!!!"34CL%+,?%@C"*01E*FCL'	--c.DEECII%'Xx.B%C%Cbf%LC"CI*6v*>CL'']h&&%(%:C"*6x*@*G*G<K +H +M +MCL'']e##%(%7C"*6u*=*D*D<K +E +M +MCL'']h&&%(%:C"*6x*@*G*G<K +H +M +MCL'' &&GHHH
r6   c                 X    t          | j        | j        | j        j        d                   S )z6
        (float) Akaike Information Criterion
        r   )r   r3  rZ   r   r*   r   s    r4   r   zMarkovSwitchingResults.aic  $     48TY(9!(<===r6   c                 X    t          | j        | j        | j        j        d                   S )z5
        (float) Bayes Information Criterion
        r   )r   r3  rZ   r   r*   r   s    r4   r   zMarkovSwitchingResults.bic"  r  r6   c                     | j                             | j        d          }t          |          \  }}| j        6t
          j                            t          j        |                    | _        | S )z
        (array) The variance / covariance matrix. Computed using the numerical
        Hessian approximated by complex step or finite differences methods.
        TrA  )	rf  r  r   r   r  r%   r   r  r;   )r|   evaluated_hessianneg_covsingular_valuess       r4   r  z(MarkovSwitchingResults.cov_params_approx*  sd     !J..t{.MM#01B#C#C :..rw/G/GHHDJxr6   c                    | j                             | j        d          j        }t	          t          j        ||                    \  }}| j        6t
          j        	                    t          j
        |                    | _        |S )zy
        (array) The variance / covariance matrix. Computed using the outer
        product of gradients method.
        TrA  )rf  r  r   r.   r   r%   innerr  r   r  r;   )r|   r  
cov_paramsr  s       r4   r  z%MarkovSwitchingResults.cov_params_opg8  sw     J(($(GGI	&3HY	**', ',#
O :..rw/G/GHHDJr6   c                 @   | j         }| j                            | j        d          }t	          t          j        t          j        ||          |                    \  }}| j        6t
          j        	                    t          j
        |                    | _        |S )z
        (array) The QMLE variance / covariance matrix. Computed using the
        numerical Hessian as the evaluated hessian.
        TrA  )r  rf  r  r   r   r%   r   r  r   r  r;   )r|   cov_opgr  r  r  s        r4   r  z(MarkovSwitchingResults.cov_params_robustG  s     % J..t{.MM&3F26+W557HII'
 '
#
O :..rw/G/GHHDJr6   c                 @    | j                             | j                  S )zW
        (array) The predicted values of the model. An (nobs x k_endog) array.
        rf  r   r   r   s    r4   fittedvaluesz#MarkovSwitchingResults.fittedvaluesX      
 z!!$+...r6   c                 X    t          | j        | j        | j        j        d                   S )z<
        (float) Hannan-Quinn Information Criterion
        r   )r   r3  rZ   r   r*   r   s    r4   r   zMarkovSwitchingResults.hqic_  s$     DHdi):1)=>>>r6   c                 @    | j                             | j                  S zY
        (float) The value of the log-likelihood function evaluated at `params`.
        )rf  r  r   r   s    r4   rj  zMarkovSwitchingResults.llf_obsg  s    
 z$$T[111r6   c                 @    | j                             | j                  S r  )rf  r  r   r   s    r4   r3  zMarkovSwitchingResults.llfn  r  r6   c                 *    | j         j        | j        z
  S )zI
        (array) The model residuals. An (nobs x k_endog) array.
        )rf  r   r  r   s    r4   rX  zMarkovSwitchingResults.residu  s    
 z$"333r6   c                 4    t          j        | j                  S r   )r%   r/   r_   r   s    r4   joint_likelihoodsz(MarkovSwitchingResults.joint_likelihoods|  s    vd/000r6   c                 J    | j                             | j        ||||          S )a  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.
        probabilities : str or array_like, optional
            Specifies the weighting probabilities used in constructing the
            prediction as a weighted average. If a string, can be 'predicted',
            'filtered', or 'smoothed'. Otherwise can be an array of
            probabilities to use. Default is smoothed.
        conditional : bool or int, optional
            Whether or not to return predictions conditional on current or
            past regimes. If False, returns a single vector of weighted
            predictions. If True or 1, returns predictions conditional on the
            current regime. For larger integers, returns predictions
            conditional on the current regime and some number of past regimes.

        Returns
        -------
        predict : ndarray
            Array of out of in-sample predictions and / or out-of-sample
            forecasts. An (npredict x k_endog) array.
        )r   r   r   r   r  )r|   r   r   r   r   s        r4   r   zMarkovSwitchingResults.predict  s2    H z!!$+U0=.9 " ; ; 	;r6   r   c                     t           )a  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int, str, or datetime, optional
            If an integer, the number of steps to forecast from the end of the
            sample. Can also be a date string to parse or a datetime type.
            However, if the dates index does not have a fixed frequency, steps
            must be an integer. Default
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. See `FilterResults.predict` for more details.

        Returns
        -------
        forecast : ndarray
            Array of out of sample forecasts. A (steps x k_endog) array.
        r   )r|   stepsr/  s      r4   forecastzMarkovSwitchingResults.forecast  s
    ( "!r6   皙?Tc                 4	   ddl m} | j        }|d}|d}| j        j        S| j        j        }||         }	d|	j        |	j        |	j        fz  g}
|d         }	|
dd|	j        |	j        |	j        fz  z   gz  }
n+t          |          dt          | j        j	                  z   g}
||j
        j        }t          |t                    s|g}d	g}|                    d
|d         gf           t          dt!          |                    D ]#}|                    dd||         z   gf           $|ddd|
d         gfd|
d         gfgz  }d| j        j	        gfdd| j        z  gfdd| j        z  gfdd| j        z  gfdd| j        z  gfg}t+          | d          r|                    d| j        gf            |            }|                    | |||           ddlddl m d&fd	}|j        }d t          |j                  D             }i }|j                                        D ]\  }}t!          |          }|dk    rg ||<   t          |          D ]t}||         rAt          | j                  D ]+}||                             |||f         |                    ,K||                             |d|f         |                    ut          | j                  D ]G}||         }t!          |          dk    r* || |d|z            }|j                            |           Hg }|                                D ]\  }}|                    |           t!          |          dk    r' || |d           }|j                            |           |d         } || |d!          }|j                            |           g }t+          | d          r)d"| j         v r |                    | j         d"                    | j!        t!          | j"                  k     r7|                    d#tG          | $                                          z             |rDd$ tK          |          D             }|&                    dd%           |'                    |           |S )'ay  
        Summarize the Model

        Parameters
        ----------
        alpha : float, optional
            Significance level for the confidence intervals. Default is 0.05.
        start : int, optional
            Integer of the start observation. Default is 0.
        title : str, optional
            The title of the summary table.
        model_name : str
            The name of the model used. Default is to use model class name.
        display_params : bool, optional
            Whether or not to display tables of estimated parameters. Default
            is True. Usually only used internally.

        Returns
        -------
        summary : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        r   )SummaryNzMarkov Switching Model Resultsz%02d-%02d-%02dr"   z- z - )zDep. Variable:NzModel:r    z+ )zDate:N)zTime:NzSample:zNo. Observations:zLog Likelihoodz%#5.3fAICBICHQICr   zCovariance Type:)gleftgrighttitle)summary_paramsTc                 D   | | j         |         | j        |         | j        |         | j        |         |                               |         f}fdt          j        | j        j                  |         	                                D             } |d |d|          S )Nc                 >    g | ]}                     d d|          S )z\[\d+\]$r  )sub)r<   rm  res     r4   r>   zFMarkovSwitchingResults.summary.<locals>.make_table.<locals>.<listcomp>  s6       26{B--  r6   F)ynamexnamealphause_tr  )
r   bsetvaluespvaluesconf_intr%   r&   r   r   r   )	r|   maskr  	strip_endr  r   r  r  r  s	         r4   
make_tablez2MarkovSwitchingResults.summary.<locals>.make_table  s    T*DHTN<%t|D'9==''-/C   .//5<<>>  K
 ">#T(-U%I I I Ir6   c                     g | ]}g S rq   rq   rr   s     r4   r>   z2MarkovSwitchingResults.summary.<locals>.<listcomp>"  s    ;;;q;;;r6   rV   zRegime %d parameterszNon-switching parameterszRegime transition parametersr  zmCovariance matrix is singular or near-singular, with condition number %6.3g. Standard errors may be unstable.c                 *    g | ]\  }}d |dz    d| S )[r   z] rq   )r<   rF   texts      r4   r>   z2MarkovSwitchingResults.summary.<locals>.<listcomp>N  s@     6 6 6 D )Q(($(( 6 6 6r6   z	Warnings:r`  )(statsmodels.iolib.summaryr  rf  r   r   monthdayyearr   rZ   r   r   r  listr   rB   r)   r3  r   r   r   r  r   add_table_2colsr  r  r   rY   rw   r   tablesextendr   r  r   r   r  	enumerateinsertadd_extra_txt)r|   r  r   r  
model_namedisplay_paramsr  rf  r   r   sampletop_leftrF   	top_rightsummaryr  r   regime_masksother_masksr   rw   ru   rA   r  table_masketextr  r  s    `                         @@r4   r  zMarkovSwitchingResults.summary  s   : 	655555 
=4E=E9?&IOEeA&!'15!&)AABFb	At.!'15!&1IIIJJFF%jj%#djo*>*>">?F 1J *d++ 	&$J,-JqM?3444q#j//** 	: 	:AOOR$A"6!789999$&)	
 	
 !4:?"3448 345X()*X()*h*+,
	 4$$ 	COO/$-ABBB'))HY&+ 	  	- 	- 	- 				<<<<<<	I 	I 	I 	I 	I 	I 	I 	I !;;E%/$:$:;;;$.4466 	? 	?NC9~~H)))!K8__ ? ?Q< ?"4>22 B B$Q..vaf~a/@AAAAB  $++F1c6N1,=>>>>? t~&& 	- 	-A?D4yy1}}"
4/E/IJJ%%e,,,%++-- 	 	JCKKt99q==JtT+EFFEN!!%((( )*
4'EFFe$$$ 4$$ 	7$-)G)GLL}5666:DK((((LL &(24??3D3D(E(EF G G G  	)6 6$-e$4$46 6 6ELLK(((!!%(((r6   )r{  N)r{  r_  rL   )r  NNNT)r   r   r   r   r  r}   r  r   r   r   r  r  r  r  r   rj  r3  rX  ra  r  r   r  r  rq   r6   r4   r   r   p  s        8 EVG VG VG VGp1 1 1 1f > > ^> > > ^>   ^   ^   ^  / / ^/ ? ? ^? 2 2 ^2 / / ^/ 4 4 ^4 1 1 X1 ;?!&; &; &; &;P" " " ", EI#U U U U U Ur6   r   c                       e Zd ZdddddZ ej        ej        j        e          ZddiZ	 ej        ej        j
        e	          Z
dS )r   cov)r  r  r  r  r  r   N)r   r   r   _attrswrapunion_dictsr  TimeSeriesResultsWrapper_wrap_attrs_methods_wrap_methodsrq   r6   r4   r   r   V  sx        "#"	 F #$"6#B#N#)+ +K 	GH %D$'5xA AMMMr6   r   )>r   r>  numpyr%   pandasr  scipy.specialr   statsmodels.base.datar   statsmodels.base.wrapperbasewrapperr  statsmodels.tools.decoratorsr   statsmodels.tools.eval_measuresr   r   r   statsmodels.tools.numdiffr	   r
   statsmodels.tools.sm_exceptionsr   statsmodels.tools.toolsr   r   statsmodels.tsa.base.tsa_modeltsa	tsa_modelr  1statsmodels.tsa.regime_switching._hamilton_filterr   r   r   r   .statsmodels.tsa.regime_switching._kim_smootherr   r   r   r    statsmodels.tsa.statespace.toolsr   r   r   rS   ri   r5   rG   rg   rl   rn   TimeSeriesModelr   r   r  r  r   ResultsWrapperr   populate_wrapperrq   r6   r4   <module>r     s             # # # # # # , , , , , , ' ' ' ' ' ' ' ' ' 7 7 7 7 7 7 : : : : : : : : : : F F F F F F F F = = = = = = 8 8 8 8 8 8 8 8 / / / / / / / / / / / /                                
$8	$8" "  
!2	!2    4  Dy7 y7 y7xGI GI GITY. Y. Y. Y. Y. Y. Y. Y.x\ \ \ \ \f, \ \ \~ _, _, _, _, _, _, _, _,D7 7 7 7 7. 7 7 7>c c c c cV: c c cLA A A A AD$7 A A A  3,. . . . .r6   