【问题标题】:Search list of dicts for values greater than given value?搜索大于给定值的值的字典列表?
【发布时间】:2020-06-22 11:01:18
【问题描述】:

所以我有一个 dicts 列表,其中包含 4 种不同潜在期权交易的不同行使价、买入价和隐含波动率。

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

在这里,代码搜索具有最高implicit_volatility 的选项并给我一个输出。

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]))

然后我将它们单独保存为变量以启动交易。

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

我真的不再需要“最高隐含波动率”代码了。

我现在的任务是,我如何搜索行使价 > 3 且买入价

然后我需要将匹配字典的所有键(strike、bid、implicit_volatility)保存为单独的变量,就像我对上面所做的那样。

【问题讨论】:

    标签: python list dictionary finance computational-finance


    【解决方案1】:

    试试这个:

    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)
    

    输出:

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

    【讨论】:

    • 问题,你能说明如何将每个键保存为单独的变量吗?
    • 这样的? x = {'strike_price': '3.5', 'bid_price': '0.20', 'implied_volatility': '0.88'}strike = x["strike_price"]bid= x["bid_price"]vol= x["implied_volatility"]
    • 是的。但是我有没有机会将它们保存为浮点数而不是字符串?
    • 是的。您可以使用float() 函数来实现这一点。您可以使用strike = float(x["strike_price"]) 而不是strike = x["strike_price"]。这是一个有用的链接来解释Python Casting
    猜你喜欢
    • 2023-01-01
    • 2013-04-14
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多