Skip to content

Commit

Permalink
CLN: General clean of univariate volatility
Browse files Browse the repository at this point in the history
Clean up types
Simplify cython directives
  • Loading branch information
bashtage committed Oct 1, 2018
1 parent 5dbe48e commit 0325caa
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 84 deletions.
65 changes: 19 additions & 46 deletions arch/univariate/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from arch.utility.exceptions import ConvergenceWarning, StartingValueWarning, \
convergence_warning, starting_value_warning

__all__ = ['implicit_constant', 'ARCHModelResult', 'ARCHModel']
__all__ = ['implicit_constant', 'ARCHModelResult', 'ARCHModel', 'ARCHModelForecast']

# Callback variables
_callback_iter, _callback_llf = 0, 0.0,
Expand Down Expand Up @@ -583,7 +583,7 @@ def starting_values(self):
@cached_property
def num_params(self):
"""
Returns the number of parameters
Number of parameters in the model
"""
raise NotImplementedError('Subclasses must implement')

Expand Down Expand Up @@ -658,7 +658,7 @@ def forecast(self, params, horizon=1, start=None, align='origin', method='analyt
Parameters
----------
params : ndarray, optional
params : {ndarray, Series}, optional
Alternative parameters to use. If not provided, the parameters
estimated when fitting the model are used. Must be identical in
shape to the parameters computed by fitting the model.
Expand Down Expand Up @@ -784,21 +784,8 @@ class ARCHModelFixedResult(_SummaryRepr):
----------
loglikelihood : float
Value of the log-likelihood
aic : float
Akaike information criteria
bic : float
Schwarz/Bayes information criteria
conditional_volatility : {ndarray, Series}
nobs element array containing the conditional volatility (square root
of conditional variance). The values are aligned with the input data
so that the value in the t-th position is the variance of t-th error,
which is computed using time-(t-1) information.
params : Series
Estimated parameters
nobs : int
Number of observations used in the estimation
num_params : int
Number of parameters in the model
resid : {ndarray, Series}
nobs element array containing model residuals
model : ARCHModel
Expand Down Expand Up @@ -919,9 +906,9 @@ def summary(self):
headers=header, title=title)
smry.tables.append(table)

extra_text = ('Results generated with user-specified parameters.',
extra_text = ['Results generated with user-specified parameters.',
'Since the model was not estimated, there are no std. '
'errors.')
'errors.']
smry.add_extra_txt(extra_text)
return smry

Expand Down Expand Up @@ -960,6 +947,14 @@ def params(self):
def conditional_volatility(self):
"""
Estimated conditional volatility
Returns
-------
conditional_volatility : {ndarray, Series}
nobs element array containing the conditional volatility (square
root of conditional variance). The values are aligned with the
input data so that the value in the t-th position is the variance
of t-th error, which is computed using time-(t-1) information.
"""
if self._is_pandas:
return pd.Series(self._volatility,
Expand All @@ -971,7 +966,7 @@ def conditional_volatility(self):
@cached_property
def nobs(self):
"""
Number of data points used ot estimate model
Number of data points used to estimate model
"""
return self._nobs

Expand Down Expand Up @@ -1274,33 +1269,10 @@ class ARCHModelResult(ARCHModelFixedResult):
----------
loglikelihood : float
Value of the log-likelihood
aic : float
Akaike information criteria
bic : float
Schwarz/Bayes information criteria
conditional_volatility : {ndarray, Series}
nobs element array containing the conditional volatility (square root
of conditional variance). The values are aligned with the input data
so that the value in the t-th position is the variance of t-th error,
which is computed using time-(t-1) information.
params : Series
Estimated parameters
param_cov : DataFrame
Estimated variance-covariance of the parameters
rsquared : float
R-squared
rsquared_adj : float
Degree of freedom adjusted R-squared
nobs : int
Number of observations used in the estimation
num_params : int
Number of parameters in the model
tvalues : Series
Array of t-statistics for the null the coefficient is 0
std_err : Series
Array of parameter standard errors
pvalues : Series
Array of p-values for the t-statistics
resid : {ndarray, Series}
nobs element array containing model residuals
model : ARCHModel
Expand Down Expand Up @@ -1509,15 +1481,15 @@ def pvalues(self):
@cached_property
def std_err(self):
"""
Parameter standard error
Array of parameter standard errors
"""
return pd.Series(np.sqrt(np.diag(self.param_cov)),
index=self._names, name='std_err')

@cached_property
def tvalues(self):
"""
t-statistics for the null the coefficient is 0
Array of t-statistics testing the null that the coefficient are 0
"""
tvalues = self.params / self.std_err
tvalues.name = 'tvalues'
Expand Down Expand Up @@ -1621,8 +1593,6 @@ class ARCHModelForecast(object):
Forecast values for the conditional variance of the process
residual_variance : DataFrame
Forecast values for the conditional variance of the residuals
simulations : ARCHModelForecastSimulation
Object containing detailed simulation results if using a simulation-based method
"""

def __init__(self, index, mean, variance, residual_variance,
Expand Down Expand Up @@ -1656,4 +1626,7 @@ def residual_variance(self):

@property
def simulations(self):
"""
Detailed simulation results if using a simulation-based method
"""
return self._sim
7 changes: 4 additions & 3 deletions arch/univariate/distribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,8 @@ def __const_b(self, parameters):
a = self.__const_a(parameters)
return (1 + 3 * lam ** 2 - a ** 2) ** .5

def __const_c(self, parameters):
@staticmethod
def __const_c(parameters):
"""Compute c constant.
Parameters
Expand All @@ -523,8 +524,8 @@ def __const_c(self, parameters):
c : float
Log of the constant used in loglikelihood
"""
eta, lam = parameters
# return gamma((eta+1)/2) / ((pi*(eta-2))**.5 * gamma(eta/2))
eta = parameters[0]
# return gamma((eta+1)/2) / ((pi*(eta-2))**.5 * gamma(eta/2))
return gammaln((eta + 1) / 2) - gammaln(eta / 2) - log(pi * (eta - 2)) / 2

def ppf(self, arg, parameters):
Expand Down
32 changes: 15 additions & 17 deletions arch/univariate/mean.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ class HARX(ARCHModel):
nobs element vector containing the dependent variable
x : {ndarray, DataFrame}, optional
nobs by k element array containing exogenous regressors
lags : {scalar, array}, optional
lags : {scalar, ndarray}, optional
Description of lag structure of the HAR. Scalar included all lags
between 1 and the value. A 1-d array includes the HAR lags 1:lags[0],
1:lags[1], ... A 2-d array includes the HAR lags of the form
Expand Down Expand Up @@ -199,13 +199,11 @@ def _static_gaussian_loglikelihood(resids):
def _model_description(self, include_lags=True):
"""Generates the model description for use by __str__ and related
functions"""
if include_lags:
if self.lags is not None:
lagstr = ['[' + str(lag[0]) + ':' + str(lag[1]) + ']'
for lag in self._lags.T]
lagstr = ', '.join(lagstr)
else:
lagstr = 'none'
lagstr = 'none'
if include_lags and self.lags is not None:
lagstr = ['[' + str(lag[0]) + ':' + str(lag[1]) + ']'
for lag in self._lags.T]
lagstr = ', '.join(lagstr)
xstr = str(self._x.shape[1]) if self._x is not None else '0'
conststr = 'yes' if self.constant else 'no'
od = OrderedDict()
Expand Down Expand Up @@ -282,7 +280,7 @@ def simulate(self, params, nobs, burn=500, initial_value=None, x=None,
initial_value : {ndarray, float}, optional
Either a scalar value or `max(lags)` array set of initial values to
use when initializing the model. If omitted, 0.0 is used.
x : array, optional
x : {ndarray, DataFrame}, optional
nobs + burn by k array of exogenous variables to include in the
simulation.
initial_value_vol : {ndarray, float}, optional
Expand Down Expand Up @@ -886,7 +884,7 @@ def simulate(self, params, nobs, burn=500, initial_value=None, x=None,
Parameters
----------
params : array
params : {ndarray, DataFrame}
Parameters to use when simulating the model. Parameter order is
[volatility distribution]. There are no mean parameters.
nobs : int
Expand Down Expand Up @@ -1020,17 +1018,17 @@ def __init__(self, y=None, x=None, lags=None, constant=True,
def _model_description(self, include_lags=True):
"""Generates the model description for use by __str__ and related
functions"""
if include_lags:
if self.lags is not None:
lagstr = [str(lag[1]) for lag in self._lags.T]
lagstr = ', '.join(lagstr)
else:
lagstr = 'none'
lagstr = 'none'
if include_lags and self.lags is not None:
lagstr = [str(lag[1]) for lag in self._lags.T]
lagstr = ', '.join(lagstr)

xstr = str(self._x.shape[1]) if self._x is not None else '0'
conststr = 'yes' if self.constant else 'no'
od = OrderedDict()
od['constant'] = conststr
od['lags'] = lagstr
if include_lags:
od['lags'] = lagstr
od['no. of exog'] = xstr
od['volatility'] = self.volatility.__str__()
od['distribution'] = self.distribution.__str__()
Expand Down
19 changes: 3 additions & 16 deletions arch/univariate/recursions.pyx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!python
#cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True

import numpy as np
cimport numpy as np
cimport cython

__all__ = ['harch_recursion','arch_recursion','garch_recursion',
'egarch_recursion']
Expand All @@ -16,9 +18,6 @@ cdef extern from 'float.h':

cdef double LNSIGMA_MAX = log(DBL_MAX)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def harch_recursion(double[::1] parameters,
double[::1] resids,
double[::1] sigma2,
Expand Down Expand Up @@ -69,9 +68,6 @@ def harch_recursion(double[::1] parameters,

return np.asarray(sigma2)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def arch_recursion(double[::1] parameters,
double[::1] resids,
double[::1] sigma2,
Expand Down Expand Up @@ -121,9 +117,6 @@ def arch_recursion(double[::1] parameters,

return np.asarray(sigma2)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def garch_recursion(double[::1] parameters,
double[::1] fresids,
double[::1] sresids,
Expand Down Expand Up @@ -199,9 +192,6 @@ def garch_recursion(double[::1] parameters,

return np.asarray(sigma2)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def egarch_recursion(double[::1] parameters,
double[::1] resids,
double[::1] sigma2,
Expand Down Expand Up @@ -282,9 +272,6 @@ def egarch_recursion(double[::1] parameters,



@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def midas_recursion(double[::1] parameters,
double[::1] weights,
double[::1] resids,
Expand Down
2 changes: 1 addition & 1 deletion arch/univariate/volatility.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
egarch_recursion, midas_recursion)

__all__ = ['GARCH', 'ARCH', 'HARCH', 'ConstantVariance', 'EWMAVariance', 'RiskMetrics2006',
'EGARCH', 'FixedVariance', 'BootstrapRng', 'MIDASHyperbolic']
'EGARCH', 'FixedVariance', 'BootstrapRng', 'MIDASHyperbolic', 'VolatilityProcess']


class BootstrapRng(object):
Expand Down
2 changes: 1 addition & 1 deletion arch/utility/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from pandas import DataFrame, NaT, Series, Timestamp, to_datetime

__all__ = ['ensure1d', 'parse_dataframe', 'DocStringInheritor',
'date_to_index']
'date_to_index', 'cutoff_to_index']

deprecation_doc = """
{func} has been moved. Please use {new_location}.{func}.
Expand Down

0 comments on commit 0325caa

Please sign in to comment.