
    M/Phe                         d dl Zd dlZd dlmZ d dl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ZmZmZ  G d d	e          Z G d
 de          Z eee           dS )    N)
inv_boxcox)boxcoxrv_continuousrv_discrete)	rv_frozen)
PandasData)Results)ResultsWrapperpopulate_wrapperunion_dictsc                       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
j        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j        d             ZddZddZd Z	 	 	 	 	 ddZ xZS ) HoltWintersResultsa  
    Results from fitting Exponential Smoothing models.

    Parameters
    ----------
    model : ExponentialSmoothing instance
        The fitted model instance.
    params : dict
        All the parameters for the Exponential Smoothing model.
    sse : float
        The sum of squared errors.
    aic : float
        The Akaike information criterion.
    aicc : float
        AIC with a correction for finite sample sizes.
    bic : float
        The Bayesian information criterion.
    optimized : bool
        Flag indicating whether the model parameters were optimized to fit
        the data.
    level : ndarray
        An array of the levels values that make up the fitted values.
    trend : ndarray
        An array of the trend values that make up the fitted values.
    season : ndarray
        An array of the seasonal values that make up the fitted values.
    params_formatted : pd.DataFrame
        DataFrame containing all parameters, their short names and a flag
        indicating whether the parameter's value was optimized to fit the data.
    resid : ndarray
        An array of the residuals of the fittedvalues and actual values.
    k : int
        The k parameter used to remove the bias in AIC, BIC etc.
    fittedvalues : ndarray
        An array of the fitted values. Fitted by the Exponential Smoothing
        model.
    fittedfcast : ndarray
        An array of both the fitted values and forecast values.
    fcastvalues : ndarray
        An array of the forecast values forecast by the Exponential Smoothing
        model.
    mle_retvals : {None, scipy.optimize.optimize.OptimizeResult}
        Optimization results if the parameters were optimized to fit the data.
    Nc                 D   |j         | _         t                                          ||           || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        || _        || _        || _        || _        || _        || _        d S N)datasuper__init___model_sse_aic_aicc_bic
_optimized_level_trend_season_params_formatted_fittedvalues_fittedfcast_fcastvalues_resid_k_mle_retvals)selfmodelparamssseaicaiccbic	optimizedleveltrendseasonparams_formattedresidkfittedvaluesfittedfcastfcastvaluesmle_retvals	__class__s                     c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/holtwinters/results.pyr   zHoltWintersResults.__init__B   s    ( J	'''		
	#!1)'''    c                     | j         S )z3
        The Akaike information criterion.
        )r   r$   s    r7   r(   zHoltWintersResults.aici       
 yr8   c                     | j         S )z@
        AIC with a correction for finite sample sizes.
        )r   r:   s    r7   r)   zHoltWintersResults.aiccp   s    
 zr8   c                     | j         S )z5
        The Bayesian information criterion.
        )r   r:   s    r7   r*   zHoltWintersResults.bicw   r;   r8   c                     | j         S )zS
        The sum of squared errors between the data and the fittted value.
        )r   r:   s    r7   r'   zHoltWintersResults.sse~   r;   r8   c                     | j         S )zA
        The model used to produce the results instance.
        r   r:   s    r7   r%   zHoltWintersResults.model       
 {r8   c                     || _         d S r   r@   r$   values     r7   r%   zHoltWintersResults.model   s    r8   c                     | j         S )zO
        An array of the levels values that make up the fitted values.
        )r   r:   s    r7   r,   zHoltWintersResults.level   rA   r8   c                     | j         S )zU
        Flag indicating if model parameters were optimized to fit the data.
        )r   r:   s    r7   r+   zHoltWintersResults.optimized   s    
 r8   c                     | j         S )zN
        An array of the trend values that make up the fitted values.
        )r   r:   s    r7   r-   zHoltWintersResults.trend   rA   r8   c                     | j         S )zQ
        An array of the seasonal values that make up the fitted values.
        )r   r:   s    r7   r.   zHoltWintersResults.season   s    
 |r8   c                     | j         S )z
        DataFrame containing all parameters

        Contains short names and a flag indicating whether the parameter's
        value was optimized to fit the data.
        )r   r:   s    r7   r/   z#HoltWintersResults.params_formatted   s     %%r8   c                     | j         S )z/
        An array of the fitted values
        )r   r:   s    r7   r2   zHoltWintersResults.fittedvalues   s    
 !!r8   c                     | j         S )zI
        An array of both the fitted values and forecast values.
        )r   r:   s    r7   r3   zHoltWintersResults.fittedfcast       
   r8   c                     | j         S )z1
        An array of the forecast values
        )r    r:   s    r7   r4   zHoltWintersResults.fcastvalues   rL   r8   c                     | j         S )zR
        An array of the residuals of the fittedvalues and actual values.
        )r!   r:   s    r7   r0   zHoltWintersResults.resid   rA   r8   c                     | j         S )zJ
        The k parameter used to remove the bias in AIC, BIC etc.
        )r"   r:   s    r7   r1   zHoltWintersResults.k   s    
 wr8   c                     | j         S )zX
        Optimization results if the parameters were optimized to fit the data.
        r#   r:   s    r7   r5   zHoltWintersResults.mle_retvals   rL   r8   c                     || _         d S r   rQ   rC   s     r7   r5   zHoltWintersResults.mle_retvals   s    !r8   c                 D    | j                             | j        ||          S )a  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, ie.,
            the first forecast is start. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.

        Returns
        -------
        forecast : ndarray
            Array of out of sample forecasts.
        )r%   predictr&   )r$   startends      r7   rT   zHoltWintersResults.predict   s     . z!!$+uc:::r8      c                    	 t          | j        j        dd          }t          |t                    s^t          | j        j        t
          j        t
          j        f          r.| j        j        d         |z   }| j        j        d         ||z  z   }n| j        j        j        d         }||z   dz
  }| j        	                    | j
        ||          S # t          $ r!  | j        j        dd|i| j
        j        cY S w xY w)	a'  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int
            The number of out of sample forecasts from the end of the
            sample.

        Returns
        -------
        forecast : ndarray
            Array of out of sample forecasts
        freqrW   r   )rU   rV   hN )getattrr%   _index
isinstanceintpdDatetimeIndexPeriodIndexshaperT   r&   AttributeError_predictr4   )r$   stepsrY   rU   rV   s        r7   forecastzHoltWintersResults.forecast   s   	K4:,fa88DdC(( (Z
!B$4bn#E. . ( 
)"-4j'+edl:
)/2ema':%%dkC%HHH 	K 	K 	K&4:&>>>$+>>JJJJ	Ks   CC (C<;C<c                    ddl m} ddlm} | j        }|j        j        dz   }d}| j        j        j        }t          |t          j                  r|j        d         }n!t          |t          j                  r|j        }| j        j        dn| j        j        }ddddd	d
}| j        d         }	|	rdnd}
t          |	t$                    r|	n| j        d         }t          |t&                    r|d}d|gfd|j        j        gfdt%          t)          j        | j                            gfd|| j        j                 gfd|| j        j                 gfdt%          |          gfdt%          |
          gfdt%          |          gfg}dt%          t1          | j        j                            gfd| j        dgfd| j        dgfd| j        dgfd| j        dgfddg} |            }|                    | |||            | j        }d! }g }|                                 D ]e\  }}|!                     ||j"        d"                   |j"        d         d#t%          tG          |j"        d$                             d#g           f ||g d%d&tI          |j%                  '          }|j&        !                    |           |S )(a6  
        Summarize the fitted Model

        Returns
        -------
        smry : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        r   )Summary)SimpleTablez Model ResultsendogNAdditiveMultiplicativeNone)addadditivemulmultiplicativeN
use_boxcoxTFlamdaz>10.5fzDep. Variable:zModel:z
Optimized:zTrend:z	Seasonal:zSeasonal Periods:zBox-Cox:zBox-Cox Coeff.:zNo. Observations:SSEz5.3fAICBICAICC)zDate:N)zTime:N)gleftgrighttitlec                 B   t          j        |           }d}t          j        |           rt          |           dS |dk    r!t	          t          j        |                    }|dk    s|dk     r| dS t          d|z
  d          }d| d	}|                    |           S )
NrW   >20r      z>20.5g   z{:>20.zf})npabsisnanstrr`   log10minformat)xabs_xscaledecfmts        r7   _fmtz(HoltWintersResults.summary.<locals>._fmtc  s    F1IIEEx{{ 'a&&&zzBHUOO,,qyyEBJJ}}$a%i##C$C$$$C::a== r8   rW   r~      )coeffcoder+    )headersr|   stubs)'statsmodels.iolib.summaryrj   statsmodels.iolib.tablerk   r%   r6   __name__r   
orig_endogr_   ra   	DataFramecolumnsSeriesnameseasonalseasonal_periodsr&   r   floatr   anyr+   r-   lenrl   r'   r(   r*   r)   add_table_2colsr/   iterrowsappendilocboollistindextables)r$   rj   rk   r%   r|   dep_variabler   r   lookup	transformbox_cox_transformbox_cox_coefftop_left	top_rightsmry	formattedr   tab_valsparams_tables                        r7   summaryzHoltWintersResults.summary  sn    	655555777777
(+;;Z_/
j",// 	+%-a0LL
BI.. 	+%?L z"* D, 	 "#.
 
 K-	$-8DD5#Is33MIIW9M 	 mU++ 	6,55M~.012Ct~ 6 67789tz/0126$*"5678 3'7#8#8"9:#/0012]!3!3 45	
 !3s4:+;'<'<#=#=">?''()''()''()))*+
	 wyy% 	 	
 	
 	
 )		! 	! 	!  ))++ 	 	GAtJJD1&&y|))4	!--..44    #{222y''	
 
 
 	<(((r8   rp   c                 B   |dv rddd|         }|dvrt          d          ||dk    r| j        j        }nC|dk    rd	}n:| j                            |          \  }}}t	          |t
                    r|j        }|d	k     r|| j        j        z  }|| j        j        k    rt          d
          | j        j        }	| j        j        }
| j        j	        }| j
        d         }| j
        d         }| j
        d         }| j
        d         }| j
        d         }| j
        d         }t          | j        j        d          }dd| j        j        z  z   |dz   | j        j        z  z   |
z   }|dk    }|	dk    }|dk    }|rt          j        }t          j        }d}nt          j        }t          j        }d	}|rt          j        }d}nt          j        }d	}| j        }| j        }| j        }t          j        ||f          }t          j        |dz   |f          } t          j        |dz   |f          }!t          j        ||z   |f          }"|d	k    r)| j
        d         | dddf<   | j
        d         |!dddf<   n$||dz
           | dddf<   ||dz
           |!dddf<   d	|k    r`||k    rZ| j
        d         }#t          j        |#|d         |d|         f          }$t          j        |$|df          j        |"| dddf<   n1t          j        |||z
  |         |df          j        |"| dddf<   |	||!ddddf<   d}d	}|||"ddddf<   d	}|
sd}|rt3          | j        |          }%n| j        }%|dk    r| j        j        |%z
  }&n| j        j        |%z
  |%z  }&t          j        t          j        |&dz            t=          |&          |z
  z            }'t	          |t          j                  r |j         ||fk    rt          d          |}(ni|dk    r&t          j!        "                    |&||fd          }(n=||%t          j!        #                    ||          |'z  }(nt	          |tH                    r9t          j!        %                    |          })|)#                    ||          |'z  }(nt	          |t          j!        j%                  r|#                    ||          |'z  }(nt          d          t	          |tL          tN          f          r%|(                    |&          }* |j)        |*d||fi}(n=t	          |tT                    r|)                    ||f          }(nt          d          tW          |          D ]4}+ ||!|+dz
  ddf         |          }, || |+dz
  ddf         |,          }-|"|+|z
  ddf         }. ||-|.          }/|dk    r+d}0|rd|.z  nd}1|r|1| |+dz
  ddf         z  n|1}2|rd|-z  nd}3n4|/}0|rd	n|.}1|r|1| |+dz
  ddf         z  n|1| |+dz
  ddf         z   }2|rd	n|-}3|/|0|(|+ddf         z  z   ||+ddf<   |-|||-z  |1z   z  |(|+ddf         z  z   | |+ddf<   |,|||,z  |2z   z  |(|+ddf         z  z   |!|+ddf<   |.|||.z  |3z   z  |(|+ddf         z  z   |"|+ddf<   6|rtY          ||          }t          j-        t          j.        |                    }4|j         d	         dk    r|j/        dk    r|4dddf         }4t	          | j        j0        tb                    s|4S | j        2                    |||z   dz
            \  }}}}5|dk    r"tg          j4        |4|5| j        j5                  }4ntg          j6        |4|5           }4|4S )!a  
        Random simulations using the state space formulation.

        Parameters
        ----------
        nsimulations : int
            The number of simulation steps.
        anchor : int, str, or datetime, optional
            First period for simulation. The simulation will be conditional on
            all existing datapoints prior to the `anchor`.  Type depends on the
            index of the given `endog` in the model. Two special cases are the
            strings 'start' and 'end'. `start` refers to beginning the
            simulation at the first period of the sample, and `end` refers to
            beginning the simulation at the first period after the sample.
            Integer values can run from 0 to `nobs`, or can be negative to
            apply negative indexing. Finally, if a date/time index was provided
            to the model, then this argument can be a date string to parse or a
            datetime type. Default is 'end'.
        repetitions : int, optional
            Number of simulated paths to generate. Default is 1 simulated path.
        error : {"add", "mul", "additive", "multiplicative"}, optional
            Error model for state space formulation. Default is ``"add"``.
        random_errors : optional
            Specifies how the random errors should be obtained. Can be one of
            the following:

            * ``None``: Random normally distributed values with variance
              estimated from the fit errors drawn from numpy's standard
              RNG (can be seeded with the `random_state` argument). This is the
              default option.
            * A distribution function from ``scipy.stats``, e.g.
              ``scipy.stats.norm``: Fits the distribution function to the fit
              errors and draws from the fitted distribution.
              Note the difference between ``scipy.stats.norm`` and
              ``scipy.stats.norm()``, the latter one is a frozen distribution
              function.
            * A frozen distribution function from ``scipy.stats``, e.g.
              ``scipy.stats.norm(scale=2)``: Draws from the frozen distribution
              function.
            * A ``np.ndarray`` with shape (`nsimulations`, `repetitions`): Uses
              the given values as random errors.
            * ``"bootstrap"``: Samples the random errors from the fit errors.

        random_state : int or np.random.RandomState, optional
            A seed for the random number generator or a
            ``np.random.RandomState`` object. Only used if `random_errors` is
            ``None``. Default is ``None``.

        Returns
        -------
        sim : pd.Series, pd.DataFrame or np.ndarray
            An ``np.ndarray``, ``pd.Series``, or ``pd.DataFrame`` of simulated
            values.
            If the original data was a ``pd.Series`` or ``pd.DataFrame``, `sim`
            will be a ``pd.Series`` if `repetitions` is 1, and a
            ``pd.DataFrame`` of shape (`nsimulations`, `repetitions`) else.
            Otherwise, if `repetitions` is 1, a ``np.ndarray`` of shape
            (`nsimulations`,) is returned, and if `repetitions` is not 1 a
            ``np.ndarray`` of shape (`nsimulations`, `repetitions`) is
            returned.

        Notes
        -----
        The simulation is based on the state space model of the Holt-Winter's
        methods. The state space model assumes that the true value at time
        :math:`t` is randomly distributed around the prediction value.
        If using the additive error model, this means:

        .. math::

            y_t &= \hat{y}_{t|t-1} + e_t\\
            e_t &\sim \mathcal{N}(0, \sigma^2)

        Using the multiplicative error model:

        .. math::

            y_t &= \hat{y}_{t|t-1} \cdot (1 + e_t)\\
            e_t &\sim \mathcal{N}(0, \sigma^2)

        Inserting these equations into the smoothing equation formulation leads
        to the state space equations. The notation used here follows
        [1]_.

        Additionally,

        .. math::

           B_t &= b_{t-1} \circ_d \phi\\
           L_t &= l_{t-1} \circ_b B_t\\
           S_t &= s_{t-m}\\
           Y_t &= L_t \circ_s S_t,

        where :math:`\circ_d` is the operation linking trend and damping
        parameter (multiplication if the trend is additive, power if the trend
        is multiplicative), :math:`\circ_b` is the operation linking level and
        trend (addition if the trend is additive, multiplication if the trend
        is multiplicative), and :math:`\circ_s` is the operation linking
        seasonality to the rest.

        The state space equations can then be formulated as

        .. math::

           y_t &= Y_t + \eta \cdot e_t\\
           l_t &= L_t + \alpha \cdot (M_e \cdot L_t + \kappa_l) \cdot e_t\\
           b_t &= B_t + \beta \cdot (M_e \cdot B_t + \kappa_b) \cdot e_t\\
           s_t &= S_t + \gamma \cdot (M_e \cdot S_t + \kappa_s) \cdot e_t\\

        with

        .. math::

           \eta &= \begin{cases}
                       Y_t\quad\text{if error is multiplicative}\\
                       1\quad\text{else}
                   \end{cases}\\
           M_e &= \begin{cases}
                       1\quad\text{if error is multiplicative}\\
                       0\quad\text{else}
                   \end{cases}\\

        and, when using the additive error model,

        .. math::

           \kappa_l &= \begin{cases}
                       \frac{1}{S_t}\quad
                       \text{if seasonality is multiplicative}\\
                       1\quad\text{else}
                   \end{cases}\\
           \kappa_b &= \begin{cases}
                       \frac{\kappa_l}{l_{t-1}}\quad
                       \text{if trend is multiplicative}\\
                       \kappa_l\quad\text{else}
                   \end{cases}\\
           \kappa_s &= \begin{cases}
                       \frac{1}{L_t}\quad\text{if seasonality is
                                               multiplicative}\\
                       1\quad\text{else}
                   \end{cases}

        When using the multiplicative error model

        .. math::

           \kappa_l &= \begin{cases}
                       0\quad
                       \text{if seasonality is multiplicative}\\
                       S_t\quad\text{else}
                   \end{cases}\\
           \kappa_b &= \begin{cases}
                       \frac{\kappa_l}{l_{t-1}}\quad
                       \text{if trend is multiplicative}\\
                       \kappa_l + l_{t-1}\quad\text{else}
                   \end{cases}\\
           \kappa_s &= \begin{cases}
                       0\quad\text{if seasonality is multiplicative}\\
                       L_t\quad\text{else}
                   \end{cases}

        References
        ----------
        .. [1] Hyndman, R.J., & Athanasopoulos, G. (2018) *Forecasting:
           principles and practice*, 2nd edition, OTexts: Melbourne,
           Australia. OTexts.com/fpp2. Accessed on February 28th 2020.
        )rq   rs   rp   rr   )rp   rr   zerror must be 'add' or 'mul'!NrV   rU   r   z/Cannot anchor simulation outside of the sample.rt   ru   smoothing_levelsmoothing_trendsmoothing_seasonaldamping_trendrW   r   initial_levelrZ   initial_trendinitial_seasonszNIf random_errors is an ndarray, it must have shape (nsimulations, repetitions)	bootstrapT)sizereplacezWArgument random_state must be None, an integer, or an instance of np.random.RandomStater   )r   z,Argument random_errors has unexpected value!)r   r   )r   )7
ValueErrorr%   nobs_get_index_locr_   slicerU   r-   damped_trendr   r&   maxr   	has_trendhas_seasonalr   multiplypowerrp   r,   r.   emptyconcatenatetileTr   r2   _ysqrtsumr   ndarrayrd   randomchoicerandnr`   RandomStater   r   fitrvsr   ranger   
atleast_1dsqueezer   r   r   _get_prediction_indexra   r   endog_namesr   )6r$   nsimulationsanchorrepetitionserrorrandom_errorsrandom_state	start_idxr   r-   dampedr   rt   ru   alphabetagammaphimn_paramsmul_seasonal	mul_trend	mul_errorop_bop_d	neutral_bop_s	neutral_sr,   r   r.   ylvlbsr   _sfittedr0   sigmaepsrngr&   tb0l0s0y0etakappa_lkappa_bkappa_ssimr   s6                                                         r7   simulatezHoltWintersResults.simulate  s	   d 222!&%@@GE&&<=== >Vu__
IIwII"j77??OIq!)U++ ,%O	q==(Itz&&NOOO 
 (:&[.
G$-.{,-01k/*
+Q//$*&&'1u
//0  	  5(UN	UN	  	;D8DII6D;DI 	;DII6DI 
HlK011hq(+677HlQ&455HlQ&455>>_5CAAAJ{?3Ab!!!eHHy1}-CAAAJi!m,Ab!!!eH	>>i1nn"k*;<O ,fZiZ.@A B [!$4557Aqbcc111fIIy1}y01K3C  qbcc111fI
 =AaaadGCDAaaadGE 	C  	'D-u55FF&FE>>JMF*EEZ]V+v5Euax((CJJ,ABCC mRZ00 	M"|[&AAA 2    CCk)))""\;7 #  CC "#ioolK@@5HL#.. 	i++L99iik::UBL")*?@@ "(({CCeK >   {'CDD 	M"&&u--F#-#VN<2MNNCCy11 	M##,)D#EECCKLLL|$$ 	J 	JAaAqqqk3''Bc!a%(mR((B1q5!!!8Bb"B~~$07!b&&a5>K'CAqqqM11G$07!b&&a+3!! !1Gc!a%(m++ 3q1uaaax=0 
  ,3!!3QT?*AadGUi"nw&>?#ad)KKC111I49r>G#;<s1aaa4yHHAadG5INW$<=AqqqD	IIAadGG 	%1e$$AmBJqMM**71:??qvzzdAAAg,C$*/:66 	J99y</!3
 
1a !)Cu4:3IJJJCC,s%000C
r8   r   )NN)rW   )NrW   rp   NN)r   
__module____qualname____doc__r   propertyr(   r)   r*   r'   r%   setterr,   r+   r-   r.   r/   r2   r3   r4   r0   r1   r5   rT   rh   r   r	  __classcell__)r6   s   @r7   r   r      s       + +~ %%( %( %( %( %( %(N   X   X   X   X   X \  \   X   X   X   X & & X& " " X" ! ! X! ! ! X!   X   X ! ! X! " " "; ; ; ;2K K K K<g g gX i i i i i i i ir8   r   c                   n    e Zd ZdddddddZ eej        e          ZdddZ eej        e          ZdS )HoltWintersResultsWrapperrows)r2   r,   r0   r.   r-   slopedates)rT   rh   N)	r   r
  r  _attrsr   r
   _wrap_attrs_methods_wrap_methodsr\   r8   r7   r  r    sc         F +n8&AAK"88HK <hGGMMMr8   r  )numpyr   pandasra   scipy.specialr   scipy.statsr   r   r   scipy.stats.distributionsr   statsmodels.base.datar   statsmodels.base.modelr	   statsmodels.base.wrapperr
   r   r   r   r  r\   r8   r7   <module>r!     sM           $ $ $ $ $ $         
 0 / / / / / , , , , , , * * * * * *         Y Y Y Y Y Y Y YxH H H H H H H H  *,> ? ? ? ? ?r8   