如何使字典仅按最大值输出(implied_volatility)?

How to make dictionary to output by max value only (implied_volatility)?

所以标题为 'option' 的字典通过 strike_price、ask_price、delta 和 implied_volatility 吐出结果(可交易期权)。但我不需要它来吐出所有可交易的选项。我只希望输出显示 1 个具有最高 implied_volatility (IV) 的可交易期权,因此例如,结果应该只显示具有最高 IV 的期权:

行使价:43.0000,卖价:0.030000,买价:0.000000,Delta:0.008705,IV:1.449510 - 因为这里的 IV 是下面整个输出中最高的。

我该怎么做?

import config 
import robin_stocks as r 

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


#specify criteria to search for options of a given symbol and its exp date
symbol = 'GDX'
expirationDate = '2020-06-19'


search_option = r.find_options_for_stock_by_expiration(symbol,expirationDate,optionType='call')


for option in search_option:

        print("Strike Price: {}, Ask: {}, Bid: {}, Delta: {}, IV: {}".format(option['strike_price'],option['ask_price'],option['bid_price'],option['delta'], option['implied_volatility']))


**OUTPUT**:
Strike Price: 42.0000, Ask: 0.030000, Bid: 0.000000, Delta: 0.009354, IV: 1.335719
Strike Price: 43.0000, Ask: 0.030000, Bid: 0.000000, Delta: 0.008705, IV: 1.449510
Strike Price: 35.5000, Ask: 0.060000, Bid: 0.040000, Delta: 0.073395, IV: 0.634361
Strike Price: 36.5000, Ask: 0.030000, Bid: 0.020000, Delta: 0.041370, IV: 0.743600

您可以return具有最高 IV 的选项执行如下操作:

def find_highest_iv(search_option):
    max_iv = max([option['implied_volatility'] for option in search_option ])
    for option in search_option:
        for k,v in option.items():
            if k == 'implied_volatility' and v == max_iv:
                return option

如果有两个选项具有相同的 IV,这将 return 第一个在 search_options 中找到。可能有更 pythonic shorthand 的方法来做到这一点,但这应该有效。

在代码的 for 循环中替换这个。

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}, Ask: {ask_price}, Bid: {bid_price}, Delta: {delta}, IV: {implied_volatility}".format(**search_option[highest_idx]))

这里可能需要考虑search_option为空的情况

希望对您有所帮助。