Skip to content

Commit

Permalink
Merge pull request #346 from bashtage/additional-typing-clean
Browse files Browse the repository at this point in the history
CLN: Improve typing
  • Loading branch information
bashtage authored Jan 31, 2020
2 parents 2fa03cc + 8c213e3 commit b585c45
Show file tree
Hide file tree
Showing 10 changed files with 122 additions and 66 deletions.
10 changes: 6 additions & 4 deletions arch/bootstrap/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def _loo_jackknife(
func: Callable[..., NDArray],
nobs: int,
args: Sequence[ArrayLike],
kwargs: ArrayLike,
kwargs: Dict[str, ArrayLike],
) -> NDArray:
"""
Leave one out jackknife estimation
Expand Down Expand Up @@ -137,7 +137,9 @@ def _add_extra_kwargs(
if extra_kwargs is None:
return kwargs
else:
return dict(list(kwargs.items()) + list(extra_kwargs.items()))
kwargs_copy = kwargs.copy()
kwargs_copy.update(extra_kwargs)
return kwargs_copy


class IIDBootstrap(object, metaclass=DocStringInheritor):
Expand Down Expand Up @@ -666,7 +668,7 @@ def clone(self, *args: ArrayLike, **kwargs: ArrayLike) -> "IIDBootstrap":
bs
Bootstrap instance
"""
pos_arguments = copy.deepcopy(self._parameters)
pos_arguments: List[Union[int, ArrayLike]] = copy.deepcopy(self._parameters)
pos_arguments.extend(args)
bs = self.__class__(*pos_arguments, **kwargs)
if self._seed is not None:
Expand Down Expand Up @@ -1088,7 +1090,7 @@ def update_indices(self) -> Tuple[List[NDArray], Dict[str, NDArray]]:
return pos_indices, kw_indices

@property
def index(self) -> NDArray:
def index(self) -> Tuple[List[NDArray], Dict[str, NDArray]]:
"""
Returns the current index of the bootstrap
Expand Down
2 changes: 1 addition & 1 deletion arch/data/binary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

def load() -> DataFrame:
"""
Load the graduate school admissions dataused in the examples
Load the graduate school admissions data used in the examples
Returns
-------
Expand Down
4 changes: 2 additions & 2 deletions arch/tests/bootstrap/test_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ def test_apply(bs_setup):
bs.seed(23456)

results = bs.apply(bs_setup.func, 1000)
bs.reset(23456)
bs.reset(True)
direct_results = []
for pos, _ in bs.bootstrap(1000):
direct_results.append(bs_setup.func(*pos))
Expand All @@ -619,7 +619,7 @@ def test_apply_series(bs_setup):
bs.seed(23456)

results = bs.apply(bs_setup.func, 1000)
bs.reset(23456)
bs.reset(True)
direct_results = []
for pos, _ in bs.bootstrap(1000):
direct_results.append(bs_setup.func(*pos))
Expand Down
16 changes: 8 additions & 8 deletions arch/tests/univariate/test_mean.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def test_constant_mean(self):
direct = pd.DataFrame(
index=np.arange(self.y.shape[0]),
columns=["h.{0:>02d}".format(i + 1) for i in range(20)],
dtype=np.float64,
dtype="double",
)
direct.iloc[20:, :] = res.params.iloc[0]
# TODO
Expand Down Expand Up @@ -156,7 +156,7 @@ def test_zero_mean(self):
direct = pd.DataFrame(
index=np.arange(self.y.shape[0]),
columns=["h.{0:>02d}".format(i + 1) for i in range(99)],
dtype=np.float64,
dtype="double",
)
direct.iloc[:, :] = 0.0
assert isinstance(forecasts, ARCHModelForecast)
Expand Down Expand Up @@ -271,7 +271,7 @@ def test_har(self):
direct = pd.DataFrame(
index=np.arange(t),
columns=["h." + str(i + 1) for i in range(6)],
dtype=np.float64,
dtype="float64",
)

params = np.asarray(res.params)
Expand Down Expand Up @@ -303,7 +303,7 @@ def test_har(self):
direct = pd.DataFrame(
index=self.y_series.index,
columns=["h." + str(i + 1) for i in range(6)],
dtype=np.float64,
dtype="float64",
)
forecasts = res.forecast(horizon=6)
params = np.asarray(res.params)
Expand Down Expand Up @@ -393,7 +393,7 @@ def test_ar(self):
direct = pd.DataFrame(
index=np.arange(y.shape[0]),
columns=["h." + str(i + 1) for i in range(5)],
dtype=np.float64,
dtype="float64",
)
params = res.params.iloc[:-1]
for i in range(2, y.shape[0]):
Expand Down Expand Up @@ -458,10 +458,10 @@ def test_ar_plot(self):

res.plot(scale=360)
res.hedgehog_plot(start=500)
res.hedgehog_plot(start=500, type="mean")
res.hedgehog_plot(type="volatility")
res.hedgehog_plot(start=500, plot_type="mean")
res.hedgehog_plot(plot_type="volatility")
res.hedgehog_plot(start=500, method="simulation", simulations=100)
res.hedgehog_plot(type="volatility", method="bootstrap")
res.hedgehog_plot(plot_type="volatility", method="bootstrap")

def test_arch_arx(self):
self.rng.seed(12345)
Expand Down
5 changes: 3 additions & 2 deletions arch/tests/univariate/test_moment.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from numpy import exp, inf, log, nan, pi
from numpy import exp, inf, log, nan, ones_like, pi
from numpy.testing import assert_almost_equal, assert_equal
import pytest
from scipy.integrate import quad
Expand Down Expand Up @@ -43,7 +43,8 @@ def test_moment(dist, params):

# verify moments that exist
def f(x, n):
return (x ** n) * exp(dist.loglikelihood(params, x, 1, True))
sigma2 = ones_like(x)
return (x ** n) * exp(dist.loglikelihood(params, x, sigma2, True))

for n in range(6): # moments 0-5

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@
# Compute tau star
err_large = res_large.resid
# Missing 1 parameter here, replace with 0
params = np.append(res_small.params, 0.0)
params = np.append(np.asarray(res_small.params), np.zeros(1))
err_small = lhs_large - rhs_large.dot(params)
# Find the location that minimizes the total absolute error
m = lhs_large.shape[0]
Expand Down
2 changes: 1 addition & 1 deletion arch/unitroot/unitroot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1820,7 +1820,7 @@ def auto_bandwidth(
for i in range(n + 1):
a = list(y[i:])
b = list(y[: len(y) - i])
sig[i] = sum([i * j for (i, j) in zip(a, b)])
sig[i] = int(sum([i * j for (i, j) in zip(a, b)]))

sigma_m1 = sig[1 : len(sig)] # sigma without the 1st element
s0 = sig[0] + 2 * sum(sigma_m1)
Expand Down
24 changes: 12 additions & 12 deletions arch/univariate/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def _parse_parameters(self, x: ArrayLike) -> Tuple[NDArray, NDArray, NDArray]:

def fix(
self,
params: ArrayLike1D,
params: Union[Sequence[float], ArrayLike1D],
first_obs: Union[int, DateLike] = None,
last_obs: Union[int, DateLike] = None,
) -> "ARCHModelFixedResult":
Expand Down Expand Up @@ -464,7 +464,7 @@ def fix(

var_bounds = v.variance_bounds(resids)

params = np.asarray(params)
params = ensure1d(params, "params", False)
loglikelihood = -1.0 * self._loglikelihood(params, sigma2, backcast, var_bounds)

mp, vp, dp = self._parse_parameters(params)
Expand Down Expand Up @@ -1453,7 +1453,7 @@ def hedgehog_plot(
>>> sim_data.index = pd.date_range('2000-01-01',periods=250)
>>> am = arch_model(sim_data['data'],mean='HAR',lags=[1,5,22], vol='Constant')
>>> res = am.fit()
>>> fig = res.hedgehog_plot(type='mean')
>>> fig = res.hedgehog_plot(plot_type='mean')
"""
import matplotlib.pyplot as plt

Expand Down Expand Up @@ -1888,7 +1888,7 @@ def _format_forecasts(
horizon = values.shape[1]
format_str = "{0:>0" + str(int(np.ceil(np.log10(horizon + 0.5)))) + "}"
columns = ["h." + format_str.format(h + 1) for h in range(horizon)]
forecasts = DataFrame(values, index=index, columns=columns, dtype=np.float64)
forecasts = DataFrame(values, index=index, columns=columns, dtype="float")
return forecasts


Expand Down Expand Up @@ -1917,30 +1917,30 @@ class ARCHModelForecastSimulation(object):

def __init__(
self,
values: DataFrame,
residuals: DataFrame,
variances: DataFrame,
residual_variances: DataFrame,
values: NDArray,
residuals: NDArray,
variances: NDArray,
residual_variances: NDArray,
) -> None:
self._values = values
self._residuals = residuals
self._variances = variances
self._residual_variances = residual_variances

@property
def values(self) -> DataFrame:
def values(self) -> NDArray:
return self._values

@property
def residuals(self) -> DataFrame:
def residuals(self) -> NDArray:
return self._residuals

@property
def variances(self) -> DataFrame:
def variances(self) -> NDArray:
return self._variances

@property
def residual_variances(self) -> DataFrame:
def residual_variances(self) -> NDArray:
return self._residual_variances


Expand Down
Loading

0 comments on commit b585c45

Please sign in to comment.