我可以将值从一个Python文件传递到另一个文件吗?

时间:2019-06-18 15:38:19

标签: python scipy

我试图循环运行另一个文件。 FileA:

cov_matrix是我从彭博社导入的协方差矩阵,而rets是也从彭博社导入的数据框。

max_vol = [8,9,10]

def func1(weights):
    return max_vol[i] - np.sqrt(np.dot(cov_matrix, weights))

def obj(weights):
    return np.sum(rets.T*weights)

cons = {'type':'ineq', 'fun': func1}
bnds = (0,6) in range 30

def minimixe()
    scipy.minimize(obj, initial_weights, bounds = bnds, method = 'SLSQP', constraints = cons}

我想对max_vol的多个值运行最小化函数。

我尝试在for循环中运行整个程序,但是即使对于max_vol的值不同,我也会得到相同的结果。因此,我尝试从另一个文件B调用整个文件A。

import fileA
    for i in range(8,10):
    fileA.minimize()

但是我收到未定义的错误。

我尝试直接传递我以最小化,但是func1的列表索引超出范围错误

def func1(weights):
    return max_vol[i] - np.sqrt(np.dot(cov_matrix, weights))

cons = {'type':'ineq', 'fun': func1}
bnds = (0,6) in range 30

def minimixe()
    scipy.minimize(obj, initial_weights, bounds = bnds, method = 'SLSQP', constraints = cons}

for i in range(8,10)
    minimize(i)    

我该如何处理?

1 个答案:

答案 0 :(得分:1)

原因是scipy.minimize使用默认参数调用func1,您可以使用functools.partiali添加为位置arg并将其传递给{{1 }}:

scipy.minimize

这允许将from functools import partial # add that argument here so you don't get a nameError def func1(i, weights): return max_vol[i] - np.sqrt(np.dot(cov_matrix, weights)) # add the argument here so that you can call it in fileB def minimize(i): # partial will return a new function with the first positional argument # specified already cons = {'type':'ineq', 'fun': partial(func1, i)} # now this can work as expected scipy.minimize(obj, initial_weights, bounds = bnds, method = 'SLSQP', constraints = cons} 作为第一个位置arg传递给i,而func1不需要显式地进行操作。您现在可以这样称呼它:

scipy