Skip to content

Commit cc62df7

Browse files
committed
REF: Restructure
Move kernel info closer to kernels
1 parent 7e9f37d commit cc62df7

File tree

7 files changed

+56
-59
lines changed

7 files changed

+56
-59
lines changed

arch/covariance/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from typing import Dict, Type
2+
3+
from . import kernel
4+
5+
KERNEL_ESTIMATORS: Dict[str, Type[kernel.CovarianceEstimator]] = {
6+
est_name.lower(): getattr(kernel, est_name) for est_name in kernel.KERNELS
7+
}
8+
KERNEL_ESTIMATORS.update(
9+
{est_name: getattr(kernel, est_name) for est_name in kernel.KERNELS}
10+
)
11+
KNOWN_KERNELS = "\n".join(sorted([k for k in KERNEL_ESTIMATORS]))
12+
KERNEL_ERR = f"kernel is not a known estimator. Must be one of:\n {KNOWN_KERNELS}"

arch/covariance/kernel.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"Andrews",
2525
"Gallant",
2626
"NeweyWest",
27+
"normalize_kernel_name",
2728
]
2829

2930
KERNELS = [
@@ -42,6 +43,22 @@
4243
]
4344

4445

46+
def normalize_kernel_name(name: str) -> str:
47+
"""
48+
Normalize a Kernel name using standard replacements
49+
50+
Removes - and _ and converts to lower case.
51+
52+
Returns
53+
-------
54+
str
55+
The normalized kernel name.
56+
"""
57+
name = name.replace("-", "").replace("_", "")
58+
name = name.lower()
59+
return name
60+
61+
4562
class CovarianceEstimate(object):
4663
r"""
4764
Covariance estimate using a long-run covariance estimator

arch/covariance/var.py

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Dict, NamedTuple, Optional, Tuple, Type
1+
from typing import Dict, NamedTuple, Optional, Tuple
22

33
import numpy as np
44
from numpy import zeros
@@ -7,8 +7,12 @@
77
from statsmodels.tools import add_constant
88
from statsmodels.tsa.tsatools import lagmat
99

10-
from arch.covariance import kernel
11-
from arch.covariance.kernel import CovarianceEstimate, CovarianceEstimator
10+
from arch.covariance import KERNEL_ERR, KERNEL_ESTIMATORS
11+
from arch.covariance.kernel import (
12+
CovarianceEstimate,
13+
CovarianceEstimator,
14+
normalize_kernel_name,
15+
)
1216
from arch.typing import ArrayLike, NDArray
1317

1418

@@ -19,21 +23,6 @@ class VARModel(NamedTuple):
1923
intercept: bool
2024

2125

22-
def _normalize_name(name: str) -> str:
23-
name = name.replace("-", "").replace("_", "")
24-
name = name.lower()
25-
return name
26-
27-
28-
KERNELS: Dict[str, Type[CovarianceEstimator]] = {}
29-
for name in kernel.__all__:
30-
estimator = getattr(kernel, name)
31-
if issubclass(estimator, kernel.CovarianceEstimator):
32-
KERNELS[_normalize_name(name)] = estimator
33-
KERNELS[name] = estimator
34-
print(KERNELS)
35-
36-
3726
class PreWhitenRecoloredCovariance(CovarianceEstimator):
3827
"""
3928
Parameters
@@ -86,20 +75,11 @@ def __init__(
8675
self._auto_lag_selection = True
8776
self._format_lags(lags)
8877
self._sample_autocov = sample_autocov
89-
original_kernel = kernel
90-
kernel = _normalize_name(kernel)
91-
if kernel not in KERNELS:
92-
import string
93-
94-
available = [key for key in KERNELS if key[0] in string.ascii_uppercase]
95-
available_val = "\n ".join(
96-
[f"{knl} {_normalize_name(knl)}" for knl in available]
97-
)
98-
raise ValueError(
99-
f"kernel {original_kernel} was not found. The available kernels "
100-
f"are:\n\n{available_val}"
101-
)
102-
self._kernel = KERNELS[kernel]
78+
kernel = normalize_kernel_name(kernel)
79+
if kernel not in KERNEL_ESTIMATORS:
80+
raise ValueError(KERNEL_ERR)
81+
82+
self._kernel = KERNEL_ESTIMATORS[kernel]
10383
self._kernel_instance: Optional[CovarianceEstimator] = None
10484

10585
# Attach for testing only

arch/tests/covariance/test_var.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def direct_var(
108108
else:
109109
# Branch is a workaround of NumPy 1.15
110110
# TODO: Remove after NumPy 1.15 dropped
111-
resids[:, i: i + 1] = lhs[:, i: i + 1]
111+
resids[:, i : i + 1] = lhs[:, i : i + 1]
112112
return params, resids
113113

114114

arch/unitroot/_phillips_ouliaris.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,10 @@
77
from statsmodels.iolib.table import SimpleTable
88
from statsmodels.regression.linear_model import RegressionResults
99

10-
import arch.covariance.kernel as lrcov
10+
from arch.covariance import KERNEL_ERR, KERNEL_ESTIMATORS
11+
from arch.covariance.kernel import CovarianceEstimator
1112
from arch.typing import ArrayLike1D, ArrayLike2D
12-
from arch.unitroot._shared import (
13-
KERNEL_ERR,
14-
KERNEL_ESTIMATORS,
15-
ResidualCointegrationTestResult,
16-
_cross_section,
17-
)
13+
from arch.unitroot._shared import ResidualCointegrationTestResult, _cross_section
1814
from arch.unitroot.critical_values.phillips_ouliaris import (
1915
CV_PARAMETERS,
2016
CV_TAU_MIN,
@@ -314,7 +310,7 @@ def __init__(
314310
order: int = 2,
315311
xsection: Optional[RegressionResults] = None,
316312
test_type: str = "Za",
317-
kernel_est: Optional[lrcov.CovarianceEstimator] = None,
313+
kernel_est: Optional[CovarianceEstimator] = None,
318314
rho: float = 0.0,
319315
) -> None:
320316
super().__init__(

arch/unitroot/_shared.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
from typing import Any, Dict, NamedTuple, Optional, Tuple, Type
1+
from typing import Any, Dict, NamedTuple, Optional, Tuple
22

33
import pandas as pd
44
from statsmodels.iolib.summary import Summary
55
from statsmodels.regression.linear_model import OLS, RegressionResults
66

7-
import arch.covariance.kernel as lrcov
7+
from arch.covariance import KERNEL_ESTIMATORS
88
from arch.typing import ArrayLike1D, ArrayLike2D
99
from arch.utility.array import ensure1d, ensure2d
1010
from arch.utility.timeseries import add_trend
@@ -14,13 +14,6 @@
1414
except ImportError:
1515
pass
1616

17-
KERNEL_ESTIMATORS: Dict[str, Type[lrcov.CovarianceEstimator]] = {
18-
kernel.lower(): getattr(lrcov, kernel) for kernel in lrcov.KERNELS
19-
}
20-
KERNEL_ESTIMATORS.update({kernel: getattr(lrcov, kernel) for kernel in lrcov.KERNELS})
21-
KNOWN_KERNELS = "\n".join(sorted([k for k in KERNEL_ESTIMATORS]))
22-
KERNEL_ERR = f"kernel is not a known estimator. Must be one of:\n {KNOWN_KERNELS}"
23-
2417

2518
class CointegrationSetup(NamedTuple):
2619
y: pd.Series

arch/unitroot/cointegration.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
from statsmodels.iolib.table import SimpleTable
99
from statsmodels.regression.linear_model import OLS, RegressionResults
1010

11-
import arch.covariance.kernel as lrcov
11+
from arch.covariance import KERNEL_ERR, KERNEL_ESTIMATORS
12+
from arch.covariance.kernel import CovarianceEstimate, CovarianceEstimator
1213
from arch.typing import ArrayLike1D, ArrayLike2D, NDArray
1314
from arch.unitroot._engle_granger import EngleGrangerTestResults, engle_granger
1415
from arch.unitroot._phillips_ouliaris import (
@@ -17,8 +18,6 @@
1718
phillips_ouliaris,
1819
)
1920
from arch.unitroot._shared import (
20-
KERNEL_ERR,
21-
KERNEL_ESTIMATORS,
2221
_check_cointegrating_regression,
2322
_check_kernel,
2423
_cross_section,
@@ -46,7 +45,7 @@ def __init__(
4645
params: pd.Series,
4746
cov: pd.DataFrame,
4847
resid: pd.Series,
49-
kernel_est: lrcov.CovarianceEstimator,
48+
kernel_est: CovarianceEstimator,
5049
num_x: int,
5150
trend: str,
5251
df_adjust: bool,
@@ -126,7 +125,7 @@ def rsquared_adj(self) -> float:
126125
return self._rsquared_adj
127126

128127
@cached_property
129-
def _cov_est(self) -> lrcov.CovarianceEstimate:
128+
def _cov_est(self) -> CovarianceEstimate:
130129
r = np.asarray(self._resid)
131130
kern_class = self._kernel_est.__class__
132131
bw = self._bandwidth
@@ -329,7 +328,7 @@ def __init__(
329328
lags: int,
330329
leads: int,
331330
cov_type: str,
332-
kernel_est: lrcov.CovarianceEstimator,
331+
kernel_est: CovarianceEstimator,
333332
num_x: int,
334333
trend: str,
335334
reg_results: RegressionResults,
@@ -776,7 +775,7 @@ def _cov(
776775
df_adjust: bool,
777776
rhs: pd.DataFrame,
778777
resids: pd.Series,
779-
) -> Tuple[pd.DataFrame, lrcov.CovarianceEstimator]:
778+
) -> Tuple[pd.DataFrame, CovarianceEstimator]:
780779
"""Estimate the covariance"""
781780
kernel = kernel.lower().replace("-", "").replace("_", "")
782781
if kernel not in KERNEL_ESTIMATORS:
@@ -810,7 +809,7 @@ def __init__(
810809
cov: pd.DataFrame,
811810
resid: pd.Series,
812811
omega_112: float,
813-
kernel_est: lrcov.CovarianceEstimator,
812+
kernel_est: CovarianceEstimator,
814813
num_x: int,
815814
trend: str,
816815
df_adjust: bool,
@@ -981,7 +980,7 @@ def __init__(
981980

982981
def _common_fit(
983982
self, kernel: str, bandwidth: Optional[float], force_int: bool, diff: bool
984-
) -> Tuple[lrcov.CovarianceEstimator, NDArray, NDArray]:
983+
) -> Tuple[CovarianceEstimator, NDArray, NDArray]:
985984
kernel = _check_kernel(kernel)
986985
res = _cross_section(self._y, self._x, self._trend)
987986
x = np.asarray(self._x)

0 commit comments

Comments
 (0)