Back to Community
Finding Sector Averages

Hello,

I am trying to implement a strategy using the pe ratio of a stock compared to the average pe ratio of stocks in the same sector. How would I find the average pe of a sector?

My code is currently:

universe = monthly_top_volume & base_universe

    # Alpha Generation  
    # ----------------  
    # Compute Z-scores of free cash flow yield and earnings yield.  
    # Both of these are fundamental value measures.  
    vr = mstar.valuation_ratios  
    #fcf_zscore = vr.fcf_yield.latest.zscore(mask=universe)  
    #yield_zscore = vr.earning_yield.latest.zscore(mask=universe)  
    pe = vr.pe_ratio  
    sent_factor = sentdex.sentiment_signal.latest  
    **sector_pe = mstar.asset_classification.morningstar_sector_code.vr.pe_ratio.latest(mask=universe)**  
    score = compute_score(pe, sector_pe, sent_factor)  
2 responses
from quantopian.pipeline.classifiers.morningstar import Sector

pe = vr.pe_ratio  
demean_by_sector_pe = pe.demean(groupby=Sector())

Jack,

Luca cut to the chase of what you were actually looking for, but there's also an answer to the question as stated.

sector_pe = pe - pe.demean(groupby=Sector())  

This will assign to each stock the average pe for that stock's sector.

There are also a couple of neat (and less counter-intuitive) hacks to get the variance, but I will leave those as an exercise for the reader.