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
变量。我可能有一个愚蠢的时刻,但是我似乎找不到问题所在。任何建议表示赞赏。
谢谢
答案 0 :(得分:1)
看来我犯了一个愚蠢的错误。我用整数来计算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