QuantConnect / Documentation

QuantConnect Wiki Style Documentation Behind QuantConnect
https://www.quantconnect.com/docs/v2/
Apache License 2.0
171 stars 135 forks source link

Universe Selection Sorting Errors #1539

Closed DerekMelchin closed 9 months ago

DerekMelchin commented 10 months ago

Expected Behavior

The universe selection examples work as intended.

Actual Behavior

The examples in the documentation don't remove NaN values before sorting. For example, if we use

    def FundamentalFunction(self, fundamentals: List[Fundamental]) -> List[Symbol]:
        sorted_by_pe_ratio = sorted(
            [f for f in fundamentals if f.HasFundamentalData], 
            key=lambda fundamental: fundamental.ValuationRatios.PERatio
        )
        self.Log(f"First: {sorted_by_pe_ratio[0].ValuationRatios.PERatio} / min: {min([x.ValuationRatios.PERatio for x in sorted_by_pe_ratio])}")

then we get

2023-11-06 00:00:00 :First: 0.429257 / min: 0.001089 2023-11-07 00:00:00 :First: 0.429257 / min: 0.001089 2023-11-08 00:00:00 :First: 0.429257 / min: 0.001089 2023-11-09 00:00:00 :First: 0.429257 / min: 0.001089 2023-11-10 00:00:00 :First: 0.429257 / min: 0.001089 2023-11-11 00:00:00 :First: 0.429257 / min: 0.001089

The examples need to be updated to include np.isnan(). For example

    def FundamentalFunction(self, fundamentals: List[Fundamental]) -> List[Symbol]:
        sorted_by_pe_ratio = sorted(
            [f for f in fundamentals if f.HasFundamentalData and not np.isnan(f.ValuationRatios.PERatio)], 
            key=lambda fundamental: fundamental.ValuationRatios.PERatio
        )
        self.Log(f"First: {sorted_by_pe_ratio[0].ValuationRatios.PERatio} / min: {min([x.ValuationRatios.PERatio for x in sorted_by_pe_ratio])}")

2023-11-06 00:00:00 :First: 0.001089 / min: 0.001089 2023-11-07 00:00:00 :First: 0.001089 / min: 0.001089 2023-11-08 00:00:00 :First: 0.001089 / min: 0.001089 2023-11-09 00:00:00 :First: 0.001089 / min: 0.001089 2023-11-10 00:00:00 :First: 0.001089 / min: 0.001089 2023-11-11 00:00:00 :First: 0.001089 / min: 0.001089

The second code snippet under Create Universes is an example of one that may not work as intended. The text should also explicitly mention the requirement of np.isnan() where appropriate.

Checklist