pythonlistdictionaryfinancecomputational-finance

Ignore None values and skip to next value?


This list of dictionaries changes regularly.

search_option = [{'strike_price': '1', 'bid_price': '0.25', 'implied_volatility': '0.94' }, 
{'strike_price': '3.5', 'bid_price': '0.20', 'implied_volatility': '0.88'},
{'strike_price': '2', 'bid_price': '0.05', 'implied_volatility': None}, 
{'strike_price': '3.5', 'bid_price': '0.31', 'implied_volatility': '0.25'}]

Here the code searches for an option with an implied volatility below 0.9.

for option_list in search_option:
    if option_list is not None:
        option_list = ([i for i in search_option if float(i["implied_volatility"]) < 0.90])
    print(option_list)

I occasionally get this error:

float() argument must be a string or a number, not 'NoneType'

My question is, how can I leave the search the same (implied_volatility < 0.9) while at the same time ignoring the None values? In other words, if it's 'None' then skip to the next available option.


Solution

  • Try this:

    option_list = ([i for i in search_option if i["implied_volatility"] and float(i["implied_volatility"]) < 0.90])
    
    

    You also do not have to iterate through the search_option with a for loop you can just use the code above to replace it.