
    M/PhV,                         d Z ddlZddl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 ddlmZ g d	Zd
 Zd Z	 	 	 	 	 ddZ G d d          ZdS )z+
Seasonal Decomposition by Moving Averages
    N)nanmean)PandasWrapper
array_like)STL)convolution_filter)MSTL)freq_to_period)r   seasonal_decomposeseasonal_meanDecomposeResultr   c           
         t          d t          |           D                       }| j        d         dz
  t          d t          | ddd                   D                       z
  }t          ||z   |          }t	          |||z
            }t
          j                            t
          j        t          j	        ||          t          j
        ||z
            f         | ||         d          d         \  }}t          j	        d|          t
          j        |         z  t
          j        |         z   j        }| j        dk    r|                                }|| d|<   t
          j                            t
          j        t          j	        ||          t          j
        ||z
            f         | ||         d          d         \  }}t          j	        |dz   | j        d                   t
          j        |         z  t
          j        |         z   j        }| j        dk    r|                                }|| |dz   d<   | S )z
    Replace nan values on trend's end-points with least-squares extrapolated
    values with regression considering npoints closest defined points.
    c              3   l   K   | ]/\  }}t          j        t          j        |                    +|V  0d S Nnpanyisnan.0ivalss      X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/seasonal.py	<genexpr>z%_extrapolate_trend.<locals>.<genexpr>   sQ        a1G1G	         r      c              3   l   K   | ]/\  }}t          j        t          j        |                    +|V  0d S r   r   r   s      r   r   z%_extrapolate_trend.<locals>.<genexpr>"   sR       
 
46"(4..))

 
 
 
 
 
r   N)rcond)next	enumerateshapeminmaxr   linalglstsqc_arangeonesTndimsqueeze)	trendnpointsfrontback
front_last
back_firstknextras	            r   _extrapolate_trendr5      s0   
   "5))    E 	A
	
 
 
$U44R4[11
 
 
 
 
	
 	 UW_d++JUD7N++J9??
biz**BGJ4F,G,GGHeJ    		DAq
 Yq%  258+beAh69EzQE&5&M9??
bi
D))274*3D+E+EEFjo    		DAq
 YtaxQ00258;beAhFIEzQE$(**Lr   c                 b     t          j         fdt                    D                       S )z
    Return means for each period in x. period is an int that gives the
    number of periods per cycle. E.g., 12 for monthly. NaNs are ignored
    in the mean.
    c                 D    g | ]}t          |d          d          S )Nr   axis)
pd_nanmean)r   r   periodxs     r   
<listcomp>z!seasonal_mean.<locals>.<listcomp>H   s0    MMM!Z!)V)1555MMMr   )r   arrayrange)r<   r;   s   ``r   r   r   B   s4     8MMMMMuV}}MMMNNNr   additiveTc                    |}t          |           }| t          t          | dd          dd          }t          | dd          } t          |           }t	          j        t	          j        |                     st          d          |                    d          r't	          j	        | d	k              rt          d
          |#|t          |          }|}nt          d          | j        d	         d|z  k     r$t          dd|z   d| j        d	          d          |H|dz  d	k    r't	          j        dgdg|dz
  z  z   dgz             |z  }nt	          j        d|z  |          }t          |          dz   }	t          | ||	          }
|dk    r|dz
  }|d	k    rt!          |
|dz             }
|                    d          r| |
z  }n| |
z
  }t#          ||          }|                    d          r|t	          j        |d	          z  }n|t	          j        |d	          z  }t	          j        |j        ||z  dz             j        d|         }|                    d          r	| |z  |
z  }n||z
  }g }t+          ||
|| fd          D ]A\  }}|                    |                    |                                |                     Bt3          |d	         |d         |d         |d                   S )a	  
    Seasonal decomposition using moving averages.

    Parameters
    ----------
    x : array_like
        Time series. If 2d, individual series are in columns. x must contain 2
        complete cycles.
    model : {"additive", "multiplicative"}, optional
        Type of seasonal component. Abbreviations are accepted.
    filt : array_like, optional
        The filter coefficients for filtering out the seasonal component.
        The concrete moving average method used in filtering is determined by
        two_sided.
    period : int, optional
        Period of the series (e.g., 1 for annual, 4 for quarterly, etc). Must
        be used if x is not a pandas object or if the index of x does not have
        a frequency. Overrides default periodicity of x if x is a pandas
        object with a timeseries index.
    two_sided : bool, optional
        The moving average method used in filtering.
        If True (default), a centered moving average is computed using the
        filt. If False, the filter coefficients are for past values only.
    extrapolate_trend : int or 'freq', optional
        If set to > 0, the trend resulting from the convolution is
        linear least-squares extrapolated on both ends (or the single one
        if two_sided is False) considering this many (+1) closest points.
        If set to 'freq', use `freq` closest points. Setting this parameter
        results in no NaN values in trend or resid components.

    Returns
    -------
    DecomposeResult
        A object with seasonal, trend, and resid attributes.

    See Also
    --------
    statsmodels.tsa.filters.bk_filter.bkfilter
        Baxter-King filter.
    statsmodels.tsa.filters.cf_filter.cffilter
        Christiano-Fitzgerald asymmetric, random walk filter.
    statsmodels.tsa.filters.hp_filter.hpfilter
        Hodrick-Prescott filter.
    statsmodels.tsa.filters.convolution_filter
        Linear filtering via convolution.
    statsmodels.tsa.seasonal.STL
        Season-Trend decomposition using LOESS.

    Notes
    -----
    This is a naive decomposition. More sophisticated methods should
    be preferred.

    The additive model is Y[t] = T[t] + S[t] + e[t]

    The multiplicative model is Y[t] = T[t] * S[t] * e[t]

    The results are obtained by first estimating the trend by applying
    a convolution filter to the data. The trend is then removed from the
    series and the average of this de-trended series for each period is
    the returned seasonal component.
    Nindexinferred_freqr<      )maxdimz,This function does not handle missing valuesmr   zJMultiplicative seasonality is not appropriate for zero and negative valueszxYou must specify a period or x must be a pandas object with a PeriodIndex or a DatetimeIndex with a freq not set to Nonez'x must have 2 complete cycles requires z observations. x only has z observation(s)g      ?r   g      ?freqr8   )seasonalr,   residN)columns   )rH   r,   rI   observed)r   getattrr   lenr   allisfinite
ValueError
startswithr   r	   r!   r>   repeatintr   r5   r   meantiler)   zipappendwrapr+   r   )r<   modelfiltr;   	two_sidedextrapolate_trendpfreqpwnobsnsidesr,   	detrendedperiod_averagesrH   rI   resultssnames                     r   r
   r
   K   su   L E	q		B~7D11?DII1c!$$$Aq66D6"+a..!! IGHHH 6!q&>> 	/  
 ~"5))EFFO   	wqzAIDa%i D D()
D D D
 
 	

 |A:??8SEQC6A:$66#>??&HDD9S6\622D^^aFq$//EF"""QJ1"5*;a*?@@ I		I	#Iv66O <27?;;;;27?;;;;w($&.1*<==?FH %Hu$H$G	5%#%I  ; ;4 	rwwqyy{{Dw99::::ajaj	   r   c                       e Zd ZdZddZed             Zed             Zed             Zed             Z	ed             Z
ed	             Z	 	 	 	 	 ddZdS )r   a  
    Results class for seasonal decompositions

    Parameters
    ----------
    observed : array_like
        The data series that has been decomposed.
    seasonal : array_like
        The seasonal component of the data series.
    trend : array_like
        The trend component of the data series.
    resid : array_like
        The residual component of the data series.
    weights : array_like, optional
        The weights used to reduce outlier influence.
    Nc                     || _         || _        |Jt          j        |          }t	          |t
          j                  rt          j        ||j        d          }|| _        || _	        || _
        d S )Nweights)rB   rf   )	_seasonal_trendr   	ones_like
isinstancepdSeriesrB   _weights_resid	_observed)selfrL   rH   r,   rI   ri   s         r   __init__zDecomposeResult.__init__   sr    !?l8,,G(BI.. )8>	    !r   c                     | j         S )zObserved data)rr   rs   s    r   rL   zDecomposeResult.observed        ~r   c                     | j         S )z The estimated seasonal component)rj   rv   s    r   rH   zDecomposeResult.seasonal  rw   r   c                     | j         S )zThe estimated trend component)rk   rv   s    r   r,   zDecomposeResult.trend	       {r   c                     | j         S )zThe estimated residuals)rq   rv   s    r   rI   zDecomposeResult.resid  rz   r   c                     | j         S )z)The weights used in the robust estimation)rp   rv   s    r   ri   zDecomposeResult.weights  s     }r   c                     | j         j        S )zNumber of observations)rr   r!   rv   s    r   r`   zDecomposeResult.nobs  s     ~##r   TFc                 P   ddl m} ddlm}  |            } |             |r
| j        dfgng }	|	|r
| j        dfgng z  }	| j        j        dk    r|	|r
| j        dfgng z  }	n| j        j        dk    rt          | j        t          j
                  r'| j        j        D ]}
|	|r| j        |
         dfgng z  }	n=t          | j        j        d                   D ]}|	|r| j        dd|f         dfgng z  }	|	|r
| j        d	fgng z  }	|	|r
| j        d
fgng z  }	t          | j        t          j
        t          j        f          r:| j        j        d         }| j        j        d         | j        j        |dz
           f}nd| j        j        d         dz
  f}|                    t'          |	          dd          \  }}t)          t+          ||	                    D ]\  }\  }\  }	}|d	k    r|                    |	           n1|                    |	dd           |                    |ddd           t/          |	d|          }|dk    r|                                }|dk    r	|r|j        n|j        } ||           |                    |           |                                 |S )a@  
        Plot estimated components

        Parameters
        ----------
        observed : bool
            Include the observed series in the plot
        seasonal : bool
            Include the seasonal component in the plot
        trend : bool
            Include the trend component in the plot
        resid : bool
            Include the residual in the plot
        weights : bool
            Include the weights in the plot (if any)

        Returns
        -------
        matplotlib.figure.Figure
            The figure instance that containing the plot.
        r   )register_matplotlib_converters)_import_mplObservedr,   r   rH   Nresidualri   T)sharexonone)marker	linestyle)r   r   z#000000)colorzorderrf   )pandas.plottingr   statsmodels.graphics.utilsr   rr   r,   rH   r*   rm   rn   	DataFramerJ   r?   r!   rI   ri   ro   rB   subplotsrN   r    rW   plotrM   
capitalize	set_title
set_ylabelset_xlimtight_layout)rs   rL   rH   r,   rI   ri   r   r   pltseriescolr   r`   xlimfigaxsaxdef_namerf   titles                       r   r   zDecomposeResult.plot  s'   : 	CBBBBB::::::kmm&&(((3;C4>:.//U:DJ()):=""xGz233RGFF]!##$-66 	=0  C>FN$-,j9::BFF
 t}21566  A?GO$-1-z:;;RFF 	=DJ
+,,2=@DL),--b@dnr|RY&?@@ 	4>'*D>'*DN,@,JJDDt~+A.23D<<FQt<<<S+4Sf5E5E+F+F 	 	'A'&VX:%%sf===fIbAAA66844D:%%(($%FFxFBLLR]EE$KKKKK
r   r   )TTTTF)__name__
__module____qualname____doc__rt   propertyrL   rH   r,   rI   ri   r`   r    r   r   r   r      s         "" " " "   X   X   X   X   X $ $ X$ L L L L L Lr   r   )r@   NNTr   )r   numpyr   pandasrn   pandas.core.nanopsr   r:   statsmodels.tools.validationr   r   statsmodels.tsa.stl._stlr   #statsmodels.tsa.filters.filtertoolsr   statsmodels.tsa.stl.mstlr   statsmodels.tsa.tsatoolsr	   __all__r5   r   r
   r   r   r   r   <module>r      s4            4 4 4 4 4 4 B B B B B B B B ( ( ( ( ( ( B B B B B B ) ) ) ) ) ) 3 3 3 3 3 3  ( ( (VO O O 	R R R RjI I I I I I I I I Ir   