
    M/Ph@                         d Z ddlZddlmc mZ ddlmZ  G d dej	                  Z
 G d dej                  Z G d d	ej                  Z ej        ee           dS )
zH
Markov switching regression models

Author: Chad Fulton
License: BSD-3
    N)markov_switchingc                        e Zd ZdZ	 	 	 	 d fd	Zd	 Zd
 Zd Zed             Z	 fdZ
ddZddZed             Zed             Z fdZ fdZ xZS )MarkovRegressiona  
    First-order k-regime Markov switching regression model

    Parameters
    ----------
    endog : array_like
        The endogenous variable.
    k_regimes : int
        The number of regimes.
    trend : {'n', 'c', 't', 'ct'}
        Whether or not to include a trend. To include an intercept, time trend,
        or both, set `trend='c'`, `trend='t'`, or `trend='ct'`. For no trend,
        set `trend='n'`. Default is an intercept.
    exog : array_like, optional
        Array of exogenous regressors, shaped nobs x k.
    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.
    switching_trend : bool or iterable, optional
        If a boolean, sets whether or not all trend coefficients are
        switching across regimes. If an iterable, should be of length equal
        to the number of trend variables, where each element is
        a boolean describing whether the corresponding coefficient is
        switching. Default is True.
    switching_exog : bool or iterable, optional
        If a boolean, sets whether or not all regression coefficients are
        switching across regimes. If an iterable, should be of length equal
        to the number of exogenous variables, where each element is
        a boolean describing whether the corresponding coefficient is
        switching. Default is True.
    switching_variance : bool, optional
        Whether or not there is regime-specific heteroskedasticity, i.e.
        whether or not the error term has a switching variance. Default is
        False.

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

    The model can be written as:

    .. math::

        y_t = a_{S_t} + x_t' \beta_{S_t} + \varepsilon_t \\
        \varepsilon_t \sim N(0, \sigma_{S_t}^2)

    i.e. the model is a dynamic linear regression where the coefficients and
    the variance of the error term may be switching across regimes.

    The `trend` is accommodated by prepending columns to the `exog` array. Thus
    if `trend='c'`, the passed `exog` array should not already have a column of
    ones.

    See the notebook `Markov switching dynamic regression
    <../examples/notebooks/generated/markov_regression.html>`__ for an
    overview.

    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.
    cNr   TFnonec           
      <   ddl m}  ||dd          | _        || _        || _        |	| _        t          j        |          \  | _        }t          |          }d| _
        | j        | _        d }|dk    rt          j        |df          }d| _
        n|dk    r3t          j        |          dz   d d t          j        f         }d| _
        n^|d	k    rXt          j        t          j        |df          t          j        |          dz   d d t          j        f         f         }d
| _
        |-||nt          j        ||f         }| xj        | j
        z  c_        t#                                          ||||||
||           | j        du s	| j        du r| j        g| j
        z  | _        n,t          | j                  | j
        k    st'          d          | j        du s	| j        du r| j        g| j        z  | _        n,t          | j                  | j        k    st'          d          t          j        | j        | j        f                             t,                                                    | _        | j        | j        d<   | j        rdgndg| j        d<   d S )Nr   )string_liketrend)nr   ctt)optionsr      r   r      )order	exog_tvtpexogdatesfreqmissingTFz-Invalid iterable passed to `switching_trend`.z,Invalid iterable passed to `switching_exog`.r   variance)statsmodels.tools.validationr	   r
   switching_trendswitching_exogswitching_variancer   prepare_exogk_exoglenk_trend_k_exognponesarangenewaxisc_super__init__
ValueErrorr_astypebooltolistswitching_coeffs
parameters)selfendog	k_regimesr
   r   r   r   r   r   r   r   r   r   r	   nobs
trend_exog	__class__s                   r/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/regime_switching/markov_regression.pyr'   zMarkovRegression.__init__V   s    	=<<<<< [9NOOO
.,"4 -9$??T 5zz{
C<<$++JDLLc\\)D//A-qqq"*}=JDLLd]]rway11 "	$! 3QQQ
]C D EJDL!!%::25T9I3JDLLDL(LL 	9EYTdG 	 	5 	5 	5
 4''4+?5+H+H$($8#9DL#HD  T)**dl::LMMM$&&$*=*F*F#'#6"7$+"EDT())T[88KLLL E$&%& ''-vd||FFHH 	
 #'"7-1-D&Mqcc1#
###    c                 B   t          j        |d          }t          j        | j        | j        f|j                  }t          | j                  D ]?}| j        dk    r2|| j        |df                  }t          j	        | j
        |          ||<   @|dddddf         S )aj  
        In-sample prediction, conditional on the current regime

        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   )ndmindtyper   r   N)r!   arrayzerosr1   r2   r:   ranger    r.   dotr   )r/   paramspredicticoeffss        r5   predict_conditionalz$MarkovRegression.predict_conditional   s     &*** (DNDI6flKKKt~&& 	7 	7A|a6	 :;VDIv66
qqq$z""r6   c                 t    t          j        |                     |          | j        d          }| j        |z
  S )Nr   )axis)r!   repeatrC   r1   r0   )r/   r?   r@   s      r5   _residzMarkovRegression._resid   s<    )D44V<< N4 4 4zG##r6   c                 (   |                      |          }|| j        d                                                  }| j        rt	          j        || j        ddf          }d|dz  z  |z  dt	          j        dt          j        z  |z            z  z
  }|S )zS
        Compute loglikelihoods conditional on the current period's regime
        r   r   g      r         ?)	rG   r.   squeezer   r!   reshaper1   logpi)r/   r?   residr   conditional_loglikelihoodss        r5   _conditional_loglikelihoodsz,MarkovRegression._conditional_loglikelihoods   s     F## $/*56>>@@" 	Dz(T^Q,BCCH 5!8Oh&rva"%i(6J/K/K)KK 	# *)r6   c                 "    dt           t          fiS )Nfit)MarkovRegressionResultsMarkovRegressionResultsWrapper)r/   s    r5   _res_classeszMarkovRegression._res_classes   s    /68 9 	9r6   c                    t                                          |          \  }}t          j        |j                  }d}| j        dk    rb|                     || j        | j        | j	        j
        d         |          }t          | j                  D ]}||         || j	        |df         <   |                     || j        | j        ||          || j	        d         <   ||fS )z
        EM iteration

        Notes
        -----
        This uses the inherited _em_iteration method for computing the
        non-TVTP transition probabilities and then performs the EM step for
        regression coefficients and variances.
        Nr   r   r   )r&   _em_iterationr!   sqrtsmoothed_marginal_probabilitiesr    _em_exogr0   r   r.   	switchingr=   r1   _em_variance)r/   params0resultparams1tmprB   rA   r4   s          r5   rW   zMarkovRegression._em_iteration   s      ''//88gf<== <!]]64:ty#'?#<V#DcK KF4>** @ @6<Qi6	233 04/@/@DJ	6308 08
+, wr6   c                    |j         d         }t          j        | j        |f          }t          j        |          sa|dd| f         }t          j        t          j                            |          |          }	|	|dd| f<   |t          j        ||	          z
  }t          j        |          r|dd|f         }
|t          j	        |j
                  }t          | j                  D ]c}||         |z  }||         ddt          j        f         |
z  }t          j        t          j                            |          |          |||f<   d|S )z5
        EM step for regression coefficients
        r   N)shaper!   r<   r1   allr>   linalgpinvanyrX   rY   r=   r$   )r/   r^   r0   r   r[   r`   r   rB   nonswitching_exognonswitching_coeffsr   rA   	tmp_endogtmp_exogs                 r5   rZ   zMarkovRegression._em_exog   sV    A4>6233 vi   	K $QQQ
] 3ry~~&788%@@  $7F111yj=!BF#46IJJJE 6) 	A!!!!Y,/N{gfDEE4>** A AFUN	q6!!!RZ-0>AF29>>(33Y?? q)|$$ r6   c                    |dn|j         d         }| j        rt          j        | j                  }t          | j                  D ]q}|dk    r|t          j        |||                   z
  }	n|}	t          j        |	dz  |j        |         z            t          j        |j        |                   z  ||<   rnd}|t          j	        |j                  }t          | j                  D ]m}||         |z  }
|dk    r>||         ddt          j
        f         |z  }|
t          j        |||                   z
  }	n|
}	|t          j        |	dz            z  }n|| j        z  }|S )z'
        EM step for variances
        Nr   r   r   )rb   r   r!   r<   r1   r=   r>   sumrY   rX   r$   r2   )r/   r^   r0   r   betasr`   r   r   rA   rN   ri   rj   s               r5   r\   zMarkovRegression._em_variance  s    l
1" 	"x//H4>** G GA::!BF4q$:$::EE!EF5!8!A!DE F FF6A!DEEF G H{gfDEE4>** - -FUN	A::"1vaaam4t;H%xq(B(BBEE%EBF5!8,,,	!Hr6   c                    t           j        j                            |           }| j        dk    rt          j        t
          j                            | j	                  | j
                  }t          j        | j
        t          j        | j	        |          z
            }t          j        | j                  r5t          | j                  D ]}||| j        z  z  || j        |df         <    n*||| j        d         <   nt          j        | j
                  }| j        r.t          j        |dz  || j                  || j        d         <   n||| j        d         <   |S )a   
        (array) Starting parameters for maximum likelihood estimation.

        Notes
        -----
        These are not very sophisticated and / or good. We set equal transition
        probabilities and interpolate regression coefficients between zero and
        the OLS estimates, where the interpolation is based on the regime
        number. We rely heavily on the EM algorithm to quickly find much better
        starting parameters, which are then used by the typical scoring
        approach.
        r   r   g      $@)numr   )r   MarkovSwitchingstart_paramsfgetr    r!   r>   rd   re   r   r0   varrf   r-   r=   r1   r.   r   linspace)r/   r?   betar   rA   s        r5   rq   zMarkovRegression.start_params"  sG    "1>CCDII <!6")..33TZ@@Dvdj26$)T+B+BBCCHvd+,, 7t~.. 5 5ADN 23 4?1f95665 37tv.//vdj))H " 	;HsNH$.III 4?:.// 3;F4?:./r6   c                     t          j        t          j        j                            |           t                    }t          j        | j                  r;t          | j
                  D ]%fd| j        D             || j        df         <   &n| j        || j        d         <   | j        r-t          | j
                  D ]dz  || j        df         <   nd|| j        d         <   |                                S )z
        (list of str) List of human readable parameter names (for parameters
        actually included in the model).
        r9   c                     g | ]	}d |fz  
S )z%s[%d] ).0	exog_namerA   s     r5   
<listcomp>z0MarkovRegression.param_names.<locals>.<listcomp>X  s5     ;P ;P ;P2;H	1~-;P ;P ;Pr6   r   z
sigma2[%d]r   sigma2)r!   r;   r   rp   param_namesrr   objectrf   r-   r=   r1   
exog_namesr.   r   r,   )r/   r}   rA   s     @r5   r}   zMarkovRegression.param_namesJ  s9    h,8==dCC  
 6$'(( 	C4>** P P;P ;P ;P ;P?C;P ;P ;PDOAvI677P 48?K/0 " 	@4>** O O>JQ>NDOAzM:;;O 8@K
34!!###r6   c                     t                                          |          }|| j        d                  || j        d         <   || j        d                  dz  || j        d         <   |S )a  
        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.
        r   r   r   )r&   transform_paramsr.   )r/   unconstrainedconstrainedr4   s      r5   r   z!MarkovRegression.transform_paramsf  sr    $ gg.. 
 $/&12 	DOF+,
 $/*569 	DOJ/0 r6   c                     t                                          |          }|| j        d                  || j        d         <   || j        d                  dz  || j        d         <   |S )a  
        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.
        r   r   rI   )r&   untransform_paramsr.   )r/   r   r   r4   s      r5   r   z#MarkovRegression.untransform_params  sr    " 22 
 /0 	dof-.
 
34c9 	doj12 r6   )
r   Nr   NTTFNNr   )N)__name__
__module____qualname____doc__r'   rC   rG   rP   propertyrU   rW   rZ   r\   rq   r}   r   r   __classcell__)r4   s   @r5   r   r      sT       F FP FGFJ<@7N 7N 7N 7N 7N 7Nr# # #:$ $ $
* * *$ 9 9 X9    <   8   @ % % X%N $ $ X$6    >        r6   r   c                       e Zd ZdZdS )rS   a  
    Class to hold results from fitting a Markov switching regression model

    Parameters
    ----------
    model : MarkovRegression 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.
    N)r   r   r   r   rx   r6   r5   rS   rS     s         8 	Dr6   rS   c                       e Zd ZdS )rT   N)r   r   r   rx   r6   r5   rT   rT     s        Dr6   rT   )r   numpyr!   statsmodels.base.wrapperbasewrapperwrap statsmodels.tsa.regime_switchingr   rp   r   MarkovSwitchingResultsrS   MarkovSwitchingResultsWrapperrT   populate_wrapperrx   r6   r5   <module>r      s        ' ' ' ' ' ' ' ' ' = = = = = =T T T T T'7 T T Tn	 	 	 	 	.E 	 	 	@	 	 	 	 	6	 	 	  4-/ / / / /r6   