code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def load_results_jmulti(dataset, dt_s_list): """ Parameters ---------- dataset : module A data module in the statsmodels/datasets directory that defines a __str__() method returning the dataset's name. dt_s_list : list A list of strings where each string represents a combination of deterministic terms. Returns ------- result : dict A dict (keys: tuples of deterministic terms and seasonal terms) of dicts (keys: strings "est" (for estimators), "se" (for standard errors), "t" (for t-values), "p" (for p-values)) of dicts (keys: strings "alpha", "beta", "Gamma" and other results) """ source = "jmulti" results_dict_per_det_terms = dict.fromkeys(dt_s_list) for dt_s in dt_s_list: dt_string = dt_s_tup_to_string(dt_s) params_file = dataset.__str__()+"_"+source+"_"+dt_string+".txt" params_file = os.path.join(here, params_file) # sections in jmulti output: section_headers = ["Lagged endogenous term", # parameter matrices "Deterministic term"] # c, s, ct if dt_string == "nc": del section_headers[-1] results = dict() results["est"] = dict.fromkeys(section_headers) results["se"] = dict.fromkeys(section_headers) results["t"] = dict.fromkeys(section_headers) results["p"] = dict.fromkeys(section_headers) result = [] result_se = [] result_t = [] result_p = [] rows = 0 started_reading_section = False start_end_mark = "-----" # --------------------------------------------------------------------- # parse information about \alpha, \beta, \Gamma, deterministic of VECM # and A_i and deterministic of corresponding VAR: section = -1 params_file = open(params_file, encoding='latin_1') for line in params_file: if section == -1 and section_headers[section+1] not in line: continue if section < len(section_headers)-1 \ and section_headers[section+1] in line: # new section section += 1 continue if not started_reading_section: if line.startswith(start_end_mark): started_reading_section = True continue if started_reading_section: if line.startswith(start_end_mark): if result == []: # no values collected in section "Legend" started_reading_section = False continue results["est"][section_headers[section]] = np.column_stack( result) result = [] results["se"][section_headers[section]] = np.column_stack( result_se) result_se = [] results["t"][section_headers[section]] = np.column_stack( result_t) result_t = [] results["p"][section_headers[section]] = np.column_stack( result_p) result_p = [] started_reading_section = False continue str_number = r"-?\d+\.\d{3}" regex_est = re.compile(str_number + r"[^\)\]\}]") est_col = re.findall(regex_est, line) # standard errors in parantheses in JMulTi output: regex_se = re.compile(r"\(" + str_number + r"\)") se_col = re.findall(regex_se, line) # t-values in brackets in JMulTi output: regex_t_value = re.compile(r"\[" + str_number + r"\]") t_col = re.findall(regex_t_value, line) # p-values in braces in JMulTi output: regex_p_value = re.compile(r"\{" + str_number + r"\}") p_col = re.findall(regex_p_value, line) if result == [] and est_col != []: rows = len(est_col) if est_col != []: est_col = [float(el) for el in est_col] result.append(est_col) elif se_col != []: for i in range(rows): se_col[i] = se_col[i].replace("(", "").replace(")", "") se_col = [float(el) for el in se_col] result_se.append(se_col) elif t_col != []: for i in range(rows): t_col[i] = t_col[i].replace("[", "").replace("]", "") t_col = [float(el) for el in t_col] result_t.append(t_col) elif p_col != []: for i in range(rows): p_col[i] = p_col[i].replace("{", "").replace("}", "") p_col = [float(el) for el in p_col] result_p.append(p_col) params_file.close() # --------------------------------------------------------------------- # parse information regarding \Sigma_u sigmau_file = dataset.__str__() + "_" + source + "_" + dt_string \ + "_Sigmau" + ".txt" sigmau_file = os.path.join(here, sigmau_file) rows_to_parse = 0 # all numbers of Sigma_u in notation with e (e.g. 2.283862e-05) regex_est = re.compile(r"\s+\S+e\S+") sigmau_section_reached = False sigmau_file = open(sigmau_file, encoding='latin_1') for line in sigmau_file: if line.startswith("Log Likelihood:"): line = line[len("Log Likelihood:"):] results["log_like"] = float(re.findall(regex_est, line)[0]) continue if not sigmau_section_reached and "Covariance:" not in line: continue if "Covariance:" in line: sigmau_section_reached = True row = re.findall(regex_est, line) rows_to_parse = len(row) # Sigma_u quadratic ==> #rows==#cols sigma_u = np.empty((rows_to_parse, rows_to_parse)) row = re.findall(regex_est, line) rows_to_parse -= 1 sigma_u[rows_to_parse] = row # rows are added in reverse order... if rows_to_parse == 0: break sigmau_file.close() results["est"]["Sigma_u"] = sigma_u[::-1] # ...and reversed again here # --------------------------------------------------------------------- # parse forecast related output: fc_file = dataset.__str__() + "_" + source + "_" + dt_string \ + "_fc5" + ".txt" fc_file = os.path.join(here, fc_file) fc, lower, upper, plu_min = [], [], [], [] fc_file = open(fc_file, encoding='latin_1') for line in fc_file: str_number = r"(\s+-?\d+\.\d{3}\s*)" regex_number = re.compile(str_number) numbers = re.findall(regex_number, line) if numbers == []: continue fc.append(float(numbers[0])) lower.append(float(numbers[1])) upper.append(float(numbers[2])) plu_min.append(float(numbers[3])) fc_file.close() neqs = len(results["est"]["Sigma_u"]) fc = np.hstack(np.vsplit(np.array(fc)[:, None], neqs)) lower = np.hstack(np.vsplit(np.array(lower)[:, None], neqs)) upper = np.hstack(np.vsplit(np.array(upper)[:, None], neqs)) results["fc"] = dict.fromkeys(["fc", "lower", "upper"]) results["fc"]["fc"] = fc results["fc"]["lower"] = lower results["fc"]["upper"] = upper # --------------------------------------------------------------------- # parse output related to Granger-caus. and instantaneous causality: results["granger_caus"] = dict.fromkeys(["p", "test_stat"]) results["granger_caus"]["p"] = dict() results["granger_caus"]["test_stat"] = dict() results["inst_caus"] = dict.fromkeys(["p", "test_stat"]) results["inst_caus"]["p"] = dict() results["inst_caus"]["test_stat"] = dict() vn = dataset.variable_names # all possible combinations of potentially causing variables # (at least 1 variable and not all variables together): var_combs = sublists(vn, 1, len(vn)-1) if debug_mode: print("\n\n\n" + dt_string) for causing in var_combs: caused = tuple(name for name in vn if name not in causing) causality_file = dataset.__str__() + "_" + source + "_" \ + dt_string + "_granger_causality_" \ + stringify_var_names(causing, "_") + ".txt" causality_file = os.path.join(here, causality_file) causality_file = open(causality_file, encoding="latin_1") causality_results = [] for line in causality_file: str_number = r"\d+\.\d{4}" regex_number = re.compile(str_number) number = re.search(regex_number, line) if number is None: continue number = float(number.group(0)) causality_results.append(number) causality_file.close() results["granger_caus"]["test_stat"][(causing, caused)] = \ causality_results[0] results["granger_caus"]["p"][(causing, caused)] =\ causality_results[1] results["inst_caus"]["test_stat"][(causing, caused)] = \ causality_results[2] results["inst_caus"]["p"][(causing, caused)] = \ causality_results[3] # --------------------------------------------------------------------- # parse output related to impulse-response analysis: ir_file = dataset.__str__() + "_" + source + "_" + dt_string \ + "_ir" + ".txt" ir_file = os.path.join(here, ir_file) ir_file = open(ir_file, encoding='latin_1') causing = None caused = None data = None regex_vars = re.compile(r"\w+") regex_vals = re.compile(r"-?\d+\.\d{4}") line_start_causing = "time" data_line_indicator = "point estimate" data_rows_read = 0 for line in ir_file: if causing is None and not line.startswith(line_start_causing): continue # no relevant info in the header if line.startswith(line_start_causing): line = line[4:] causing = re.findall(regex_vars, line) # 21 periods shown in JMulTi output data = np.empty((21, len(causing))) continue if caused is None: caused = re.findall(regex_vars, line) continue # now start collecting the values: if data_line_indicator not in line: continue start = line.find(data_line_indicator) + len(data_line_indicator) line = line[start:] data[data_rows_read] = re.findall(regex_vals, line) data_rows_read += 1 ir_file.close() results["ir"] = data # --------------------------------------------------------------------- # parse output related to lag order selection: lagorder_file = dataset.__str__() + "_" + source + "_" + dt_string \ + "_lagorder" + ".txt" lagorder_file = os.path.join(here, lagorder_file) lagorder_file = open(lagorder_file, encoding='latin_1') results["lagorder"] = dict() aic_start = "Akaike Info Criterion:" fpe_start = "Final Prediction Error:" hqic_start = "Hannan-Quinn Criterion:" bic_start = "Schwarz Criterion:" for line in lagorder_file: if line.startswith(aic_start): results["lagorder"]["aic"] = int(line[len(aic_start):]) elif line.startswith(fpe_start): results["lagorder"]["fpe"] = int(line[len(fpe_start):]) elif line.startswith(hqic_start): results["lagorder"]["hqic"] = int(line[len(hqic_start):]) elif line.startswith(bic_start): results["lagorder"]["bic"] = int(line[len(bic_start):]) lagorder_file.close() # --------------------------------------------------------------------- # parse output related to non-normality-test: test_norm_file = dataset.__str__() + "_" + source + "_" + dt_string \ + "_diag" + ".txt" test_norm_file = os.path.join(here, test_norm_file) test_norm_file = open(test_norm_file, encoding='latin_1') results["test_norm"] = dict() section_start_marker = "TESTS FOR NONNORMALITY" section_reached = False subsection_start_marker = "Introduction to Multiple Time Series A" subsection_reached = False line_start_statistic = "joint test statistic:" line_start_pvalue = " p-value:" for line in test_norm_file: if not section_reached: if section_start_marker in line: section_reached = True # section w/ relevant results found continue if not subsection_reached: if subsection_start_marker in line: subsection_reached = True continue if "joint_pvalue" in results["test_norm"].keys(): break if line.startswith(line_start_statistic): line_end = line[len(line_start_statistic):] results["test_norm"]["joint_test_statistic"] = float(line_end) if line.startswith(line_start_pvalue): line_end = line[len(line_start_pvalue):] results["test_norm"]["joint_pvalue"] = float(line_end) test_norm_file.close() # --------------------------------------------------------------------- # parse output related to testing the whiteness of the residuals: whiteness_file = dataset.__str__() + "_" + source + "_" + dt_string \ + "_diag" + ".txt" whiteness_file = os.path.join(here, whiteness_file) whiteness_file = open(whiteness_file, encoding='latin_1') results["whiteness"] = dict() section_start_marker = "PORTMANTEAU TEST" order_start = "tested order:" statistic_start = "test statistic:" p_start = " p-value:" adj_statistic_start = "adjusted test statistic:" unadjusted_finished = False in_section = False for line in whiteness_file: if not in_section and section_start_marker not in line: continue if not in_section and section_start_marker in line: in_section = True continue if line.startswith(order_start): results["whiteness"]["tested order"] = int( line[len(order_start):]) continue if line.startswith(statistic_start): results["whiteness"]["test statistic"] = float( line[len(statistic_start):]) continue if line.startswith(adj_statistic_start): results["whiteness"]["test statistic adj."] = float( line[len(adj_statistic_start):]) continue if line.startswith(p_start): # same for unadjusted and adjusted if not unadjusted_finished: results["whiteness"]["p-value"] = \ float(line[len(p_start):]) unadjusted_finished = True else: results["whiteness"]["p-value adjusted"] = \ float(line[len(p_start):]) break whiteness_file.close() # --------------------------------------------------------------------- if debug_mode: print_debug_output(results, dt_string) results_dict_per_det_terms[dt_s] = results return results_dict_per_det_terms
Parameters ---------- dataset : module A data module in the statsmodels/datasets directory that defines a __str__() method returning the dataset's name. dt_s_list : list A list of strings where each string represents a combination of deterministic terms. Returns ------- result : dict A dict (keys: tuples of deterministic terms and seasonal terms) of dicts (keys: strings "est" (for estimators), "se" (for standard errors), "t" (for t-values), "p" (for p-values)) of dicts (keys: strings "alpha", "beta", "Gamma" and other results)
load_results_jmulti
python
statsmodels/statsmodels
statsmodels/tsa/vector_ar/tests/JMulTi_results/parse_jmulti_var_output.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/vector_ar/tests/JMulTi_results/parse_jmulti_var_output.py
BSD-3-Clause
def fit(self, start_params=None, transformed=True, includes_fixed=False, method=None, method_kwargs=None, gls=None, gls_kwargs=None, cov_type=None, cov_kwds=None, return_params=False, low_memory=False): """ Fit (estimate) the parameters of the model. Parameters ---------- start_params : array_like, optional Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start_params. transformed : bool, optional Whether or not `start_params` is already transformed. Default is True. includes_fixed : bool, optional If parameters were previously fixed with the `fix_params` method, this argument describes whether or not `start_params` also includes the fixed parameters, in addition to the free parameters. Default is False. method : str, optional The method used for estimating the parameters of the model. Valid options include 'statespace', 'innovations_mle', 'hannan_rissanen', 'burg', 'innovations', and 'yule_walker'. Not all options are available for every specification (for example 'yule_walker' can only be used with AR(p) models). method_kwargs : dict, optional Arguments to pass to the fit function for the parameter estimator described by the `method` argument. gls : bool, optional Whether or not to use generalized least squares (GLS) to estimate regression effects. The default is False if `method='statespace'` and is True otherwise. gls_kwargs : dict, optional Arguments to pass to the GLS estimation fit method. Only applicable if GLS estimation is used (see `gls` argument for details). cov_type : str, optional The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: - 'opg' for the outer product of gradient estimator - 'oim' for the observed information matrix estimator, calculated using the method of Harvey (1989) - 'approx' for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. - 'robust' for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presence of some misspecifications. Intermediate calculations use the 'oim' method. - 'robust_approx' is the same as 'robust' except that the intermediate calculations use the 'approx' method. - 'none' for no covariance matrix calculation. Default is 'opg' unless memory conservation is used to avoid computing the loglikelihood values for each observation, in which case the default is 'oim'. cov_kwds : dict or None, optional A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust_approx** - 'approx_complex_step' : bool, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. - 'approx_centered' : bool, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. return_params : bool, optional Whether or not to return only the array of maximizing parameters. Default is False. low_memory : bool, optional If set to True, techniques are applied to substantially reduce memory usage. If used, some features of the results object will not be available (including smoothed results and in-sample prediction), although out-of-sample forecasting is possible. Default is False. Returns ------- ARIMAResults Examples -------- >>> mod = sm.tsa.arima.ARIMA(endog, order=(1, 0, 0)) >>> res = mod.fit() >>> print(res.summary()) """ # Determine which method to use # 1. If method is specified, make sure it is valid if method is not None: self._spec_arima.validate_estimator(method) # 2. Otherwise, use state space # TODO: may want to consider using innovations (MLE) if possible here, # (since in some cases it may be faster than state space), but it is # less tested. else: method = 'statespace' # Can only use fixed parameters with the following methods methods_with_fixed_params = ['statespace', 'hannan_rissanen'] if self._has_fixed_params and method not in methods_with_fixed_params: raise ValueError( "When parameters have been fixed, only the methods " f"{methods_with_fixed_params} can be used; got '{method}'." ) # Handle kwargs related to the fit method if method_kwargs is None: method_kwargs = {} required_kwargs = [] if method == 'statespace': required_kwargs = ['enforce_stationarity', 'enforce_invertibility', 'concentrate_scale'] elif method == 'innovations_mle': required_kwargs = ['enforce_invertibility'] for name in required_kwargs: if name in method_kwargs: raise ValueError('Cannot override model level value for "%s"' ' when method="%s".' % (name, method)) method_kwargs[name] = getattr(self, name) # Handle kwargs related to GLS estimation if gls_kwargs is None: gls_kwargs = {} # Handle starting parameters # TODO: maybe should have standard way of computing starting # parameters in this class? if start_params is not None: if method not in ['statespace', 'innovations_mle']: raise ValueError('Estimation method "%s" does not use starting' ' parameters, but `start_params` argument was' ' given.' % method) method_kwargs['start_params'] = start_params method_kwargs['transformed'] = transformed method_kwargs['includes_fixed'] = includes_fixed # Perform estimation, depending on whether we have exog or not p = None fit_details = None has_exog = self._spec_arima.exog is not None if has_exog or method == 'statespace': # Use GLS if it was explicitly requested (`gls = True`) or if it # was left at the default (`gls = None`) and the ARMA estimator is # anything but statespace. # Note: both GLS and statespace are able to handle models with # integration, so we don't need to difference endog or exog here. if has_exog and (gls or (gls is None and method != 'statespace')): if self._has_fixed_params: raise NotImplementedError( 'GLS estimation is not yet implemented for the case ' 'with fixed parameters.' ) p, fit_details = estimate_gls( self.endog, exog=self.exog, order=self.order, seasonal_order=self.seasonal_order, include_constant=False, arma_estimator=method, arma_estimator_kwargs=method_kwargs, **gls_kwargs) elif method != 'statespace': raise ValueError('If `exog` is given and GLS is disabled' ' (`gls=False`), then the only valid' " method is 'statespace'. Got '%s'." % method) else: method_kwargs.setdefault('disp', 0) res = super().fit( return_params=return_params, low_memory=low_memory, cov_type=cov_type, cov_kwds=cov_kwds, **method_kwargs) if not return_params: res.fit_details = res.mlefit else: # Handle differencing if we have an integrated model # (these methods do not support handling integration internally, # so we need to manually do the differencing) endog = self.endog order = self._spec_arima.order seasonal_order = self._spec_arima.seasonal_order if self._spec_arima.is_integrated: warnings.warn('Provided `endog` series has been differenced' ' to eliminate integration prior to parameter' ' estimation by method "%s".' % method, stacklevel=2,) endog = diff( endog, k_diff=self._spec_arima.diff, k_seasonal_diff=self._spec_arima.seasonal_diff, seasonal_periods=self._spec_arima.seasonal_periods) if order[1] > 0: order = (order[0], 0, order[2]) if seasonal_order[1] > 0: seasonal_order = (seasonal_order[0], 0, seasonal_order[2], seasonal_order[3]) if self._has_fixed_params: method_kwargs['fixed_params'] = self._fixed_params.copy() # Now, estimate parameters if method == 'yule_walker': p, fit_details = yule_walker( endog, ar_order=order[0], demean=False, **method_kwargs) elif method == 'burg': p, fit_details = burg(endog, ar_order=order[0], demean=False, **method_kwargs) elif method == 'hannan_rissanen': p, fit_details = hannan_rissanen( endog, ar_order=order[0], ma_order=order[2], demean=False, **method_kwargs) elif method == 'innovations': p, fit_details = innovations( endog, ma_order=order[2], demean=False, **method_kwargs) # innovations computes estimates through the given order, so # we want to take the estimate associated with the given order p = p[-1] elif method == 'innovations_mle': p, fit_details = innovations_mle( endog, order=order, seasonal_order=seasonal_order, demean=False, **method_kwargs) # In all cases except method='statespace', we now need to extract the # parameters and, optionally, create a new results object if p is not None: # Need to check that fitted parameters satisfy given restrictions if (self.enforce_stationarity and self._spec_arima.max_reduced_ar_order > 0 and not p.is_stationary): raise ValueError('Non-stationary autoregressive parameters' ' found with `enforce_stationarity=True`.' ' Consider setting it to False or using a' ' different estimation method, such as' ' method="statespace".') if (self.enforce_invertibility and self._spec_arima.max_reduced_ma_order > 0 and not p.is_invertible): raise ValueError('Non-invertible moving average parameters' ' found with `enforce_invertibility=True`.' ' Consider setting it to False or using a' ' different estimation method, such as' ' method="statespace".') # Build the requested results if return_params: res = p.params else: # Handle memory conservation option if low_memory: conserve_memory = self.ssm.conserve_memory self.ssm.set_conserve_memory(MEMORY_CONSERVE) # Perform filtering / smoothing if (self.ssm.memory_no_predicted or self.ssm.memory_no_gain or self.ssm.memory_no_smoothing): func = self.filter else: func = self.smooth res = func(p.params, transformed=True, includes_fixed=True, cov_type=cov_type, cov_kwds=cov_kwds) # Save any details from the fit method res.fit_details = fit_details # Reset memory conservation if low_memory: self.ssm.set_conserve_memory(conserve_memory) return res
Fit (estimate) the parameters of the model. Parameters ---------- start_params : array_like, optional Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start_params. transformed : bool, optional Whether or not `start_params` is already transformed. Default is True. includes_fixed : bool, optional If parameters were previously fixed with the `fix_params` method, this argument describes whether or not `start_params` also includes the fixed parameters, in addition to the free parameters. Default is False. method : str, optional The method used for estimating the parameters of the model. Valid options include 'statespace', 'innovations_mle', 'hannan_rissanen', 'burg', 'innovations', and 'yule_walker'. Not all options are available for every specification (for example 'yule_walker' can only be used with AR(p) models). method_kwargs : dict, optional Arguments to pass to the fit function for the parameter estimator described by the `method` argument. gls : bool, optional Whether or not to use generalized least squares (GLS) to estimate regression effects. The default is False if `method='statespace'` and is True otherwise. gls_kwargs : dict, optional Arguments to pass to the GLS estimation fit method. Only applicable if GLS estimation is used (see `gls` argument for details). cov_type : str, optional The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: - 'opg' for the outer product of gradient estimator - 'oim' for the observed information matrix estimator, calculated using the method of Harvey (1989) - 'approx' for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. - 'robust' for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presence of some misspecifications. Intermediate calculations use the 'oim' method. - 'robust_approx' is the same as 'robust' except that the intermediate calculations use the 'approx' method. - 'none' for no covariance matrix calculation. Default is 'opg' unless memory conservation is used to avoid computing the loglikelihood values for each observation, in which case the default is 'oim'. cov_kwds : dict or None, optional A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust_approx** - 'approx_complex_step' : bool, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. - 'approx_centered' : bool, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. return_params : bool, optional Whether or not to return only the array of maximizing parameters. Default is False. low_memory : bool, optional If set to True, techniques are applied to substantially reduce memory usage. If used, some features of the results object will not be available (including smoothed results and in-sample prediction), although out-of-sample forecasting is possible. Default is False. Returns ------- ARIMAResults Examples -------- >>> mod = sm.tsa.arima.ARIMA(endog, order=(1, 0, 0)) >>> res = mod.fit() >>> print(res.summary())
fit
python
statsmodels/statsmodels
statsmodels/tsa/arima/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/model.py
BSD-3-Clause
def exog_params(self): """(array) Parameters associated with exogenous variables.""" return self._params_split['exog_params']
(array) Parameters associated with exogenous variables.
exog_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def ar_params(self): """(array) Autoregressive (non-seasonal) parameters.""" return self._params_split['ar_params']
(array) Autoregressive (non-seasonal) parameters.
ar_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def ar_poly(self): """(Polynomial) Autoregressive (non-seasonal) lag polynomial.""" coef = np.zeros(self.spec.max_ar_order + 1) coef[0] = 1 ix = self.spec.ar_lags coef[ix] = -self._params_split['ar_params'] return Polynomial(coef)
(Polynomial) Autoregressive (non-seasonal) lag polynomial.
ar_poly
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def ma_params(self): """(array) Moving average (non-seasonal) parameters.""" return self._params_split['ma_params']
(array) Moving average (non-seasonal) parameters.
ma_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def ma_poly(self): """(Polynomial) Moving average (non-seasonal) lag polynomial.""" coef = np.zeros(self.spec.max_ma_order + 1) coef[0] = 1 ix = self.spec.ma_lags coef[ix] = self._params_split['ma_params'] return Polynomial(coef)
(Polynomial) Moving average (non-seasonal) lag polynomial.
ma_poly
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def seasonal_ar_params(self): """(array) Seasonal autoregressive parameters.""" return self._params_split['seasonal_ar_params']
(array) Seasonal autoregressive parameters.
seasonal_ar_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def seasonal_ar_poly(self): """(Polynomial) Seasonal autoregressive lag polynomial.""" # Need to expand the polynomial according to the season s = self.spec.seasonal_periods coef = [1] if s > 0: expanded = np.zeros(self.spec.max_seasonal_ar_order) ix = np.array(self.spec.seasonal_ar_lags, dtype=int) - 1 expanded[ix] = -self._params_split['seasonal_ar_params'] coef = np.r_[1, np.pad(np.reshape(expanded, (-1, 1)), [(0, 0), (s - 1, 0)], 'constant').flatten()] return Polynomial(coef)
(Polynomial) Seasonal autoregressive lag polynomial.
seasonal_ar_poly
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def seasonal_ma_params(self): """(array) Seasonal moving average parameters.""" return self._params_split['seasonal_ma_params']
(array) Seasonal moving average parameters.
seasonal_ma_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def seasonal_ma_poly(self): """(Polynomial) Seasonal moving average lag polynomial.""" # Need to expand the polynomial according to the season s = self.spec.seasonal_periods coef = np.array([1]) if s > 0: expanded = np.zeros(self.spec.max_seasonal_ma_order) ix = np.array(self.spec.seasonal_ma_lags, dtype=int) - 1 expanded[ix] = self._params_split['seasonal_ma_params'] coef = np.r_[1, np.pad(np.reshape(expanded, (-1, 1)), [(0, 0), (s - 1, 0)], 'constant').flatten()] return Polynomial(coef)
(Polynomial) Seasonal moving average lag polynomial.
seasonal_ma_poly
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def sigma2(self): """(float) Innovation variance.""" return self._params_split['sigma2']
(float) Innovation variance.
sigma2
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def reduced_ar_poly(self): """(Polynomial) Reduced form autoregressive lag polynomial.""" return self.ar_poly * self.seasonal_ar_poly
(Polynomial) Reduced form autoregressive lag polynomial.
reduced_ar_poly
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def reduced_ma_poly(self): """(Polynomial) Reduced form moving average lag polynomial.""" return self.ma_poly * self.seasonal_ma_poly
(Polynomial) Reduced form moving average lag polynomial.
reduced_ma_poly
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def params(self): """(array) Complete parameter vector.""" if self._params is None: self._params = self.spec.join_params(**self._params_split) return self._params.copy()
(array) Complete parameter vector.
params
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def is_complete(self): """(bool) Are current parameter values all filled in (i.e. not NaN).""" return not np.any(np.isnan(self.params))
(bool) Are current parameter values all filled in (i.e. not NaN).
is_complete
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def is_valid(self): """(bool) Are current parameter values valid (e.g. variance > 0).""" valid = True try: self.spec.validate_params(self.params) except ValueError: valid = False return valid
(bool) Are current parameter values valid (e.g. variance > 0).
is_valid
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def is_stationary(self): """(bool) Is the reduced autoregressive lag poylnomial stationary.""" validate_basic(self.ar_params, self.k_ar_params, title='AR coefficients') validate_basic(self.seasonal_ar_params, self.k_seasonal_ar_params, title='seasonal AR coefficients') ar_stationary = True seasonal_ar_stationary = True if self.k_ar_params > 0: ar_stationary = is_invertible(self.ar_poly.coef) if self.k_seasonal_ar_params > 0: seasonal_ar_stationary = is_invertible(self.seasonal_ar_poly.coef) return ar_stationary and seasonal_ar_stationary
(bool) Is the reduced autoregressive lag poylnomial stationary.
is_stationary
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def is_invertible(self): """(bool) Is the reduced moving average lag poylnomial invertible.""" # Short-circuit if there is no MA component validate_basic(self.ma_params, self.k_ma_params, title='MA coefficients') validate_basic(self.seasonal_ma_params, self.k_seasonal_ma_params, title='seasonal MA coefficients') ma_stationary = True seasonal_ma_stationary = True if self.k_ma_params > 0: ma_stationary = is_invertible(self.ma_poly.coef) if self.k_seasonal_ma_params > 0: seasonal_ma_stationary = is_invertible(self.seasonal_ma_poly.coef) return ma_stationary and seasonal_ma_stationary
(bool) Is the reduced moving average lag poylnomial invertible.
is_invertible
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def to_dict(self): """ Return the parameters split by type into a dictionary. Returns ------- split_params : dict Dictionary with keys 'exog_params', 'ar_params', 'ma_params', 'seasonal_ar_params', 'seasonal_ma_params', and (unless `concentrate_scale=True`) 'sigma2'. Values are the parameters associated with the key, based on the `params` argument. """ return self._params_split.copy()
Return the parameters split by type into a dictionary. Returns ------- split_params : dict Dictionary with keys 'exog_params', 'ar_params', 'ma_params', 'seasonal_ar_params', 'seasonal_ma_params', and (unless `concentrate_scale=True`) 'sigma2'. Values are the parameters associated with the key, based on the `params` argument.
to_dict
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def to_pandas(self): """ Return the parameters as a Pandas series. Returns ------- series : pd.Series Pandas series with index set to the parameter names. """ return pd.Series(self.params, index=self.param_names)
Return the parameters as a Pandas series. Returns ------- series : pd.Series Pandas series with index set to the parameter names.
to_pandas
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def __repr__(self): """Represent SARIMAXParams object as a string.""" components = [] if self.k_exog_params: components.append('exog=%s' % str(self.exog_params)) if self.k_ar_params: components.append('ar=%s' % str(self.ar_params)) if self.k_ma_params: components.append('ma=%s' % str(self.ma_params)) if self.k_seasonal_ar_params: components.append('seasonal_ar=%s' % str(self.seasonal_ar_params)) if self.k_seasonal_ma_params: components.append('seasonal_ma=%s' % str(self.seasonal_ma_params)) if not self.spec.concentrate_scale: components.append('sigma2=%s' % self.sigma2) return 'SARIMAXParams(%s)' % ', '.join(components)
Represent SARIMAXParams object as a string.
__repr__
python
statsmodels/statsmodels
statsmodels/tsa/arima/params.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/params.py
BSD-3-Clause
def standardize_lag_order(order, title=None): """ Standardize lag order input. Parameters ---------- order : int or array_like Maximum lag order (if integer) or iterable of specific lag orders. title : str, optional Description of the order (e.g. "autoregressive") to use in error messages. Returns ------- order : int or list of int Maximum lag order if consecutive lag orders were specified, otherwise a list of integer lag orders. Notes ----- It is ambiguous if order=[1] is meant to be a boolean list or a list of lag orders to include, but this is irrelevant because either interpretation gives the same result. Order=[0] would be ambiguous, except that 0 is not a valid lag order to include, so there is no harm in interpreting as a boolean list, in which case it is the same as order=0, which seems like reasonable behavior. Examples -------- >>> standardize_lag_order(3) 3 >>> standardize_lag_order(np.arange(1, 4)) 3 >>> standardize_lag_order([1, 3]) [1, 3] """ order = np.array(order) title = 'order' if title is None else '%s order' % title # Only integer orders are valid if not np.all(order == order.astype(int)): raise ValueError('Invalid %s. Non-integer order (%s) given.' % (title, order)) order = order.astype(int) # Only positive integers are valid if np.any(order < 0): raise ValueError('Terms in the %s cannot be negative.' % title) # Try to squeeze out an irrelevant trailing dimension if order.ndim == 2 and order.shape[1] == 1: order = order[:, 0] elif order.ndim > 1: raise ValueError('Invalid %s. Must be an integer or' ' 1-dimensional array-like object (e.g. list,' ' ndarray, etc.). Got %s.' % (title, order)) # Option 1: the typical integer response (implies including all # lags up through and including the value) if order.ndim == 0: order = order.item() elif len(order) == 0: order = 0 else: # Option 2: boolean list has_zeros = (0 in order) has_multiple_ones = np.sum(order == 1) > 1 has_gt_one = np.any(order > 1) if has_zeros or has_multiple_ones: if has_gt_one: raise ValueError('Invalid %s. Appears to be a boolean list' ' (since it contains a 0 element and/or' ' multiple elements) but also contains' ' elements greater than 1 like a list of' ' lag orders.' % title) order = (np.where(order == 1)[0] + 1) # (Default) Option 3: list of lag orders to include else: order = np.sort(order) # If we have an empty list, set order to zero if len(order) == 0: order = 0 # If we actually were given consecutive lag orders, just use integer elif np.all(order == np.arange(1, len(order) + 1)): order = order[-1] # Otherwise, convert to list else: order = order.tolist() # Check for duplicates has_duplicate = isinstance(order, list) and np.any(np.diff(order) == 0) if has_duplicate: raise ValueError('Invalid %s. Cannot have duplicate elements.' % title) return order
Standardize lag order input. Parameters ---------- order : int or array_like Maximum lag order (if integer) or iterable of specific lag orders. title : str, optional Description of the order (e.g. "autoregressive") to use in error messages. Returns ------- order : int or list of int Maximum lag order if consecutive lag orders were specified, otherwise a list of integer lag orders. Notes ----- It is ambiguous if order=[1] is meant to be a boolean list or a list of lag orders to include, but this is irrelevant because either interpretation gives the same result. Order=[0] would be ambiguous, except that 0 is not a valid lag order to include, so there is no harm in interpreting as a boolean list, in which case it is the same as order=0, which seems like reasonable behavior. Examples -------- >>> standardize_lag_order(3) 3 >>> standardize_lag_order(np.arange(1, 4)) 3 >>> standardize_lag_order([1, 3]) [1, 3]
standardize_lag_order
python
statsmodels/statsmodels
statsmodels/tsa/arima/tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/tools.py
BSD-3-Clause
def validate_basic(params, length, allow_infnan=False, title=None): """ Validate parameter vector for basic correctness. Parameters ---------- params : array_like Array of parameters to validate. length : int Expected length of the parameter vector. allow_infnan : bool, optional Whether or not to allow `params` to contain -np.inf, np.inf, and np.nan. Default is False. title : str, optional Description of the parameters (e.g. "autoregressive") to use in error messages. Returns ------- params : ndarray Array of validated parameters. Notes ----- Basic check that the parameters are numeric and that they are the right shape. Optionally checks for NaN / infinite values. """ title = '' if title is None else ' for %s' % title # Check for invalid type and coerce to non-integer try: params = np.array(params, dtype=object) is_complex = [isinstance(p, complex) for p in params.ravel()] dtype = complex if any(is_complex) else float params = np.array(params, dtype=dtype) except TypeError: raise ValueError('Parameters vector%s includes invalid values.' % title) # Check for NaN, inf if not allow_infnan and (np.any(np.isnan(params)) or np.any(np.isinf(params))): raise ValueError('Parameters vector%s includes NaN or Inf values.' % title) params = np.atleast_1d(np.squeeze(params)) # Check for right number of parameters if params.shape != (length,): plural = '' if length == 1 else 's' raise ValueError('Specification%s implies %d parameter%s, but' ' values with shape %s were provided.' % (title, length, plural, params.shape)) return params
Validate parameter vector for basic correctness. Parameters ---------- params : array_like Array of parameters to validate. length : int Expected length of the parameter vector. allow_infnan : bool, optional Whether or not to allow `params` to contain -np.inf, np.inf, and np.nan. Default is False. title : str, optional Description of the parameters (e.g. "autoregressive") to use in error messages. Returns ------- params : ndarray Array of validated parameters. Notes ----- Basic check that the parameters are numeric and that they are the right shape. Optionally checks for NaN / infinite values.
validate_basic
python
statsmodels/statsmodels
statsmodels/tsa/arima/tools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/tools.py
BSD-3-Clause
def is_ar_consecutive(self): """ (bool) Is autoregressive lag polynomial consecutive. I.e. does it include all lags up to and including the maximum lag. """ return (self.max_seasonal_ar_order == 0 and not isinstance(self.ar_order, list))
(bool) Is autoregressive lag polynomial consecutive. I.e. does it include all lags up to and including the maximum lag.
is_ar_consecutive
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def is_ma_consecutive(self): """ (bool) Is moving average lag polynomial consecutive. I.e. does it include all lags up to and including the maximum lag. """ return (self.max_seasonal_ma_order == 0 and not isinstance(self.ma_order, list))
(bool) Is moving average lag polynomial consecutive. I.e. does it include all lags up to and including the maximum lag.
is_ma_consecutive
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def is_integrated(self): """ (bool) Is the model integrated. I.e. does it have a nonzero `diff` or `seasonal_diff`. """ return self.diff > 0 or self.seasonal_diff > 0
(bool) Is the model integrated. I.e. does it have a nonzero `diff` or `seasonal_diff`.
is_integrated
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def is_seasonal(self): """(bool) Does the model include a seasonal component.""" return self.seasonal_periods != 0
(bool) Does the model include a seasonal component.
is_seasonal
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def k_exog_params(self): """(int) Number of parameters associated with exogenous variables.""" return len(self.exog_names)
(int) Number of parameters associated with exogenous variables.
k_exog_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def k_ar_params(self): """(int) Number of autoregressive (non-seasonal) parameters.""" return len(self.ar_lags)
(int) Number of autoregressive (non-seasonal) parameters.
k_ar_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def k_ma_params(self): """(int) Number of moving average (non-seasonal) parameters.""" return len(self.ma_lags)
(int) Number of moving average (non-seasonal) parameters.
k_ma_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def k_seasonal_ar_params(self): """(int) Number of seasonal autoregressive parameters.""" return len(self.seasonal_ar_lags)
(int) Number of seasonal autoregressive parameters.
k_seasonal_ar_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def k_seasonal_ma_params(self): """(int) Number of seasonal moving average parameters.""" return len(self.seasonal_ma_lags)
(int) Number of seasonal moving average parameters.
k_seasonal_ma_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def k_params(self): """(int) Total number of model parameters.""" k_params = (self.k_exog_params + self.k_ar_params + self.k_ma_params + self.k_seasonal_ar_params + self.k_seasonal_ma_params) if not self.concentrate_scale: k_params += 1 return k_params
(int) Total number of model parameters.
k_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def exog_names(self): """(list of str) Names associated with exogenous parameters.""" exog_names = self._model.exog_names return [] if exog_names is None else exog_names
(list of str) Names associated with exogenous parameters.
exog_names
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def ar_names(self): """(list of str) Names of (non-seasonal) autoregressive parameters.""" return ['ar.L%d' % i for i in self.ar_lags]
(list of str) Names of (non-seasonal) autoregressive parameters.
ar_names
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def ma_names(self): """(list of str) Names of (non-seasonal) moving average parameters.""" return ['ma.L%d' % i for i in self.ma_lags]
(list of str) Names of (non-seasonal) moving average parameters.
ma_names
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def seasonal_ar_names(self): """(list of str) Names of seasonal autoregressive parameters.""" s = self.seasonal_periods return ['ar.S.L%d' % (i * s) for i in self.seasonal_ar_lags]
(list of str) Names of seasonal autoregressive parameters.
seasonal_ar_names
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def seasonal_ma_names(self): """(list of str) Names of seasonal moving average parameters.""" s = self.seasonal_periods return ['ma.S.L%d' % (i * s) for i in self.seasonal_ma_lags]
(list of str) Names of seasonal moving average parameters.
seasonal_ma_names
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def param_names(self): """(list of str) Names of all model parameters.""" names = (self.exog_names + self.ar_names + self.ma_names + self.seasonal_ar_names + self.seasonal_ma_names) if not self.concentrate_scale: names.append('sigma2') return names
(list of str) Names of all model parameters.
param_names
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def valid_estimators(self): """ (list of str) Estimators that could be used with specification. Note: does not consider the presense of `exog` in determining valid estimators. If there are exogenous variables, then feasible Generalized Least Squares should be used through the `gls` estimator, and the `valid_estimators` are the estimators that could be passed as the `arma_estimator` argument to `gls`. """ estimators = {'yule_walker', 'burg', 'innovations', 'hannan_rissanen', 'innovations_mle', 'statespace'} # Properties has_ar = self.max_ar_order != 0 has_ma = self.max_ma_order != 0 has_seasonal = self.seasonal_periods != 0 # Only state space can handle missing data or concentrated scale if self._has_missing: estimators.intersection_update(['statespace']) # Only numerical MLE estimators can enforce restrictions if ((self.enforce_stationarity and self.max_ar_order > 0) or (self.enforce_invertibility and self.max_ma_order > 0)): estimators.intersection_update(['innovations_mle', 'statespace']) # Innovations: no AR, non-consecutive MA, seasonal if has_ar or not self.is_ma_consecutive or has_seasonal: estimators.discard('innovations') # Yule-Walker/Burg: no MA, non-consecutive AR, seasonal if has_ma or not self.is_ar_consecutive or has_seasonal: estimators.discard('yule_walker') estimators.discard('burg') # Hannan-Rissanen: no seasonal if has_seasonal: estimators.discard('hannan_rissanen') # Innovations MLE: cannot have enforce_stationary=False or # concentratre_scale=True if self.enforce_stationarity is False or self.concentrate_scale: estimators.discard('innovations_mle') return estimators
(list of str) Estimators that could be used with specification. Note: does not consider the presense of `exog` in determining valid estimators. If there are exogenous variables, then feasible Generalized Least Squares should be used through the `gls` estimator, and the `valid_estimators` are the estimators that could be passed as the `arma_estimator` argument to `gls`.
valid_estimators
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def validate_estimator(self, estimator): """ Validate an SARIMA estimator. Parameters ---------- estimator : str Name of the estimator to validate against the current state of the specification. Possible values are: 'yule_walker', 'burg', 'innovations', 'hannan_rissanen', 'innovoations_mle', 'statespace'. Notes ----- This method will raise a `ValueError` if an invalid method is passed, and otherwise will return None. This method does not consider the presense of `exog` in determining valid estimators. If there are exogenous variables, then feasible Generalized Least Squares should be used through the `gls` estimator, and a "valid" estimator is one that could be passed as the `arma_estimator` argument to `gls`. This method only uses the attributes `enforce_stationarity` and `concentrate_scale` to determine the validity of numerical maximum likelihood estimators. These only include 'innovations_mle' (which does not support `enforce_stationarity=False` or `concentrate_scale=True`) and 'statespace' (which supports all combinations of each). Examples -------- >>> spec = SARIMAXSpecification(order=(1, 0, 2)) >>> spec.validate_estimator('yule_walker') ValueError: Yule-Walker estimator does not support moving average components. >>> spec.validate_estimator('burg') ValueError: Burg estimator does not support moving average components. >>> spec.validate_estimator('innovations') ValueError: Burg estimator does not support autoregressive components. >>> spec.validate_estimator('hannan_rissanen') # returns None >>> spec.validate_estimator('innovations_mle') # returns None >>> spec.validate_estimator('statespace') # returns None >>> spec.validate_estimator('not_an_estimator') ValueError: "not_an_estimator" is not a valid estimator. """ has_ar = self.max_ar_order != 0 has_ma = self.max_ma_order != 0 has_seasonal = self.seasonal_periods != 0 has_missing = self._has_missing titles = { 'yule_walker': 'Yule-Walker', 'burg': 'Burg', 'innovations': 'Innovations', 'hannan_rissanen': 'Hannan-Rissanen', 'innovations_mle': 'Innovations MLE', 'statespace': 'State space' } # Only state space form can support missing data if estimator != 'statespace': if has_missing: raise ValueError('%s estimator does not support missing' ' values in `endog`.' % titles[estimator]) # Only state space and innovations MLE can enforce parameter # restrictions if estimator not in ['innovations_mle', 'statespace']: if self.max_ar_order > 0 and self.enforce_stationarity: raise ValueError('%s estimator cannot enforce a stationary' ' autoregressive lag polynomial.' % titles[estimator]) if self.max_ma_order > 0 and self.enforce_invertibility: raise ValueError('%s estimator cannot enforce an invertible' ' moving average lag polynomial.' % titles[estimator]) # Now go through specific disqualifications for each estimator if estimator in ['yule_walker', 'burg']: if has_seasonal: raise ValueError('%s estimator does not support seasonal' ' components.' % titles[estimator]) if not self.is_ar_consecutive: raise ValueError('%s estimator does not support' ' non-consecutive autoregressive lags.' % titles[estimator]) if has_ma: raise ValueError('%s estimator does not support moving average' ' components.' % titles[estimator]) elif estimator == 'innovations': if has_seasonal: raise ValueError('Innovations estimator does not support' ' seasonal components.') if not self.is_ma_consecutive: raise ValueError('Innovations estimator does not support' ' non-consecutive moving average lags.') if has_ar: raise ValueError('Innovations estimator does not support' ' autoregressive components.') elif estimator == 'hannan_rissanen': if has_seasonal: raise ValueError('Hannan-Rissanen estimator does not support' ' seasonal components.') elif estimator == 'innovations_mle': if self.enforce_stationarity is False: raise ValueError('Innovations MLE estimator does not support' ' non-stationary autoregressive components,' ' but `enforce_stationarity` is set to False') if self.concentrate_scale: raise ValueError('Innovations MLE estimator does not support' ' concentrating the scale out of the' ' log-likelihood function') elif estimator == 'statespace': # State space form supports all variations of SARIMAX. pass else: raise ValueError('"%s" is not a valid estimator.' % estimator)
Validate an SARIMA estimator. Parameters ---------- estimator : str Name of the estimator to validate against the current state of the specification. Possible values are: 'yule_walker', 'burg', 'innovations', 'hannan_rissanen', 'innovoations_mle', 'statespace'. Notes ----- This method will raise a `ValueError` if an invalid method is passed, and otherwise will return None. This method does not consider the presense of `exog` in determining valid estimators. If there are exogenous variables, then feasible Generalized Least Squares should be used through the `gls` estimator, and a "valid" estimator is one that could be passed as the `arma_estimator` argument to `gls`. This method only uses the attributes `enforce_stationarity` and `concentrate_scale` to determine the validity of numerical maximum likelihood estimators. These only include 'innovations_mle' (which does not support `enforce_stationarity=False` or `concentrate_scale=True`) and 'statespace' (which supports all combinations of each). Examples -------- >>> spec = SARIMAXSpecification(order=(1, 0, 2)) >>> spec.validate_estimator('yule_walker') ValueError: Yule-Walker estimator does not support moving average components. >>> spec.validate_estimator('burg') ValueError: Burg estimator does not support moving average components. >>> spec.validate_estimator('innovations') ValueError: Burg estimator does not support autoregressive components. >>> spec.validate_estimator('hannan_rissanen') # returns None >>> spec.validate_estimator('innovations_mle') # returns None >>> spec.validate_estimator('statespace') # returns None >>> spec.validate_estimator('not_an_estimator') ValueError: "not_an_estimator" is not a valid estimator.
validate_estimator
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def split_params(self, params, allow_infnan=False): """ Split parameter array by type into dictionary. Parameters ---------- params : array_like Array of model parameters. allow_infnan : bool, optional Whether or not to allow `params` to contain -np.inf, np.inf, and np.nan. Default is False. Returns ------- split_params : dict Dictionary with keys 'exog_params', 'ar_params', 'ma_params', 'seasonal_ar_params', 'seasonal_ma_params', and (unless `concentrate_scale=True`) 'sigma2'. Values are the parameters associated with the key, based on the `params` argument. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.split_params([0.5, 4]) {'exog_params': array([], dtype=float64), 'ar_params': array([0.5]), 'ma_params': array([], dtype=float64), 'seasonal_ar_params': array([], dtype=float64), 'seasonal_ma_params': array([], dtype=float64), 'sigma2': 4.0} """ params = validate_basic(params, self.k_params, allow_infnan=allow_infnan, title='joint parameters') ix = [self.k_exog_params, self.k_ar_params, self.k_ma_params, self.k_seasonal_ar_params, self.k_seasonal_ma_params] names = ['exog_params', 'ar_params', 'ma_params', 'seasonal_ar_params', 'seasonal_ma_params'] if not self.concentrate_scale: ix.append(1) names.append('sigma2') ix = np.cumsum(ix) out = dict(zip(names, np.split(params, ix))) if 'sigma2' in out: out['sigma2'] = out['sigma2'].item() return out
Split parameter array by type into dictionary. Parameters ---------- params : array_like Array of model parameters. allow_infnan : bool, optional Whether or not to allow `params` to contain -np.inf, np.inf, and np.nan. Default is False. Returns ------- split_params : dict Dictionary with keys 'exog_params', 'ar_params', 'ma_params', 'seasonal_ar_params', 'seasonal_ma_params', and (unless `concentrate_scale=True`) 'sigma2'. Values are the parameters associated with the key, based on the `params` argument. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.split_params([0.5, 4]) {'exog_params': array([], dtype=float64), 'ar_params': array([0.5]), 'ma_params': array([], dtype=float64), 'seasonal_ar_params': array([], dtype=float64), 'seasonal_ma_params': array([], dtype=float64), 'sigma2': 4.0}
split_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def join_params(self, exog_params=None, ar_params=None, ma_params=None, seasonal_ar_params=None, seasonal_ma_params=None, sigma2=None): """ Join parameters into a single vector. Parameters ---------- exog_params : array_like, optional Parameters associated with exogenous regressors. Required if `exog` is part of specification. ar_params : array_like, optional Parameters associated with (non-seasonal) autoregressive component. Required if this component is part of the specification. ma_params : array_like, optional Parameters associated with (non-seasonal) moving average component. Required if this component is part of the specification. seasonal_ar_params : array_like, optional Parameters associated with seasonal autoregressive component. Required if this component is part of the specification. seasonal_ma_params : array_like, optional Parameters associated with seasonal moving average component. Required if this component is part of the specification. sigma2 : array_like, optional Innovation variance parameter. Required unless `concentrated_scale=True`. Returns ------- params : ndarray Array of parameters. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.join_params(ar_params=0.5, sigma2=4) array([0.5, 4. ]) """ definitions = [ ('exogenous variables', self.k_exog_params, exog_params), ('AR terms', self.k_ar_params, ar_params), ('MA terms', self.k_ma_params, ma_params), ('seasonal AR terms', self.k_seasonal_ar_params, seasonal_ar_params), ('seasonal MA terms', self.k_seasonal_ma_params, seasonal_ma_params), ('variance', int(not self.concentrate_scale), sigma2)] params_list = [] for title, k, params in definitions: if k > 0: # Validate if params is None: raise ValueError('Specification includes %s, but no' ' parameters were provided.' % title) params = np.atleast_1d(np.squeeze(params)) if not params.shape == (k,): raise ValueError('Specification included %d %s, but' ' parameters with shape %s were provided.' % (k, title, params.shape)) # Otherwise add to the list params_list.append(params) return np.concatenate(params_list)
Join parameters into a single vector. Parameters ---------- exog_params : array_like, optional Parameters associated with exogenous regressors. Required if `exog` is part of specification. ar_params : array_like, optional Parameters associated with (non-seasonal) autoregressive component. Required if this component is part of the specification. ma_params : array_like, optional Parameters associated with (non-seasonal) moving average component. Required if this component is part of the specification. seasonal_ar_params : array_like, optional Parameters associated with seasonal autoregressive component. Required if this component is part of the specification. seasonal_ma_params : array_like, optional Parameters associated with seasonal moving average component. Required if this component is part of the specification. sigma2 : array_like, optional Innovation variance parameter. Required unless `concentrated_scale=True`. Returns ------- params : ndarray Array of parameters. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.join_params(ar_params=0.5, sigma2=4) array([0.5, 4. ])
join_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def validate_params(self, params): """ Validate parameter vector by raising ValueError on invalid values. Parameters ---------- params : array_like Array of model parameters. Notes ----- Primarily checks that the parameters have the right shape and are not NaN or infinite. Also checks if parameters are consistent with a stationary process if `enforce_stationarity=True` and that they are consistent with an invertible process if `enforce_invertibility=True`. Finally, checks that the variance term is positive, unless `concentrate_scale=True`. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.validate_params([-0.5, 4.]) # returns None >>> spec.validate_params([-0.5, -2]) ValueError: Non-positive variance term. >>> spec.validate_params([-1.5, 4.]) ValueError: Non-stationary autoregressive polynomial. """ # Note: split_params includes basic validation params = self.split_params(params) # Specific checks if self.enforce_stationarity: if self.k_ar_params: ar_poly = np.r_[1, -params['ar_params']] if not is_invertible(ar_poly): raise ValueError('Non-stationary autoregressive' ' polynomial.') if self.k_seasonal_ar_params: seasonal_ar_poly = np.r_[1, -params['seasonal_ar_params']] if not is_invertible(seasonal_ar_poly): raise ValueError('Non-stationary seasonal autoregressive' ' polynomial.') if self.enforce_invertibility: if self.k_ma_params: ma_poly = np.r_[1, params['ma_params']] if not is_invertible(ma_poly): raise ValueError('Non-invertible moving average' ' polynomial.') if self.k_seasonal_ma_params: seasonal_ma_poly = np.r_[1, params['seasonal_ma_params']] if not is_invertible(seasonal_ma_poly): raise ValueError('Non-invertible seasonal moving average' ' polynomial.') if not self.concentrate_scale: if params['sigma2'] <= 0: raise ValueError('Non-positive variance term.')
Validate parameter vector by raising ValueError on invalid values. Parameters ---------- params : array_like Array of model parameters. Notes ----- Primarily checks that the parameters have the right shape and are not NaN or infinite. Also checks if parameters are consistent with a stationary process if `enforce_stationarity=True` and that they are consistent with an invertible process if `enforce_invertibility=True`. Finally, checks that the variance term is positive, unless `concentrate_scale=True`. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.validate_params([-0.5, 4.]) # returns None >>> spec.validate_params([-0.5, -2]) ValueError: Non-positive variance term. >>> spec.validate_params([-1.5, 4.]) ValueError: Non-stationary autoregressive polynomial.
validate_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def constrain_params(self, unconstrained): """ Constrain parameter values to be valid through transformations. Parameters ---------- unconstrained : array_like Array of model unconstrained parameters. Returns ------- constrained : ndarray Array of model parameters transformed to produce a valid model. Notes ----- This is usually only used when performing numerical minimization of the log-likelihood function. This function is necessary because the minimizers consider values over the entire real space, while SARIMAX models require parameters in subspaces (for example positive variances). Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.constrain_params([10, -2]) array([-0.99504, 4. ]) """ unconstrained = self.split_params(unconstrained) params = {} if self.k_exog_params: params['exog_params'] = unconstrained['exog_params'] if self.k_ar_params: if self.enforce_stationarity: params['ar_params'] = constrain(unconstrained['ar_params']) else: params['ar_params'] = unconstrained['ar_params'] if self.k_ma_params: if self.enforce_invertibility: params['ma_params'] = -constrain(unconstrained['ma_params']) else: params['ma_params'] = unconstrained['ma_params'] if self.k_seasonal_ar_params: if self.enforce_stationarity: params['seasonal_ar_params'] = ( constrain(unconstrained['seasonal_ar_params'])) else: params['seasonal_ar_params'] = ( unconstrained['seasonal_ar_params']) if self.k_seasonal_ma_params: if self.enforce_invertibility: params['seasonal_ma_params'] = ( -constrain(unconstrained['seasonal_ma_params'])) else: params['seasonal_ma_params'] = ( unconstrained['seasonal_ma_params']) if not self.concentrate_scale: params['sigma2'] = unconstrained['sigma2']**2 return self.join_params(**params)
Constrain parameter values to be valid through transformations. Parameters ---------- unconstrained : array_like Array of model unconstrained parameters. Returns ------- constrained : ndarray Array of model parameters transformed to produce a valid model. Notes ----- This is usually only used when performing numerical minimization of the log-likelihood function. This function is necessary because the minimizers consider values over the entire real space, while SARIMAX models require parameters in subspaces (for example positive variances). Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.constrain_params([10, -2]) array([-0.99504, 4. ])
constrain_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def unconstrain_params(self, constrained): """ Reverse transformations used to constrain parameter values to be valid. Parameters ---------- constrained : array_like Array of model parameters. Returns ------- unconstrained : ndarray Array of parameters with constraining transformions reversed. Notes ----- This is usually only used when performing numerical minimization of the log-likelihood function. This function is the (approximate) inverse of `constrain_params`. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.unconstrain_params([-0.5, 4.]) array([0.57735, 2. ]) """ constrained = self.split_params(constrained) params = {} if self.k_exog_params: params['exog_params'] = constrained['exog_params'] if self.k_ar_params: if self.enforce_stationarity: params['ar_params'] = unconstrain(constrained['ar_params']) else: params['ar_params'] = constrained['ar_params'] if self.k_ma_params: if self.enforce_invertibility: params['ma_params'] = unconstrain(-constrained['ma_params']) else: params['ma_params'] = constrained['ma_params'] if self.k_seasonal_ar_params: if self.enforce_stationarity: params['seasonal_ar_params'] = ( unconstrain(constrained['seasonal_ar_params'])) else: params['seasonal_ar_params'] = ( constrained['seasonal_ar_params']) if self.k_seasonal_ma_params: if self.enforce_invertibility: params['seasonal_ma_params'] = ( unconstrain(-constrained['seasonal_ma_params'])) else: params['seasonal_ma_params'] = ( constrained['seasonal_ma_params']) if not self.concentrate_scale: params['sigma2'] = constrained['sigma2']**0.5 return self.join_params(**params)
Reverse transformations used to constrain parameter values to be valid. Parameters ---------- constrained : array_like Array of model parameters. Returns ------- unconstrained : ndarray Array of parameters with constraining transformions reversed. Notes ----- This is usually only used when performing numerical minimization of the log-likelihood function. This function is the (approximate) inverse of `constrain_params`. Examples -------- >>> spec = SARIMAXSpecification(ar_order=1) >>> spec.unconstrain_params([-0.5, 4.]) array([0.57735, 2. ])
unconstrain_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def __repr__(self): """Represent SARIMAXSpecification object as a string.""" components = [] if self.endog is not None: components.append('endog=%s' % self._model.endog_names) if self.k_exog_params: components.append('exog=%s' % self.exog_names) components.append('order=%s' % str(self.order)) if self.seasonal_periods > 0: components.append('seasonal_order=%s' % str(self.seasonal_order)) if self.enforce_stationarity is not None: components.append('enforce_stationarity=%s' % self.enforce_stationarity) if self.enforce_invertibility is not None: components.append('enforce_invertibility=%s' % self.enforce_invertibility) if self.concentrate_scale is not None: components.append('concentrate_scale=%s' % self.concentrate_scale) return 'SARIMAXSpecification(%s)' % ', '.join(components)
Represent SARIMAXSpecification object as a string.
__repr__
python
statsmodels/statsmodels
statsmodels/tsa/arima/specification.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/specification.py
BSD-3-Clause
def test_nonstationary_gls_error(): # GH-6540 endog = pd.read_csv( io.StringIO( """\ data\n 9.112\n9.102\n9.103\n9.099\n9.094\n9.090\n9.108\n9.088\n9.091\n9.083\n9.095\n 9.090\n9.098\n9.093\n9.087\n9.088\n9.083\n9.095\n9.077\n9.082\n9.082\n9.081\n 9.081\n9.079\n9.088\n9.096\n9.081\n9.098\n9.081\n9.094\n9.091\n9.095\n9.097\n 9.108\n9.104\n9.098\n9.085\n9.093\n9.094\n9.092\n9.093\n9.106\n9.097\n9.108\n 9.100\n9.106\n9.114\n9.111\n9.097\n9.099\n9.108\n9.108\n9.110\n9.101\n9.111\n 9.114\n9.111\n9.126\n9.124\n9.112\n9.120\n9.142\n9.136\n9.131\n9.106\n9.112\n 9.119\n9.125\n9.123\n9.138\n9.133\n9.133\n9.137\n9.133\n9.138\n9.136\n9.128\n 9.127\n9.143\n9.128\n9.135\n9.133\n9.131\n9.136\n9.120\n9.127\n9.130\n9.116\n 9.132\n9.128\n9.119\n9.119\n9.110\n9.132\n9.130\n9.124\n9.130\n9.135\n9.135\n 9.119\n9.119\n9.136\n9.126\n9.122\n9.119\n9.123\n9.121\n9.130\n9.121\n9.119\n 9.106\n9.118\n9.124\n9.121\n9.127\n9.113\n9.118\n9.103\n9.112\n9.110\n9.111\n 9.108\n9.113\n9.117\n9.111\n9.100\n9.106\n9.109\n9.113\n9.110\n9.101\n9.113\n 9.111\n9.101\n9.097\n9.102\n9.100\n9.110\n9.110\n9.096\n9.095\n9.090\n9.104\n 9.097\n9.099\n9.095\n9.096\n9.085\n9.097\n9.098\n9.090\n9.080\n9.093\n9.085\n 9.075\n9.067\n9.072\n9.062\n9.068\n9.053\n9.051\n9.049\n9.052\n9.059\n9.070\n 9.058\n9.074\n9.063\n9.057\n9.062\n9.058\n9.049\n9.047\n9.062\n9.052\n9.052\n 9.044\n9.060\n9.062\n9.055\n9.058\n9.054\n9.044\n9.047\n9.050\n9.048\n9.041\n 9.055\n9.051\n9.028\n9.030\n9.029\n9.027\n9.016\n9.023\n9.031\n9.042\n9.035\n """ ), index_col=None, ) mod = ARIMA( endog, order=(18, 0, 39), enforce_stationarity=False, enforce_invertibility=False, ) with pytest.raises(ValueError, match="Roots of the autoregressive"): mod.fit(method="hannan_rissanen", low_memory=True, cov_type="none")
\ data\n 9.112\n9.102\n9.103\n9.099\n9.094\n9.090\n9.108\n9.088\n9.091\n9.083\n9.095\n 9.090\n9.098\n9.093\n9.087\n9.088\n9.083\n9.095\n9.077\n9.082\n9.082\n9.081\n 9.081\n9.079\n9.088\n9.096\n9.081\n9.098\n9.081\n9.094\n9.091\n9.095\n9.097\n 9.108\n9.104\n9.098\n9.085\n9.093\n9.094\n9.092\n9.093\n9.106\n9.097\n9.108\n 9.100\n9.106\n9.114\n9.111\n9.097\n9.099\n9.108\n9.108\n9.110\n9.101\n9.111\n 9.114\n9.111\n9.126\n9.124\n9.112\n9.120\n9.142\n9.136\n9.131\n9.106\n9.112\n 9.119\n9.125\n9.123\n9.138\n9.133\n9.133\n9.137\n9.133\n9.138\n9.136\n9.128\n 9.127\n9.143\n9.128\n9.135\n9.133\n9.131\n9.136\n9.120\n9.127\n9.130\n9.116\n 9.132\n9.128\n9.119\n9.119\n9.110\n9.132\n9.130\n9.124\n9.130\n9.135\n9.135\n 9.119\n9.119\n9.136\n9.126\n9.122\n9.119\n9.123\n9.121\n9.130\n9.121\n9.119\n 9.106\n9.118\n9.124\n9.121\n9.127\n9.113\n9.118\n9.103\n9.112\n9.110\n9.111\n 9.108\n9.113\n9.117\n9.111\n9.100\n9.106\n9.109\n9.113\n9.110\n9.101\n9.113\n 9.111\n9.101\n9.097\n9.102\n9.100\n9.110\n9.110\n9.096\n9.095\n9.090\n9.104\n 9.097\n9.099\n9.095\n9.096\n9.085\n9.097\n9.098\n9.090\n9.080\n9.093\n9.085\n 9.075\n9.067\n9.072\n9.062\n9.068\n9.053\n9.051\n9.049\n9.052\n9.059\n9.070\n 9.058\n9.074\n9.063\n9.057\n9.062\n9.058\n9.049\n9.047\n9.062\n9.052\n9.052\n 9.044\n9.060\n9.062\n9.055\n9.058\n9.054\n9.044\n9.047\n9.050\n9.048\n9.041\n 9.055\n9.051\n9.028\n9.030\n9.029\n9.027\n9.016\n9.023\n9.031\n9.042\n9.035\n
test_nonstationary_gls_error
python
statsmodels/statsmodels
statsmodels/tsa/arima/tests/test_model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/tests/test_model.py
BSD-3-Clause
def innovations(endog, ma_order=0, demean=True): """ Estimate MA parameters using innovations algorithm. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ma_order : int, optional Maximum moving average order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the moving average coefficients. Default is True. Returns ------- parameters : list of SARIMAXParams objects List elements correspond to estimates at different `ma_order`. For example, parameters[0] is an `SARIMAXParams` instance corresponding to `ma_order=0`. other_results : Bunch Includes one component, `spec`, containing the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 5.1.3. This procedure assumes that the series is stationary. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer. """ spec = max_spec = SARIMAXSpecification(endog, ma_order=ma_order) endog = max_spec.endog if demean: endog = endog - endog.mean() if not max_spec.is_ma_consecutive: raise ValueError('Innovations estimation unavailable for models with' ' seasonal or otherwise non-consecutive MA orders.') sample_acovf = acovf(endog, fft=True) theta, v = innovations_algo(sample_acovf, nobs=max_spec.ma_order + 1) ma_params = [theta[i, :i] for i in range(1, max_spec.ma_order + 1)] sigma2 = v out = [] for i in range(max_spec.ma_order + 1): spec = SARIMAXSpecification(ma_order=i) p = SARIMAXParams(spec=spec) if i == 0: p.params = sigma2[i] else: p.params = np.r_[ma_params[i - 1], sigma2[i]] out.append(p) # Construct other results other_results = Bunch({ 'spec': spec, }) return out, other_results
Estimate MA parameters using innovations algorithm. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ma_order : int, optional Maximum moving average order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the moving average coefficients. Default is True. Returns ------- parameters : list of SARIMAXParams objects List elements correspond to estimates at different `ma_order`. For example, parameters[0] is an `SARIMAXParams` instance corresponding to `ma_order=0`. other_results : Bunch Includes one component, `spec`, containing the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 5.1.3. This procedure assumes that the series is stationary. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer.
innovations
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/innovations.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/innovations.py
BSD-3-Clause
def burg(endog, ar_order=0, demean=True): """ Estimate AR parameters using Burg technique. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ar_order : int, optional Autoregressive order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the autoregressive coefficients. Returns ------- parameters : SARIMAXParams object Contains the parameter estimates from the final iteration. other_results : Bunch Includes one component, `spec`, which is the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 5.1.2. This procedure assumes that the series is stationary. This function is a light wrapper around `statsmodels.linear_model.burg`. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer. """ spec = SARIMAXSpecification(endog, ar_order=ar_order) endog = spec.endog # Workaround for statsmodels.tsa.stattools.pacf_burg which does not work # on integer input # TODO: remove when possible if np.issubdtype(endog.dtype, np.dtype(int)): endog = endog * 1.0 if not spec.is_ar_consecutive: raise ValueError('Burg estimation unavailable for models with' ' seasonal or otherwise non-consecutive AR orders.') p = SARIMAXParams(spec=spec) if ar_order == 0: p.sigma2 = np.var(endog) else: p.ar_params, p.sigma2 = linear_model.burg(endog, order=ar_order, demean=demean) # Construct other results other_results = Bunch({ 'spec': spec, }) return p, other_results
Estimate AR parameters using Burg technique. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ar_order : int, optional Autoregressive order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the autoregressive coefficients. Returns ------- parameters : SARIMAXParams object Contains the parameter estimates from the final iteration. other_results : Bunch Includes one component, `spec`, which is the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 5.1.2. This procedure assumes that the series is stationary. This function is a light wrapper around `statsmodels.linear_model.burg`. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer.
burg
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/burg.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/burg.py
BSD-3-Clause
def durbin_levinson(endog, ar_order=0, demean=True, adjusted=False): """ Estimate AR parameters at multiple orders using Durbin-Levinson recursions. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ar_order : int, optional Autoregressive order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the autoregressive coefficients. Default is True. adjusted : bool, optional Whether to use the "adjusted" autocovariance estimator, which uses n - h degrees of freedom rather than n. This option can result in a non-positive definite autocovariance matrix. Default is False. Returns ------- parameters : list of SARIMAXParams objects List elements correspond to estimates at different `ar_order`. For example, parameters[0] is an `SARIMAXParams` instance corresponding to `ar_order=0`. other_results : Bunch Includes one component, `spec`, containing the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 2.5.1. This procedure assumes that the series is stationary. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer. """ spec = max_spec = SARIMAXSpecification(endog, ar_order=ar_order) endog = max_spec.endog # Make sure we have a consecutive process if not max_spec.is_ar_consecutive: raise ValueError('Durbin-Levinson estimation unavailable for models' ' with seasonal or otherwise non-consecutive AR' ' orders.') gamma = acovf(endog, adjusted=adjusted, fft=True, demean=demean, nlag=max_spec.ar_order) # If no AR component, just a variance computation if max_spec.ar_order == 0: ar_params = [None] sigma2 = [gamma[0]] # Otherwise, AR model else: Phi = np.zeros((max_spec.ar_order, max_spec.ar_order)) v = np.zeros(max_spec.ar_order + 1) Phi[0, 0] = gamma[1] / gamma[0] v[0] = gamma[0] v[1] = v[0] * (1 - Phi[0, 0]**2) for i in range(1, max_spec.ar_order): tmp = Phi[i-1, :i] Phi[i, i] = (gamma[i + 1] - np.dot(tmp, gamma[i:0:-1])) / v[i] Phi[i, :i] = (tmp - Phi[i, i] * tmp[::-1]) v[i + 1] = v[i] * (1 - Phi[i, i]**2) ar_params = [None] + [Phi[i, :i + 1] for i in range(max_spec.ar_order)] sigma2 = v # Compute output out = [] for i in range(max_spec.ar_order + 1): spec = SARIMAXSpecification(ar_order=i) p = SARIMAXParams(spec=spec) if i == 0: p.params = sigma2[i] else: p.params = np.r_[ar_params[i], sigma2[i]] out.append(p) # Construct other results other_results = Bunch({ 'spec': spec, }) return out, other_results
Estimate AR parameters at multiple orders using Durbin-Levinson recursions. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ar_order : int, optional Autoregressive order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the autoregressive coefficients. Default is True. adjusted : bool, optional Whether to use the "adjusted" autocovariance estimator, which uses n - h degrees of freedom rather than n. This option can result in a non-positive definite autocovariance matrix. Default is False. Returns ------- parameters : list of SARIMAXParams objects List elements correspond to estimates at different `ar_order`. For example, parameters[0] is an `SARIMAXParams` instance corresponding to `ar_order=0`. other_results : Bunch Includes one component, `spec`, containing the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 2.5.1. This procedure assumes that the series is stationary. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer.
durbin_levinson
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/durbin_levinson.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/durbin_levinson.py
BSD-3-Clause
def hannan_rissanen(endog, ar_order=0, ma_order=0, demean=True, initial_ar_order=None, unbiased=None, fixed_params=None): """ Estimate ARMA parameters using Hannan-Rissanen procedure. Parameters ---------- endog : array_like Input time series array, assumed to be stationary. ar_order : int or list of int Autoregressive order ma_order : int or list of int Moving average order demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the ARMA coefficients. Default is True. initial_ar_order : int, optional Order of long autoregressive process used for initial computation of residuals. unbiased : bool, optional Whether or not to apply the bias correction step. Default is True if the estimated coefficients from the previous step imply a stationary and invertible process and False otherwise. fixed_params : dict, optional Dictionary with names of fixed parameters as keys (e.g. 'ar.L1', 'ma.L2'), which correspond to SARIMAXSpecification.param_names. Dictionary values are the values of the associated fixed parameters. Returns ------- parameters : SARIMAXParams object other_results : Bunch Includes three components: `spec`, containing the `SARIMAXSpecification` instance corresponding to the input arguments; `initial_ar_order`, containing the autoregressive lag order used in the first step; and `resid`, which contains the computed residuals from the last step. Notes ----- The primary reference is [1]_, section 5.1.4, which describes a three-step procedure that we implement here. 1. Fit a large-order AR model via Yule-Walker to estimate residuals 2. Compute AR and MA estimates via least squares 3. (Unless the estimated coefficients from step (2) are non-stationary / non-invertible or `unbiased=False`) Perform bias correction The order used for the AR model in the first step may be given as an argument. If it is not, we compute it as suggested by [2]_. The estimate of the variance that we use is computed from the residuals of the least-squares regression and not from the innovations algorithm. This is because our fast implementation of the innovations algorithm is only valid for stationary processes, and the Hannan-Rissanen procedure may produce estimates that imply non-stationary processes. To avoid inconsistency, we never compute this latter variance here, even if it is possible. See test_hannan_rissanen::test_brockwell_davis_example_517 for an example of how to compute this variance manually. This procedure assumes that the series is stationary, but if this is not true, it is still possible that this procedure will return parameters that imply a non-stationary / non-invertible process. Note that the third stage will only be applied if the parameters from the second stage imply a stationary / invertible model. If `unbiased=True` is given, then non-stationary / non-invertible parameters in the second stage will throw an exception. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer. .. [2] Gomez, Victor, and Agustin Maravall. 2001. "Automatic Modeling Methods for Univariate Series." A Course in Time Series Analysis, 171–201. """ spec = SARIMAXSpecification(endog, ar_order=ar_order, ma_order=ma_order) fixed_params = _validate_fixed_params(fixed_params, spec.param_names) endog = spec.endog if demean: endog = endog - endog.mean() p = SARIMAXParams(spec=spec) nobs = len(endog) max_ar_order = spec.max_ar_order max_ma_order = spec.max_ma_order # Default initial_ar_order is as suggested by Gomez and Maravall (2001) if initial_ar_order is None: initial_ar_order = max(np.floor(np.log(nobs)**2).astype(int), 2 * max(max_ar_order, max_ma_order)) # Create a spec, just to validate the initial autoregressive order _ = SARIMAXSpecification(endog, ar_order=initial_ar_order) # Unpack fixed and free ar/ma lags, ix, and params (fixed only) params_info = _package_fixed_and_free_params_info( fixed_params, spec.ar_lags, spec.ma_lags ) # Compute lagged endog lagged_endog = lagmat(endog, max_ar_order, trim='both') # If no AR or MA components, this is just a variance computation mod = None if max_ma_order == 0 and max_ar_order == 0: p.sigma2 = np.var(endog, ddof=0) resid = endog.copy() # If no MA component, this is just CSS elif max_ma_order == 0: # extract 1) lagged_endog with free params; 2) lagged_endog with fixed # params; 3) endog residual after applying fixed params if applicable X_with_free_params = lagged_endog[:, params_info.free_ar_ix] X_with_fixed_params = lagged_endog[:, params_info.fixed_ar_ix] y = endog[max_ar_order:] if X_with_fixed_params.shape[1] != 0: y = y - X_with_fixed_params.dot(params_info.fixed_ar_params) # no free ar params -> variance computation on the endog residual if X_with_free_params.shape[1] == 0: p.ar_params = params_info.fixed_ar_params p.sigma2 = np.var(y, ddof=0) resid = y.copy() # otherwise OLS with endog residual (after applying fixed params) as y, # and lagged_endog with free params as X else: mod = OLS(y, X_with_free_params) res = mod.fit() resid = res.resid p.sigma2 = res.scale p.ar_params = _stitch_fixed_and_free_params( fixed_ar_or_ma_lags=params_info.fixed_ar_lags, fixed_ar_or_ma_params=params_info.fixed_ar_params, free_ar_or_ma_lags=params_info.free_ar_lags, free_ar_or_ma_params=res.params, spec_ar_or_ma_lags=spec.ar_lags ) # Otherwise ARMA model else: # Step 1: Compute long AR model via Yule-Walker, get residuals initial_ar_params, _ = yule_walker( endog, order=initial_ar_order, method='mle') X = lagmat(endog, initial_ar_order, trim='both') y = endog[initial_ar_order:] resid = y - X.dot(initial_ar_params) # Get lagged residuals for `exog` in least-squares regression lagged_resid = lagmat(resid, max_ma_order, trim='both') # Step 2: estimate ARMA model via least squares ix = initial_ar_order + max_ma_order - max_ar_order X_with_free_params = np.c_[ lagged_endog[ix:, params_info.free_ar_ix], lagged_resid[:, params_info.free_ma_ix] ] X_with_fixed_params = np.c_[ lagged_endog[ix:, params_info.fixed_ar_ix], lagged_resid[:, params_info.fixed_ma_ix] ] y = endog[initial_ar_order + max_ma_order:] if X_with_fixed_params.shape[1] != 0: y = y - X_with_fixed_params.dot( np.r_[params_info.fixed_ar_params, params_info.fixed_ma_params] ) # Step 2.1: no free ar params -> variance computation on the endog # residual if X_with_free_params.shape[1] == 0: p.ar_params = params_info.fixed_ar_params p.ma_params = params_info.fixed_ma_params p.sigma2 = np.var(y, ddof=0) resid = y.copy() # Step 2.2: otherwise OLS with endog residual (after applying fixed # params) as y, and lagged_endog and lagged_resid with free params as X else: mod = OLS(y, X_with_free_params) res = mod.fit() k_free_ar_params = len(params_info.free_ar_lags) p.ar_params = _stitch_fixed_and_free_params( fixed_ar_or_ma_lags=params_info.fixed_ar_lags, fixed_ar_or_ma_params=params_info.fixed_ar_params, free_ar_or_ma_lags=params_info.free_ar_lags, free_ar_or_ma_params=res.params[:k_free_ar_params], spec_ar_or_ma_lags=spec.ar_lags ) p.ma_params = _stitch_fixed_and_free_params( fixed_ar_or_ma_lags=params_info.fixed_ma_lags, fixed_ar_or_ma_params=params_info.fixed_ma_params, free_ar_or_ma_lags=params_info.free_ma_lags, free_ar_or_ma_params=res.params[k_free_ar_params:], spec_ar_or_ma_lags=spec.ma_lags ) resid = res.resid p.sigma2 = res.scale # Step 3: bias correction (if requested) # Step 3.1: validate `unbiased` argument and handle setting the default if unbiased is True: if len(fixed_params) != 0: raise NotImplementedError( "Third step of Hannan-Rissanen estimation to remove " "parameter bias is not yet implemented for the case " "with fixed parameters." ) elif not (p.is_stationary and p.is_invertible): raise ValueError( "Cannot perform third step of Hannan-Rissanen estimation " "to remove parameter bias, because parameters estimated " "from the second step are non-stationary or " "non-invertible." ) elif unbiased is None: if len(fixed_params) != 0: unbiased = False else: unbiased = p.is_stationary and p.is_invertible # Step 3.2: bias correction if unbiased is True: if mod is None: raise ValueError("Must have free parameters to use unbiased") Z = np.zeros_like(endog) ar_coef = p.ar_poly.coef ma_coef = p.ma_poly.coef for t in range(nobs): if t >= max(max_ar_order, max_ma_order): # Note: in the case of non-consecutive lag orders, the # polynomials have the appropriate zeros so we don't # need to subset `endog[t - max_ar_order:t]` or # Z[t - max_ma_order:t] tmp_ar = np.dot( -ar_coef[1:], endog[t - max_ar_order:t][::-1]) tmp_ma = np.dot(ma_coef[1:], Z[t - max_ma_order:t][::-1]) Z[t] = endog[t] - tmp_ar - tmp_ma V = lfilter([1], ar_coef, Z) W = lfilter(np.r_[1, -ma_coef[1:]], [1], Z) lagged_V = lagmat(V, max_ar_order, trim='both') lagged_W = lagmat(W, max_ma_order, trim='both') exog = np.c_[ lagged_V[ max(max_ma_order - max_ar_order, 0):, params_info.free_ar_ix ], lagged_W[ max(max_ar_order - max_ma_order, 0):, params_info.free_ma_ix ] ] mod_unbias = OLS(Z[max(max_ar_order, max_ma_order):], exog) res_unbias = mod_unbias.fit() p.ar_params = ( p.ar_params + res_unbias.params[:spec.k_ar_params]) p.ma_params = ( p.ma_params + res_unbias.params[spec.k_ar_params:]) # Recompute sigma2 resid = mod.endog - mod.exog.dot( np.r_[p.ar_params, p.ma_params]) p.sigma2 = np.inner(resid, resid) / len(resid) # TODO: Gomez and Maravall (2001) or Gomez (1998) # propose one more step here to further improve MA estimates # Construct results other_results = Bunch({ 'spec': spec, 'initial_ar_order': initial_ar_order, 'resid': resid }) return p, other_results
Estimate ARMA parameters using Hannan-Rissanen procedure. Parameters ---------- endog : array_like Input time series array, assumed to be stationary. ar_order : int or list of int Autoregressive order ma_order : int or list of int Moving average order demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the ARMA coefficients. Default is True. initial_ar_order : int, optional Order of long autoregressive process used for initial computation of residuals. unbiased : bool, optional Whether or not to apply the bias correction step. Default is True if the estimated coefficients from the previous step imply a stationary and invertible process and False otherwise. fixed_params : dict, optional Dictionary with names of fixed parameters as keys (e.g. 'ar.L1', 'ma.L2'), which correspond to SARIMAXSpecification.param_names. Dictionary values are the values of the associated fixed parameters. Returns ------- parameters : SARIMAXParams object other_results : Bunch Includes three components: `spec`, containing the `SARIMAXSpecification` instance corresponding to the input arguments; `initial_ar_order`, containing the autoregressive lag order used in the first step; and `resid`, which contains the computed residuals from the last step. Notes ----- The primary reference is [1]_, section 5.1.4, which describes a three-step procedure that we implement here. 1. Fit a large-order AR model via Yule-Walker to estimate residuals 2. Compute AR and MA estimates via least squares 3. (Unless the estimated coefficients from step (2) are non-stationary / non-invertible or `unbiased=False`) Perform bias correction The order used for the AR model in the first step may be given as an argument. If it is not, we compute it as suggested by [2]_. The estimate of the variance that we use is computed from the residuals of the least-squares regression and not from the innovations algorithm. This is because our fast implementation of the innovations algorithm is only valid for stationary processes, and the Hannan-Rissanen procedure may produce estimates that imply non-stationary processes. To avoid inconsistency, we never compute this latter variance here, even if it is possible. See test_hannan_rissanen::test_brockwell_davis_example_517 for an example of how to compute this variance manually. This procedure assumes that the series is stationary, but if this is not true, it is still possible that this procedure will return parameters that imply a non-stationary / non-invertible process. Note that the third stage will only be applied if the parameters from the second stage imply a stationary / invertible model. If `unbiased=True` is given, then non-stationary / non-invertible parameters in the second stage will throw an exception. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer. .. [2] Gomez, Victor, and Agustin Maravall. 2001. "Automatic Modeling Methods for Univariate Series." A Course in Time Series Analysis, 171–201.
hannan_rissanen
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/hannan_rissanen.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/hannan_rissanen.py
BSD-3-Clause
def _validate_fixed_params(fixed_params, spec_param_names): """ Check that keys in fixed_params are a subset of spec.param_names except "sigma2" Parameters ---------- fixed_params : dict spec_param_names : list of string SARIMAXSpecification.param_names """ if fixed_params is None: fixed_params = {} assert isinstance(fixed_params, dict) fixed_param_names = set(fixed_params.keys()) valid_param_names = set(spec_param_names) - {"sigma2"} invalid_param_names = fixed_param_names - valid_param_names if len(invalid_param_names) > 0: raise ValueError( f"Invalid fixed parameter(s): {sorted(list(invalid_param_names))}." f" Please select among {sorted(list(valid_param_names))}." ) return fixed_params
Check that keys in fixed_params are a subset of spec.param_names except "sigma2" Parameters ---------- fixed_params : dict spec_param_names : list of string SARIMAXSpecification.param_names
_validate_fixed_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/hannan_rissanen.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/hannan_rissanen.py
BSD-3-Clause
def _package_fixed_and_free_params_info(fixed_params, spec_ar_lags, spec_ma_lags): """ Parameters ---------- fixed_params : dict spec_ar_lags : list of int SARIMAXSpecification.ar_lags spec_ma_lags : list of int SARIMAXSpecification.ma_lags Returns ------- Bunch with (lags) fixed_ar_lags, fixed_ma_lags, free_ar_lags, free_ma_lags; (ix) fixed_ar_ix, fixed_ma_ix, free_ar_ix, free_ma_ix; (params) fixed_ar_params, free_ma_params """ # unpack fixed lags and params fixed_ar_lags_and_params = [] fixed_ma_lags_and_params = [] for key, val in fixed_params.items(): lag = int(key.split(".")[-1].lstrip("L")) if key.startswith("ar"): fixed_ar_lags_and_params.append((lag, val)) elif key.startswith("ma"): fixed_ma_lags_and_params.append((lag, val)) fixed_ar_lags_and_params.sort() fixed_ma_lags_and_params.sort() fixed_ar_lags = [lag for lag, _ in fixed_ar_lags_and_params] fixed_ar_params = np.array([val for _, val in fixed_ar_lags_and_params]) fixed_ma_lags = [lag for lag, _ in fixed_ma_lags_and_params] fixed_ma_params = np.array([val for _, val in fixed_ma_lags_and_params]) # unpack free lags free_ar_lags = [lag for lag in spec_ar_lags if lag not in set(fixed_ar_lags)] free_ma_lags = [lag for lag in spec_ma_lags if lag not in set(fixed_ma_lags)] # get ix for indexing purposes: `ar_ix`, and `ma_ix` below, are to account # for non-consecutive lags; for indexing purposes, must have dtype int free_ar_ix = np.array(free_ar_lags, dtype=int) - 1 free_ma_ix = np.array(free_ma_lags, dtype=int) - 1 fixed_ar_ix = np.array(fixed_ar_lags, dtype=int) - 1 fixed_ma_ix = np.array(fixed_ma_lags, dtype=int) - 1 return Bunch( # lags fixed_ar_lags=fixed_ar_lags, fixed_ma_lags=fixed_ma_lags, free_ar_lags=free_ar_lags, free_ma_lags=free_ma_lags, # ixs fixed_ar_ix=fixed_ar_ix, fixed_ma_ix=fixed_ma_ix, free_ar_ix=free_ar_ix, free_ma_ix=free_ma_ix, # fixed params fixed_ar_params=fixed_ar_params, fixed_ma_params=fixed_ma_params, )
Parameters ---------- fixed_params : dict spec_ar_lags : list of int SARIMAXSpecification.ar_lags spec_ma_lags : list of int SARIMAXSpecification.ma_lags Returns ------- Bunch with (lags) fixed_ar_lags, fixed_ma_lags, free_ar_lags, free_ma_lags; (ix) fixed_ar_ix, fixed_ma_ix, free_ar_ix, free_ma_ix; (params) fixed_ar_params, free_ma_params
_package_fixed_and_free_params_info
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/hannan_rissanen.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/hannan_rissanen.py
BSD-3-Clause
def _stitch_fixed_and_free_params(fixed_ar_or_ma_lags, fixed_ar_or_ma_params, free_ar_or_ma_lags, free_ar_or_ma_params, spec_ar_or_ma_lags): """ Stitch together fixed and free params, by the order of lags, for setting SARIMAXParams.ma_params or SARIMAXParams.ar_params Parameters ---------- fixed_ar_or_ma_lags : list or np.array fixed_ar_or_ma_params : list or np.array fixed_ar_or_ma_params corresponds with fixed_ar_or_ma_lags free_ar_or_ma_lags : list or np.array free_ar_or_ma_params : list or np.array free_ar_or_ma_params corresponds with free_ar_or_ma_lags spec_ar_or_ma_lags : list SARIMAXSpecification.ar_lags or SARIMAXSpecification.ma_lags Returns ------- list of fixed and free params by the order of lags """ assert len(fixed_ar_or_ma_lags) == len(fixed_ar_or_ma_params) assert len(free_ar_or_ma_lags) == len(free_ar_or_ma_params) all_lags = np.r_[fixed_ar_or_ma_lags, free_ar_or_ma_lags] all_params = np.r_[fixed_ar_or_ma_params, free_ar_or_ma_params] assert set(all_lags) == set(spec_ar_or_ma_lags) lag_to_param_map = dict(zip(all_lags, all_params)) # Sort params by the order of their corresponding lags in # spec_ar_or_ma_lags (e.g. SARIMAXSpecification.ar_lags or # SARIMAXSpecification.ma_lags) all_params_sorted = [lag_to_param_map[lag] for lag in spec_ar_or_ma_lags] return all_params_sorted
Stitch together fixed and free params, by the order of lags, for setting SARIMAXParams.ma_params or SARIMAXParams.ar_params Parameters ---------- fixed_ar_or_ma_lags : list or np.array fixed_ar_or_ma_params : list or np.array fixed_ar_or_ma_params corresponds with fixed_ar_or_ma_lags free_ar_or_ma_lags : list or np.array free_ar_or_ma_params : list or np.array free_ar_or_ma_params corresponds with free_ar_or_ma_lags spec_ar_or_ma_lags : list SARIMAXSpecification.ar_lags or SARIMAXSpecification.ma_lags Returns ------- list of fixed and free params by the order of lags
_stitch_fixed_and_free_params
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/hannan_rissanen.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/hannan_rissanen.py
BSD-3-Clause
def yule_walker(endog, ar_order=0, demean=True, adjusted=False): """ Estimate AR parameters using Yule-Walker equations. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ar_order : int, optional Autoregressive order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the autoregressive coefficients. Default is True. adjusted : bool, optional Whether to use the adjusted autocovariance estimator, which uses n - h degrees of freedom rather than n. For some processes this option may result in a non-positive definite autocovariance matrix. Default is False. Returns ------- parameters : SARIMAXParams object Contains the parameter estimates from the final iteration. other_results : Bunch Includes one component, `spec`, which is the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 5.1.1. This procedure assumes that the series is stationary. For a description of the effect of the adjusted estimate of the autocovariance function, see 2.4.2 of [1]_. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer. """ spec = SARIMAXSpecification(endog, ar_order=ar_order) endog = spec.endog p = SARIMAXParams(spec=spec) if not spec.is_ar_consecutive: raise ValueError('Yule-Walker estimation unavailable for models with' ' seasonal or non-consecutive AR orders.') # Estimate parameters method = 'adjusted' if adjusted else 'mle' p.ar_params, sigma = linear_model.yule_walker( endog, order=ar_order, demean=demean, method=method) p.sigma2 = sigma**2 # Construct other results other_results = Bunch({ 'spec': spec, }) return p, other_results
Estimate AR parameters using Yule-Walker equations. Parameters ---------- endog : array_like or SARIMAXSpecification Input time series array, assumed to be stationary. ar_order : int, optional Autoregressive order. Default is 0. demean : bool, optional Whether to estimate and remove the mean from the process prior to fitting the autoregressive coefficients. Default is True. adjusted : bool, optional Whether to use the adjusted autocovariance estimator, which uses n - h degrees of freedom rather than n. For some processes this option may result in a non-positive definite autocovariance matrix. Default is False. Returns ------- parameters : SARIMAXParams object Contains the parameter estimates from the final iteration. other_results : Bunch Includes one component, `spec`, which is the `SARIMAXSpecification` instance corresponding to the input arguments. Notes ----- The primary reference is [1]_, section 5.1.1. This procedure assumes that the series is stationary. For a description of the effect of the adjusted estimate of the autocovariance function, see 2.4.2 of [1]_. References ---------- .. [1] Brockwell, Peter J., and Richard A. Davis. 2016. Introduction to Time Series and Forecasting. Springer.
yule_walker
python
statsmodels/statsmodels
statsmodels/tsa/arima/estimators/yule_walker.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/arima/estimators/yule_walker.py
BSD-3-Clause
def fix_params(self, values): """ Temporarily fix parameters for estimation. Parameters ---------- values : dict Values to fix. The key is the parameter name and the value is the fixed value. Yields ------ None No value returned. Examples -------- >>> from statsmodels.datasets.macrodata import load_pandas >>> data = load_pandas() >>> import statsmodels.tsa.api as tsa >>> mod = tsa.ExponentialSmoothing(data.data.realcons, trend="add", ... initialization_method="estimated") >>> with mod.fix_params({"smoothing_level": 0.2}): ... mod.fit() """ values = dict_like(values, "values") valid_keys = ("smoothing_level",) if self.has_trend: valid_keys += ("smoothing_trend",) if self.has_seasonal: valid_keys += ("smoothing_seasonal",) m = self.seasonal_periods valid_keys += tuple([f"initial_seasonal.{i}" for i in range(m)]) if self.damped_trend: valid_keys += ("damping_trend",) if self._initialization_method in ("estimated", None): extra_keys = [ key.replace("smoothing_", "initial_") for key in valid_keys if "smoothing_" in key ] valid_keys += tuple(extra_keys) for key in values: if key not in valid_keys: valid = ", ".join(valid_keys[:-1]) + ", and " + valid_keys[-1] raise KeyError( f"{key} if not allowed. Only {valid} are supported in " "this specification." ) if "smoothing_level" in values: alpha = values["smoothing_level"] if alpha <= 0.0: raise ValueError("smoothing_level must be in (0, 1)") beta = values.get("smoothing_trend", 0.0) if beta > alpha: raise ValueError("smoothing_trend must be <= smoothing_level") gamma = values.get("smoothing_seasonal", 0.0) if gamma > 1 - alpha: raise ValueError( "smoothing_seasonal must be <= 1 - smoothing_level" ) try: self._fixed_parameters = values yield finally: self._fixed_parameters = {}
Temporarily fix parameters for estimation. Parameters ---------- values : dict Values to fix. The key is the parameter name and the value is the fixed value. Yields ------ None No value returned. Examples -------- >>> from statsmodels.datasets.macrodata import load_pandas >>> data = load_pandas() >>> import statsmodels.tsa.api as tsa >>> mod = tsa.ExponentialSmoothing(data.data.realcons, trend="add", ... initialization_method="estimated") >>> with mod.fix_params({"smoothing_level": 0.2}): ... mod.fit()
fix_params
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def predict(self, params, start=None, end=None): """ In-sample and out-of-sample prediction. Parameters ---------- params : ndarray The fitted model parameters. start : int, str, or datetime 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. end : int, str, or datetime 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. Returns ------- ndarray The predicted values. """ if start is None: freq = getattr(self._index, "freq", 1) if isinstance(freq, int): start = self._index.shape[0] else: start = self._index[-1] + freq start, end, out_of_sample, _ = self._get_prediction_index( start=start, end=end ) if out_of_sample > 0: res = self._predict(h=out_of_sample, **params) else: res = self._predict(h=0, **params) return res.fittedfcast[start : end + out_of_sample + 1]
In-sample and out-of-sample prediction. Parameters ---------- params : ndarray The fitted model parameters. start : int, str, or datetime 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. end : int, str, or datetime 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. Returns ------- ndarray The predicted values.
predict
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def fit( self, smoothing_level=None, smoothing_trend=None, smoothing_seasonal=None, damping_trend=None, *, optimized=True, remove_bias=False, start_params=None, method=None, minimize_kwargs=None, use_brute=True, use_boxcox=None, use_basinhopping=None, initial_level=None, initial_trend=None, ): """ Fit the model Parameters ---------- smoothing_level : float, optional The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. smoothing_trend : float, optional The beta value of the Holt's trend method, if the value is set then this value will be used as the value. smoothing_seasonal : float, optional The gamma value of the holt winters seasonal method, if the value is set then this value will be used as the value. damping_trend : float, optional The phi value of the damped method, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. start_params : array_like, optional Starting values to used when optimizing the fit. If not provided, starting values are determined using a combination of grid search and reasonable values based on the initial values of the data. See the notes for the structure of the model parameters. method : str, optional The minimizer used. Valid options are "L-BFGS-B" , "TNC", "SLSQP" (default), "Powell", "trust-constr", "basinhopping" (also "bh") and "least_squares" (also "ls"). basinhopping tries multiple starting values in an attempt to find a global minimizer in non-convex problems, and so is slower than the others. minimize_kwargs : dict[str, Any] A dictionary of keyword arguments passed to SciPy's minimize function if method is one of "L-BFGS-B", "TNC", "SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping or least_squares functions. The valid keywords are optimizer specific. Consult SciPy's documentation for the full set of options. use_brute : bool, optional Search for good starting values using a brute force (grid) optimizer. If False, a naive set of starting values is used. use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use the value as lambda. .. deprecated:: 0.12 Set use_boxcox when constructing the model use_basinhopping : bool, optional Deprecated. Using Basin Hopping optimizer to find optimal values. Use ``method`` instead. .. deprecated:: 0.12 Use ``method`` instead. initial_level : float, optional Value to use when initializing the fitted level. .. deprecated:: 0.12 Set initial_level when constructing the model initial_trend : float, optional Value to use when initializing the fitted trend. .. deprecated:: 0.12 Set initial_trend when constructing the model or set initialization_method. Returns ------- HoltWintersResults See statsmodels.tsa.holtwinters.HoltWintersResults. Notes ----- This is a full implementation of the holt winters exponential smoothing as per [1]. This includes all the unstable methods as well as the stable methods. The implementation of the library covers the functionality of the R library as much as possible whilst still being Pythonic. The parameters are ordered [alpha, beta, gamma, initial_level, initial_trend, phi] which are then followed by m seasonal values if the model contains a seasonal smoother. Any parameter not relevant for the model is omitted. For example, a model that has a level and a seasonal component, but no trend and is not damped, would have starting values [alpha, gamma, initial_level, s0, s1, ..., s<m-1>] where sj is the initial value for seasonal component j. References ---------- [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. """ # Variable renames to alpha,beta, etc as this helps with following the # mathematical notation in general alpha = float_like(smoothing_level, "smoothing_level", True) beta = float_like(smoothing_trend, "smoothing_trend", True) gamma = float_like(smoothing_seasonal, "smoothing_seasonal", True) phi = float_like(damping_trend, "damping_trend", True) initial_level = float_like(initial_level, "initial_level", True) initial_trend = float_like(initial_trend, "initial_trend", True) start_params = array_like(start_params, "start_params", optional=True) minimize_kwargs = dict_like( minimize_kwargs, "minimize_kwargs", optional=True ) minimize_kwargs = {} if minimize_kwargs is None else minimize_kwargs use_basinhopping = bool_like( use_basinhopping, "use_basinhopping", optional=True ) supported_methods = ("basinhopping", "bh") supported_methods += ("least_squares", "ls") supported_methods += ( "L-BFGS-B", "TNC", "SLSQP", "Powell", "trust-constr", ) method = string_like( method, "method", options=supported_methods, lower=False, optional=True, ) # TODO: Deprecate initial_level and related parameters from fit if initial_level is not None or initial_trend is not None: raise ValueError( "Initial values were set during model construction. These " "cannot be changed during fit." ) if use_boxcox is not None: raise ValueError( "use_boxcox was set at model initialization and cannot " "be changed" ) elif self._use_boxcox is None: use_boxcox = False else: use_boxcox = self._use_boxcox if use_basinhopping is not None: raise ValueError( "use_basinhopping is deprecated. Set optimization method " "using 'method'." ) data = self._data damped = self.damped_trend phi = phi if damped else 1.0 if self._use_boxcox is None: if use_boxcox == "log": lamda = 0.0 y = boxcox(data, lamda) elif isinstance(use_boxcox, float): lamda = use_boxcox y = boxcox(data, lamda) elif use_boxcox: y, lamda = boxcox(data) # use_boxcox = lamda else: y = data.squeeze() else: y = self._y self._y = y res = _OptConfig() res.alpha = alpha res.beta = beta res.phi = phi res.gamma = gamma res.level = initial_level res.trend = initial_trend res.seasonal = None res.y = y res.params = start_params res.mle_retvals = res.mask = None method = "SLSQP" if method is None else method if optimized: res = self._optimize_parameters( res, use_brute, method, minimize_kwargs ) else: l0, b0, s0 = self.initial_values( initial_level=initial_level, initial_trend=initial_trend ) res.level = l0 res.trend = b0 res.seasonal = s0 if self._fixed_parameters: fp = self._fixed_parameters res.alpha = fp.get("smoothing_level", res.alpha) res.beta = fp.get("smoothing_trend", res.beta) res.gamma = fp.get("smoothing_seasonal", res.gamma) res.phi = fp.get("damping_trend", res.phi) res.level = fp.get("initial_level", res.level) res.trend = fp.get("initial_trend", res.trend) res.seasonal = fp.get("initial_seasonal", res.seasonal) hwfit = self._predict( h=0, smoothing_level=res.alpha, smoothing_trend=res.beta, smoothing_seasonal=res.gamma, damping_trend=res.phi, initial_level=res.level, initial_trend=res.trend, initial_seasons=res.seasonal, use_boxcox=use_boxcox, remove_bias=remove_bias, is_optimized=res.mask, ) hwfit._results.mle_retvals = res.mle_retvals return hwfit
Fit the model Parameters ---------- smoothing_level : float, optional The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. smoothing_trend : float, optional The beta value of the Holt's trend method, if the value is set then this value will be used as the value. smoothing_seasonal : float, optional The gamma value of the holt winters seasonal method, if the value is set then this value will be used as the value. damping_trend : float, optional The phi value of the damped method, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. start_params : array_like, optional Starting values to used when optimizing the fit. If not provided, starting values are determined using a combination of grid search and reasonable values based on the initial values of the data. See the notes for the structure of the model parameters. method : str, optional The minimizer used. Valid options are "L-BFGS-B" , "TNC", "SLSQP" (default), "Powell", "trust-constr", "basinhopping" (also "bh") and "least_squares" (also "ls"). basinhopping tries multiple starting values in an attempt to find a global minimizer in non-convex problems, and so is slower than the others. minimize_kwargs : dict[str, Any] A dictionary of keyword arguments passed to SciPy's minimize function if method is one of "L-BFGS-B", "TNC", "SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping or least_squares functions. The valid keywords are optimizer specific. Consult SciPy's documentation for the full set of options. use_brute : bool, optional Search for good starting values using a brute force (grid) optimizer. If False, a naive set of starting values is used. use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use the value as lambda. .. deprecated:: 0.12 Set use_boxcox when constructing the model use_basinhopping : bool, optional Deprecated. Using Basin Hopping optimizer to find optimal values. Use ``method`` instead. .. deprecated:: 0.12 Use ``method`` instead. initial_level : float, optional Value to use when initializing the fitted level. .. deprecated:: 0.12 Set initial_level when constructing the model initial_trend : float, optional Value to use when initializing the fitted trend. .. deprecated:: 0.12 Set initial_trend when constructing the model or set initialization_method. Returns ------- HoltWintersResults See statsmodels.tsa.holtwinters.HoltWintersResults. Notes ----- This is a full implementation of the holt winters exponential smoothing as per [1]. This includes all the unstable methods as well as the stable methods. The implementation of the library covers the functionality of the R library as much as possible whilst still being Pythonic. The parameters are ordered [alpha, beta, gamma, initial_level, initial_trend, phi] which are then followed by m seasonal values if the model contains a seasonal smoother. Any parameter not relevant for the model is omitted. For example, a model that has a level and a seasonal component, but no trend and is not damped, would have starting values [alpha, gamma, initial_level, s0, s1, ..., s<m-1>] where sj is the initial value for seasonal component j. References ---------- [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014.
fit
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def initial_values( self, initial_level=None, initial_trend=None, force=False ): """ Compute initial values used in the exponential smoothing recursions. Parameters ---------- initial_level : {float, None} The initial value used for the level component. initial_trend : {float, None} The initial value used for the trend component. force : bool Force the calculation even if initial values exist. Returns ------- initial_level : float The initial value used for the level component. initial_trend : {float, None} The initial value used for the trend component. initial_seasons : list The initial values used for the seasonal components. Notes ----- Convenience function the exposes the values used to initialize the recursions. When optimizing parameters these are used as starting values. Method used to compute the initial value depends on when components are included in the model. In a simple exponential smoothing model without trend or a seasonal components, the initial value is set to the first observation. When a trend is added, the trend is initialized either using y[1]/y[0], if multiplicative, or y[1]-y[0]. When the seasonal component is added the initialization adapts to account for the modified structure. """ if self._initialization_method is not None and not force: return ( self._initial_level, self._initial_trend, self._initial_seasonal, ) y = self._y trend = self.trend seasonal = self.seasonal has_seasonal = self.has_seasonal has_trend = self.has_trend m = self.seasonal_periods l0 = initial_level b0 = initial_trend if has_seasonal: l0 = y[np.arange(self.nobs) % m == 0].mean() if l0 is None else l0 if b0 is None and has_trend: # TODO: Fix for short m lead, lag = y[m : m + m], y[:m] if trend == "mul": b0 = np.exp((np.log(lead.mean()) - np.log(lag.mean())) / m) else: b0 = ((lead - lag) / m).mean() s0 = list(y[:m] / l0) if seasonal == "mul" else list(y[:m] - l0) elif has_trend: l0 = y[0] if l0 is None else l0 if b0 is None: b0 = y[1] / y[0] if trend == "mul" else y[1] - y[0] s0 = [] else: if l0 is None: l0 = y[0] b0 = None s0 = [] return l0, b0, s0
Compute initial values used in the exponential smoothing recursions. Parameters ---------- initial_level : {float, None} The initial value used for the level component. initial_trend : {float, None} The initial value used for the trend component. force : bool Force the calculation even if initial values exist. Returns ------- initial_level : float The initial value used for the level component. initial_trend : {float, None} The initial value used for the trend component. initial_seasons : list The initial values used for the seasonal components. Notes ----- Convenience function the exposes the values used to initialize the recursions. When optimizing parameters these are used as starting values. Method used to compute the initial value depends on when components are included in the model. In a simple exponential smoothing model without trend or a seasonal components, the initial value is set to the first observation. When a trend is added, the trend is initialized either using y[1]/y[0], if multiplicative, or y[1]-y[0]. When the seasonal component is added the initialization adapts to account for the modified structure.
initial_values
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def _predict( self, h=None, smoothing_level=None, smoothing_trend=None, smoothing_seasonal=None, initial_level=None, initial_trend=None, damping_trend=None, initial_seasons=None, use_boxcox=None, lamda=None, remove_bias=None, is_optimized=None, ): """ Helper prediction function Parameters ---------- h : int, optional The number of time steps to forecast ahead. """ # Variable renames to alpha, beta, etc as this helps with following the # mathematical notation in general alpha = smoothing_level beta = smoothing_trend gamma = smoothing_seasonal phi = damping_trend # Start in sample and out of sample predictions data = self.endog damped = self.damped_trend has_seasonal = self.has_seasonal has_trend = self.has_trend trend = self.trend seasonal = self.seasonal m = self.seasonal_periods phi = phi if damped else 1.0 if use_boxcox == "log": lamda = 0.0 y = boxcox(data, 0.0) elif isinstance(use_boxcox, float): lamda = use_boxcox y = boxcox(data, lamda) elif use_boxcox: y, lamda = boxcox(data) else: lamda = None y = data.squeeze() if np.ndim(y) != 1: raise NotImplementedError("Only 1 dimensional data supported") y_alpha = np.zeros((self.nobs,)) y_gamma = np.zeros((self.nobs,)) alphac = 1 - alpha y_alpha[:] = alpha * y betac = 1 - beta if beta is not None else 0 gammac = 1 - gamma if gamma is not None else 0 if has_seasonal: y_gamma[:] = gamma * y lvls = np.zeros((self.nobs + h + 1,)) b = np.zeros((self.nobs + h + 1,)) s = np.zeros((self.nobs + h + m + 1,)) lvls[0] = initial_level b[0] = initial_trend s[:m] = initial_seasons phi_h = ( np.cumsum(np.repeat(phi, h + 1) ** np.arange(1, h + 1 + 1)) if damped else np.arange(1, h + 1 + 1) ) trended = {"mul": np.multiply, "add": np.add, None: lambda lvl, b: lvl}[ trend ] detrend = {"mul": np.divide, "add": np.subtract, None: lambda lvl, b: 0}[ trend ] dampen = {"mul": np.power, "add": np.multiply, None: lambda b, phi: 0}[ trend ] nobs = self.nobs if seasonal == "mul": for i in range(1, nobs + 1): lvls[i] = y_alpha[i - 1] / s[i - 1] + ( alphac * trended(lvls[i - 1], dampen(b[i - 1], phi)) ) if has_trend: b[i] = (beta * detrend(lvls[i], lvls[i - 1])) + ( betac * dampen(b[i - 1], phi) ) s[i + m - 1] = y_gamma[i - 1] / trended( lvls[i - 1], dampen(b[i - 1], phi) ) + (gammac * s[i - 1]) _trend = b[1 : nobs + 1].copy() season = s[m : nobs + m].copy() lvls[nobs:] = lvls[nobs] if has_trend: b[:nobs] = dampen(b[:nobs], phi) b[nobs:] = dampen(b[nobs], phi_h) trend = trended(lvls, b) s[nobs + m - 1 :] = [ s[(nobs - 1) + j % m] for j in range(h + 1 + 1) ] fitted = trend * s[:-m] elif seasonal == "add": for i in range(1, nobs + 1): lvls[i] = ( y_alpha[i - 1] - (alpha * s[i - 1]) + (alphac * trended(lvls[i - 1], dampen(b[i - 1], phi))) ) if has_trend: b[i] = (beta * detrend(lvls[i], lvls[i - 1])) + ( betac * dampen(b[i - 1], phi) ) s[i + m - 1] = ( y_gamma[i - 1] - (gamma * trended(lvls[i - 1], dampen(b[i - 1], phi))) + (gammac * s[i - 1]) ) _trend = b[1 : nobs + 1].copy() season = s[m : nobs + m].copy() lvls[nobs:] = lvls[nobs] if has_trend: b[:nobs] = dampen(b[:nobs], phi) b[nobs:] = dampen(b[nobs], phi_h) trend = trended(lvls, b) s[nobs + m - 1 :] = [ s[(nobs - 1) + j % m] for j in range(h + 1 + 1) ] fitted = trend + s[:-m] else: for i in range(1, nobs + 1): lvls[i] = y_alpha[i - 1] + ( alphac * trended(lvls[i - 1], dampen(b[i - 1], phi)) ) if has_trend: b[i] = (beta * detrend(lvls[i], lvls[i - 1])) + ( betac * dampen(b[i - 1], phi) ) _trend = b[1 : nobs + 1].copy() season = s[m : nobs + m].copy() lvls[nobs:] = lvls[nobs] if has_trend: b[:nobs] = dampen(b[:nobs], phi) b[nobs:] = dampen(b[nobs], phi_h) trend = trended(lvls, b) fitted = trend level = lvls[1 : nobs + 1].copy() if use_boxcox or use_boxcox == "log" or isinstance(use_boxcox, float): fitted = inv_boxcox(fitted, lamda) err = fitted[: -h - 1] - data sse = err.T @ err # (s0 + gamma) + (b0 + beta) + (l0 + alpha) + phi k = m * has_seasonal + 2 * has_trend + 2 + 1 * damped aic = self.nobs * np.log(sse / self.nobs) + k * 2 dof_eff = self.nobs - k - 3 if dof_eff > 0: aicc_penalty = (2 * (k + 2) * (k + 3)) / dof_eff else: aicc_penalty = np.inf aicc = aic + aicc_penalty bic = self.nobs * np.log(sse / self.nobs) + k * np.log(self.nobs) resid = data - fitted[: -h - 1] if remove_bias: fitted += resid.mean() self.params = { "smoothing_level": alpha, "smoothing_trend": beta, "smoothing_seasonal": gamma, "damping_trend": phi if damped else np.nan, "initial_level": lvls[0], "initial_trend": b[0] / phi if phi > 0 else 0, "initial_seasons": s[:m], "use_boxcox": use_boxcox, "lamda": lamda, "remove_bias": remove_bias, } # Format parameters into a DataFrame codes = ["alpha", "beta", "gamma", "l.0", "b.0", "phi"] codes += [f"s.{i}" for i in range(m)] idx = [ "smoothing_level", "smoothing_trend", "smoothing_seasonal", "initial_level", "initial_trend", "damping_trend", ] idx += [f"initial_seasons.{i}" for i in range(m)] formatted = [alpha, beta, gamma, lvls[0], b[0], phi] formatted += s[:m].tolist() formatted = list(map(lambda v: np.nan if v is None else v, formatted)) formatted = np.array(formatted) if is_optimized is None: optimized = np.zeros(len(codes), dtype=bool) else: optimized = is_optimized.astype(bool) included = [True, has_trend, has_seasonal, True, has_trend, damped] included += [True] * m formatted = pd.DataFrame( [[c, f, o] for c, f, o in zip(codes, formatted, optimized)], columns=["name", "param", "optimized"], index=idx, ) formatted = formatted.loc[included] hwfit = HoltWintersResults( self, self.params, fittedfcast=fitted, fittedvalues=fitted[: -h - 1], fcastvalues=fitted[-h - 1 :], sse=sse, level=level, trend=_trend, season=season, aic=aic, bic=bic, aicc=aicc, resid=resid, k=k, params_formatted=formatted, optimized=optimized, ) return HoltWintersResultsWrapper(hwfit)
Helper prediction function Parameters ---------- h : int, optional The number of time steps to forecast ahead.
_predict
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def fit( self, smoothing_level=None, *, optimized=True, start_params=None, initial_level=None, use_brute=True, use_boxcox=None, remove_bias=False, method=None, minimize_kwargs=None, ): """ Fit the model Parameters ---------- smoothing_level : float, optional The smoothing_level value of the simple exponential smoothing, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood. start_params : ndarray, optional Starting values to used when optimizing the fit. If not provided, starting values are determined using a combination of grid search and reasonable values based on the initial values of the data. initial_level : float, optional Value to use when initializing the fitted level. use_brute : bool, optional Search for good starting values using a brute force (grid) optimizer. If False, a naive set of starting values is used. use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use the value as lambda. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. method : str, default "L-BFGS-B" The minimizer used. Valid options are "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", "trust-constr", "basinhopping" (also "bh") and "least_squares" (also "ls"). basinhopping tries multiple starting values in an attempt to find a global minimizer in non-convex problems, and so is slower than the others. minimize_kwargs : dict[str, Any] A dictionary of keyword arguments passed to SciPy's minimize function if method is one of "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping or least_squares. The valid keywords are optimizer specific. Consult SciPy's documentation for the full set of options. Returns ------- HoltWintersResults See statsmodels.tsa.holtwinters.HoltWintersResults. Notes ----- This is a full implementation of the simple exponential smoothing as per [1]. References ---------- [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. """ return super().fit( smoothing_level=smoothing_level, optimized=optimized, start_params=start_params, initial_level=initial_level, use_brute=use_brute, remove_bias=remove_bias, use_boxcox=use_boxcox, method=method, minimize_kwargs=minimize_kwargs, )
Fit the model Parameters ---------- smoothing_level : float, optional The smoothing_level value of the simple exponential smoothing, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood. start_params : ndarray, optional Starting values to used when optimizing the fit. If not provided, starting values are determined using a combination of grid search and reasonable values based on the initial values of the data. initial_level : float, optional Value to use when initializing the fitted level. use_brute : bool, optional Search for good starting values using a brute force (grid) optimizer. If False, a naive set of starting values is used. use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use the value as lambda. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. method : str, default "L-BFGS-B" The minimizer used. Valid options are "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", "trust-constr", "basinhopping" (also "bh") and "least_squares" (also "ls"). basinhopping tries multiple starting values in an attempt to find a global minimizer in non-convex problems, and so is slower than the others. minimize_kwargs : dict[str, Any] A dictionary of keyword arguments passed to SciPy's minimize function if method is one of "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping or least_squares. The valid keywords are optimizer specific. Consult SciPy's documentation for the full set of options. Returns ------- HoltWintersResults See statsmodels.tsa.holtwinters.HoltWintersResults. Notes ----- This is a full implementation of the simple exponential smoothing as per [1]. References ---------- [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014.
fit
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def fit( self, smoothing_level=None, smoothing_trend=None, *, damping_trend=None, optimized=True, start_params=None, initial_level=None, initial_trend=None, use_brute=True, use_boxcox=None, remove_bias=False, method=None, minimize_kwargs=None, ): """ Fit the model Parameters ---------- smoothing_level : float, optional The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. smoothing_trend : float, optional The beta value of the Holt's trend method, if the value is set then this value will be used as the value. damping_trend : float, optional The phi value of the damped method, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood. start_params : ndarray, optional Starting values to used when optimizing the fit. If not provided, starting values are determined using a combination of grid search and reasonable values based on the initial values of the data. initial_level : float, optional Value to use when initializing the fitted level. .. deprecated:: 0.12 Set initial_level when constructing the model initial_trend : float, optional Value to use when initializing the fitted trend. .. deprecated:: 0.12 Set initial_trend when constructing the model use_brute : bool, optional Search for good starting values using a brute force (grid) optimizer. If False, a naive set of starting values is used. use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use the value as lambda. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. method : str, default "L-BFGS-B" The minimizer used. Valid options are "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", "trust-constr", "basinhopping" (also "bh") and "least_squares" (also "ls"). basinhopping tries multiple starting values in an attempt to find a global minimizer in non-convex problems, and so is slower than the others. minimize_kwargs : dict[str, Any] A dictionary of keyword arguments passed to SciPy's minimize function if method is one of "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping or least_squares. The valid keywords are optimizer specific. Consult SciPy's documentation for the full set of options. Returns ------- HoltWintersResults See statsmodels.tsa.holtwinters.HoltWintersResults. Notes ----- This is a full implementation of the Holt's exponential smoothing as per [1]. References ---------- [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. """ return super().fit( smoothing_level=smoothing_level, smoothing_trend=smoothing_trend, damping_trend=damping_trend, optimized=optimized, start_params=start_params, initial_level=initial_level, initial_trend=initial_trend, use_brute=use_brute, use_boxcox=use_boxcox, remove_bias=remove_bias, method=method, minimize_kwargs=minimize_kwargs, )
Fit the model Parameters ---------- smoothing_level : float, optional The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. smoothing_trend : float, optional The beta value of the Holt's trend method, if the value is set then this value will be used as the value. damping_trend : float, optional The phi value of the damped method, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood. start_params : ndarray, optional Starting values to used when optimizing the fit. If not provided, starting values are determined using a combination of grid search and reasonable values based on the initial values of the data. initial_level : float, optional Value to use when initializing the fitted level. .. deprecated:: 0.12 Set initial_level when constructing the model initial_trend : float, optional Value to use when initializing the fitted trend. .. deprecated:: 0.12 Set initial_trend when constructing the model use_brute : bool, optional Search for good starting values using a brute force (grid) optimizer. If False, a naive set of starting values is used. use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use the value as lambda. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. method : str, default "L-BFGS-B" The minimizer used. Valid options are "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", "trust-constr", "basinhopping" (also "bh") and "least_squares" (also "ls"). basinhopping tries multiple starting values in an attempt to find a global minimizer in non-convex problems, and so is slower than the others. minimize_kwargs : dict[str, Any] A dictionary of keyword arguments passed to SciPy's minimize function if method is one of "L-BFGS-B" (default), "TNC", "SLSQP", "Powell", or "trust-constr", or SciPy's basinhopping or least_squares. The valid keywords are optimizer specific. Consult SciPy's documentation for the full set of options. Returns ------- HoltWintersResults See statsmodels.tsa.holtwinters.HoltWintersResults. Notes ----- This is a full implementation of the Holt's exponential smoothing as per [1]. References ---------- [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014.
fit
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/model.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/model.py
BSD-3-Clause
def to_restricted(p, sel, bounds): """ Transform parameters from the unrestricted [0,1] space to satisfy both the bounds and the 2 constraints beta <= alpha and gamma <= (1-alpha) Parameters ---------- p : ndarray The parameters to transform sel : ndarray Array indicating whether a parameter is being estimated. If not estimated, not transformed. bounds : ndarray 2-d array of bounds where bound for element i is in row i and stored as [lb, ub] Returns ------- """ a, b, g = p[:3] if sel[0]: lb = max(LOWER_BOUND, bounds[0, 0]) ub = min(1 - LOWER_BOUND, bounds[0, 1]) a = lb + a * (ub - lb) if sel[1]: lb = bounds[1, 0] ub = min(a, bounds[1, 1]) b = lb + b * (ub - lb) if sel[2]: lb = bounds[2, 0] ub = min(1.0 - a, bounds[2, 1]) g = lb + g * (ub - lb) return a, b, g
Transform parameters from the unrestricted [0,1] space to satisfy both the bounds and the 2 constraints beta <= alpha and gamma <= (1-alpha) Parameters ---------- p : ndarray The parameters to transform sel : ndarray Array indicating whether a parameter is being estimated. If not estimated, not transformed. bounds : ndarray 2-d array of bounds where bound for element i is in row i and stored as [lb, ub] Returns -------
to_restricted
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def to_unrestricted(p, sel, bounds): """ Transform parameters to the unrestricted [0,1] space Parameters ---------- p : ndarray Parameters that strictly satisfy the constraints Returns ------- ndarray Parameters all in (0,1) """ # eps < a < 1 - eps # eps < b <= a # eps < g <= 1 - a a, b, g = p[:3] if sel[0]: lb = max(LOWER_BOUND, bounds[0, 0]) ub = min(1 - LOWER_BOUND, bounds[0, 1]) a = (a - lb) / (ub - lb) if sel[1]: lb = bounds[1, 0] ub = min(p[0], bounds[1, 1]) b = (b - lb) / (ub - lb) if sel[2]: lb = bounds[2, 0] ub = min(1.0 - p[0], bounds[2, 1]) g = (g - lb) / (ub - lb) return a, b, g
Transform parameters to the unrestricted [0,1] space Parameters ---------- p : ndarray Parameters that strictly satisfy the constraints Returns ------- ndarray Parameters all in (0,1)
to_unrestricted
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_init(x, hw_args: HoltWintersArgs): """ Initialization for the Holt Models """ # Map back to the full set of parameters hw_args.p[hw_args.xi.astype(bool)] = x # Ensure alpha and beta satisfy the requirements if hw_args.transform: alpha, beta, _ = to_restricted(hw_args.p, hw_args.xi, hw_args.bounds) else: alpha, beta = hw_args.p[:2] # Level, trend and dampening l0, b0, phi = hw_args.p[3:6] # Save repeated calculations alphac = 1 - alpha betac = 1 - beta # Setup alpha * y y_alpha = alpha * hw_args.y # In-place operations hw_args.lvl[0] = l0 hw_args.b[0] = b0 return alpha, beta, phi, alphac, betac, y_alpha
Initialization for the Holt Models
holt_init
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt__(x, hw_args: HoltWintersArgs): """ Simple Exponential Smoothing Minimization Function (,) """ _, _, _, alphac, _, y_alpha = holt_init(x, hw_args) n = hw_args.n lvl = hw_args.lvl for i in range(1, n): lvl[i] = (y_alpha[i - 1]) + (alphac * (lvl[i - 1])) return hw_args.y - lvl
Simple Exponential Smoothing Minimization Function (,)
holt__
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_mul_dam(x, hw_args: HoltWintersArgs): """ Multiplicative and Multiplicative Damped Minimization Function (M,) & (Md,) """ _, beta, phi, alphac, betac, y_alpha = holt_init(x, hw_args) lvl = hw_args.lvl b = hw_args.b for i in range(1, hw_args.n): lvl[i] = (y_alpha[i - 1]) + (alphac * (lvl[i - 1] * b[i - 1] ** phi)) b[i] = (beta * (lvl[i] / lvl[i - 1])) + (betac * b[i - 1] ** phi) return hw_args.y - lvl * b**phi
Multiplicative and Multiplicative Damped Minimization Function (M,) & (Md,)
holt_mul_dam
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_add_dam(x, hw_args: HoltWintersArgs): """ Additive and Additive Damped Minimization Function (A,) & (Ad,) """ _, beta, phi, alphac, betac, y_alpha = holt_init(x, hw_args) lvl = hw_args.lvl b = hw_args.b for i in range(1, hw_args.n): lvl[i] = (y_alpha[i - 1]) + (alphac * (lvl[i - 1] + phi * b[i - 1])) b[i] = (beta * (lvl[i] - lvl[i - 1])) + (betac * phi * b[i - 1]) return hw_args.y - (lvl + phi * b)
Additive and Additive Damped Minimization Function (A,) & (Ad,)
holt_add_dam
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win_init(x, hw_args: HoltWintersArgs): """Initialization for the Holt Winters Seasonal Models""" hw_args.p[hw_args.xi.astype(bool)] = x if hw_args.transform: alpha, beta, gamma = to_restricted( hw_args.p, hw_args.xi, hw_args.bounds ) else: alpha, beta, gamma = hw_args.p[:3] l0, b0, phi = hw_args.p[3:6] s0 = hw_args.p[6:] alphac = 1 - alpha betac = 1 - beta gammac = 1 - gamma y_alpha = alpha * hw_args.y y_gamma = gamma * hw_args.y hw_args.lvl[:] = 0 hw_args.b[:] = 0 hw_args.s[:] = 0 hw_args.lvl[0] = l0 hw_args.b[0] = b0 hw_args.s[: hw_args.m] = s0 return alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma
Initialization for the Holt Winters Seasonal Models
holt_win_init
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win__mul(x, hw_args: HoltWintersArgs): """ Multiplicative Seasonal Minimization Function (,M) """ (_, _, _, _, alphac, _, gammac, y_alpha, y_gamma) = holt_win_init( x, hw_args ) lvl = hw_args.lvl s = hw_args.s m = hw_args.m for i in range(1, hw_args.n): lvl[i] = (y_alpha[i - 1] / s[i - 1]) + (alphac * (lvl[i - 1])) s[i + m - 1] = (y_gamma[i - 1] / (lvl[i - 1])) + (gammac * s[i - 1]) return hw_args.y - lvl * s[: -(m - 1)]
Multiplicative Seasonal Minimization Function (,M)
holt_win__mul
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win__add(x, hw_args: HoltWintersArgs): """ Additive Seasonal Minimization Function (,A) """ (alpha, _, gamma, _, alphac, _, gammac, y_alpha, y_gamma) = holt_win_init( x, hw_args ) lvl = hw_args.lvl s = hw_args.s m = hw_args.m for i in range(1, hw_args.n): lvl[i] = ( (y_alpha[i - 1]) - (alpha * s[i - 1]) + (alphac * (lvl[i - 1])) ) s[i + m - 1] = ( y_gamma[i - 1] - (gamma * (lvl[i - 1])) + (gammac * s[i - 1]) ) return hw_args.y - lvl - s[: -(m - 1)]
Additive Seasonal Minimization Function (,A)
holt_win__add
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win_add_mul_dam(x, hw_args: HoltWintersArgs): """ Additive and Additive Damped with Multiplicative Seasonal Minimization Function (A,M) & (Ad,M) """ ( _, beta, _, phi, alphac, betac, gammac, y_alpha, y_gamma, ) = holt_win_init(x, hw_args) lvl = hw_args.lvl b = hw_args.b s = hw_args.s m = hw_args.m for i in range(1, hw_args.n): lvl[i] = (y_alpha[i - 1] / s[i - 1]) + ( alphac * (lvl[i - 1] + phi * b[i - 1]) ) b[i] = (beta * (lvl[i] - lvl[i - 1])) + (betac * phi * b[i - 1]) s[i + m - 1] = (y_gamma[i - 1] / (lvl[i - 1] + phi * b[i - 1])) + ( gammac * s[i - 1] ) return hw_args.y - (lvl + phi * b) * s[: -(m - 1)]
Additive and Additive Damped with Multiplicative Seasonal Minimization Function (A,M) & (Ad,M)
holt_win_add_mul_dam
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win_mul_mul_dam(x, hw_args: HoltWintersArgs): """ Multiplicative and Multiplicative Damped with Multiplicative Seasonal Minimization Function (M,M) & (Md,M) """ ( _, beta, _, phi, alphac, betac, gammac, y_alpha, y_gamma, ) = holt_win_init(x, hw_args) lvl = hw_args.lvl s = hw_args.s b = hw_args.b m = hw_args.m for i in range(1, hw_args.n): lvl[i] = (y_alpha[i - 1] / s[i - 1]) + ( alphac * (lvl[i - 1] * b[i - 1] ** phi) ) b[i] = (beta * (lvl[i] / lvl[i - 1])) + (betac * b[i - 1] ** phi) s[i + m - 1] = (y_gamma[i - 1] / (lvl[i - 1] * b[i - 1] ** phi)) + ( gammac * s[i - 1] ) return hw_args.y - (lvl * b**phi) * s[: -(m - 1)]
Multiplicative and Multiplicative Damped with Multiplicative Seasonal Minimization Function (M,M) & (Md,M)
holt_win_mul_mul_dam
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win_add_add_dam(x, hw_args: HoltWintersArgs): """ Additive and Additive Damped with Additive Seasonal Minimization Function (A,A) & (Ad,A) """ ( alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma, ) = holt_win_init(x, hw_args) lvl = hw_args.lvl s = hw_args.s b = hw_args.b m = hw_args.m for i in range(1, hw_args.n): lvl[i] = ( (y_alpha[i - 1]) - (alpha * s[i - 1]) + (alphac * (lvl[i - 1] + phi * b[i - 1])) ) b[i] = (beta * (lvl[i] - lvl[i - 1])) + (betac * phi * b[i - 1]) s[i + m - 1] = ( y_gamma[i - 1] - (gamma * (lvl[i - 1] + phi * b[i - 1])) + (gammac * s[i - 1]) ) return hw_args.y - ((lvl + phi * b) + s[: -(m - 1)])
Additive and Additive Damped with Additive Seasonal Minimization Function (A,A) & (Ad,A)
holt_win_add_add_dam
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def holt_win_mul_add_dam(x, hw_args: HoltWintersArgs): """ Multiplicative and Multiplicative Damped with Additive Seasonal Minimization Function (M,A) & (M,Ad) """ ( alpha, beta, gamma, phi, alphac, betac, gammac, y_alpha, y_gamma, ) = holt_win_init(x, hw_args) lvl = hw_args.lvl s = hw_args.s b = hw_args.b m = hw_args.m for i in range(1, hw_args.n): lvl[i] = ( (y_alpha[i - 1]) - (alpha * s[i - 1]) + (alphac * (lvl[i - 1] * b[i - 1] ** phi)) ) b[i] = (beta * (lvl[i] / lvl[i - 1])) + (betac * b[i - 1] ** phi) s[i + m - 1] = ( y_gamma[i - 1] - (gamma * (lvl[i - 1] * b[i - 1] ** phi)) + (gammac * s[i - 1]) ) return hw_args.y - ((lvl * phi * b) + s[: -(m - 1)])
Multiplicative and Multiplicative Damped with Additive Seasonal Minimization Function (M,A) & (M,Ad)
holt_win_mul_add_dam
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/_smoothers.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/_smoothers.py
BSD-3-Clause
def aic(self): """ The Akaike information criterion. """ return self._aic
The Akaike information criterion.
aic
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def aicc(self): """ AIC with a correction for finite sample sizes. """ return self._aicc
AIC with a correction for finite sample sizes.
aicc
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def bic(self): """ The Bayesian information criterion. """ return self._bic
The Bayesian information criterion.
bic
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def sse(self): """ The sum of squared errors between the data and the fittted value. """ return self._sse
The sum of squared errors between the data and the fittted value.
sse
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def model(self): """ The model used to produce the results instance. """ return self._model
The model used to produce the results instance.
model
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def level(self): """ An array of the levels values that make up the fitted values. """ return self._level
An array of the levels values that make up the fitted values.
level
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def optimized(self): """ Flag indicating if model parameters were optimized to fit the data. """ return self._optimized
Flag indicating if model parameters were optimized to fit the data.
optimized
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def trend(self): """ An array of the trend values that make up the fitted values. """ return self._trend
An array of the trend values that make up the fitted values.
trend
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def season(self): """ An array of the seasonal values that make up the fitted values. """ return self._season
An array of the seasonal values that make up the fitted values.
season
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def params_formatted(self): """ DataFrame containing all parameters Contains short names and a flag indicating whether the parameter's value was optimized to fit the data. """ return self._params_formatted
DataFrame containing all parameters Contains short names and a flag indicating whether the parameter's value was optimized to fit the data.
params_formatted
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def fittedvalues(self): """ An array of the fitted values """ return self._fittedvalues
An array of the fitted values
fittedvalues
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def fittedfcast(self): """ An array of both the fitted values and forecast values. """ return self._fittedfcast
An array of both the fitted values and forecast values.
fittedfcast
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def fcastvalues(self): """ An array of the forecast values """ return self._fcastvalues
An array of the forecast values
fcastvalues
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def resid(self): """ An array of the residuals of the fittedvalues and actual values. """ return self._resid
An array of the residuals of the fittedvalues and actual values.
resid
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def k(self): """ The k parameter used to remove the bias in AIC, BIC etc. """ return self._k
The k parameter used to remove the bias in AIC, BIC etc.
k
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def mle_retvals(self): """ Optimization results if the parameters were optimized to fit the data. """ return self._mle_retvals
Optimization results if the parameters were optimized to fit the data.
mle_retvals
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def predict(self, start=None, end=None): """ 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. """ return self.model.predict(self.params, start, end)
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.
predict
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def forecast(self, steps=1): """ 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 """ try: freq = getattr(self.model._index, "freq", 1) if not isinstance(freq, int) and isinstance( self.model._index, (pd.DatetimeIndex, pd.PeriodIndex) ): start = self.model._index[-1] + freq end = self.model._index[-1] + steps * freq else: start = self.model._index.shape[0] end = start + steps - 1 return self.model.predict(self.params, start=start, end=end) except AttributeError: # May occur when the index does not have a freq return self.model._predict(h=steps, **self.params).fcastvalues
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
forecast
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def summary(self): """ 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 """ from statsmodels.iolib.summary import Summary from statsmodels.iolib.table import SimpleTable model = self.model title = model.__class__.__name__ + " Model Results" dep_variable = "endog" orig_endog = self.model.data.orig_endog if isinstance(orig_endog, pd.DataFrame): dep_variable = orig_endog.columns[0] elif isinstance(orig_endog, pd.Series): dep_variable = orig_endog.name seasonal_periods = ( None if self.model.seasonal is None else self.model.seasonal_periods ) lookup = { "add": "Additive", "additive": "Additive", "mul": "Multiplicative", "multiplicative": "Multiplicative", None: "None", } transform = self.params["use_boxcox"] box_cox_transform = True if transform else False box_cox_coeff = ( transform if isinstance(transform, str) else self.params["lamda"] ) if isinstance(box_cox_coeff, float): box_cox_coeff = f"{box_cox_coeff:>10.5f}" top_left = [ ("Dep. Variable:", [dep_variable]), ("Model:", [model.__class__.__name__]), ("Optimized:", [str(np.any(self.optimized))]), ("Trend:", [lookup[self.model.trend]]), ("Seasonal:", [lookup[self.model.seasonal]]), ("Seasonal Periods:", [str(seasonal_periods)]), ("Box-Cox:", [str(box_cox_transform)]), ("Box-Cox Coeff.:", [str(box_cox_coeff)]), ] top_right = [ ("No. Observations:", [str(len(self.model.endog))]), ("SSE", [f"{self.sse:5.3f}"]), ("AIC", [f"{self.aic:5.3f}"]), ("BIC", [f"{self.bic:5.3f}"]), ("AICC", [f"{self.aicc:5.3f}"]), ("Date:", None), ("Time:", None), ] smry = Summary() smry.add_table_2cols( self, gleft=top_left, gright=top_right, title=title ) formatted = self.params_formatted # type: pd.DataFrame def _fmt(x): abs_x = np.abs(x) scale = 1 if np.isnan(x): return f"{str(x):>20}" if abs_x != 0: scale = int(np.log10(abs_x)) if scale > 4 or scale < -3: return f"{x:>20.5g}" dec = min(7 - scale, 7) fmt = f"{{:>20.{dec}f}}" return fmt.format(x) tab = [] for _, vals in formatted.iterrows(): tab.append( [ _fmt(vals.iloc[1]), f"{vals.iloc[0]:>20}", f"{str(bool(vals.iloc[2])):>20}", ] ) params_table = SimpleTable( tab, headers=["coeff", "code", "optimized"], title="", stubs=list(formatted.index), ) smry.tables.append(params_table) return smry
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
summary
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/results.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/results.py
BSD-3-Clause
def _simple_dbl_exp_smoother(x, alpha, beta, l0, b0, nforecast=0): """ Simple, slow, direct implementation of double exp smoothing for testing """ n = x.shape[0] lvals = np.zeros(n) b = np.zeros(n) xhat = np.zeros(n) f = np.zeros(nforecast) lvals[0] = l0 b[0] = b0 # Special case the 0 observations since index -1 is not available xhat[0] = l0 + b0 lvals[0] = alpha * x[0] + (1 - alpha) * (l0 + b0) b[0] = beta * (lvals[0] - l0) + (1 - beta) * b0 for t in range(1, n): # Obs in index t is the time t forecast for t + 1 lvals[t] = alpha * x[t] + (1 - alpha) * (lvals[t - 1] + b[t - 1]) b[t] = beta * (lvals[t] - lvals[t - 1]) + (1 - beta) * b[t - 1] xhat[1:] = lvals[0:-1] + b[0:-1] f[:] = lvals[-1] + np.arange(1, nforecast + 1) * b[-1] err = x - xhat return lvals, b, f, err, xhat
Simple, slow, direct implementation of double exp smoothing for testing
_simple_dbl_exp_smoother
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/tests/test_holtwinters.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/tests/test_holtwinters.py
BSD-3-Clause
def simulate_expected_results_r(): """ obtained from ets.simulate in the R package forecast, data is from fpp2 package. library(magrittr) library(fpp2) library(forecast) concat <- function(...) { return(paste(..., sep="")) } error <- c("A", "M") trend <- c("A", "M", "N") seasonal <- c("A", "M", "N") models <- outer(error, trend, FUN = "concat") %>% outer(seasonal, FUN = "concat") %>% as.vector # innov from np.random.seed(0); np.random.randn(4) innov <- c(1.76405235, 0.40015721, 0.97873798, 2.2408932) params <- expand.grid(models, c(TRUE, FALSE)) results <- apply(params, 1, FUN = function(p) { tryCatch( simulate(ets(austourists, model = p[1], damped = as.logical(p[2])), innov = innov), error = function(e) c(NA, NA, NA, NA)) }) %>% t rownames(results) <- apply(params, 1, FUN = function(x) paste(x[1], x[2])) """ damped = { "AAA": [77.84173, 52.69818, 65.83254, 71.85204], "MAA": [207.81653, 136.97700, 253.56234, 588.95800], "MAM": [215.83822, 127.17132, 269.09483, 704.32105], "MMM": [216.52591, 132.47637, 283.04889, 759.08043], "AAN": [62.51423, 61.87381, 63.14735, 65.11360], "MAN": [168.25189, 90.46201, 133.54769, 232.81738], "MMN": [167.97747, 90.59675, 134.20300, 235.64502], } undamped = { "AAA": [77.10860, 51.51669, 64.46857, 70.36349], "MAA": [209.23158, 149.62943, 270.65579, 637.03828], "ANA": [77.09320, 51.52384, 64.36231, 69.84786], "MNA": [207.86986, 169.42706, 313.97960, 793.97948], "MAM": [214.45750, 106.19605, 211.61304, 492.12223], "MMM": [221.01861, 158.55914, 403.22625, 1389.33384], "MNM": [215.00997, 140.93035, 309.92465, 875.07985], "AAN": [63.66619, 63.09571, 64.45832, 66.51967], "MAN": [172.37584, 91.51932, 134.11221, 230.98970], "MMN": [169.88595, 97.33527, 142.97017, 252.51834], "ANN": [60.53589, 59.51851, 60.17570, 61.63011], "MNN": [163.01575, 112.58317, 172.21992, 338.93918], } return {True: damped, False: undamped}
obtained from ets.simulate in the R package forecast, data is from fpp2 package. library(magrittr) library(fpp2) library(forecast) concat <- function(...) { return(paste(..., sep="")) } error <- c("A", "M") trend <- c("A", "M", "N") seasonal <- c("A", "M", "N") models <- outer(error, trend, FUN = "concat") %>% outer(seasonal, FUN = "concat") %>% as.vector # innov from np.random.seed(0); np.random.randn(4) innov <- c(1.76405235, 0.40015721, 0.97873798, 2.2408932) params <- expand.grid(models, c(TRUE, FALSE)) results <- apply(params, 1, FUN = function(p) { tryCatch( simulate(ets(austourists, model = p[1], damped = as.logical(p[2])), innov = innov), error = function(e) c(NA, NA, NA, NA)) }) %>% t rownames(results) <- apply(params, 1, FUN = function(x) paste(x[1], x[2]))
simulate_expected_results_r
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/tests/test_holtwinters.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/tests/test_holtwinters.py
BSD-3-Clause
def simulate_fit_state_r(): """ The final state from the R model fits to get an exact comparison Obtained with this R script: library(magrittr) library(fpp2) library(forecast) concat <- function(...) { return(paste(..., sep="")) } as_dict_string <- function(named) { string <- '{' for (name in names(named)) { string <- concat(string, "\"", name, "\": ", named[name], ", ") } string <- concat(string, '}') return(string) } get_var <- function(named, name) { if (name %in% names(named)) val <- c(named[name]) else val <- c(NaN) names(val) <- c(name) return(val) } error <- c("A", "M") trend <- c("A", "M", "N") seasonal <- c("A", "M", "N") models <- outer(error, trend, FUN = "concat") %>% outer(seasonal, FUN = "concat") %>% as.vector # innov from np.random.seed(0); np.random.randn(4) innov <- c(1.76405235, 0.40015721, 0.97873798, 2.2408932) n <- length(austourists) + 1 # print fit parameters and final states for (damped in c(TRUE, FALSE)) { print(paste("damped =", damped)) for (model in models) { state <- tryCatch((function(){ fit <- ets(austourists, model = model, damped = damped) pars <- c() # alpha, beta, gamma, phi for (name in c("alpha", "beta", "gamma", "phi")) { pars <- c(pars, get_var(fit$par, name)) } # l, b, s1, s2, s3, s4 states <- c() for (name in c("l", "b", "s1", "s2", "s3", "s4")) states <- c(states, get_var(fit$states[n,], name)) c(pars, states) })(), error = function(e) rep(NA, 10)) cat(concat("\"", model, "\": ", as_dict_string(state), ",\n")) } } """ damped = { "AAA": { "alpha": 0.35445427317618, "beta": 0.0320074905894167, "gamma": 0.399933869627979, "phi": 0.979999965983533, "l": 62.003405788717, "b": 0.706524957599738, "s1": 3.58786406600866, "s2": -0.0747450283892903, "s3": -11.7569356589817, "s4": 13.3818805055271, }, "MAA": { "alpha": 0.31114284033284, "beta": 0.0472138763848083, "gamma": 0.309502324693322, "phi": 0.870889202791893, "l": 59.2902342851514, "b": 0.62538315801909, "s1": 5.66660224738038, "s2": 2.16097311633352, "s3": -9.20020909069337, "s4": 15.3505801601698, }, "MAM": { "alpha": 0.483975835390643, "beta": 0.00351728130401287, "gamma": 0.00011309784353818, "phi": 0.979999998322032, "l": 63.0042707536293, "b": 0.275035160634846, "s1": 1.03531670491486, "s2": 0.960515682506077, "s3": 0.770086097577864, "s4": 1.23412213281709, }, "MMM": { "alpha": 0.523526123191035, "beta": 0.000100021136675999, "gamma": 0.000100013723372502, "phi": 0.971025672907157, "l": 63.2030316675533, "b": 1.00458391644788, "s1": 1.03476354353096, "s2": 0.959953222294316, "s3": 0.771346403552048, "s4": 1.23394845160922, }, "AAN": { "alpha": 0.014932817259302, "beta": 0.0149327068053362, "gamma": np.nan, "phi": 0.979919958387887, "l": 60.0651024395378, "b": 0.699112782133822, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, "MAN": { "alpha": 0.0144217343786778, "beta": 0.0144216994589862, "gamma": np.nan, "phi": 0.979999719878659, "l": 60.1870032363649, "b": 0.698421913047609, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, "MMN": { "alpha": 0.015489181776072, "beta": 0.0154891632646377, "gamma": np.nan, "phi": 0.975139118496093, "l": 60.1855946424729, "b": 1.00999589024928, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, } undamped = { "AAA": { "alpha": 0.20281951627363, "beta": 0.000169786227368617, "gamma": 0.464523797585052, "phi": np.nan, "l": 62.5598121416791, "b": 0.578091734736357, "s1": 2.61176734723357, "s2": -1.24386240029203, "s3": -12.9575427049515, "s4": 12.2066400808086, }, "MAA": { "alpha": 0.416371920801538, "beta": 0.000100008012920072, "gamma": 0.352943901103959, "phi": np.nan, "l": 62.0497742976079, "b": 0.450130087198346, "s1": 3.50368220490457, "s2": -0.0544297321113539, "s3": -11.6971093199679, "s4": 13.1974985095916, }, "ANA": { "alpha": 0.54216694759434, "beta": np.nan, "gamma": 0.392030170511872, "phi": np.nan, "l": 57.606831186929, "b": np.nan, "s1": 8.29613785790501, "s2": 4.6033791939889, "s3": -7.43956343440823, "s4": 17.722316385643, }, "MNA": { "alpha": 0.532842556756286, "beta": np.nan, "gamma": 0.346387433608713, "phi": np.nan, "l": 58.0372808528325, "b": np.nan, "s1": 7.70802088750111, "s2": 4.14885814748503, "s3": -7.72115936226225, "s4": 17.1674660340923, }, "MAM": { "alpha": 0.315621390571192, "beta": 0.000100011993615961, "gamma": 0.000100051297784532, "phi": np.nan, "l": 62.4082004238551, "b": 0.513327867101983, "s1": 1.03713425342421, "s2": 0.959607104686072, "s3": 0.770172817592091, "s4": 1.23309264451638, }, "MMM": { "alpha": 0.546068965886, "beta": 0.0737816453485457, "gamma": 0.000100031693302807, "phi": np.nan, "l": 63.8203866275649, "b": 1.01833305374778, "s1": 1.03725227137871, "s2": 0.961177239042923, "s3": 0.771173487523454, "s4": 1.23036313932852, }, "MNM": { "alpha": 0.608993139624813, "beta": np.nan, "gamma": 0.000167258612971303, "phi": np.nan, "l": 63.1472153330648, "b": np.nan, "s1": 1.0384840572776, "s2": 0.961456755855531, "s3": 0.768427399477366, "s4": 1.23185085956321, }, "AAN": { "alpha": 0.0097430554119077, "beta": 0.00974302759255084, "gamma": np.nan, "phi": np.nan, "l": 61.1430969243248, "b": 0.759041621012503, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, "MAN": { "alpha": 0.0101749952821338, "beta": 0.0101749138539332, "gamma": np.nan, "phi": np.nan, "l": 61.6020426238699, "b": 0.761407500773051, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, "MMN": { "alpha": 0.0664382968951546, "beta": 0.000100001678373356, "gamma": np.nan, "phi": np.nan, "l": 60.7206911970871, "b": 1.01221899136391, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, "ANN": { "alpha": 0.196432515825523, "beta": np.nan, "gamma": np.nan, "phi": np.nan, "l": 58.7718395431632, "b": np.nan, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, "MNN": { "alpha": 0.205985314333856, "beta": np.nan, "gamma": np.nan, "phi": np.nan, "l": 58.9770839944419, "b": np.nan, "s1": np.nan, "s2": np.nan, "s3": np.nan, "s4": np.nan, }, } return {True: damped, False: undamped}
The final state from the R model fits to get an exact comparison Obtained with this R script: library(magrittr) library(fpp2) library(forecast) concat <- function(...) { return(paste(..., sep="")) } as_dict_string <- function(named) { string <- '{' for (name in names(named)) { string <- concat(string, "\"", name, "\": ", named[name], ", ") } string <- concat(string, '}') return(string) } get_var <- function(named, name) { if (name %in% names(named)) val <- c(named[name]) else val <- c(NaN) names(val) <- c(name) return(val) } error <- c("A", "M") trend <- c("A", "M", "N") seasonal <- c("A", "M", "N") models <- outer(error, trend, FUN = "concat") %>% outer(seasonal, FUN = "concat") %>% as.vector # innov from np.random.seed(0); np.random.randn(4) innov <- c(1.76405235, 0.40015721, 0.97873798, 2.2408932) n <- length(austourists) + 1 # print fit parameters and final states for (damped in c(TRUE, FALSE)) { print(paste("damped =", damped)) for (model in models) { state <- tryCatch((function(){ fit <- ets(austourists, model = model, damped = damped) pars <- c() # alpha, beta, gamma, phi for (name in c("alpha", "beta", "gamma", "phi")) { pars <- c(pars, get_var(fit$par, name)) } # l, b, s1, s2, s3, s4 states <- c() for (name in c("l", "b", "s1", "s2", "s3", "s4")) states <- c(states, get_var(fit$states[n,], name)) c(pars, states) })(), error = function(e) rep(NA, 10)) cat(concat("\"", model, "\": ", as_dict_string(state), ",\n")) } }
simulate_fit_state_r
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/tests/test_holtwinters.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/tests/test_holtwinters.py
BSD-3-Clause
def test_simulate_expected_r( trend, seasonal, damped, error, austourists, simulate_expected_results_r, simulate_fit_state_r, ): """ Test for :meth:``statsmodels.tsa.holtwinters.HoltWintersResults``. The tests are using the implementation in the R package ``forecast`` as reference, and example data is taken from ``fpp2`` (package and book). """ short_name = {"add": "A", "mul": "M", None: "N"} model_name = short_name[error] + short_name[trend] + short_name[seasonal] if model_name in simulate_expected_results_r[damped]: expected = np.asarray(simulate_expected_results_r[damped][model_name]) state = simulate_fit_state_r[damped][model_name] else: return # create HoltWintersResults object with same parameters as in R fit = ExponentialSmoothing( austourists, seasonal_periods=4, trend=trend, seasonal=seasonal, damped_trend=damped, ).fit( smoothing_level=state["alpha"], smoothing_trend=state["beta"], smoothing_seasonal=state["gamma"], damping_trend=state["phi"], optimized=False, ) # set the same final state as in R fit._level[-1] = state["l"] fit._trend[-1] = state["b"] fit._season[-1] = state["s1"] fit._season[-2] = state["s2"] fit._season[-3] = state["s3"] fit._season[-4] = state["s4"] # for MMM with damped trend the fit fails if np.any(np.isnan(fit.fittedvalues)): return innov = np.asarray([[1.76405235, 0.40015721, 0.97873798, 2.2408932]]).T sim = fit.simulate(4, repetitions=1, error=error, random_errors=innov) assert_almost_equal(expected, sim.values, 5)
Test for :meth:``statsmodels.tsa.holtwinters.HoltWintersResults``. The tests are using the implementation in the R package ``forecast`` as reference, and example data is taken from ``fpp2`` (package and book).
test_simulate_expected_r
python
statsmodels/statsmodels
statsmodels/tsa/holtwinters/tests/test_holtwinters.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/tsa/holtwinters/tests/test_holtwinters.py
BSD-3-Clause