首页 > 解决方案 > 如何通过嵌套字典进行有效循环,对字典进行最小化?

问题描述

我试图多次最小化一个功能。我开发了一个名为BlackScholesModel; 这个类包含要最小化的函数,它是类中的difference方法BlackScholesModel

我创建了一个嵌套字典来保存每个类对象。嵌套字典的代码是:

expirations = ('2020-12-17', '2021-12-16')
today = datetime.now()
stock_price = stockquotes.Stock("^GSPC").current_price

BSM = {name:name for name in expirations}

for i, a in enumerate(expirations):
    strikeP = {count:count for count in range(0,len(expirations))}
    for j in range(0,len(strike[a])):
        strikeP[j] = BlackScholesModel(datetime.strptime(expirations[i],"%Y-%m-%d"),\
                                       today,stock_price,strike[a][j],\
                                       premium=call_premium[a][j])
    BSM[a] = strikeP

输出:

{'2020-12-17': {0: <BlackScholesMerton.BlackScholesModel at 0x22deb7f5708>, 
                1: <BlackScholesMerton.BlackScholesModel at 0x22debc805c8>, 
                2: <BlackScholesMerton.BlackScholesModel at 0x22dec1312c8>},
 '2021-12-16': {0: <BlackScholesMerton.BlackScholesModel at 0x22debd324c8>,
                1: <BlackScholesMerton.BlackScholesModel at 0x22debd36088>,
                2: <BlackScholesMerton.BlackScholesModel at 0x22debd36fc8>,}}

有了这个嵌套字典,我想遍历每个元素并最小化每个类方法difference;但是,len(BSM['2020-12-17'])是 93,len(BSM['2021-12-16'])是 50。我有以下代码:

implied_vol = {name:name for name in expirations}

x0 = 1

for i, a in enumerate(expirations):
    strikeP = {count:count for count in range(0,len(expirations))}
    for j in range(0,len(BSM[a])):
        strikeP[j] = minimize(BSM[a][j].difference,x0)['x']
    implied_vol[a] = strikeP

由于交易量很大,计算机无法完成此操作。我正在尝试找到一种方法来提高我的代码效率。我想以类似于嵌套字典的格式存储每个最小结果BSM。任何帮助或想法都非常受欢迎。

标签: pythondataframedictionaryfor-loopnested-loops

解决方案


毛里西奥

您是否尝试过估算函数的平均执行时间minimize(BlackScholesModel.difference, x0)?有了这个估计的数字,是否可以执行您需要的最小化数量?

假设可以在合理的时间内执行此操作,您可以通过并行执行来更快地执行此操作:

from joblib import Parallel, delayed

def minimize_expiration(expiration_dict):
    strikeP = {}
    for i, bs in expiration_dict.items():
        strikeP[i] = minimize(bs.difference,x0)['x']
    return strikeP

N_JOBS = -1 # number of cores to use (-1 to use all available cores)
implied_vol_list = Parallel(n_jobs=N_JOBS, verbose=1)(delayed(minimize_expiration)(BSM[expiration]) for expiration in expirations)

IV = {expiration: iv for expiration, iv in zip(expirations, implied_vol_list)}

如果 BlackScholesModel 的实现不可序列化,您可能会遇到这种方法的问题


推荐阅读