I am trying to create a custom factor that returns +1 if the trend is positive, -1 if the trend is negative, and 0 if there is no trend. Direction of the trend is calculated by a fast MA and a slow MA.
My plan is to use the result as a multiplier for a future calculation in the algorithm, so that I can return positive numbers when the trend is up, and negative numbers when the trend is down.
I am not experienced in Python, and am really struggling with Custom Factors. Am I on the right track here? I am receiving errors when I try to use the result in pipeline calculations.
Error Message: NonWindowSafeInput: Can't compute windowed expression trend_direction((NumExprFactor(expr='x_0 / x_1', bindings={'x_0': SimpleMovingAverage((USEquityPricing.close::float64,), window_length=9), 'x_1': SimpleMovingAverage((USEquityPricing.close::float64,), window_length=20)}),), window_length=1) with windowed input NumExprFactor(expr='x_0 / x_1', bindings={'x_0': SimpleMovingAverage((USEquityPricing.close::float64,), window_length=9), 'x_1': SimpleMovingAverage((USEquityPricing.close::float64,), window_length=20)}).
fast_ma = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=9)
slow_ma = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=20)
ma_ratio = fast_ma / slow_ma
class trend_direction(CustomFactor):
inputs = [ma_ratio]
window_length = 1
def compute(self, today, assets, out, highs, lows):
if ma_ratio > 1.0:
trend_direction = 1.0
elif ma_ratio < 1.0:
trend_direction = -1.0
else:
trend_direction = 0
def compute(self, today, assets, out, highs, lows):
if ma_ratio > 1.0:
trend_direction = 1.0
elif ma_ratio < 1.0:
trend_direction = -1.0
else:
trend_direction = 0