我发现我的问题很奇怪。我把整个文件放在这里,现在替换以前的文件。
import pandas as pd
import numpy as np
from option_pricer import BS_Call, r_input
from scipy.optimize import leastsq
## this function returns the error vector
def res_bs(p):
sigma = p
err = np.zeros(len(k))
for i in range(len(k)):
err[i] = (callEu[i]-BS_Call(sigma, r[i], T[i]/360, s[i], k[i] ))/sqrt(len(k))
return err
## this function returns the root mean squared error
def rmse_bs(p):
return sqrt(sum(res_bs(p)**2))
## this function converts the raw data into variables to be used
def params_in(options):
k = options.strk_prc
k = pd.np.array(k)
T = options.tmy
T = pd.np.array(T)
s = options.undl_prc
s = pd.np.array(s)
callEu = options.eur_call_prc
callEu = pd.np.array(callEu)
callAm = options.ame_call_prc
callAm = pd.np.array(callAm)
r1 = unique(options.r1)
r1 = pd.np.array(r1)
r2 = unique(options.r2)
r2 = pd.np.array(r2)
r3 = unique(options.r3)
r3 = pd.np.array(r3)
r4 = unique(options.r4)
r4 = pd.np.array(r4)
r5 = unique(options.r5)
r5 = pd.np.array(r5)
r = r_input(T, r1, r2, r3, r4, r5)
return [k, T, s, callEu, callAm, r]
## the calibration routine
def calib_bs(data):
tdDays = sorted(set(data.d_td))
N = len(tdDays)
sigma_implied = np.zeros(N)
rmseBS = np.zeros(N)
for i in range(N):
options = data[data['d_td']==tdDays[i]]
global k, T, s, callEu, callAm, r
[k, T, s, callEu, callAm, r] = params_in(options)
p0 = 0.05
sigma_implied[i] = leastsq(res_bs, p0)[0]
rmseBS[i] = rmse_bs(sigma_implied[i])
return [sigma_implied, rmseBS]
data = pd.read_csv("mydata.csv")
[sigma, rmseBS] = calib_bs(data)
如果我直接在 Spyder 中执行上述操作(按“F5”),那么结果就是p0
!但是,如果我以交互方式执行——即加载数据、定义函数,然后调用校准函数——我会得到正确的答案!
我的直觉告诉我这个问题与 Python 执行命令的方式或顺序有关。但我对此一无所知。
谁能告诉我如何修改代码以允许直接执行而不是交互?
附录: 我尝试了以下测试,没有发现任何问题。也就是说,结果是正确的,它不依赖于我如何执行代码,例如,直接(“F5”)或交互地执行它。“data.csv”文件可以是任何东西,我用 np.arrange(1,41).reshape(20,2) 制作了一个矩阵并将其保存为 data.csv
import numpy as np
from scipy.optimize import leastsq
import pandas as pd
from testFuncs import f ## f is f(x, p) return x*p,一个线性函数
def ssr(p):
beta = p
err = np.zeros(len(x))
for i in range(len(x)):
err[i] = ( y[i]-f(x[i],beta) )
return err
def calibration(data):
l = data.count()[0]
a = data.a
a = pd.np.array(a)
b = data.b
b = pd.np.array(b)
par = np.zeros(l/5)
for i in range(l/5):
global x, y
x = a[i*5:(i+1)*5]
y = b[i*5:(i+1)*5]
p0 = 1
par[i] = leastsq(ssr, p0)[0]
return par
result = calibration(data)