Skip to content

Commit

Permalink
0.9.39 新增两个 rolling 工具函数
Browse files Browse the repository at this point in the history
  • Loading branch information
zengbin93 committed Dec 13, 2023
1 parent ec67a2d commit d7e59bb
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pythonpackage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ name: Python package

on:
push:
branches: [ master, V0.9.38 ]
branches: [ master, V0.9.39 ]
pull_request:
branches: [ master ]

Expand Down
6 changes: 4 additions & 2 deletions czsc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,14 @@
normalize_feature,
normalize_ts_feature,
feture_cross_layering,
rolling_rank,
rolling_norm,
)

__version__ = "0.9.38"
__version__ = "0.9.39"
__author__ = "zengbin93"
__email__ = "[email protected]"
__date__ = "20231126"
__date__ = "20231212"


def welcome():
Expand Down
47 changes: 47 additions & 0 deletions czsc/utils/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,50 @@ def _layering(x):
df[f"{x_col}分层"] = df[f"{x_col}分层"].fillna(-1)
df[f'{x_col}分层'] = df[f'{x_col}分层'].apply(lambda x: f'第{str(int(x+1)).zfill(2)}层')
return df


def rolling_rank(df: pd.DataFrame, col, n=None, new_col=None, **kwargs):
"""计算序列的滚动排名
:param df: pd.DataFrame
待计算的数据
:param col: str
待计算的列
:param n: int
滚动窗口大小, 默认为None, 表示计算 expanding 排名,否则计算 rolling 排名
:param new_col: str
新列名,默认为 None, 表示使用 f'{col}_rank' 作为新列名
:param kwargs:
min_periods: int
最小计算周期
"""
min_periods = kwargs.get('min_periods', 1)
new_col = new_col if new_col else f'{col}_rank'
if n is None:
df[new_col] = df[col].expanding(min_periods=min_periods).rank()
else:
df[new_col] = df[col].rolling(window=n, min_periods=min_periods).rank()


def rolling_norm(df: pd.DataFrame, col, n=None, new_col=None, **kwargs):
"""计算序列的滚动归一化值
:param df: pd.DataFrame
待计算的数据
:param col: str
待计算的列
:param n: int
滚动窗口大小, 默认为None, 表示计算 expanding ,否则计算 rolling
:param new_col: str
新列名,默认为 None, 表示使用 f'{col}_norm' 作为新列名
:param kwargs:
min_periods: int
最小计算周期
"""
min_periods = kwargs.get('min_periods', 1)
new_col = new_col if new_col else f'{col}_norm'

if n is None:
df[new_col] = df[col].expanding(min_periods=min_periods).apply(lambda x: (x[-1] - x.mean()) / x.std(), raw=True)
else:
df[new_col] = df[col].rolling(window=n, min_periods=min_periods).apply(lambda x: (x[-1] - x.mean()) / x.std(), raw=True)

0 comments on commit d7e59bb

Please sign in to comment.