如何用 Polars 计算 SMMA(平滑移动平均线)?

问题描述 投票:0回答:1

我想用 Polars 计算 SMMA。 如果可能的话,通过一个选择,因为我想获得 Expression 而不是 DataFrame。

我有

frame_length (window_size)
和价格
DataFrame(['1.2, 5.4, 6.1, 4.3, ...])
.

在普通的 Python 中,它非常简单:

def get_smma(sum_in_frame: float, prev_smma: float, frame_length: int) -> float:
    return (sum_in_frame - prev_smma) / float(frame_length)

或者至少可以在 Polars 中拥有

rolling recursion
或访问
previous calculated value

recursion moving-average python-polars
1个回答
0
投票

我认为访问以前的值的唯一方法是通过

pl.cumfold
——这是一个水平操作。

df = pl.DataFrame({"price": [1.2, 5.4, 6.1, 4.3]})

df.select("price").unstack(1).select(smma = 
   pl.cumfold(
      acc = 0, 
      exprs = pl.all(),
      function = lambda prev_smma, price: 
         (df.get_column("price").sum() - prev_smma) / df.height
   )
)
shape: (1, 1)
┌─────────────────────────────────┐
│ smma                            │
│ ---                             │
│ struct[4]                       │
╞═════════════════════════════════╡
│ {4.25,3.1875,3.453125,3.386719} │
└─────────────────────────────────┘
© www.soinside.com 2019 - 2024. All rights reserved.