Ejemplo n.º 1
0
def make_open_conic(P0, T0, P2, T2, P):
    ''' Construct an arbitrary open conic arc in three-dimensional
    space.  The resulting NURBS curve consists of either one, two, or
    four segments connected with C1 continuity.

    Source: The NURBS Book (2nd Ed.), Pg. 317.

    '''

    P0, T0 = [np.asfarray(V) for V in P0, T0]
    P2, T2 = [np.asfarray(V) for V in P2, T2]
    P = np.asfarray(P)
    P1, w1 = make_one_arc(P0, T0, P2, T2, P)
    if w1 <= -1.0:
        raise ParabolaOrHyperbolaOutsideConvexHull(w1)
    if w1 >= 1.0:  # hyperbola or parabola
        nsegs = 1
    else:  # ellipse
        if w1 > 0.0 and util.angle(P0, P1, P2) > 60.0:
            nsegs = 1
        elif w1 < 0.0 and util.angle(P0, P1, P2) > 90.0:
            nsegs = 4
        else:
            nsegs = 2
    n = 2 * nsegs
    Pw = np.zeros((n + 1, 4))
    U = np.zeros(n + 4)
    j = 2 * nsegs + 1
    U[j:] = 1.0
    Pw[0] = np.hstack((P0, 1.0))
    Pw[n] = np.hstack((P2, 1.0))
    if nsegs == 1:
        Pw[1] = np.hstack((w1 * P1, w1))
        cpol = curve.ControlPolygon(Pw=Pw)
        return curve.Curve(cpol, (2, ), (U, ))
    Q1, S, R1, wqr = split_arc(P0, P1, w1, P2)
    if nsegs == 2:
        Pw[2] = np.hstack((S, 1.0))
        Pw[1] = np.hstack((wqr * Q1, wqr))
        Pw[3] = np.hstack((wqr * R1, wqr))
        U[3] = U[4] = 0.5
        cpol = curve.ControlPolygon(Pw=Pw)
        return curve.Curve(cpol, (2, ), (U, ))
    Pw[4] = np.hstack((S, 1.0))
    w1 = wqr
    HQ1, HS, HR1, wqr = split_arc(P0, Q1, w1, S)
    Pw[2] = np.hstack((HS, 1.0))
    Pw[1] = np.hstack((wqr * HQ1, wqr))
    Pw[3] = np.hstack((wqr * HR1, wqr))
    HQ1, HS, HR1, wqr = split_arc(S, R1, w1, P2)
    Pw[6] = np.hstack((HS, 1.0))
    Pw[5] = np.hstack((wqr * HQ1, wqr))
    Pw[7] = np.hstack((wqr * HR1, wqr))
    for i in xrange(2):
        U[i + 3] = 0.25
        U[i + 5] = 0.5
        U[i + 7] = 0.75
    cpol = curve.ControlPolygon(Pw=Pw)
    return curve.Curve(cpol, (2, ), (U, ))
Ejemplo n.º 2
0
def refit_curve(C, ncp, p=3, num=1000):
    ''' Refit an arbitrary Curve with another Curve of arbitrary degree
    by sampling it at equally spaced intervals.  If possible the
    original end derivatives are kept intact.

    Parameters
    ----------
    C = the Curve to refit
    ncp = the number of control points to use in the fit
    p = the degree to use in the fit
    num = the number of points to sample C with

    Returns
    -------
    Curve = the refitted Curve

    '''

    U, = C.U
    us, = util.construct_flat_grid((U, ), (num, ))
    Q = C.eval_points(us).T
    Ds, De = [], []
    if ncp > 3:
        Ds = C.eval_derivatives(U[0], 1)[1:]
        De = C.eval_derivatives(U[-1], 1)[1:]
    U, Pw = global_curve_approx_fixedn_ders(num - 1, Q, p, ncp - 1, len(Ds),
                                            Ds, len(De), De, us)
    return curve.Curve(curve.ControlPolygon(Pw=Pw), (p, ), (U, ))
Ejemplo n.º 3
0
def randTSGen(F0, Sigma, Kappa, StartDate, EndDate):

    ts = curve.Curve()
    factors = len(Sigma)

    date = StartDate
    ts[date] = F0

    F = F0
    while tenor.RDateAdd('1d', date, Holidays=[]) <= EndDate:
        lastDate = date
        date = tenor.RDateAdd('1d', date, Holidays=[])

        dt = (date - lastDate).days / 365.0
        tau = (EndDate - date).days / 365.0

        x = 0.0
        for sig, kap in zip(Sigma, Kappa):
            x = x - 0.5 * sig**2 * math.exp(
                -2 * kap * tau) * dt + sig * math.exp(
                    -kap * tau) * math.sqrt(dt) * random.gauss(0, 1)

        F = F * math.exp(x)
        ts[date] = F

    return ts
Ejemplo n.º 4
0
def Crack_ATMVol_TermStr(tsList,
                         weights,
                         expiryT,
                         termTenor="1m",
                         exceptionDateList=[]):

    dates = []
    if len(tsList) != len(weights):
        raise ValueError, 'The number of elements of weights and time series should be equal'

    for ts in tsList:
        if dates == []:
            dates = ts.Dates()
        else:
            dates = [d for d in ts.Dates() if d in dates]

    Crk = curve.Curve()
    undFwd = curve.Curve()

    for d in dates:
        Fwd = [ts[d] for ts in tsList]
        Crk[d] = sum([f * w for (f, w) in zip(Fwd, weights)])
        undFwd[d] = tsList[0][d]

    IsCall = 1
    CrkVol = BS_ATMVol_TermStr(IsCall,
                               Crk,
                               expiryT,
                               rd=0,
                               rf=0.0,
                               endVol=0.0,
                               termTenor=termTenor,
                               rehedge_period="1d",
                               exceptionDateList=exceptionDateList)
    undVol = BS_ATMVol_TermStr(IsCall,
                               undFwd,
                               expiryT,
                               rd=0,
                               rf=0.0,
                               endVol=0.0,
                               termTenor=termTenor,
                               rehedge_period="1d",
                               exceptionDateList=exceptionDateList)

    return CrkVol, undVol
Ejemplo n.º 5
0
def make_full_ellipse(P0, T0, P2, T2, P):
    ''' Construct a full ellipse in three-dimensional space based on
    information given in the form of Group 2: start and end points,
    together with their tangent directions and an additional point.

    Source: The NURBS Book (2nd Ed.), Pg. 318-320.

    '''

    P0, T0 = [np.asfarray(V) for V in P0, T0]
    P2, T2 = [np.asfarray(V) for V in P2, T2]
    P = np.asfarray(P)
    P1, w1 = make_one_arc(P0, T0, P2, T2, P)
    S, T = P0 - P1, P2 - P1
    k = 1.0 / w1**2
    e = k / (k - 1.0) / 2
    a = util.norm(S)**2
    b = np.dot(S, T)
    g = util.norm(T)**2
    d = a * g - b**2
    E = a + g - 2 * b
    ls = np.roots((2 * d, -(k * E + 4 * b), 2 * (k - 1)))
    l1, l2 = np.sort(ls)
    r1, r2 = np.sqrt(e / l1), np.sqrt(e / l2)
    if abs(k / 2 - g * l1) > abs(k / 2 - a * l1):
        xb = k / 2 - g * l1
        yb = b * l1 - k / 2 + 1
    else:
        xb = b * l1 - k / 2 + 1
        yb = k / 2 - a * l1
    r = a * xb**2 + 2 * b * xb * yb + g * yb**2
    x0, y0 = xb / r, yb / r
    Q1 = P1 + (e + r1 * x0) * S + (e + r1 * y0) * T
    Q2 = P1 + (e - r1 * x0) * S + (e - r1 * y0) * T
    U = util.normalize(Q2 - Q1)
    V = np.cross(U, util.normalize(np.cross(S, T)))
    Pw, Uq = np.zeros((8 + 1, 4)), np.zeros(8 + 4)
    C = P1 + e * (S + T)
    Pw[0] = Pw[8] = np.hstack((C + r1 * U, 1.0))
    Pw[1] = np.hstack((w1 * (C + r1 * U + r2 * V), w1))
    Pw[2] = np.hstack((C + r2 * V, 1.0))
    Pw[3] = np.hstack((w1 * (C + r2 * V - r1 * U), w1))
    Pw[4] = np.hstack((C - r1 * U, 1.0))
    Pw[5] = np.hstack((w1 * (C - r1 * U - r2 * V), w1))
    Pw[6] = np.hstack((C - r2 * V, 1.0))
    Pw[7] = np.hstack((w1 * (C - r2 * V + r1 * U), w1))
    for i in xrange(3):
        Uq[i] = 0.0
        Uq[i + 9] = 1.0
    for i in xrange(2):
        Uq[i + 3] = 0.25
        Uq[i + 5] = 0.5
        Uq[i + 7] = 0.75
    cpol = curve.ControlPolygon(Pw=Pw)
    return curve.Curve(cpol, (2, ), (Uq, ))
Ejemplo n.º 6
0
def BS_ConstDelta_VolSurf(tsFwd,
                          moneynessList,
                          expiryT,
                          rd=0.0,
                          rf=0.0,
                          exceptionDateList=[]):
    ts = curve.Curve()
    rptTenor = '-1m'
    rehedge_period = '1d'
    IsCall = 1

    for d in tsFwd.Dates():
        if d not in exceptionDateList:
            ts[d] = tsFwd[d]

    DateList = [x for x in ts.Dates() if x not in exceptionDateList]
    TSstart = DateList[0]
    TSend = DateList[-1]

    date = copy.copy(TSend)
    endDate = tenor.RDateAdd('1d', date)
    startDate = tenor.RDateAdd(rptTenor, date, exceptionDateList)

    volTS = curve.GRCurve()
    while startDate >= TSstart:
        subTS = ts.Slice(startDate, endDate)
        vol = []
        if len(subTS) < 2:
            print 'No data in time series further than ', startDate
            break

        if 0.0 in subTS.Values():
            print 'Price is zero at some date from ', startDate, ' to ', endDate
            break

        # for the moment, consider ATM vol
        for m in moneynessList:
            strike = subTS.Values()[0] * m
            if IsCall:
                finalValue = max((subTS.Values()[-1] - strike), 0)
            else:
                finalValue = max((strike - subTS.Values()[-1]), 0)

        vol += [
            BSrealizedVol(IsCall, subTS, strike, expiryT, rd, rf, finalValue,
                          rehedge_period, exceptionDateList)
        ]
        if None in vol:
            print 'no vol is found to match PnL- strike:' + str(
                m) + ' expiry:' + expiryT

        volTS[startDate] = vol
        startDate = tenor.RDateAdd(rptTenor, startDate, exceptionDateList)

    return volTS
Ejemplo n.º 7
0
def BS_VolSurf_TermStr(tsFwd,
                       moneyness,
                       expiryT,
                       rd=0.0,
                       rf=0.0,
                       endVol=0.0,
                       termTenor="1m",
                       rehedge_period="1d",
                       exceptionDateList=[]):
    ts = curve.Curve()
    rptTenor = '-' + termTenor
Ejemplo n.º 8
0
 def parse(self):
     super(ParameterData126, self).parse()
     n, p = [int(p) for p in self.params[1:3]]
     U = self.params[7:9 + n + p]
     w = self.params[9 + n + p:10 + 2 * n + p]
     P = self.params[10 + 2 * n + p:13 + 5 * n + p]
     w = np.resize(w, (n + 1, 1))
     P = np.resize(P, (n + 1, 3))
     P *= w
     Pw = np.concatenate((P, w), axis=1)
     c = curve.Curve(curve.ControlPolygon(Pw=Pw), (p, ), (U, ))
     objs.append(c)
Ejemplo n.º 9
0
def _test_():
    import curve
    grids = [1, 2, 3, 4]
    dfs = [0.99, 0.98, 0.97, 0.96]
    c = curve.Curve(grids, dfs, interpolation_method='monotone_convex')
    start = 0
    end = 3
    simple = SimpleRate(start, end)
    print('Simple rate :', simple.par_rate(c))
    roll = 0.5
    swap = SingleCurrencySwap(start, end, roll)
    print('Swap rate :', swap.par_rate(c))
Ejemplo n.º 10
0
def test_SingleTermStrComp():
    IsCall = 1
    startD = datetime.date(2006, 1, 1)
    endD = datetime.date(2008, 12, 31)

    trueVol = curve.Curve()
    avgVol = curve.Curve()
    varVol = curve.Curve()

    expiryT = endD
    Sigma = [0.4, 0.2]
    Kappa = [2.0, 0.001]
    numPath = 100
    for i in range(numPath):
        ts = randTSGen(1, Sigma, Kappa, StartDate=startD, EndDate=endD)
        volTS = BSHistVol.BS_ATMVol_TermStr(IsCall,
                                            ts,
                                            expiryT,
                                            rd=0.0,
                                            rf=0.0,
                                            endVol=0.0,
                                            termTenor="22d",
                                            rehedgingTenor="1d",
                                            exceptionDateList=[])

        if i == 0:
            for d in volTS.Dates():
                tau = (expiryT - d).days / 365.0
                x = 0.0
                for sig, kap in zip(Sigma, Kappa):
                    x = x + sig**2 * ((1 - math.exp(-2 * kap * tau)) /
                                      (2 * kap * tau))

                x = math.sqrt(x)
                trueVol[d] = x
                avgVol[d] = 0.0
                varVol[d] = 0.0

        for d in volTS.Dates():
            avgVol[d] += volTS[d] / (numPath * 1.0)
            varVol[d] += (volTS[d] - trueVol[d])**2 / (numPath * 1.0)

    plotList = [avgVol, trueVol]
    legendList = ['Vol', 'True Vol']
    plotxy.PlotCurves(plotList, Legends=legendList)
    diff = curve.Curve()
    rvar = curve.Curve()
    Texp = curve.Curve()
    for d in trueVol.Dates():
        diff[d] = avgVol[d] - trueVol[d]
        varVol[d] = math.sqrt(varVol[d])
        rvar[d] = varVol[d] / trueVol[d]
        Texp[d] = (expiryT - d).days / 365.0 * 12.0

    DiffRatio = [(Texp[d], diff[d], varVol[d], rvar[d])
                 for d in trueVol.Dates()]
    print DiffRatio
Ejemplo n.º 11
0
def rand2DTSGen(F0, Sigma, Kappa, rho, StartDate, EndDate):

    ts1 = curve.Curve()
    ts2 = curve.Curve()

    date = StartDate
    ts1[date] = F0[0]
    ts2[date] = F0[1]

    P = F0[0]
    G = F0[1]

    while tenor.RDateAdd('1d', date, Holidays=[]) <= EndDate:
        lastDate = date
        date = tenor.RDateAdd('1d', date, Holidays=[])

        dt = (date - lastDate).days / 365.0
        tau = (EndDate - date).days / 365.0

        y1 = random.gauss(0, 1)
        y2 = y1 * rho + math.sqrt(1 - rho**2) * random.gauss(0, 1)

        x1 = -0.5 * Sigma[0]**2 * math.exp(
            -2 * Kappa[0] * tau) * dt + Sigma[0] * math.exp(
                -Kappa[0] * tau) * math.sqrt(dt) * y1
        x2 = -0.5 * Sigma[1]**2 * math.exp(
            -2 * Kappa[1] * tau) * dt + Sigma[1] * math.exp(
                -Kappa[1] * tau) * math.sqrt(dt) * y2

        P = P * math.exp(x1)
        G = G * math.exp(x2)

        ts1[date] = P
        ts2[date] = G

    return ts1, ts2
Ejemplo n.º 12
0
 def testSearchEngine(cls, searchEngine, testQueries, measure):
     x = range(0, 101)
     meanCurve = Curve.Curve(x, [0. for i in x])
     numberOfCurves = 0
     for testQuery in testQueries.testQueries:
         query = testQuery.query
         if len(testQuery.expectedResult) > 0:
             curve = cls.getCurve(searchEngine, testQuery, measure)
             if len(curve) > 0:
                 numberOfCurves += 1
                 curve.removeWrongPoints()
                 curve.extrapolate(x)
                 meanCurve += curve
     meanCurve = (1. / numberOfCurves) * meanCurve
     return meanCurve
def Ed(seam, C):
    value = 0
    for c in C:
        new_c = curve.Curve()
        for point in c.points:
            new_point = point
            if point[1] < seam[point[0]]:
                new_point[1] = new_point[1] - 1

            new_c.addPoint(new_point)

        c.transformBookstein()
        new_c.transformBookstein()
        value = value + curve.deformation(c.bookstein, new_c.bookstein)

    return value
Ejemplo n.º 14
0
 def getCurve(cls, searchEngine, testQuery, measure):
     results = searchEngine.search(testQuery.query)
     relevant = len(testQuery.expectedResult)
     tp = [0 for i in range(0, len(results))]
     for j in range(0, len(results)):
         tp[j] = tp[max(0, j - 1)]
         if results[j] in testQuery.expectedResult:
             tp[j] += 1
     curve = Curve.Curve([], [])
     for j in range(0, len(results)):
         if j == 0 or tp[j] > tp[j - 1]:
             fp = j + 1 - tp[j]
             fn = relevant - tp[j]
             curve.append(measure.getRecall(tp[j], fp, fn),
                          measure.getMeasure(tp[j], fp, fn))
     return curve
Ejemplo n.º 15
0
callabletypes = [
    types.FunctionType, types.MethodType, types.ClassType,
    types.BuiltinFunctionType, types.BuiltinMethodType
]
sequencetypes = [types.TupleType, types.ListType]
mappingtypes = [types.DictType]

try:
    import ExtensionClass
    callabletypes.append(ExtensionClass.ExtensionClassType)
except:
    pass
try:
    import curve
    c = curve.Curve()
    callabletypes.append(type(c.read))
except:
    pass


def finisher(Object):
    if type(Object) in callabletypes:
        return "("
    elif type(Object) in sequencetypes:
        return "["
    elif type(Object) in mappingtypes:
        return "{"
    elif members(Object):
        return "."
    return " "
Ejemplo n.º 16
0
    N = 0xc0256a57b1434a4970e315e3e572ad7b6b6268ca27a1bc14a5ec8d6e8f46ab63
    a = 138931309558156184106311716917677778941761847991286360325642242809534952018704195842136094062347931842162775765708572232752796610393601192925341167860358529602430304979627494497048448960083384310735203052588819895230906248500388348984991092188849520120483947949612966752973461165325952933739065855693165670941141036576698048539586409219548698834122183984266610530679658299939991747759033936995784464828547439035421618098378714023855965416127212175477937
    alpha = 3
    strategy = [256, 128, 110, 64, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 46, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 14, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 6, 4, 2, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 64, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 128, 64, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 64, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 32, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 16, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1, 8, 4, 2, 1, 1, 2, 1, 1, 4, 2, 1, 1, 2, 1, 1]

# Choice of Delta depending on nbIterations and n
Delta = nbIterations
if protocol == 'fp' :
    while Delta % (n-2) != 0 or (Delta // (n-2)) % 2 != 0:
        Delta += 1
else :
    while Delta % n != 0 or (Delta // n) % 2 != 0:
        Delta += 1
print('Delta = %d' % Delta)

c = curve.Curve(f, n, N, a, alpha, Delta, strategy)

if protocol == 'fp' :
    # for the Fp protocol, choose Delta = (n-2) * evenNumber
    assert c.Delta % (c.n - 2) == 0
    assert (c.Delta // (c.n - 2)) % 2 == 0
else :
    # for the Fp2 protocol, choose Delta = n * number
    assert c.Delta % c.n == 0
    assert (c.Delta // c.n) % 2 == 0

file = open("timing_" + protocol + "_" + method + "_" + pSize + "_" + str(c.Delta) + "steps.txt", "a")

file.write("VDF over " + protocol + " with log_2(p) = " + str(ZZ(c.p).nbits()) + " and log_2(T) = " + str(ZZ(c.Delta).nbits()) + ".\n")
if method == 'kernel4' :
    file.write('Points of [4]-torsion stored.\n\n')
Ejemplo n.º 17
0
def BS_ATMVol_TermStr(IsCall,
                      tsFwd,
                      expiryT,
                      rd=0.0,
                      rf=0.0,
                      endVol=0.0,
                      termTenor="1m",
                      rehedge_period="1d",
                      exceptionDateList=[]):

    ts = curve.Curve()
    for d in tsFwd.Dates():
        if d not in exceptionDateList and d <= expiryT:
            ts[d] = tsFwd[d]

    rptTenor = '-' + termTenor
    DateList = [x for x in ts.Dates() if x not in exceptionDateList]
    TSstart = DateList[0]
    TSend = DateList[-1]

    date = copy.copy(TSend)
    endDate = tenor.RDateAdd('1d', date)
    startDate = tenor.RDateAdd(rptTenor, date, exceptionDateList)
    finalValue = 0.0

    volTS = curve.Curve()
    while startDate >= TSstart:
        subTS = ts.Slice(startDate, endDate)

        if len(subTS) < 2:
            print 'No data in time series further than ', startDate
            break

        if 0.0 in subTS.Values():
            print 'Price is zero at some date from ', startDate, ' to ', endDate
            break

        # for the moment, consider ATM vol
        strike = subTS.Values()[0]

        if endVol > 0:
            tau = (expiryT - subTS.Dates()[-1]).days / YEARLY_DAYS
            finalValue = bsopt.BSOpt(IsCall,
                                     subTS.Values()[-1], strike, endVol, tau,
                                     rd, rf)
            refVol = endVol
        elif endVol == 0:
            if IsCall:
                finalValue = max((subTS.Values()[-1] - strike), 0)
            else:
                finalValue = max((strike - subTS.Values()[-1]), 0)
            refVol = 0.5
        elif endVol == None:
            raise ValueError, 'no vol is found to match PnL'

        vol = BSrealizedVol(IsCall,
                            subTS,
                            strike,
                            expiryT,
                            rd,
                            rf,
                            finalValue,
                            rehedge_period,
                            exceptionDateList,
                            refVol=refVol)
        volTS[startDate] = vol
        endVol = vol

        date = startDate
        endDate = tenor.RDateAdd('1d', date)
        startDate = tenor.RDateAdd(rptTenor, date, exceptionDateList)

    return volTS
Ejemplo n.º 18
0
def make_circle_nrat(O, X, Y, r, ths, the, p=3, TOL=1e-5):
    ''' Construct a nonrational approximation to a circular arc in
    three-dimensional space of arbitrary sweep angle theta (0 deg <
    theta <= 360 deg).

    In particular, the circular arc approximates

     C(u) = O + r * cos(u) * X + r * sin(u) * Y    ths <= u <= the

    and is oriented counter-clockwise in the local coordinate system
    defined by O, X and Y.

    Parameters
    ----------
    O = the center of the circular arc
    X = a vector lying in the plane of definition of the circular arc
    Y = a vector in the plane of definition of the circular arc, and
        orthogonal to X
    r = the radius
    ths, the = the start and end angles (in degrees), measured with
               respect to X
    p = the degree of the circular arc
    TOL = the maximum deviation from an exact circular arc

    Returns
    -------
    Curve = the circular arc

    Source
    ------
    Piegl & Tiller, Circle Approximation Using Integral B-Spline Curves,
    Computer-Aided Design, 2003.

    '''

    X, Y = [util.normalize(V) for V in (X, Y)]
    if not np.allclose(np.dot(X, Y), 0.0):
        raise NonOrthogonalAxes(X, Y)
    if not r > 0 or not p > 1 or not ths < the:
        raise ImproperInput(r, ths, the)
    k = p - 1
    n = k
    if p == 2:
        n += 1
    ths, the = [np.deg2rad(th) for th in (ths, the)]
    the0 = the
    dth = the - ths
    Q = np.zeros((n + 2, 3))
    ns = 0
    while True:
        ns += 1
        Ds, De = (util.eval_ders_trigo(ths, k), util.eval_ders_trigo(the, k))
        for i in xrange(1, k + 1):
            Ds[i] *= dth**i
            De[i] *= dth**i
        us = np.linspace(ths, the, n + 2)
        for i, u in enumerate(us):
            Q[i] = util.eval_ders_trigo(u, 0)
        U, Pw = fit.global_curve_interp_ders(n + 1, Q, p, k, Ds[1:], k, De[1:])
        nf = Pw.shape[0] - 1
        mU = knot.midpoints_knot_vec(U)
        errs = []
        for m in mU:
            um, = curve.curve_point_projection(nf, p, U, Pw, [0, 0, 0], ui=m)
            P = curve.rat_curve_point(nf, p, U, Pw, um)
            d = abs(1.0 - util.distance(P, [0, 0, 0]))
            errs.append(d)
        if max(errs) <= TOL:
            break
        dth = (the0 - ths) / (ns + 1)
        the = ths + dth
    dtheta = np.rad2deg(the0 - ths) / ns
    cpol = curve.ControlPolygon(Pw=Pw)
    arcs = []
    for n in xrange(ns):
        arc = curve.Curve(cpol, (p, ), (U, ))
        arc.rotate(n * dtheta, L=[0, 0, 1], Q=[0, 0, 0])
        arcs.append(arc)
    arc = curve.make_composite_curve(arcs, remove=False)
    arc.scale(r)
    u = 1.0
    for n in xrange(1, ns):
        arc = arc.remove(u, k)[1]
        u += 1.0
    Z = np.cross(X, Y)
    transform.custom(arc.cobj.Pw, R=np.column_stack((X, Y, Z)), T=O)
    return arc
Ejemplo n.º 19
0
def Spread_ATMVolCorr_TermStr(ts1,
                              ts2,
                              op,
                              expiryT,
                              r1=0,
                              r2=0,
                              termTenor="1m",
                              exceptionDateList=[]):
    if op != '*' and op != '/':
        raise ValueError, 'Operator has to be either * or / for Spread_ATMVolCorr_TermStr'

    dates = [d for d in ts1.Dates() if d in ts2.Dates() and d <= expiryT]
    F1 = curve.Curve()
    F2 = curve.Curve()
    HR = curve.Curve()
    for d in dates:
        if ts1[d] > 0 and ts2[d] > 0:
            F1[d] = ts1[d]
            F2[d] = ts2[d]
            if op == '/':
                HR[d] = F1[d] / F2[d]
                r = r1 - r2
            else:
                HR[d] = F1[d] * F2[d]
                r = r1 + r2

    IsCall = 1
    HRVol = BS_ATMVol_TermStr(IsCall,
                              HR,
                              expiryT,
                              rd=r,
                              rf=0.0,
                              endVol=0.0,
                              termTenor=termTenor,
                              rehedge_period="1d",
                              exceptionDateList=exceptionDateList)
    VolF1 = BS_ATMVol_TermStr(IsCall,
                              F1,
                              expiryT,
                              rd=r1,
                              rf=0.0,
                              endVol=0.0,
                              termTenor=termTenor,
                              rehedge_period="1d",
                              exceptionDateList=exceptionDateList)
    VolF2 = BS_ATMVol_TermStr(IsCall,
                              F2,
                              expiryT,
                              rd=r2,
                              rf=0.0,
                              endVol=0.0,
                              termTenor=termTenor,
                              rehedge_period="1d",
                              exceptionDateList=exceptionDateList)

    corr = curve.Curve()
    for d in HRVol.Dates():
        if op == '/':
            corr[d] = (VolF1[d]**2 + VolF2[d]**2 -
                       HRVol[d]**2) / (2 * VolF1[d] * VolF2[d])
        else:
            corr[d] = (HRVol[d]**2 - VolF1[d]**2 -
                       VolF2[d]**2) / (2 * VolF1[d] * VolF2[d])

    return HRVol, corr, VolF1, VolF2
Ejemplo n.º 20
0
def make_circle_rat(O, X, Y, r, ths, the):
    ''' Construct, using double knots, a rational quadratic circular arc
    in three-dimensional space of arbitrary sweep angle theta (0 deg <
    theta <= 360 deg).

    In particular, the circular arc is represented exactly by

     C(u) = O + r * cos(u) * X + r * sin(u) * Y    ths <= u <= the

    and is oriented counter-clockwise in the local coordinate system
    defined by O, X and Y.

    Parameters
    ----------
    O = the center of the circular arc
    X = a vector lying in the plane of definition of the circular arc
    Y = a vector in the plane of definition of the circular arc, and
        orthogonal to X
    r = the radius
    ths, the = the start and end angles (in degrees), measured with
               respect to X

    Returns
    -------
    Curve = the circular arc

    Examples
    --------
    >>> O, X, Y = ([0, 1, 0], [1, 0, 0], [0, 0, 1])
    >>> arc = nurbs.tb.make_circle_rat(O, X, Y, 3, 75, 340)

    or

    >>> full = nurbs.tb.make_circle_rat(O, X, Y, 3, 75, 75 + 360)

    Source
    ------
    The NURBS Book (2nd Ed.), Pg. 308.

    '''

    X, Y = [util.normalize(V) for V in (X, Y)]
    if not np.allclose(np.dot(X, Y), 0.0):
        raise NonOrthogonalAxes(X, Y)
    if not r > 0:
        raise ImproperInput(r)
    if the < ths:
        the += 360.0
    theta = the - ths
    if theta <= 90.0:
        narcs = 1
    elif theta <= 180.0:
        narcs = 2
    elif theta <= 270.0:
        narcs = 3
    else:
        narcs = 4
    n = 2 * narcs
    Pw, U = np.zeros((n + 1, 4)), np.zeros(n + 4)
    ths, the, theta = [np.deg2rad(th) for th in (ths, the, theta)]
    dtheta = theta / narcs
    w1 = np.cos(dtheta / 2.0)
    P0 = O + r * np.cos(ths) * X + r * np.sin(ths) * Y
    T0 = -np.sin(ths) * X + np.cos(ths) * Y
    Pw[0] = np.hstack((P0, 1.0))
    index = 0
    angle = ths
    for i in xrange(1, narcs + 1):
        angle += dtheta
        P2 = O + r * np.cos(angle) * X + r * np.sin(angle) * Y
        Pw[index + 2] = np.hstack((P2, 1.0))
        T2 = -np.sin(angle) * X + np.cos(angle) * Y
        P1 = util.intersect_3D_lines(P0, T0, P2, T2)
        Pw[index + 1] = np.hstack((w1 * P1, w1))
        index += 2
        if i < narcs:
            P0, T0 = P2, T2
    j = 2 * narcs + 1
    U[j:] = 1.0
    if narcs == 2:
        U[3] = U[4] = 0.5
    elif narcs == 3:
        U[3] = U[4] = 1.0 / 3.0
        U[5] = U[6] = 2.0 / 3.0
    elif narcs == 4:
        U[3] = U[4] = 0.25
        U[5] = U[6] = 0.5
        U[7] = U[8] = 0.75
    return curve.Curve(curve.ControlPolygon(Pw=Pw), (2, ), (U, ))
Ejemplo n.º 21
0
def __test_curveman():
    import curve
    import curveman
    import numpy as np
    import scipy.optimize as so
    import matplotlib.pyplot as plt
    import time

    # Define instruments which we calibrate curves to
    grids_fixed_ois = [7 / 365, 1 / 12, 2 / 12, 3 / 12, 6 / 12, 9 / 12, 1]
    fixed_ois = [ZeroRate(0, end, 'JPY-OIS') for end in grids_fixed_ois]
    mid_fixed_ois = np.array(
        [0.001, 0.001, 0.0015, 0.002, 0.0022, 0.003, 0.0035])

    # Create CurveManager
    cm = curveman.CurveManager()

    # Define curves and register them to CurveManager
    grids_ois = [7 / 365, 1 / 12, 0.4, 0.6, 1]
    dfs_ois = np.ones((len(grids_ois), ))
    ois_base = curve.Curve(grids_ois, dfs_ois, 'log_linear')
    cm.append_curve('JPY-OIS-BASE', ois_base)

    turn1_from = 0.2
    turn1_to = 0.21
    turn1_size = 0.0
    turn1 = curve.TurnCurve(turn1_from, turn1_to, turn1_size)
    cm.append_curve('JPY-Turn1', turn1)

    turn2_from = 0.7
    turn2_to = 0.71
    turn2_size = 0.0
    turn2 = curve.TurnCurve(turn2_from, turn2_to, turn2_size)
    cm.append_curve('JPY-Turn2', turn2)

    cm.register_basis_curve('JPY-OIS',
                            ['JPY-OIS-BASE', 'JPY-Turn1', 'JPY-Turn2'])

    print(cm.get_grids())

    def loss(dfs):
        cm.update_curves(dfs)
        mids = np.array([ois.par_rate(cm) for ois in fixed_ois])
        return np.sum((mid_fixed_ois - mids)**2)

    #mids = [ois.par_rate(cm) for ois in fixed_ois]
    initial = np.ones((len(grids_fixed_ois), ))
    print('initial loss :', loss(initial))

    t0 = time.time()
    param = so.minimize(loss, initial, tol=1e-8, method='nelder-mead')
    t1 = time.time()
    print('time :', t1 - t0)
    print('after calib :', loss(param.x))
    print('params :', param.x)
    mids = np.array([ois.par_rate(cm) for ois in fixed_ois])
    print('calibrated ois :', mids)

    cm.update_curves(param.x)
    ts = np.arange(0, 1, 1 / 365)
    df = cm.get_curve('JPY-OIS').get_df(ts)

    fwd = -np.log(df[1:] / df[:-1]) / (ts[1:] - ts[:-1])
    plt.plot(ts[:-1], fwd, label='turned')
    plt.legend()
    plt.show()

    print(param.jac)
Ejemplo n.º 22
0

def handle_circle_menu():
    window.bind('<Button-1>', drawAcircle)


def handle_curve_menu(numOfSegments):
    window.bind('<Button-1>', drawAcurve)
    print(numOfSegments)
    global numOfSegments_g
    numOfSegments_g = numOfSegments


line = line.Line()
circle = circle.Circle()
curve = curve.Curve()
window = Tk()
window.title("EX1")

w = Canvas(window, width=screen_width, height=screen_height)
img = PhotoImage(width=screen_width, height=screen_height)
w.create_image((screen_width / 2, screen_height / 2),
               image=img,
               state="normal")

menu = Menu(window)
window.config(menu=menu)

filemenu = Menu(menu, tearoff=0)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='Exit', command=window.quit)
Ejemplo n.º 23
0
def test_CorrTestComp():
    IsCall = 1
    exceptionDateList = []
    op = '/'

    startD = datetime.date(2005, 1, 1)
    endD = datetime.date(2008, 12, 31)

    trueCorr = curve.Curve()
    avgCorr = curve.Curve()
    varCorr = curve.Curve()

    trueVol = curve.Curve()
    avgVol = curve.Curve()
    varVol = curve.Curve()

    expiryT = endD
    F = [1.0, 1.0]
    Sig = [0.8, 0.5]
    Kappa = [1.2, 0.8]
    rho = 0.9
    numPath = 200

    HRPlotList = []
    LegendList = []
    CorrPlotList = []

    for i in range(numPath):
        ts1, ts2 = rand2DTSGen(F,
                               Sig,
                               Kappa,
                               rho,
                               StartDate=startD,
                               EndDate=endD)
        HRVol, HRcorr, VolF1, VolF2 = BSHistVol.Spread_ATMVolCorr_TermStr(
            ts1=ts1,
            ts2=ts2,
            op=op,
            expiryT=expiryT,
            r1=0.0,
            r2=0.0,
            termTenor="1m",
            exceptionDateList=exceptionDateList)

        ToM = [(expiryT - x).days / 365. * 12.0 for x in HRVol.Dates()]
        cross_vol = [y * 100.0 for y in HRVol.Values()]
        corr = [y * 100.0 for y in HRcorr.Values()]

        HRPlotList.append(zip(ToM, cross_vol))
        LegendList.append(str(i))
        CorrPlotList.append(zip(ToM, corr))

        if i == 0:
            for d in HRVol.Dates():
                tau = (expiryT - d).days / 365.0
                s1 = Sig[0]**2 * (1 - math.exp(-2 * Kappa[0] * tau)) / (
                    2 * Kappa[0] * tau)
                s2 = Sig[1]**2 * (1 - math.exp(-2 * Kappa[1] * tau)) / (
                    2 * Kappa[1] * tau)
                s12 = Sig[0] * Sig[1] * rho * (
                    1 - math.exp(-(Kappa[0] + Kappa[1]) * tau)) / (
                        (Kappa[0] + Kappa[1]) * tau)
                if op == '/':
                    s = math.sqrt(s1 + s2 - 2 * s12)
                else:
                    s = math.sqrt(s1 + s2 + 2 * s12)

                r = s12 / math.sqrt(s1 * s2)

                trueVol[d] = s
                trueCorr[d] = r
                avgVol[d] = 0.0
                varVol[d] = 0.0
                avgCorr[d] = 0.0
                varCorr[d] = 0.0

        for d in HRVol.Dates():
            avgVol[d] += HRVol[d] / (numPath * 1.0)
            varVol[d] += (HRVol[d] - trueVol[d])**2 / (numPath * 1.0)
            avgCorr[d] += HRcorr[d] / (numPath * 1.0)
            varCorr[d] += (HRcorr[d] - trueCorr[d])**2 / (numPath * 1.0)

    #gridfig, ax, axF = plotxy.createFigure(pylab.figure(), GridEnabled=True)
    #plotxy.PlotXY(HRPlotList,Legends = LegendList, figure=gridfig)
    #gridfig, ax, axF = plotxy.createFigure(pylab.figure(), GridEnabled=True)
    #plotxy.PlotXY(CorrPlotList,Legends = LegendList, figure=gridfig)

    plotList = [avgVol, trueVol]
    legendList = ['Vol', 'True Vol']
    gridfig, ax, axF = plotxy.createFigure(pylab.figure(), GridEnabled=True)
    plotxy.PlotCurves(plotList, Legends=legendList, figure=gridfig)

    plotList = [avgCorr, trueCorr]
    legendList = ['Corr', 'True Corr']
    gridfig, ax, axF = plotxy.createFigure(pylab.figure(), GridEnabled=True)
    plotxy.PlotCurves(plotList, Legends=legendList, figure=gridfig)

    diff = curve.Curve()
    rcorr = curve.Curve()
    Texp = curve.Curve()
    for d in trueVol.Dates():
        diff[d] = avgCorr[d] - trueCorr[d]
        varCorr[d] = math.sqrt(varCorr[d])
        rcorr[d] = varCorr[d] / trueCorr[d]
        Texp[d] = (expiryT - d).days / 365.0 * 12.0

    DiffRatio = [(Texp[d], diff[d], varCorr[d], rcorr[d])
                 for d in trueCorr.Dates()]
    print DiffRatio
Ejemplo n.º 24
0
    a = 10088
    alpha = 1
if pSize == 'p89-toy':
    f = 1
    n = 64
    N = 27212093
    a = 6
    alpha = 1
if pSize == 'p1506':
    f = 63
    n = 1244
    N = 0xc0256a57b1434a4970e315e3e572ad7b6b6268ca27a1bc14a5ec8d6e8f46ab63
    a = 138931309558156184106311716917677778941761847991286360325642242809534952018704195842136094062347931842162775765708572232752796610393601192925341167860358529602430304979627494497048448960083384310735203052588819895230906248500388348984991092188849520120483947949612966752973461165325952933739065855693165670941141036576698048539586409219548698834122183984266610530679658299939991747759033936995784464828547439035421618098378714023855965416127212175477937
    alpha = 3

c = curve.Curve(f, n, N, a, alpha)

# The delay will depend on nbIterations *and n*
Delta = nbIterations

logging.info('Protocol: %s', protocol)
logging.info('Method: %s', method)
logging.info('Prime size: %s', pSize)
logging.info('Number of steps: %s', str(Delta))

if protocol == 'fp':
    VDF = FpVerifiableDelayFunction(method, c, Delta)
else:
    VDF = Fp2VerifiableDelayFunction(method, c, Delta)

time = cputime()