B
    ZV1              	   @   sz   d Z ddlZddlmZ ddlmZ ddlmZm	Z	 dd Z
dd	 ZdddZdddZdddZdddZdddZdS )zCorrelation plot functions.    N)sort_values)utils)acfpacfc             C   s|   t |}|rdnd}|d kr0t| t| }n8t|rRt| t|d }nd}t|tj}|d}|||fS )NFT   r   )	boolnparangelenZisscalarintZ
asanyarrayZastypemax)xlagszero	irregularnlags r   <lib/python3.7/site-packages/statsmodels/graphics/tsaplots.py_prepare_data_corr_plot   s    

r   c       	      K   s   |r|| }|d k	r|| }|r@| j |dg|f| | jf | |dd |dd d|krl|dd | d	 | j||f| | | |d k	r|d dkr|d
d  }|d
d  }|d
d  }| j||d d df | |d d d
f | dd d S )Nr   ZmarkeroZ
markersize   ZlsZ	linestyleNoneg?r   g      ?)alpha)ZvlinesZaxhline
setdefaultmarginsplotZ	set_titleZfill_between)	axtitleacf_xconfintr   r   
use_vlinesvlines_kwargskwargsr   r   r   
_plot_corr   s(    

r#   皙?TFAutocorrelationc
          	   K   s   t |\}}t| ||\}}}|	dkr,i n|	}	d}|dkrPt| ||||d}nt| ||||d\}}t||||||||	f|
 |S )a	  Plot the autocorrelation function

    Plots lags on the horizontal and the correlations on vertical axis.

    Parameters
    ----------
    x : array_like
        Array of time-series values
    ax : Matplotlib AxesSubplot instance, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    lags : int or array_like, optional
        int or Array of lag values, used on horizontal axis. Uses
        np.arange(lags) when lags is an int.  If not provided,
        ``lags=np.arange(len(corr))`` is used.
    alpha : scalar, optional
        If a number is given, the confidence intervals for the given level are
        returned. For instance if alpha=.05, 95 % confidence intervals are
        returned where the standard deviation is computed according to
        Bartlett's formula. If None, no confidence intervals are plotted.
    use_vlines : bool, optional
        If True, vertical lines and markers are plotted.
        If False, only markers are plotted.  The default marker is 'o'; it can
        be overridden with a ``marker`` kwarg.
    unbiased : bool
        If True, then denominators for autocovariance are n-k, otherwise n
    fft : bool, optional
        If True, computes the ACF via FFT.
    title : str, optional
        Title to place on plot.  Default is 'Autocorrelation'
    zero : bool, optional
        Flag indicating whether to include the 0-lag autocorrelation.
        Default is True.
    vlines_kwargs : dict, optional
        Optional dictionary of keyword arguments that are passed to vlines.
    **kwargs : kwargs, optional
        Optional keyword arguments that are directly passed on to the
        Matplotlib ``plot`` and ``axhline`` functions.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    See Also
    --------
    matplotlib.pyplot.xcorr
    matplotlib.pyplot.acorr
    mpl_examples/pylab_examples/xcorr_demo.py

    Notes
    -----
    Adapted from matplotlib's `xcorr`.

    Data are plotted as ``plot(lags, corr, **kwargs)``

    kwargs is used to pass matplotlib optional arguments to both the line
    tracing the autocorrelations and for the horizontal line at 0. These
    options must be valid for a Line2D object.

    vlines_kwargs is used to pass additional optional arguments to the
    vertical lines connecting each autocorrelation to the axis.  These options
    must be valid for a LineCollection object.
    N)r   r   fftunbiased)r   create_mpl_axr   r   r#   )r   r   r   r   r    r'   r&   r   r   r!   r"   figr   r   r   r   r   r   r   plot_acf6   s    D



r*   
ywunbiasedPartial Autocorrelationc	          	   K   s   t |\}
}|dkri n|}t| ||\}}}d}|dkrNt| |||d}nt| |||d\}}t||||||||f|	 |
S )a"  
    Plot the partial autocorrelation function

    Parameters
    ----------
    x : array_like
        Array of time-series values
    ax : Matplotlib AxesSubplot instance, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    lags : int or array_like, optional
        int or Array of lag values, used on horizontal axis. Uses
        np.arange(lags) when lags is an int.  If not provided,
        ``lags=np.arange(len(corr))`` is used.
    alpha : float, optional
        If a number is given, the confidence intervals for the given level are
        returned. For instance if alpha=.05, 95 % confidence intervals are
        returned where the standard deviation is computed according to
        1/sqrt(len(x))
    method : {'ywunbiased', 'ywmle', 'ols'}
        Specifies which method for the calculations to use:

        - yw or ywunbiased : yule walker with bias correction in denominator
          for acovf. Default.
        - ywm or ywmle : yule walker without bias correction
        - ols - regression of time series on lags of it and on constant
        - ld or ldunbiased : Levinson-Durbin recursion with bias correction
        - ldb or ldbiased : Levinson-Durbin recursion without bias correction
    use_vlines : bool, optional
        If True, vertical lines and markers are plotted.
        If False, only markers are plotted.  The default marker is 'o'; it can
        be overridden with a ``marker`` kwarg.
    title : str, optional
        Title to place on plot.  Default is 'Partial Autocorrelation'
    zero : bool, optional
        Flag indicating whether to include the 0-lag autocorrelation.
        Default is True.
    vlines_kwargs : dict, optional
        Optional dictionary of keyword arguments that are passed to vlines.
    **kwargs : kwargs, optional
        Optional keyword arguments that are directly passed on to the
        Matplotlib ``plot`` and ``axhline`` functions.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    See Also
    --------
    matplotlib.pyplot.xcorr
    matplotlib.pyplot.acorr
    mpl_examples/pylab_examples/xcorr_demo.py

    Notes
    -----
    Plots lags on the horizontal and the correlations on vertical axis.
    Adapted from matplotlib's `xcorr`.

    Data are plotted as ``plot(lags, corr, **kwargs)``

    kwargs is used to pass matplotlib optional arguments to both the line
    tracing the autocorrelations and for the horizontal line at 0. These
    options must be valid for a Line2D object.

    vlines_kwargs is used to pass additional optional arguments to the
    vertical lines connecting each autocorrelation to the axis.  These options
    must be valid for a LineCollection object.
    N)r   r   method)r   r(   r   r   r#   )r   r   r   r   r-   r    r   r   r!   r"   r)   r   r   r   r   r   r   r   	plot_pacf   s    I
r.   c             C   s   t |\}}d}g }x| D ]x\}}| }|  t|}	t|||	 }
||
  |	|
|j
d |j|j
 |
d |
d ddd ||	7 }qW || || || |dd |S )	a@  
    Consider using one of month_plot or quarter_plot unless you need
    irregular plotting.

    Parameters
    ----------
    grouped_x : iterable of DataFrames
        Should be a GroupBy object (or similar pair of group_names and groups
        as DataFrames) with a DatetimeIndex or PeriodIndex
    xticklabels : list of str
        List of season labels, one for each group.
    ylabel : str
        Lable for y axis
    ax : Matplotlib AxesSubplot instance, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    r   kr   )ZcolorsZ	linewidthg?g?)r   r(   copyZ
sort_indexr
   r   r	   appendZmeanr   valuesZhlinesZ
set_xticksZset_xticklabelsZ
set_ylabelr   )Z	grouped_xxticklabelsylabelr   r)   startZticksZseasonZdfZnobsZx_plotr   r   r   seasonal_plot   s$    


r9   c       	      C   s   ddl m} |dkr.ddlm} || dd n$ddl m}m} || ||ddd} d	d
dddd	d	dddddg}t| dd |||dS )aR  
    Seasonal plot of monthly data

    Parameters
    ----------
    x : array-like
        Seasonal data to plot. If dates is None, x must be a pandas object
        with a PeriodIndex or DatetimeIndex with a monthly frequency.
    dates : array-like, optional
        If `x` is not a pandas object, then dates must be supplied.
    ylabel : str, optional
        The label for the y-axis. Will attempt to use the `name` attribute
        of the Series.
    ax : matplotlib.axes, optional
        Existing axes instance.

    Returns
    -------
    matplotlib.Figure

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> import pandas as pd

    >>> dta = sm.datasets.elnino.load_pandas().data
    >>> dta['YEAR'] = dta.YEAR.astype(int).astype(str)
    >>> dta = dta.set_index('YEAR').T.unstack()
    >>> dates = pd.to_datetime(list(map(lambda x : '-'.join(x) + '-1',
    ...                                        dta.index.values)))

    >>> dta.index = pd.DatetimeIndex(dates, freq='MS')
    >>> fig = sm.graphics.tsa.month_plot(dta)

    .. plot:: plots/graphics_month_plot.py
    r   )	DataFrameN)_check_period_indexM)freq)SeriesPeriodIndex)indexjfmasr   ndc             S   s   | j S )N)Zmonth)yr   r   r   <lambda>=  s    zmonth_plot.<locals>.<lambda>)r7   r   )pandasr:   statsmodels.tools.datar;   r>   r?   r9   groupby)	r   datesr7   r   r:   r;   r>   r?   r6   r   r   r   
month_plot  s    %rN   c       	      C   sx   ddl m} |dkr.ddlm} || dd n$ddl m}m} || ||ddd} d	d
ddg}t| dd |||dS )a@  
    Seasonal plot of quarterly data

    Parameters
    ----------
    x : array-like
        Seasonal data to plot. If dates is None, x must be a pandas object
        with a PeriodIndex or DatetimeIndex with a monthly frequency.
    dates : array-like, optional
        If `x` is not a pandas object, then dates must be supplied.
    ylabel : str, optional
        The label for the y-axis. Will attempt to use the `name` attribute
        of the Series.
    ax : matplotlib.axes, optional
        Existing axes instance.

    Returns
    -------
    matplotlib.Figure
    r   )r:   N)r;   Q)r=   )r>   r?   )r@   Zq1Zq2Zq3Zq4c             S   s   | j S )N)Zquarter)rH   r   r   r   rI   _  s    zquarter_plot.<locals>.<lambda>)r7   r   )rJ   r:   rK   r;   r>   r?   r9   rL   )	r   rM   r7   r   r:   r;   r>   r?   r6   r   r   r   quarter_plot@  s    rP   )	NNr$   TFFr%   TN)NNr$   r+   Tr,   TN)NN)NNN)NNN)__doc__Znumpyr   Zstatsmodels.compat.pandasr   Zstatsmodels.graphicsr   Zstatsmodels.tsa.stattoolsr   r   r   r#   r*   r.   r9   rN   rP   r   r   r   r   <module>   s     
V  
W
'
2