Creating a Custom Factor with multiple inputs

Hi everyone,

I'm currently looking into a relationship between short-term momentum and high turnover. I have developed my momentum custom factor and attempting to develop my turnover factor as a screen but, I'm currently having issues with forming a proper output.

Here is what i got:

from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data.morningstar import Fundamentals
from quantopian.pipeline.data import USEquityPricing
from quantopian.pipeline.factors import Returns
from quantopian.research import run_pipeline
import numpy as np

class ShortMom(CustomFactor):
inputs = [USEquityPricing.close]
window_length = 21 # to examine short-term monthy mom in relation to turnvoer
def compute(self,today,assets,out,close):
out[:] = (close[self.window_length-1] - close[0])/close[0]
mtm_factor = ShortMom()

class TO(CustomFactor):
inputs = [USEquityPricing.volume, Fundamentals.shares_outstanding]
window_length = 21 # monthly turnover is the one we need
def compute(self,today,assets_ids, out, volume, shares):
out[:] = (volume / shares)
TO_High = TO()
TO_High_Filter = (TO_High.percentile_between(75,100, mask=(TO_High > 0)))


I know I have done something wrong with attempting to calculate the turnover but do not know how to fix it. If anyone can please help, it will be greatly appreciated!

1 response

The issue is with the 'TO' custom factor compute function. The following code

        out[:] = (close[self.window_length-1] - close[0])/close[0]



creates an array with 21 rows (ie the window_length). The function output expects a singe row. I believe the equation you probably want is

        # Sum the months volume then divide by current  outstanding shares (ie [-1])
out[:] = (np.nansum(volume, axis=0) / shares[-1])


Remember the compute function inputs are numpy 2D arrays. The rows are days (the number of rows will be the window_length), and the columns are the assets. However the output is a single 1D array. One needs to ensure the logic reduces the input arrays to this single 1D array.

See the attached notebook.

3