Search code examples
pythonlistdictionaryfinancecomputational-finance

Search list of dicts for values greater than given value?


So I have a list of dicts with different strike, bid prices and implied_volatility for 4 different potential option trades.

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'}]

And here, the code searches for the option with the highest implied_volatility and gives me an output.

highest_IV, highest_idx = 0, None
for idx, option in enumerate(search_option):
    if option['implied_volatility'] and highest_IV < float(option['implied_volatility']):
        highest_IV = float(option['implied_volatility'])
        highest_idx = idx
if highest_idx is not None:
    print("Strike Price: {strike_price}, Bid: {bid_price}, IV: {implied_volatility}".format(**search_option[highest_idx]))

I then save them separately as variables in order to initiate trades.

order_strike_price = search_option[highest_idx].get('strike_price')
order_bid_price = search_option[highest_idx].get('bid_price')
....
....

I don't really need the 'highest implied volatility' code any more.

My task now is, how can I search for an option with a strike price > 3 and a bid price < 0.25?

I then need to save all of the keys of the matching dictionary (strike, bid, implied_volatility) as separate variables like I did with the ones above.


Solution

  • Try this:

    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'}]
    
    sort = [i for i in search_option if float(i["strike_price"]) > 3 and float(i["bid_price"]) < 0.25]
    
    print(sort)
    

    Output:

    [{'strike_price': '3.5', 'bid_price': '0.20', 'implied_volatility': '0.88'}]