建议重构Polars Expr
我有一个polars expr,我无法使用上下文,因为我的功能必须返回Polars Expr。
我已经在Porars中实现了RSI指标:
rsi_indicator = (100*pl.when(pl.col("close").pct_change() >= 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0) \
.rolling_mean(window_size=window) \
/ (pl.when(pl.col("close").pct_change() >= 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0).rolling_mean(window_size=window) + \
pl.when(pl.col("close").pct_change() < 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0).abs().rolling_mean(window_size=window))).alias(f"rsi_{window}")
我会重构此代码隔离一些数量,以便轻松维护代码和可读性。 例如,我想定义一个变量
U = pl.when(pl.col("close").pct_change() >= 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0) \
.rolling_mean(window_size=window)
及其fiend v,以进行负收益,以便仅返回100*u/(u+v),但似乎不起作用。有什么建议吗?
I have a polars expr, and I cannot use a context 'cause my function has to return a polars expr.
I've implemented a RSI indicator in polars:
rsi_indicator = (100*pl.when(pl.col("close").pct_change() >= 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0) \
.rolling_mean(window_size=window) \
/ (pl.when(pl.col("close").pct_change() >= 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0).rolling_mean(window_size=window) + \
pl.when(pl.col("close").pct_change() < 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0).abs().rolling_mean(window_size=window))).alias(f"rsi_{window}")
I would refactor this code isolating some quantities in order to easily maintaining code and readability.
For example I'd like to define a variable
U = pl.when(pl.col("close").pct_change() >= 0) \
.then(pl.col("close").pct_change()) \
.otherwise(0.0) \
.rolling_mean(window_size=window)
and its fiend V for negative returns in order to return simply 100*U/(U+V) but seems it doesn't work. Any advise?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,让我们使用一些实际的财务数据,以使我们的结果看起来合理。我还将更改变量名称,以便您的代码可以正常工作。
接下来,我将根据您的问题重新格式化您的代码,然后构建
u
v 。然后,我们可以根据
u
和v
来表达rsi_indicator
:First, let's use some real financial data, so that our results look reasonable. I'll also change the variable names so that your code will work, as-is.
Next, I'll reformat your code, and construct
U
andV
, per your question.We can then express
rsi_indicator
in terms ofU
andV
as follows: