Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Python Help: Sample Fundamentals 1 Algo

This code snippet is taken from the sample funadamental algo provided by Quantopian (https://www.quantopian.com/help#sample-live-trading).

# Find sectors with the highest average PE  
sector_pe_dict = {}  
for stock in fundamental_df:  
    sector = fundamental_df[stock]['morningstar_sector_code']  
    pe = fundamental_df[stock]['pe_ratio']

    if sector in sector_pe_dict:   # <----------------------- empty dictionary?  
        sector_pe_dict[sector].append(pe)  
    else:  
        sector_pe_dict[sector] = []  

sector_pe_dict is initialized as an empty dictionary. In the for loop, the conditional stmt "if sector in sector_pe_dict" is testing an empty dictionary?

2 responses

@Dav, You've no doubt thought about your question a bit and now understand that yes, initially the dictionary is empty for the line you specify. And because it is empty the else clause will be executed.

else:  
    sector_pe_dict[sector] = []  

Which mean that next time around, the dictionary will not be empty.

But more to the point, the test is looking for a specific key in its hash key list. Empty or not, if the hashkey is not found, the else: clause takes over. But if the hashkey, in this case a "sector" is found in the dictionary, rather than create a new array for that key (sector) the sector under test is appended to the array already found in the dictionary.

This is common code for all programming languages; testing for the existence of a key in a hash collection should be made part of your coding expertise.

Thanks Market Tech for the prompt and succinct reply. I was careless and failed to mentally trace the execution into the else clause. I'm new to Python but I'm gradually settling in. :)