gpt4 book ai didi

python - 如何编写每周 EMA 的 CustomFactor - Python、Quantopian

转载 作者:行者123 更新时间:2023-12-01 07:22:27 24 4
gpt4 key购买 nike

class EWMAWeekly(CustomFactor):

inputs = [USEquityPricing.close]
window_length = (13 + 2 * 13 - 1) * 5 # Initial 13 weeks for sma, then 25 more weeks to improve the accuracy of the current ema.

def compute(
self,
today,
assets,
out,
data,
):
alpha = 2 / (13 + 1)
weekly_data = data[4::5] # len = 38, index from 0 - 37
ema = average(weekly_data[:13]) # Initial SMA
i = 0
while i < 25:
ema = weekly_data[13 + i] * alpha + ema * (1 - alpha)
i += 1

out[:] = ema

上面的CustomFactor是我目前拥有的。当我通过管道运行此命令时,输出为 average(weekly_data[:13]),这是 25 周前的 SMA。该代码不会引发任何错误,并且我已经测试了 while 循环,因此我知道它正在运行。我认为问题出在 while 循环内重新分配 ema 变量。我可能有一瞬间的愚蠢,但我似乎找不到问题所在。如有任何建议,我们将不胜感激。

谢谢

最佳答案

看来我犯了一个愚蠢的错误。我使用整数而不是 float 来计算 alpha。更正后的代码如下。

class EWMAWeekly(CustomFactor):

inputs = [USEquityPricing.close]
window_length = (13 + 2 * 13 - 1) * 5 # Initial 13 weeks for sma, then 25 more weeks to improve the accuracy of the current ema.

def compute(
self,
today,
assets,
out,
data,
):
alpha = 2.0 / (13.0 + 1.0)
weekly_data = data[4::5] # len = 38, index from 0 - 37
ema = average(weekly_data[:13]) # Initial SMA
i = 0
while i < 25:
ema = weekly_data[13 + i] * alpha + ema * (1 - alpha)
i += 1

out[:] = ema

关于python - 如何编写每周 EMA 的 CustomFactor - Python、Quantopian,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57633590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com