Search code examples
pythondictionaryfinance

How to filter out None from values in Dictionary in Python?


After searching for the options in gives an output of "Strike Price", "Ask Price", "Bid Price" and "Implied Volatility". However, I want to filter it so that it will only give me "implied volatility" above 1. Since "implied volatility" has some 'None' values in the dictionary it gives me an error:

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

import config 
import robin_stocks as r 

r.login(config.USERNAME,config.PASSWORD)

#specify criteria to search for options 

symbol = 'GE'
expirationDate = '2020-06-19'
strike = 8

#search for option given strike price, expiration date and symbol
#filter through low ask prices
#place order 


search_option = r.find_options_for_stock_by_expiration(symbol,expirationDate,optionType='call')
for option in search_option:
    if float(option['implied_volatility']) > 1:
        print("Strike Price: {}, Ask: {}, Bid: {}, IV: {}".format(option['strike_price'],option['ask_price'],option['bid_price'],option['implied_volatility']))'

Solution

  • Just add this condition in the if, as None is evaluated to False you don't need to do if val is not None, just if val is correct

    if option['implied_volatility'] and float(option['implied_volatility']) > 1
    

    Filter out the max implied_volatility

    search_option = r.find_options_for_stock_by_expiration(...)
    max_implied_volatility = max(float(option['implied_volatility'] or "-10000") for option in search_option) 
    
    for option in search_option:
    
        if option['implied_volatility'] and \
           float(option['implied_volatility']) > 1 and \
           float(option['implied_volatility']) !=max_implied_volatility :
    
            print("Strike Price: {}, Ask: {}, Bid: {}, IV: {}".format(...))'