def bsVolFitting(): nopts = 11 xs= [90.0,92.0,94.0,96.0,98.0,100.0,102.0,104.0,106.0,108.0,110.0] nxs = np.array(xs) f = 100.0 ws= list(map(lambda x: Utils.dnorm(log(x/f)*10.0), xs)) nws = np.array(ws) t = 0.5 xss = map(lambda x: [f,x,t], xs) a = 0.3 a0 = 0.1 b = 1.0 r = -0.45 r0=0.05 vv = 2.3 vv0 = 1.0 ts= list(map(lambda x: lsig(f, x, t, a, b, r, vv), xs)) nts = np.array(ts) inc = 0.0001 b0 = [r0,vv0] b1up = [r0+inc,vv0] b1dn = [r0-inc,vv0] b2up = [r0,vv0+inc] b2dn = [r0,vv0-inc] atmsig = Fitter.cubic(nxs, nts, f) def err(r, vv, x, y): alpha = alphaFromRhoV1(f, t, atmsig*f, r, vv) return lsig(f, x, t, alpha, b, r, vv) - y def derr(r,vv,x,y): dr=adnumber(r) dvv=adnumber(vv) return np.array([err(dr,vv,x,y).d(dr), err(r,dvv,x,y).d(dvv)]) def sumerrs(ps): return sum(map(lambda x, y, w: w*err(ps[0], ps[1], x, y)**2.0, nxs, nts, nws)) def dsumerrs(ps): dr = adnumber(ps[0]) dvv = adnumber(ps[1]) return np.array([sumerrs([dr, ps[1]]).d(dr), sumerrs([ps[0], dvv]).d(dvv)]) res = minimize(sumerrs, [-0.1,2.0], tol = 0.0000001, jac=dsumerrs, bounds=[(-1.0,1.0), (0.0,10.0)], method='SLSQP', options={'disp': True}) rout = res.x[0] vvout = res.x[1] alphaout = alpha = alphaFromRhoV1(f, t, atmsig*f, rout, vvout) print('xs = ' + str(nxs)) print('ts = ' + str(nts)) fits = list(map(lambda x, y: lsig(f, x, t, alphaout, b, rout, vvout) , nxs, nts)) print('fit = ' + str(fits)) print('errs(fit) = ' + str(sumerrs([rout, vvout]))) print('errs(act) = ' + str(sumerrs([r,vv]))) plt.plot(xs, fits,xs,ts) plt.title('Least-squares fit to noisy data') plt.legend(['Fit', 'Actual']) plt.show() return res
def nput(f, x, v, r, t): if (v <= 0.0) or (t <= 0.0): vrt = 1e-5 else: vrt = v * pow(t, 0.5) return exp(-r * t) * ((x - f) * Utils.pnorm((x - f) / vrt) + vrt * Utils.dnorm((x - f) / vrt))