
    M/Ph~                     ,   d Z ddlZddlZddlmZ ddlmZ ddl	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmc mZ  ej        g d	g d
g dg          Z G d de
          Z G d de          Z G d de          Z ej        ee           dS )zL
Recursive least squares model

Author: Chad Fulton
License: Simplified-BSD
    N)Appender)_is_using_pandas)MLEModel
MLEResultsMLEResultsWrapperPredictionResultsPredictionResultsWrapper)concat)Bunch)cache_readonly)g8*?g7F?gp`rȺ?gaG?g!*C
?)g@qogsOpgEqg2rgRѰs)g\bלgRPgZް
YgX<[gc                        e Zd ZdZd fd	Zed fd	            Zd Zd Zd fd	Z	d fd		Z
e fd
            Zed             Zed             Zd Z xZS )RecursiveLSai  
    Recursive least squares

    Parameters
    ----------
    endog : array_like
        The observed time-series process :math:`y`
    exog : array_like
        Array of exogenous regressors, shaped nobs x k.
    constraints : array_like, str, or tuple
            - array : An r x k array where r is the number of restrictions to
              test and k is the number of regressors. It is assumed that the
              linear combination is equal to zero.
            - str : The full hypotheses to test can be given as a string.
              See the examples.
            - tuple : A tuple of arrays in the form (R, q), ``q`` can be
              either a scalar or a length p row vector.

    Notes
    -----
    Recursive least squares (RLS) corresponds to expanding window ordinary
    least squares (OLS).

    This model applies the Kalman filter to compute recursive estimates of the
    coefficients and recursive residuals.

    References
    ----------
    .. [*] Durbin, James, and Siem Jan Koopman. 2012.
       Time Series Analysis by State Space Methods: Second Edition.
       Oxford University Press.
    Nc                    t          |d           }|st          j        |          }t          |d           }|st          j        |          }|j        dk    r#|s|d d d f         }nt          j        |          }|j        d         | _        d| _	        d x| _
        | _        |ddlm} ddlm}  |||fi |}	|	j        }
 ||
                              |          }|j        |j        c| _
        | _        | j
        j        d         | _	        t)          |          }t          j        |t)          | j
                  f          }|r^t          j        ||j                  }t/          ||gd          }t          j        | j        j        |df          |j        d d dd f<   n| j        d d df         |d d dd f<   |                    dd           g d	}|D ]	}||v r||= 
 t9                      j        |f| j        |d
| d| j        _        d| j        _         t          j        | j!        | j"        | j#        f          | d<   | j$        d d d d d f         j        | d<   | j
        | j
        d d d d d f         | ddd d d f<   t          j%        | j"                  | d<   d| d<   t          j%        | j"                  | d<   | j
        	d| _!        d S d S )N   r   )
DesignInfo)handle_data)index)axisinitializationdiffuse)missingmissing_idxformuladesign_info)k_statesexogTdesign)r   r   
transitiong      ?)obs_covr   r   )&r   np
asanyarrayasarrayndimpd	DataFrameshapek_exogk_constraints	_r_matrix	_q_matrixpatsyr   statsmodels.base.datar   param_nameslinear_constraintcoefs	constantslenzerosr   r
   tileTiloc
setdefaultsuper__init__ssmfilter_univariatefilter_concentratedk_endogr   nobsr   eye)selfendogr   constraintskwargsendog_using_pandasexog_is_using_pandasr   r   datanamesLCr=   constraint_endogformula_kwargsname	__class__s                   c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/regression/recursive_ls.pyr8   zRecursiveLS.__init__?   sc   -eT::! 	)M%((E/d;;# 	$:d##D 9>>' *AAAtG}|D))jm *.."((((((999999;ud55f55D$EE""44[AAB-/Xr|*DNDN!%!5a!8Du::D!xs4>/B/B(CDD! 4#%<0@6;k$C $C $C '78qAAA %'GDN,<tQi$H$H
111abb5!!#~aaad3aaae 	*I666 NMM" 	! 	!Dv~~4L 		
 Kd	
 	
6<	
 	
 	

 &*" (,$ 4<	"JKKX IaaaDj13[>%$(N111aaa:$>D122qqq!VDM22\ !#_VDM22\
 >%DLLL &%    c                 \    t          t          |                               ||||          S )N)rA   )r7   r   from_formula)clsr   rE   subsetrA   rK   s        rL   rO   zRecursiveLS.from_formula   s6    Xs##00$=H 1 J J 	JrM   c                      t          d          )NzLinear constraints on coefficients should be given using the `constraints` argument in constructing. the model. Other parameter constraints are not available in the resursive least squares model.)
ValueError)r?   r-   s     rL   _validate_can_fix_paramsz$RecursiveLS._validate_can_fix_params   s     L M M 	MrM   c                     |                      d          }| j                            |j                  5  |                                  }ddd           n# 1 swxY w Y   |S )z
        Fits the model by application of the Kalman filter

        Returns
        -------
        RecursiveLSResults
        T)
return_ssmN)smoothr9   fixed_scalescale)r?   smoother_resultsress      rL   fitzRecursiveLS.fit   s      ;;$;77X!!"2"899 	  	 ++--C	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  
s   AAAFc           	           t                      j        g fdddd|}|sJ|j        d d df         }d|j        d d d d df         dd}t	          t          | ||d|	                    }|S 
NTnone)transformedcov_typerV   	nonrobustz^Parameters and covariance matrix estimates are RLS estimates conditional on the entire sample.)custom_cov_typecustom_cov_paramscustom_descriptioncustom)ra   cov_kwds)r7   filterfiltered_statefiltered_state_covRecursiveLSResultsWrapperRecursiveLSResultsr?   rV   rB   resultparamsrh   rK   s         rL   ri   zRecursiveLS.filter        ;)/+/; ;39; ;
  	*111b51F#.%+%>qqq!!!Rx%H(L H /"4(,46 6 6 F
 rM   c           	           t                      j        g fdddd|}|sJ|j        d d df         }d|j        d d d d df         dd}t	          t          | ||d|	                    }|S r^   )r7   rW   rj   rk   rl   rm   rn   s         rL   rW   zRecursiveLS.smooth   rq   rM   c                 h    t                      j        }t          |t                    r|d         n|S Nr   )r7   endog_names
isinstancelist)r?   ru   rK   s     rL   ru   zRecursiveLS.endog_names   s,    gg)!+K!>!>O{1~~KOrM   c                     | j         S N)
exog_namesr?   s    rL   r-   zRecursiveLS.param_names   s
    rM   c                 *    t          j        d          S rt   )r    r2   r{   s    rL   start_paramszRecursiveLS.start_params   s     x{{rM   c                     dS )a  
        Update the parameters of the model

        Updates the representation matrices to fill in the new parameter
        values.

        Parameters
        ----------
        params : array_like
            Array of new parameters.
        transformed : bool, optional
            Whether or not `params` is already transformed. If set to False,
            `transform_params` is called. Default is True..

        Returns
        -------
        params : array_like
            Array of parameters.
        N )r?   rp   rB   s      rL   updatezRecursiveLS.update   s	    ( 	rM   ry   )NN)F)__name__
__module____qualname____doc__r8   classmethodrO   rT   r\   ri   rW   propertyru   r-   r}   r   __classcell__rK   s   @rL   r   r      sK        @O O O O O Ob J J J J J [JM M M       .     . P P P P XP   X   X      rM   r   c                       e Zd ZdZd f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ed             Zed             Zed             Z eej        j                  	 	 	 dd            Z	 	 	 d dZd!dZ	 	 d"dZd#dZ	 	 d"dZ xZS )$rm   a  
    Class to hold results from fitting a recursive least squares model.

    Parameters
    ----------
    model : RecursiveLS instance
        The fitted model instance

    Attributes
    ----------
    specification : dictionary
        Dictionary including all attributes from the recursive least squares
        model instance.

    See Also
    --------
    statsmodels.tsa.statespace.kalman_filter.FilterResults
    statsmodels.tsa.statespace.mlemodel.MLEResults
    opgc           	          t                      j        ||||fi | t          | j        | j                  }|| j        j        z
  | _        | j        | j        z
  | _	        | j        
                                | _        t          di | j        j        | j        j        d| _        | j        j        ,dD ]+}t!          | |t#          | |          dd                    *d S d S )N)r'   r(   )	forecastsforecasts_errorforecasts_error_covstandardized_forecasts_errorforecasts_error_diffuse_covr   r   r   )r7   r8   maxloglikelihood_burnk_diffuse_statesmodelr(   df_modelnobs_effectivedf_resid_get_init_kwds
_init_kwdsr   r'   specificationr)   setattrgetattr)	r?   r   rp   filter_resultsra   rB   qrJ   rK   s	           rL   r8   zRecursiveLSResults.__init__  s   6>8	
 	
7=	
 	
 	
 ')>??DJ44+dm; *3355 # 8 8j'!Z5&7 &7 8 8
 :+8 > > dGD$$7$7!$<====	 ,+> >rM   c                    d}| j         }dx}}||j        z   }t          | j        ||         | j        ||||f         dd|          }| j        | j        ||         |_        | j        | j        ||||f         |_        |S )a7  
        Estimates of regression coefficients, recursively estimated

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nr   )filteredfiltered_covsmoothedsmoothed_covoffset)	r   r'   r   rj   rk   smoothed_stater   smoothed_state_covr   )r?   outspecstartr   ends         rL   recursive_coefficientsz)RecursiveLSResults.recursive_coefficients-  s    * !t{"(s30sE#I1EF	
 
 
 *.uSy9CL".'c	59(<= 
rM   c                 <    | j         j        d         | j        dz  z  S )a  
        Recursive residuals

        Returns
        -------
        resid_recursive : array_like
            An array of length `nobs` holding the recursive
            residuals.

        Notes
        -----
        These quantities are defined in, for example, Harvey (1989)
        section 5.4. In fact, there he defines the standardized innovations in
        equation 5.4.1, but in his version they have non-unit variance, whereas
        the standardized forecast errors computed by the Kalman filter here
        assume unit variance. To convert to Harvey's definition, we need to
        multiply by the standard deviation.

        Harvey notes that in smaller samples, "although the second moment
        of the :math:`\tilde \sigma_*^{-1} \tilde v_t`'s is unity, the
        variance is not necessarily equal to unity as the mean need not be
        equal to zero", and he defines an alternative version (which are
        not provided here).
        r         ?)r   r   rY   r{   s    rL   resid_recursivez"RecursiveLSResults.resid_recursiveS  s%    4 #@C
C  	!rM   c                     t          | j        | j                  }t          j        | j        |d                   t          j        | j        |d         d          z  S )a  
        Cumulative sum of standardized recursive residuals statistics

        Returns
        -------
        cusum : array_like
            An array of length `nobs - k_exog` holding the
            CUSUM statistics.

        Notes
        -----
        The CUSUM statistic takes the form:

        .. math::

            W_t = \frac{1}{\hat \sigma} \sum_{j=k+1}^t w_j

        where :math:`w_j` is the recursive residual at time :math:`j` and
        :math:`\hat \sigma` is the estimate of the standard deviation
        from the full sample.

        Excludes the first `k_exog` datapoints.

        Due to differences in the way :math:`\hat \sigma` is calculated, the
        output of this function differs slightly from the output in the
        R package strucchange and the Stata contributed .ado file cusum6. The
        calculation in this package is consistent with the description of
        Brown et al. (1975)

        References
        ----------
        .. [*] Brown, R. L., J. Durbin, and J. M. Evans. 1975.
           "Techniques for Testing the Constancy of
           Regression Relationships over Time."
           Journal of the Royal Statistical Society.
           Series B (Methodological) 37 (2): 149-92.
        Nr   )ddof)r   nobs_diffuser   r    cumsumr   stdr?   ds     rL   cusumzRecursiveLSResults.cusump  s[    N !4#:;;	$.qrr233t+ABB/a8889 	:rM   c                     t          | j        | j                  }t          j        | j        |d         dz            }|d         }||z  S )a  
        Cumulative sum of squares of standardized recursive residuals
        statistics

        Returns
        -------
        cusum_squares : array_like
            An array of length `nobs - k_exog` holding the
            CUSUM of squares statistics.

        Notes
        -----
        The CUSUM of squares statistic takes the form:

        .. math::

            s_t = \left ( \sum_{j=k+1}^t w_j^2 \right ) \Bigg /
                  \left ( \sum_{j=k+1}^T w_j^2 \right )

        where :math:`w_j` is the recursive residual at time :math:`j`.

        Excludes the first `k_exog` datapoints.

        References
        ----------
        .. [*] Brown, R. L., J. Durbin, and J. M. Evans. 1975.
           "Techniques for Testing the Constancy of
           Regression Relationships over Time."
           Journal of the Royal Statistical Society.
           Series B (Methodological) 37 (2): 149-92.
        N   rb   )r   r   r   r    r   r   )r?   r   numerdenoms       rL   cusum_squaresz RecursiveLSResults.cusum_squares  sM    B !4#:;;	$.qrr2A566b	u}rM   c                 |    ddl m} t          j        |                    | j        d| j        dz                      S )zY
        (float) Loglikelihood at observation, computed from recursive residuals
        r   normr   )locrY   )scipy.statsr   r    logpdfr   rY   )r?   r   s     rL   llf_recursive_obsz$RecursiveLSResults.llf_recursive_obs  sO    
 	%$$$$$vdhht3%)Z_  6 6 7 7 	7rM   c                 4    t          j        | j                  S )zY
        (float) Loglikelihood defined by recursive residuals, equivalent to OLS
        )r    sumr   r{   s    rL   llf_recursivez RecursiveLSResults.llf_recursive  s    
 vd,---rM   c                 p    t          | j        | j                  }| j        |z
  | j        j        d         z  S )ssr)r   r   r   )r   r   r   r=   r   r   r   s     rL   r   zRecursiveLSResults.ssr  s5     !4#:;;	A!4!<W!EEErM   c                     t          j        | j        j        d         t          j        | j        j                  z
  dz            S )zCentered tssr   r   )r    r   r   r@   meanr{   s    rL   centered_tsszRecursiveLSResults.centered_tss  sE     vt*03wt2899:<=> ? ? 	?rM   c                 P    t          j        | j        j        d         dz            S )zuncentered tssr   r   )r    r   r   r@   r{   s    rL   uncentered_tssz!RecursiveLSResults.uncentered_tss  s$     vt*03a7888rM   c                 L    | j         r| j        | j        z
  S | j        | j        z
  S )ess)
k_constantr   r   r   r{   s    rL   r   zRecursiveLSResults.ess  s.     ? 	2$tx//&11rM   c                 X    | j         rd| j        | j        z  z
  S d| j        | j        z  z
  S )rsquaredr   )r   r   r   r   r{   s    rL   r   zRecursiveLSResults.rsquared  s8     ? 	6tx$"3333tx$"5555rM   c                      | j         | j        z  S )	mse_model)r   r   r{   s    rL   r   zRecursiveLSResults.mse_model       x$-''rM   c                      | j         | j        z  S )	mse_resid)r   r   r{   s    rL   r   zRecursiveLSResults.mse_resid  r   rM   c                 l    | j         r| j        | j        | j        z   z  S | j        | j        | j        z   z  S )	mse_total)r   r   r   r   r   r{   s    rL   r   zRecursiveLSResults.mse_total  s=     ? 	I$(EFF&$-$-*GHHrM   NF	predictedc                    || j         j        d         }| j                             |||          \  }}}}	t          |t          t
          f          r| j                             |          \  }}
}
| j         j        |s|rt          d           | j	        j
        |||z   dz   |fi |}t          | ||||	          }t          |          S )Nr   zRCannot yet perform out-of-sample or dynamic prediction in models with constraints.r   )information_setsignal_only
row_labels)r   _index_get_prediction_indexrv   bytesstr_get_index_locr)   NotImplementedErrorr   predictr   r	   )r?   r   r   dynamicr   r   r   rB   out_of_sampleprediction_index_prediction_resultsres_objs                rL   get_predictionz!RecursiveLSResults.get_prediction  s    =J%a(E J,,UC?? 	4sM#3 gs|,, 	? J55g>>MGQ:++'+% '6 7 7 7 9T083&*G? ?7=? ? $D*<4C0;/?A A A (000rM   r   皙?
upper leftc                    t          |t          t          f          r|g}t          |          }| j        j        }t          |          D ]7}||         }	t          |	t                    r|                    |	          ||<   8ddlm	}
 ddl
m}m}  |            } |||          }t          |          D ].}||         }	|                    |d|dz             }t          | j        d          r+| j        j        | j        j                                        }nt%          j        | j                  }t+          | j        | j                  }| j        }|                    ||d         |j        |	|df         d||	         z             |                                \  }}||
                    d|d	z  z
            }t%          j        |j        |	|	ddf                   }|j        |	         ||z  z
  }|j        |	         ||z  z   }|                    ||d         ||d         ||d         d
          }dd|z
  dz  z  }|dk    r[|                     ddd|!                                d                   }|"                    |           |"                    |           |#                    |||           ||dz
  k     r|j$        %                    g            0|&                                 |S )a+  
        Plot the recursively estimated coefficients on a given variable

        Parameters
        ----------
        variables : {int, str, list[int], list[str]}, optional
            Integer index or string name of the variable whose coefficient will
            be plotted. Can also be an iterable of integers or strings. Default
            is the first variable.
        alpha : float, optional
            The confidence intervals for the coefficient are (1 - alpha) %
        legend_loc : str, optional
            The location of the legend in the plot. Default is upper left.
        fig : Figure, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        All plots contain (1 - `alpha`) %  confidence intervals.
        r   r   _import_mplcreate_mpl_figr   datesNzRecursive estimates: %slabelg       @g?alphaz$%.3g \%%$ confidence intervald   )r   r   )fcr   )'rv   intr   r1   r   rz   ranger   r   r   statsmodels.graphics.utilsr   r   add_subplothasattrrE   r   	_mpl_reprr    aranger=   r   r   r   r   plotr   get_legend_handles_labelsppfsqrtr   fill_between	Rectangleget_facecolorappendlegendxaxisset_ticklabelstight_layout)r?   	variablesr   
legend_locfigfigsizek_variablesrz   ivariabler   r   r   pltaxr   r   coefhandleslabelscritical_value
std_errorsci_lowerci_upperci_polyci_labelps                              rL   plot_recursive_coefficientz-RecursiveLSResults.plot_recursive_coefficient'  sM   : i#s,, 	$"I)nn Z*
{## 	: 	:A |H(C(( :)//99	! 	%$$$$$JJJJJJJJkmmnS'**{## 1	, 1	,A |HaQ77B ty'** -ty/J	1133	$),,D%t'>??A .DGGE!""It}Xqrr\:3j6JJ  L L L !::<<OGV  !%!ebj.!9!9  WT%6x1117L%MNN
M(+nz.II  M(+nz.II //!""Ix|Xabb\ *   > !E	30 66 fa)0)>)>)@)@)C & E EA NN1%%%MM(+++IIgv:I666 ;?""''+++
rM   c                 &   |dk    rdn!|dk    rdn|dk    rdnt          d          t          | j        | j                  | j        z
  |z
  dz  fd	}|t          j        | j        g          } ||            ||          fS )
a  
        Parameters
        ----------
        alpha : float, optional
            The significance bound is alpha %.
        ddof : int, optional
            The number of periods additional to `k_exog` to exclude in
            constructing the bounds. Default is zero. This is usually used
            only for testing purposes.
        points : iterable, optional
            The points at which to evaluate the significance bounds. Default is
            two points, beginning and end of the sample.

        Notes
        -----
        Comparing against the cusum6 package for Stata, this does not produce
        exactly the same confidence bands (which are produced in cusum6 by
        lw, uw) because they burn the first k_exog + 1 periods instead of the
        first k_exog. If this change is performed
        (so that `tmp = (self.nobs - d - 1)**0.5`), then the output here
        matches cusum6.

        The cusum6 behavior does not seem to be consistent with
        Brown et al. (1975); it is likely they did that because they needed
        three initial observations to get the initial OLS estimates, whereas
        we do not need to do that.
        {Gz?g}?5^I?r   gtV?皙?gffffff?Invalid significance level.r   c                 ,    z  dz  | z
  z  z  z   S )Nr   r   )xr   scalartmps    rL   
upper_linezARecursiveLSResults._cusum_significance_bounds.<locals>.upper_line  s$    C<!f*A"6"<<<rM   )rS   r   r   r   r=   r    array)r?   r   r   pointsr*  r   r(  r)  s        @@@rL   _cusum_significance_boundsz-RecursiveLSResults._cusum_significance_bounds  s    : D==FFd]]FFd]]FF:;;; !4#:;;y1}t#c)	= 	= 	= 	= 	= 	= 	= >Xq$)n--F
6"""JJv$6$666rM   c                    ddl m}m}  |              |||          }|                    ddd          }t	          | j        d          r+| j        j        | j        j                                        }nt          j	        | j
                  }t          | j        | j                  }	|                    ||	d         | j        d           |                    d||	         |d         d	d
           |                     |          \  }
}|                    ||	         |d         g|dd|dz  z             |                    ||	         |d         g|
d           |                    |           |S )ax  
        Plot the CUSUM statistic and significance bounds.

        Parameters
        ----------
        alpha : float, optional
            The plotted significance bounds are alpha %.
        legend_loc : str, optional
            The location of the legend in the plot. Default is upper left.
        fig : Figure, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        Evidence of parameter instability may be found if the CUSUM statistic
        moves out of the significance bounds.

        References
        ----------
        .. [*] Brown, R. L., J. Durbin, and J. M. Evans. 1975.
           "Techniques for Testing the Constancy of
           Regression Relationships over Time."
           Journal of the Royal Statistical Society.
           Series B (Methodological) 37 (2): 149-92.
        r   r   r   r   NCUSUMr   rb   k333333?)colorr   k--%d%% significancer   r   )r   r   r   r   r   rE   r   r   r    r  r=   r   r   r   r  r   hlinesr-  r
  )r?   r   r  r  r  r   r   r  r   r   
lower_liner*  s               rL   
plot_cusumzRecursiveLSResults.plot_cusum  s   B 	KJJJJJJJnS'**__Q1%% 49g&& 	)49?+FIO--//EEIdi((E!4#:;; 	abb	4:W555
		!U1XuRy3	??? "&!@!@!G!G
J
q59%z5)US[9 	 	; 	; 	;
q59%z5999
		j	!!!
rM   c                    t          | j        | j                  }d| j        |z
  z  dz
  }	 g d                    |dz            }n# t
          $ r t          d          w xY wt          dd|f         }|d         |dz  z  |d         |z  z   |d         |dz  z  z   }|t          j        || j        g          }||z
  | j        |z
  z  }||z
  ||z   fS )	a  
        Notes
        -----
        Comparing against the cusum6 package for Stata, this does not produce
        exactly the same confidence bands (which are produced in cusum6 by
        lww, uww) because they use a different method for computing the
        critical value; in particular, they use tabled values from
        Table C, pp. 364-365 of "The Econometric Analysis of Time Series"
        Harvey, (1990), and use the value given to 99 observations for any
        larger number of observations. In contrast, we use the approximating
        critical values suggested in Edgerton and Wells (1994) which allows
        computing relatively good approximations for any number of
        observations.
        r   r   )r$  r   g?r#  g{Gzt?r   r%  Nr   g      ?)	r   r   r   r=   r   rS   _cusum_squares_scalarsr    r+  )	r?   r   r,  r   nixscalarscritlines	            rL   "_cusum_squares_significance_boundsz5RecursiveLSResults._cusum_squares_significance_bounds  s   " !4#:;;49q=!A%	<00066uqyAABB 	< 	< 	<:;;;	<(B/qzAsF"WQZ!^3gaj1c66II >Xq$)n--F
ty1}-d{D4K''s   A A!c                 2   ddl m}m}  |              |||          }|                    ddd          }t	          | j        d          r+| j        j        | j        j                                        }nt          j	        | j
                  }t          | j        | j                  }	|                    ||	d         | j        d           t          j	        |	| j
                  |	z
  | j
        |	z
  z  }
|                    ||	d         |
dd	
           |                     |          \  }}|                    ||	         |d         g|dd|dz  z             |                    ||	         |d         g|d           |                    |           |S )a  
        Plot the CUSUM of squares statistic and significance bounds.

        Parameters
        ----------
        alpha : float, optional
            The plotted significance bounds are alpha %.
        legend_loc : str, optional
            The location of the legend in the plot. Default is upper left.
        fig : Figure, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        Evidence of parameter instability may be found if the CUSUM of squares
        statistic moves out of the significance bounds.

        Critical values used in creating the significance bounds are computed
        using the approximate formula of [1]_.

        References
        ----------
        .. [*] Brown, R. L., J. Durbin, and J. M. Evans. 1975.
           "Techniques for Testing the Constancy of
           Regression Relationships over Time."
           Journal of the Royal Statistical Society.
           Series B (Methodological) 37 (2): 149-92.
        .. [1] Edgerton, David, and Curt Wells. 1994.
           "Critical Values for the Cusumsq Statistic
           in Medium and Large Sized Samples."
           Oxford Bulletin of Economics and Statistics 56 (3): 355-65.
        r   r   r   r   NzCUSUM of squaresr   r0  r1  r   rb   r3  r4  r   r   )r   r   r   r   r   rE   r   r   r    r  r=   r   r   r   r  r   r?  r
  )r?   r   r  r  r  r   r   r  r   r   ref_liner6  r*  s                rL   plot_cusum_squaresz%RecursiveLSResults.plot_cusum_squares  s   P 	KJJJJJJJnS'**__Q1%% 49g&& 	)49?+FIO--//EEIdi((E!4#:;; 	abb	4-5GHHHIa++a/DIMB
abb	8S444 "&!H!H!O!O
J
q59%z5)US[9 	 	; 	; 	;
q59%z5999
		j	!!!
rM   )r   )NNFr   FN)r   r   r   NN)r   N)r   r   NNry   )r   r   r   r   r8   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r!  r-  r7  r?  rB  r   r   s   @rL   rm   rm      s        (> > > > > >6 # # X#J ! ! ^!8 (: (: ^(:T # # ^#J 7 7 ^7 . . ^. F F ^F
 ? ? ^?
 9 9 ^9 2 2 ^2 6 6 ^6 ( ( ^( ( ( ^( I I ^I Xj'/00;@@E! 1  1  1 10 1D =A@D+/c c c cJ/7 /7 /7 /7b 1=%)9 9 9 9v( ( ( (B 9E-1A A A A A A A ArM   rm   c                   n    e Zd Zi Z ej        ej        e          Zi Z ej        ej	        e          Z	dS )rl   N)
r   r   r   _attrswrapunion_dictsr   _wrap_attrs_methods_wrap_methodsr   rM   rL   rl   rl   ]  sR        F"$"#4#@#)+ +KH$D$%6%D%-/ /MMMrM   rl   )r   numpyr    pandasr$   statsmodels.compat.pandasr   statsmodels.tools.datar   #statsmodels.tsa.statespace.mlemodelr   r   r   r   r	    statsmodels.tsa.statespace.toolsr
   statsmodels.tools.toolsr   statsmodels.tools.decoratorsr   statsmodels.base.wrapperbasewrapperrE  r+  r9  r   rm   rl   populate_wrapperr   rM   rL   <module>rV     s            . . . . . . 3 3 3 3 3 3              4 3 3 3 3 3 ) ) ) ) ) ) 7 7 7 7 7 7 ' ' ' ' ' ' ' ' ' "@@@@@@@@@#   \ \ \ \ \( \ \ \~]	 ]	 ]	 ]	 ]	 ]	 ]	 ]	@/ / / / / 1 / / /  /(* * * * *rM   