Skip to content

Commit ee68adc

Browse files
committed
use hasattr instead of version to check whether rolling.rank is implemented
1 parent 33ed6c3 commit ee68adc

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

qlib/data/ops.py

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,25 +1148,15 @@ class Rank(Rolling):
11481148

11491149
def __init__(self, feature, N):
11501150
super(Rank, self).__init__(feature, N, "rank")
1151-
major_version, minor_version, *_ = pd.__version__.split(".")
1152-
self._load_internal = (
1153-
self._load_internal_pd14
1154-
if int(major_version) > 1 or int(major_version) == 1 and int(minor_version) > 3
1155-
else self._load_internal_pd_below_13
1156-
)
1157-
1158-
def _load_internal_pd14(self, instrument, start_index, end_index, *args):
1159-
series = self.feature.load(instrument, start_index, end_index, *args)
1160-
if self.N == 0:
1161-
series = series.expanding(min_periods=1).rank(pct=True)
1162-
else:
1163-
series = series.rolling(self.N, min_periods=1).rank(pct=True)
1164-
return series
11651151

11661152
# for compatiblity of python 3.7, which doesn't support pandas 1.4.0+ which implements Rolling.rank
1167-
def _load_internal_pd_below_13(self, instrument, start_index, end_index, *args):
1153+
def _load_internal(self, instrument, start_index, end_index, *args):
11681154
series = self.feature.load(instrument, start_index, end_index, *args)
11691155

1156+
rolling_or_expending = series.expanding(min_periods=1) if self.N == 0 else series.rolling(self.N, min_periods=1)
1157+
if hasattr(rolling_or_expending, "rank"):
1158+
return rolling_or_expending.rank(pct=True)
1159+
11701160
def rank(x):
11711161
if np.isnan(x[-1]):
11721162
return np.nan
@@ -1175,11 +1165,7 @@ def rank(x):
11751165
return np.nan
11761166
return percentileofscore(x1, x1[-1]) / 100
11771167

1178-
if self.N == 0:
1179-
series = series.expanding(min_periods=1).apply(rank, raw=True)
1180-
else:
1181-
series = series.rolling(self.N, min_periods=1).apply(rank, raw=True)
1182-
return series
1168+
return rolling_or_expending.apply(rank, raw=True)
11831169

11841170

11851171
class Count(Rolling):

0 commit comments

Comments
 (0)