
    !gZ                    X   d dl mZ d dlm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Z d dlmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZmZmZmZ g dZd#dZd$dZd%dZ	 	 	 d&	 	 	 	 	 	 	 	 	 d'dZ 	 d(dZ!d Z"d Z#d Z$d Z%d Z&d Z'd Z(d Z)d Z*d Z+d Z,d Z-d Z.d Z/d  Z0d! Z1d)d"Z2y)*    )annotations)lrangeN)	DataFrame)offsets)	to_offset)Literal)_is_recarray_is_using_pandas)ValueWarning)NDArray)
array_like	bool_likeint_likestring_like)lagmat	lagmat2ds	add_trendduplication_matrixelimination_matrixcommutation_matrixvecvechunvecunvechfreq_to_periodc                   t        |d      }t        |dd      }t        |dd      }g d}|dk(  r| j                         S |d	k(  r|d
d }d}n#|dk(  s|dk(  r|d
d }|dk(  r|dd }d}n|dk(  rd}t        |       rddlm} t        |      t        | d
      }|rAt        | t        j                        rt        j                  |       } n&| j                         } nt        j                  |       } t        |       }t        j                  t        j                   d|dz   t        j"                        dz         }	t        j$                  |	      }	|dk(  r	|	d
d
df   }	d	|v r!|rd }
| j'                  |
d      }n<t        j(                  t        j                  |       d      }|dk(  }|| d   dk7  z  }|}t        j*                  |      r|dk(  r| j,                  dk(  rd}nyt        j                   | j.                  d         |   }t        | t        j                        r| j0                  }dj3                  |D cg c]  }t5        |       c}      }d| d}| d| d}t7        |      |dk(  r|dd
 }|	d
d
dd
f   }	|rdnd}|rEt        j                  |	| j8                  |      }	|	| g} t        j:                  | d
d
|   d      } | S |	| g} t        j<                  | d
d
|         } | S c c}w )a  
    Add a trend and/or constant to an array.

    Parameters
    ----------
    x : array_like
        Original array of data.
    trend : str {'n', 'c', 't', 'ct', 'ctt'}
        The trend to add.

        * 'n' add no trend.
        * 'c' add constant only.
        * 't' add trend only.
        * 'ct' add constant and linear trend.
        * 'ctt' add constant and linear and quadratic trend.
    prepend : bool
        If True, prepends the new data to the columns of X.
    has_constant : str {'raise', 'add', 'skip'}
        Controls what happens when trend is 'c' and a constant column already
        exists in x. 'raise' will raise an error. 'add' will add a column of
        1s. 'skip' will return the data without change. 'skip' is the default.

    Returns
    -------
    array_like
        The original data with the additional trend columns.  If x is a
        pandas Series or DataFrame, then the trend column names are 'const',
        'trend' and 'trend_squared'.

    See Also
    --------
    statsmodels.tools.tools.add_constant
        Add a constant column to an array.

    Notes
    -----
    Returns columns as ['ctt','ct','c'] whenever applicable. There is currently
    no checking for an existing trend.
    prependtrend)nctctcttoptionshas_constant)raiseaddskip)constr   trend_squaredr   r    N   r   r"   r!      r#   )recarray_exception)dtypec                v    	 t        j                  |       dk(  xr t        j                  | dk7        S #  Y yxY w)Ng        F)npptpany)ss    U/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/statsmodels/tsa/tsatools.pysafe_is_constz add_trend.<locals>.safe_is_const~   s6    !66!9+@qCx0@@! s   14 8axisr'   zx is constant.z, z3x contains one or more constant columns. Column(s) z are constant.z Adding a constant with trend='z' is not allowed.r)   indexcolumns)r   r   copyr	   statsmodels.tools.sm_exceptionsr.   NotImplementedErrorr
   
isinstancepdSeriesr   r1   
asanyarraylenvanderarangefloat64fliplrapplyr2   r3   ndimshaper<   joinstr
ValueErrorr;   concatcolumn_stack)xr   r   r&   r<   
trendorderr.   	is_pandasnobstrendarrr6   	col_constptp0col_is_constnz_constbase_errr    
const_colsmsgorders                       r5   r   r   '   s   P +Gw0LMEn.FL
 2G|vvx	#"1+
	$%3,"1+C<alG
	%
AF!"455 D)Ia#QAAMM!q6Dyy
		!TAXRZZ0*q.H yy"H|AqD>
e|! q1I66"--*3D19L#qtqy1H I66)w&66Q;/H ii
3I>G!!R\\2"#))!%G+DqCF+D!EJM%,n6  "
"A%HYZ o%'!!"+#AqrE?AbE<<IqMIIa%jq)
 H qMOOAggJ'H) ,Es   ?K4c                   t        |d      }t        |d      }t        | dd      } |d}|dk  r| j                  d   |z   }| j                  dk(  r	| dddf   } | dd|f   }|d	u r|dz   }nk|d
u r| j                  d   }nW|dk  r| j                  d   |z   dz   }|| j                  d   kD  r)| j                  d   }t        j                  dt               |}t        ||d      }t        |      }t        || j                  d         }	|rE||v r!|j                  |j                  |             n |	j                  |	j                  |             t        j                  | |d|f   || |d|	f   f      S )a  
    Returns an array with lags included given an array.

    Parameters
    ----------
    x : array_like
        An array or NumPy ndarray subclass. Can be either a 1d or 2d array with
        observations in columns.
    col : int or None
        `col` can be an int of the zero-based column index. If it's a
        1d array `col` can be None.
    lags : int
        The number of lags desired.
    drop : bool
        Whether to keep the contemporaneous variable for the data.
    insert : bool or int
        If True, inserts the lagged values after `col`. If False, appends
        the data. If int inserts the lags at int.

    Returns
    -------
    array : ndarray
        Array with lags

    Examples
    --------

    >>> import statsmodels.api as sm
    >>> data = sm.datasets.macrodata.load()
    >>> data = data.data[['year','quarter','realgdp','cpi']]
    >>> data = sm.tsa.add_lag(data, 'realgdp', lags=2)

    Notes
    -----
    Trims the array both forward and backward, so that the array returned
    so that the length of the returned array is len(`X`) - lags. The lags are
    returned in increasing order, ie., t-1,t-2,...,t-lags
    lagsdroprQ   r-   )rJ   Nr   r,   TFz<insert > number of variables, inserting at the last positionBoth)trim)r   r   r   rK   rJ   warningswarnr   r   r   popr;   r1   rP   )
rQ   colr_   r`   insertcontempins_idxndlags
first_cols	last_colss
             r5   add_lagrm      s   N D&!DT6"D1c"A
{ Qwggaj3vv{agJ3iG~'	5''!*A:WWQZ&(1,FAGGAJWWQZFMM!
 GT/FJw
+I*NN:++C01MM)//#./??AdeZ/0&!DE9<L:MNOO    c                ^   t        |d      }t        |d      }| j                  dk(  rt        |      dk(  r| j                  } n| j                  dkD  rt	        d      | j
                  d   }|dk(  r| | j                  d      z
  }n}t        j                  t        j                  t        |            |dz         }t        j                  j                  |      j                  |       }| t        j                  ||      z
  }| j                  dk(  rt        |      dk(  r|j                  }|S )	a  
    Detrend an array with a trend of given order along axis 0 or 1.

    Parameters
    ----------
    x : array_like, 1d or 2d
        Data, if 2d, then each row or column is independently detrended with
        the same trendorder, but independent trend estimates.
    order : int
        The polynomial order of the trend, zero is constant, one is
        linear trend, two is quadratic trend.
    axis : int
        Axis can be either 0, observations by rows, or 1, observations by
        columns.

    Returns
    -------
    ndarray
        The detrended series is the residual of the linear regression of the
        data on the trend of given order.
    r]   r8   r-   r,   z0x.ndim > 2 is not implemented until it is neededr   r7   )N)r   rJ   intTr?   rK   meanr1   rE   rF   floatlinalgpinvdot)rQ   r]   r8   rT   residtrendsbetas          r5   detrendr{      s    , UG$ED&!Dvv{s4yA~CC	
!!>
 	
 771:DzAFFFN"299U4[1UQY?yy~~f%))!,BFF64((vv{s4yA~Lrn   c           	        t        |d      }t        |d      }t        |ddd      }t        |dd	      }| }t        | d
dd      } t	        |d      xr |}|dn|}|j                         }|r|dv rt        d      d}| j                  \  }}	|dv r|	}||k\  rt        d      t        j                  ||z   |	|dz   z  f      }
t        dt        |dz               D ]%  }| |
||z
  ||z   |z
  |	||z
  z  |	||z
  dz   z  f<   ' |dv rd}n|dv r|}nt        d      |dv rt        |
      }n|}|r$|} t        | t              rQ| j                  D cg c]  }t!        |       }}t        t#        |            | j                  d   k7  r!t        d      t!        | j$                        g}|D cg c]  }t!        |       }}t        |      D ]>  }t!        |dz         }|j'                  |D cg c]  }t!        |      dz   |z    c}       @ t        |
d| | j(                  |      }
|
j*                  |d }|dv r4||   }|j-                  |d      }n|
|||df   }|dk(  r|
||d|f   }|dk(  r|fS |S c c}w c c}w c c}w )a,	  
    Create 2d array of lags.

    Parameters
    ----------
    x : array_like
        Data; if 2d, observation in rows and variables in columns.
    maxlag : int
        All lags from zero to maxlag are included.
    trim : {'forward', 'backward', 'both', 'none', None}
        The trimming method to use.

        * 'forward' : trim invalid observations in front.
        * 'backward' : trim invalid initial observations.
        * 'both' : trim invalid observations on both sides.
        * 'none', None : no trimming of observations.
    original : {'ex','sep','in'}
        How the original is treated.

        * 'ex' : drops the original array returning only the lagged values.
        * 'in' : returns the original array and the lagged values as a single
          array.
        * 'sep' : returns a tuple (original array, lagged values). The original
                  array is truncated to have the same number of rows as
                  the returned lagmat.
    use_pandas : bool
        If true, returns a DataFrame when the input is a pandas
        Series or DataFrame.  If false, return numpy ndarrays.

    Returns
    -------
    lagmat : ndarray
        The array with lagged observations.
    y : ndarray, optional
        Only returned if original == 'sep'.

    Notes
    -----
    When using a pandas DataFrame or Series with use_pandas=True, trim can only
    be 'forward' or 'both' since it is not possible to consistently extend
    index values.

    Examples
    --------
    >>> from statsmodels.tsa.tsatools import lagmat
    >>> import numpy as np
    >>> X = np.arange(1,7).reshape(-1,2)
    >>> lagmat(X, maxlag=2, trim="forward", original='in')
    array([[ 1.,  2.,  0.,  0.,  0.,  0.],
       [ 3.,  4.,  1.,  2.,  0.,  0.],
       [ 5.,  6.,  3.,  4.,  1.,  2.]])

    >>> lagmat(X, maxlag=2, trim="backward", original='in')
    array([[ 5.,  6.,  3.,  4.,  1.,  2.],
       [ 0.,  0.,  5.,  6.,  3.,  4.],
       [ 0.,  0.,  0.,  0.,  5.,  6.]])

    >>> lagmat(X, maxlag=2, trim="both", original='in')
    array([[ 5.,  6.,  3.,  4.,  1.,  2.]])

    >>> lagmat(X, maxlag=2, trim="none", original='in')
    array([[ 1.,  2.,  0.,  0.,  0.,  0.],
       [ 3.,  4.,  1.,  2.,  0.,  0.],
       [ 5.,  6.,  3.,  4.,  1.,  2.],
       [ 0.,  0.,  5.,  6.,  3.,  4.],
       [ 0.,  0.,  0.,  0.,  5.,  6.]])
    maxlag
use_pandasrb   Tforwardbackwardbothnoneoptionalr%   original)exsepinr$   rQ   r-   N)rJ   r/   r   )r   r   zEtrim cannot be 'none' or 'backward' when used on Series or DataFramesr   )r   r   zmaxlag should be < nobsr,   )r   r   )r   r   ztrim option not validzSColumns names must be distinct after conversion to string (if not already strings).z.L.r:   )r   r   r7   r   )r   r   r   r   r
   lowerrN   rK   r1   zerosrangerq   rD   r@   r   r<   rM   setnameextendr;   ilocr`   )rQ   r}   rb   r   r~   origrS   dropidxrT   nvarlmkstartobsstopobsr    	x_columnsrf   r<   laglag_strr_   leadss                         r5   r   r   )  s
   R fh'F:|4J7	D 8Z9LMH D1c.A t,;I\6tD::<DT11#
 	

 GJD$= ~233	4&=$&1*"56	7B1c&1*o&   	
D6MA%%
TVaZ!^44	6	
 ""	%	%011##b'a#)*3AQ3I33y>"aggaj0 0 
 QVVI'013s811= 	NC#'lGNN)L3CHu,w6LM	N r(7|177GDwwxy!}$OE99YQ9/D(7"GH,-ux''12E5U{3 4 2 Ms   I=0J/J
c           	        t        |d      }t        |dd      }t        |ddd      }||}t        ||      }t        | d      }| j                  d	k(  r"|rt        j                  |       } n3| dddf   } n)| j                  d
k(  s| j                  dkD  rt        d      | j                  \  }}	|r|rt        | j                  ddd
f   ||dd      }
|
j                  ddd|d	z   f   g}t        d	|	      D ]J  }t        | j                  dd|f   ||dd      }
|j                  |
j                  dd||d	z   f          L t        j                  |d	      S |rt        j                  |       } t        | ddd
f   ||d      ddd|d	z   f   g}t        d	|	      D ]3  }|j                  t        | dd|f   ||d      dd||d	z   f          5 t        j                   |      S )a  
    Generate lagmatrix for 2d array, columns arranged by variables.

    Parameters
    ----------
    x : array_like
        Data, 2d. Observations in rows and variables in columns.
    maxlag0 : int
        The first variable all lags from zero to maxlag are included.
    maxlagex : {None, int}
        The max lag for all other variables all lags from zero to maxlag are
        included.
    dropex : int
        Exclude first dropex lags from other variables. For all variables,
        except the first, lags from dropex to maxlagex are included.
    trim : str
        The trimming method to use.

        * 'forward' : trim invalid observations in front.
        * 'backward' : trim invalid initial observations.
        * 'both' : trim invalid observations on both sides.
        * 'none' : no trimming of observations.
    use_pandas : bool
        If true, returns a DataFrame when the input is a pandas
        Series or DataFrame.  If false, return numpy ndarrays.

    Returns
    -------
    ndarray
        The array with lagged observations, columns ordered by variable.

    Notes
    -----
    Inefficient implementation for unequal lags, implemented for convenience.
    maxlag0maxlagexT)r   rb   r   r   Nr,   r   r-   z'Only supports 1 and 2-dimensional data.r   )rb   r   r~   r7   )rb   r   )r   r   maxr
   rJ   rA   r   rN   rK   r   r   r   appendrO   r1   rC   rP   )rQ   r   r   dropexrb   r~   r}   rS   rT   r   r_   lagslir   s                r5   r   r     s   L w	*G*t<H7	D (#F D)Ivv{QA!T'
A	
1
BCCJD$ZFF1a4L&tdt
 ))A}1},-.q$ 	?Aq!tf4$4D MM$))Av1'<$<=>		?
 yya((	MM! 	qAwTD9!]w{]:JKF 1d^ 
1QT7F=6HqL((	

 ??6""rn   c                $    | j                  d      S )NF)ravelmats    r5   r   r     s    99S>rn   c                \    | j                   j                  t        t        |                   S N)rr   take_triu_indicesrD   r   s    r5   r   r     s    55::mCH-..rn   c                B    t        j                  |       \  }}|| z  |z   S r   )r1   tril_indicesr   rowscolss      r5   _tril_indicesr   #  "    #JD$!8d?rn   c                B    t        j                  |       \  }}|| z  |z   S r   )r1   triu_indicesr   s      r5   r   r   (  r   rn   c                B    t        j                  |       \  }}|| z  |z   S r   )r1   diag_indicesr   s      r5   _diag_indicesr   -  r   rn   c                    t        t        j                  t        |                   }||z  t        |       k(  sJ | j	                  ||fd      S )Nr   r]   )rq   r1   sqrtrD   reshape)vr   s     r5   r   r   2  sC    BGGCFOAq5CF??99aV39''rn   c           	     R   ddt        j                  ddt        |       z  z         z   z  }t        t        j                  |            }t        j
                  ||f      }| |t        j                  |      <   ||j                  z   }|t        j                  |      xx   dz  cc<   |S )Ng      ?r9   r,      r-   )	r1   r   rD   rq   roundr   r   rr   r   )r   r   results      r5   r   r   8  s    "rwwq1s1v:~../Drxx~DXXtTl#F$%F2??4 !fhhF 2??4 !Q&!Mrn   c                    t        | d      } t        j                  | | dz   z  dz        }t        j                  |D cg c]  }t	        |      j                          c}      j                  S c c}w )z
    Create duplication matrix D_n which satisfies vec(S) = D_n vech(S) for
    symmetric matrix S

    Returns
    -------
    D_n : ndarray
    r   r,   r-   )r   r1   eyearrayr   r   rr   )r   tmprQ   s      r5   r   r   G  sY     	CA
&&a!e!
"C8841VAY__&457774s    A/c                    t        | d      } t        t        j                  t        j                  | | f                  }t        j
                  | | z        |dk7     S )z
    Create the elimination matrix L_n which satisfies vech(M) = L_n vec(M) for
    any matrix M

    Parameters
    ----------

    Returns
    -------
    r   r   )r   r   r1   trilonesr   )r   vech_indicess     r5   r   r   U  sK     	CArwwrww1v/0L66!a%=*++rn   c                    t        | d      } t        |d      }t        j                  | |z        }t        j                  | |z        j	                  | |fd      }|j                  |j                         d      S )z
    Create the commutation matrix K_{p,q} satisfying vec(A') = K_{p,q} vec(A)

    Parameters
    ----------
    p : int
    q : int

    Returns
    -------
    K : ndarray (pq x pq)
    pqr   r   r   r7   )r   r1   r   rF   r   r   r   )r   r   Kindicess       r5   r   r   e  sl     	CACA
q1uAiiA&&1vS&9G66'--/6**rn   c           	        t        j                  | dz        }t        j                  | dz        }t        dt        |             D ]8  }||   }t        |      D ]  }||xx   ||||z
  dz
     z  z  cc<    |d| |d| : |S )z
    Transforms params to induce stationarity/invertability.

    Parameters
    ----------
    params : array_like
        The AR coefficients

    Reference
    ---------
    Jones(1980)
    r-   r,   N)r1   tanhr   rD   )params	newparamsr   jakiters         r5   _ar_transparamsr   z  s     
#I
''&1*
C1c&k"  aL1X 	7EJ!iE	A666J	7BQ	"1	 
 rn   c                ,   | j                         } | j                         }t        t        |       dz
  dd      D ]?  }| |   }t        |      D ]"  }| |   || ||z
  dz
     z  z   d|dz  z
  z  ||<   $ |d| | d| A dt        j                  |       z  }|S )z
    Inverse of the Jones reparameterization

    Parameters
    ----------
    params : array_like
        The transformed AR coefficients
    r,   r   r9   r-   N)r=   r   rD   r1   arctanh)r   r   r   r   r   
invarcoefss         r5   _ar_invtransparamsr     s     [[]F
++-C3v;?Ar* 1I1X 	E -!fQY].C*CCAF
CJ	 !Wr
 RZZ''Jrn   c           	        dt        j                  |        z
  dt        j                  |        z   z  j                         }dt        j                  |        z
  dt        j                  |        z   z  j                         }t        dt	        |             D ]8  }||   }t        |      D ]  }||xx   ||||z
  dz
     z  z  cc<    |d| |d| : |S )z
    Transforms params to induce stationarity/invertability.

    Parameters
    ----------
    params : ndarray
        The ma coeffecients of an (AR)MA model.

    Reference
    ---------
    Jones(1980)
    r,   N)r1   expr=   r   rD   )r   r   r   r   br   s         r5   _ma_transparamsr     s     bfffWo%!bfffWo*=>DDFIwAw$78
>
>
@C 1c&k"  aL1X 	7EJ!iE	A666J	7BQ	"1	 
 rn   c                   | j                         }t        t        |       dz
  dd      D ]?  }| |   }t        |      D ]"  }| |   || ||z
  dz
     z  z
  d|dz  z
  z  ||<   $ |d| | d| A t        j                  d| z
  d| z   z         }|S )z
    Inverse of the Jones reparameterization

    Parameters
    ----------
    params : ndarray
        The transformed MA coefficients
    r,   r   r9   r-   N)r=   r   rD   r1   log)macoefsr   r   r   r   
invmacoefss         r5   _ma_invtransparamsr     s     ,,.C3w<!#Q+ AJ1X 	E!%.1wq5y1}/E+EEAF
CJ	 "1g &&!g+!g+677Jrn   c           
         t        |d      }| d| } t        j                  t        |dd      D cg c]  }t        j                  | ||z
        d     c}      S c c}w )a  
    Returns the successive differences needed to unintegrate the series.

    Parameters
    ----------
    x : array_like
        The original series
    d : int
        The number of differences of the differenced series.

    Returns
    -------
    y : array_like
        The increasing differences from 0 to d-1 of the first d elements
        of x.

    See Also
    --------
    unintegrate
    dNr   r9   )r   r1   asarrayr   diff)rQ   r   is      r5   unintegrate_levelsr     sT    * 	CA	"1A::U1a_Erwwq!a%(+EFFEs   #Ac                   t        |      dd }t        |      dkD  rC|j                  d      }t        t	        j
                  t        j                  || f         |      S |d   }t	        j
                  t        j                  || f         S )ay  
    After taking n-differences of a series, return the original series

    Parameters
    ----------
    x : array_like
        The n-th differenced series
    levels : list
        A list of the first-value in each differenced series, for
        [first-difference, second-difference, ..., n-th difference]

    Returns
    -------
    y : array_like
        The original series de-differenced

    Examples
    --------
    >>> x = np.array([1, 3, 9., 19, 8.])
    >>> levels = unintegrate_levels(x, 2)
    >>> levels
    array([ 1.,  2.])
    >>> unintegrate(np.diff(x, 2), levels)
    array([  1.,   3.,   9.,  19.,   8.])
    Nr,   r9   r   )listrD   re   unintegrater1   cumsumr_)rQ   levelsx0s      r5   r   r     so    4 &\!_F
6{QZZ^299RUU2q5\2F;;	B99RUU2q5\""rn   c                   t        | t        j                        st        |       } t        | t        j                        sJ | j                  j                         } d}| dv s| j                  |      ry| dk(  s| j                  d      ry| dk(  s| j                  d      ry	| d
k(  s| j                  d      ry| dk(  ry| dk(  ry| dk(  ryt        dj                  |             )a$  
    Convert a pandas frequency to a periodicity

    Parameters
    ----------
    freq : str or offset
        Frequency to convert

    Returns
    -------
    int
        Periodicity of freq

    Notes
    -----
    Annual maps to 1, quarterly maps to 4, monthly to 12, weekly to 52.
    )zA-zAS-zY-zYS-zYE-)AYr,   Q)zQ-QSQE   M)zM-MSME   WzW-4   D   B   H   zDfreq {} not understood. Please report if you think this is in error.)	r@   r   
DateOffsetr   	rule_codeupper
startswithrN   format)freqyearly_freqss     r5   r   r     s    $ dG../dG..///>>!D4LzT__\:	(:;	(:;	-			&&,fTl
 	
rn   )r    Fr)   )Nr,   FT)r,   r   )r   r   F)
r}   rq   rb   z.Literal['forward', 'backward', 'both', 'none']r   zLiteral['ex', 'sep', 'in']r~   boolreturnzKNDArray | DataFrame | tuple[NDArray, NDArray] | tuple[DataFrame, DataFrame])Nr   r   F)r  zstr | offsets.DateOffsetr  rq   )3
__future__r   statsmodels.compat.pythonr   rc   numpyr1   pandasrA   r   pandas.tseriesr   pandas.tseries.frequenciesr   typingr   statsmodels.tools.datar	   r
   r>   r   statsmodels.tools.typingr   statsmodels.tools.validationr   r   r   r   __all__r   rm   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    rn   r5   <module>r     s    " ,     " 0  A 8 , @FMP`,b AJ04!	TT?T 0T 	T
 [Tp EJT#n/


(8, +*.,2*G4#D*
rn   