Skip to content

Commit 6a7bd5b

Browse files
authored
Merge pull request #661 from bashtage/ruff-fixes
CLN: Use ruff to improve code quality
2 parents 287b79c + b8e840b commit 6a7bd5b

File tree

98 files changed

+1125
-1040
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+1125
-1040
lines changed

ci/azure_template_posix.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ jobs:
9898
black --check linearmodels
9999
isort --check linearmodels
100100
ruff check linearmodels
101+
flake8 linearmodels
101102
displayName: 'Check style and formatting'
102103
103104
- script: |

linearmodels/__init__.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
from __future__ import annotations
3636

3737
import os
38+
import sys
3839

3940
from ._version import version as __version__, version_tuple
4041
from .asset_pricing.model import (
@@ -55,34 +56,34 @@
5556
from .system import IV3SLS, SUR, IVSystemGMM
5657

5758
OLS = _OLS
58-
WARN_ON_MISSING = os.environ.get("LINEARMODELS_WARN_ON_MISSING", True)
59-
WARN_ON_MISSING = False if WARN_ON_MISSING in ("0", "False") else True
60-
DROP_MISSING = os.environ.get("LINEARMODELS_DROP_MISSING", True)
61-
DROP_MISSING = False if DROP_MISSING in ("0", "False") else True
59+
WARN_ON_MISSING = os.environ.get("LINEARMODELS_WARN_ON_MISSING", "1")
60+
WARN_ON_MISSING = False if WARN_ON_MISSING in ("", "0", "false", "False") else True
61+
DROP_MISSING = os.environ.get("LINEARMODELS_DROP_MISSING", "1")
62+
DROP_MISSING = False if DROP_MISSING in ("", "0", "false", "False") else True
6263

6364
__all__ = [
64-
"AbsorbingLS",
65-
"PooledOLS",
66-
"PanelOLS",
67-
"FirstDifferenceOLS",
68-
"BetweenOLS",
69-
"RandomEffects",
70-
"FamaMacBeth",
71-
"IVLIML",
65+
"DROP_MISSING",
66+
"IV2SLS",
67+
"IV3SLS",
7268
"IVGMM",
7369
"IVGMMCUE",
74-
"IV2SLS",
70+
"IVLIML",
7571
"OLS",
7672
"SUR",
77-
"IV3SLS",
73+
"WARN_ON_MISSING",
74+
"AbsorbingLS",
75+
"BetweenOLS",
76+
"FamaMacBeth",
77+
"FirstDifferenceOLS",
7878
"IVSystemGMM",
7979
"LinearFactorModel",
8080
"LinearFactorModelGMM",
81+
"PanelOLS",
82+
"PooledOLS",
83+
"RandomEffects",
8184
"TradedFactorModel",
82-
"WARN_ON_MISSING",
83-
"DROP_MISSING",
84-
"version_tuple",
8585
"__version__",
86+
"version_tuple",
8687
]
8788

8889

@@ -92,12 +93,11 @@ def test(
9293
append: bool = True,
9394
location: str = "",
9495
) -> int:
95-
import sys
9696

9797
try:
98-
import pytest
99-
except ImportError: # pragma: no cover
100-
raise ImportError("Need pytest to run tests")
98+
import pytest # noqa: PLC0415
99+
except ImportError as exc: # pragma: no cover
100+
raise ImportError("Need pytest to run tests") from exc
101101

102102
cmd = ["--tb=auto"]
103103
if extra_args:
@@ -117,7 +117,7 @@ def test(
117117
print(pkg)
118118
if not os.path.exists(pkg):
119119
raise RuntimeError(f"{pkg} was not found. Unable to run tests")
120-
cmd = [pkg] + cmd
120+
cmd = [pkg, *cmd]
121121
print("running: pytest {}".format(" ".join(cmd)))
122122
status = pytest.main(cmd)
123123
if exit: # pragma: no cover
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
from .model import LinearFactorModel, LinearFactorModelGMM, TradedFactorModel
22

3-
__all__ = ["TradedFactorModel", "LinearFactorModelGMM", "LinearFactorModel"]
3+
__all__ = ["LinearFactorModel", "LinearFactorModelGMM", "TradedFactorModel"]

linearmodels/asset_pricing/covariance.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44

55
from __future__ import annotations
66

7-
import numpy
8-
from numpy import empty
7+
from numpy import empty, ndarray
98
from numpy.linalg import inv
109

1110
from linearmodels.iv.covariance import (
@@ -20,7 +19,7 @@ class _HACMixin:
2019
def __init__(self, kernel: str, bandwidth: float | None) -> None:
2120
self._kernel: str | None = None
2221
self._bandwidth: float | None = None # pragma: no cover
23-
self._moments: numpy.ndarray = empty((0,)) # pragma: no cover
22+
self._moments: ndarray = empty((0,)) # pragma: no cover
2423
self._check_kernel(kernel)
2524
self._check_bandwidth(bandwidth)
2625

@@ -56,8 +55,8 @@ def _check_bandwidth(self, bandwidth: float | None) -> None:
5655
try:
5756
assert bandwidth is not None
5857
bandwidth = float(bandwidth)
59-
except (TypeError, ValueError):
60-
raise TypeError("bandwidth must be either None or a float")
58+
except (TypeError, ValueError) as exc:
59+
raise TypeError("bandwidth must be either None or a float") from exc
6160
if bandwidth < 0:
6261
raise ValueError("bandwidth must be non-negative.")
6362

@@ -101,8 +100,8 @@ def __init__(
101100
self,
102101
xe: linearmodels.typing.data.Float64Array,
103102
*,
104-
jacobian: numpy.ndarray | None = None,
105-
inv_jacobian: numpy.ndarray | None = None,
103+
jacobian: ndarray | None = None,
104+
inv_jacobian: ndarray | None = None,
106105
center: bool = True,
107106
debiased: bool = False,
108107
df: int = 0,
@@ -234,8 +233,8 @@ def __init__(
234233
self,
235234
xe: linearmodels.typing.data.Float64Array,
236235
*,
237-
jacobian: numpy.ndarray | None = None,
238-
inv_jacobian: numpy.ndarray | None = None,
236+
jacobian: ndarray | None = None,
237+
inv_jacobian: ndarray | None = None,
239238
kernel: str | None = None,
240239
bandwidth: float | None = None,
241240
center: bool = True,

linearmodels/asset_pricing/model.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
from formulaic.materializers.types import NAAction
1212
import numpy as np
1313
from numpy.linalg import lstsq
14-
import pandas
1514
from pandas import DataFrame
1615
from scipy.optimize import minimize
1716

@@ -99,7 +98,7 @@ def __repr__(self) -> str:
9998
def _drop_missing(self) -> linearmodels.typing.data.BoolArray:
10099
data = (self.portfolios, self.factors)
101100
missing = cast(
102-
linearmodels.typing.data.BoolArray,
101+
"linearmodels.typing.data.BoolArray",
103102
np.any(np.c_[[dh.isnull for dh in data]], 0),
104103
)
105104
if any(missing):
@@ -123,11 +122,11 @@ def _validate_data(self) -> None:
123122
)
124123
self._drop_missing()
125124

126-
p = cast(linearmodels.typing.data.Float64Array, self.portfolios.ndarray)
127-
f = cast(linearmodels.typing.data.Float64Array, self.factors.ndarray)
125+
p = cast("linearmodels.typing.data.Float64Array", self.portfolios.ndarray)
126+
f = cast("linearmodels.typing.data.Float64Array", self.factors.ndarray)
128127
if has_constant(p)[0]:
129128
raise ValueError(
130-
"portfolios must not contains a constant or "
129+
"portfolios must not contain a constant or "
131130
"equivalent and must not have rank\n"
132131
"less than the dimension of the smaller shape."
133132
)
@@ -153,7 +152,7 @@ def formula(self, value: str | None) -> None:
153152

154153
@staticmethod
155154
def _prepare_data_from_formula(
156-
formula: str, data: pandas.DataFrame, portfolios: pandas.DataFrame | None
155+
formula: str, data: DataFrame, portfolios: DataFrame | None
157156
) -> tuple[DataFrame, DataFrame, str]:
158157
orig_formula = formula
159158
na_action = NAAction("raise")
@@ -224,9 +223,9 @@ def __init__(self, portfolios: IVDataLike, factors: IVDataLike):
224223
def from_formula(
225224
cls,
226225
formula: str,
227-
data: pandas.DataFrame,
226+
data: DataFrame,
228227
*,
229-
portfolios: pandas.DataFrame | None = None,
228+
portfolios: DataFrame | None = None,
230229
) -> TradedFactorModel:
231230
"""
232231
Parameters
@@ -349,7 +348,7 @@ def fit(
349348
kernel=kernel,
350349
)
351350
bw = cov_est.bandwidth
352-
_cov_config = {k: v for k, v in cov_config.items()}
351+
_cov_config = dict(cov_config.items())
353352
_cov_config["bandwidth"] = bw
354353
rp_cov_est = KernelCovariance(
355354
fe,
@@ -388,10 +387,10 @@ def fit(
388387
param_names = []
389388
for portfolio in self.portfolios.cols:
390389
param_names.append(f"alpha-{portfolio}")
391-
for factor in self.factors.cols:
392-
param_names.append(f"beta-{portfolio}-{factor}")
393-
for factor in self.factors.cols:
394-
param_names.append(f"lambda-{factor}")
390+
param_names.extend(
391+
[f"beta-{portfolio}-{factor}" for factor in self.factors.cols]
392+
)
393+
param_names.extend([f"lambda-{factor}" for factor in self.factors.cols])
395394

396395
res = AttrDict(
397396
params=params,
@@ -540,9 +539,9 @@ def __init__(
540539
def from_formula(
541540
cls,
542541
formula: str,
543-
data: pandas.DataFrame,
542+
data: DataFrame,
544543
*,
545-
portfolios: pandas.DataFrame | None = None,
544+
portfolios: DataFrame | None = None,
546545
risk_free: bool = False,
547546
sigma: linearmodels.typing.data.ArrayLike | None = None,
548547
) -> LinearFactorModel:
@@ -693,12 +692,12 @@ def fit(
693692
param_names = []
694693
for portfolio in self.portfolios.cols:
695694
param_names.append(f"alpha-{portfolio}")
696-
for factor in self.factors.cols:
697-
param_names.append(f"beta-{portfolio}-{factor}")
695+
param_names.extend(
696+
[f"beta-{portfolio}-{factor}" for factor in self.factors.cols]
697+
)
698698
if not excess_returns:
699699
param_names.append("lambda-risk_free")
700-
for factor in self.factors.cols:
701-
param_names.append(f"lambda-{factor}")
700+
param_names.extend([f"lambda-{factor}" for factor in self.factors.cols])
702701

703702
# Pivot vcv to remove unnecessary and have correct order
704703
order = np.reshape(np.arange(s1), (nport, nf + 1))
@@ -777,7 +776,7 @@ def _moments(
777776
sigma_inv = self._sigma_inv
778777

779778
f = self.factors.ndarray
780-
nobs, nf, nport, _, s1, s2, s3 = self._boundaries()
779+
nobs, nf, nport, _, _, _, _ = self._boundaries()
781780
fc = np.c_[np.ones((nobs, 1)), f]
782781
f_rep = np.tile(fc, (1, nport))
783782
eps_rep = np.tile(eps, (nf + 1, 1))
@@ -844,9 +843,9 @@ def __init__(
844843
def from_formula(
845844
cls,
846845
formula: str,
847-
data: pandas.DataFrame,
846+
data: DataFrame,
848847
*,
849-
portfolios: pandas.DataFrame | None = None,
848+
portfolios: DataFrame | None = None,
850849
risk_free: bool = False,
851850
) -> LinearFactorModelGMM:
852851
"""
@@ -1098,8 +1097,9 @@ def fit(
10981097
r2 = 1.0 - residual_ss / total_ss
10991098
param_names = []
11001099
for portfolio in self.portfolios.cols:
1101-
for factor in self.factors.cols:
1102-
param_names.append(f"beta-{portfolio}-{factor}")
1100+
param_names.extend(
1101+
[f"beta-{portfolio}-{factor}" for factor in self.factors.cols]
1102+
)
11031103
if not excess_returns:
11041104
param_names.append("lambda-risk_free")
11051105
param_names.extend([f"lambda-{f}" for f in self.factors.cols])

linearmodels/asset_pricing/results.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ def __init__(self, results: AttrDict):
338338
@property
339339
def std_errors(self) -> pd.DataFrame:
340340
"""Estimated parameter standard errors"""
341-
se = cast(linearmodels.typing.data.Float64Array, np.sqrt(np.diag(self._cov)))
341+
se = cast("linearmodels.typing.data.Float64Array", np.sqrt(np.diag(self._cov)))
342342
ase = np.sqrt(np.diag(self._alpha_vcv))
343343
nportfolio, nfactor = self._params.shape
344344
nloadings = nportfolio * (nfactor - 1)

linearmodels/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
logger = logging.getLogger(__name__)
88

9-
cow = bool(os.environ.get("LM_TEST_COPY_ON_WRITE", False))
9+
cow = bool(os.environ.get("LM_TEST_COPY_ON_WRITE", ""))
1010
if cow:
1111
try:
1212
pd.options.mode.copy_on_write = cow

linearmodels/datasets/birthweight/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from pandas import DataFrame
22

3+
from linearmodels import datasets
4+
35
DESCR = """
46
J. Mullahy (1997), "Instrumental-Variable Estimation of Count Data Models:
57
Applications to Models of Cigarette Smoking Behavior," Review of Economics
@@ -23,6 +25,5 @@
2325

2426

2527
def load() -> DataFrame:
26-
from linearmodels import datasets
2728

2829
return datasets.load(__file__, "birthweight.csv.bz2")

linearmodels/datasets/card/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from pandas import DataFrame
22

3+
from linearmodels import datasets
4+
35
DESCR = """
46
D. Card (1995), "Using Geographic Variation in College Proximity to Estimate
57
the Return to Schooling," in Aspects of Labour Market Behavior: Essays in
@@ -44,6 +46,5 @@
4446

4547

4648
def load() -> DataFrame:
47-
from linearmodels import datasets
4849

4950
return datasets.load(__file__, "card.csv.bz2")

linearmodels/datasets/fertility/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from pandas import DataFrame
22

3+
from linearmodels import datasets
4+
35
DESCR = """
46
W. Sander, "The Effect of Women's Schooling on Fertility," Economics Letters
57
40, 229-233.
@@ -35,6 +37,5 @@
3537

3638

3739
def load() -> DataFrame:
38-
from linearmodels import datasets
3940

4041
return datasets.load(__file__, "fertility.csv.bz2")

0 commit comments

Comments
 (0)