Back to Community
Dividend Class Factor Help

I am trying to buy the highest dividend in each sector. I do not know why this code will not work. I have tried it after I have ran the pipeline, and it will work. I cannot keep the ticker index name though when I do it that way.

I would like to know a better way to display my class factor.

# highest dividend in the sector

class sector_div(CustomFactor):
inputs= [morningstar.valuation_ratios.dividend_yield,morningstar.asset_classification.morningstar_sector_code]
def compute(self, today, assets, out, div, sector):
df = pd.DataFrame(index=assets, data={"div": div,
best_sector = df.groupby(['sector'], as_index=False)["div"].max()
best_sector = best_sector.drop('sector', axis=1)
out[:]= best_sector

1 response

You don't really need to create a custom factor for this. Use the 'top' method and set the ' groupby' parameter. (see

# First probably create a filter returning the universe of stocks we want to look at  
universe = Q1500US()

# Make a classifier which returns the sector for each security  
sector = Sector()

# Make a factor which returns the dividend yield for each security  
dividend_yield = morningstar.valuation_ratios.dividend_yield.latest

# Create a filter returning only the top 1 highest dividend yield securities from each sector  
top_dividend_yield =, mask=universe, groupby=sector)

# Now define a pipline with each of these factors and filters as columns  
pipe = Pipeline(  
            columns = {  
            'dividend_yield' : dividend_yield,  
            'sector' : sector,  
            screen = top_dividend_yield)

Attached is a notebook showing how this works. You can also get the top n securities (eg the top 5) simply by changing the 'top' parameter.

Loading notebook preview...
Notebook previews are currently unavailable.