Esempio n. 1
0
def test_Calendar():

    setDateFormatType(DateFormatTypes.US_LONGEST)
    end_date = Date(31, 12, 2030)

    for calendar_type in CalendarTypes:

        testCases.banner("================================")
        testCases.banner("================================")

        testCases.header("CALENDAR", "HOLIDAY")
        testCases.print("STARTING", calendar_type)

        cal = Calendar(calendar_type)
        next_date = Date(31, 12, 2020)

        while next_date < end_date:
            next_date = next_date.addDays(1)

            if next_date._d == 1 and next_date._m == 1:
                testCases.banner("================================")
#                print("=========================")

            isHolidayDay = cal.isHoliday(next_date)
            if isHolidayDay is True:
                testCases.print(cal, next_date)
#                print(cal, next_date)

    setDateFormatType(DateFormatTypes.US_LONG)
Esempio n. 2
0
def test_DateRange():

    startDate = Date(1, 1, 2010)

    endDate = startDate.addDays(3)
    tenor = "Default"
    print(tenor, dateRange(startDate, endDate))

    endDate = startDate.addDays(20)
    tenor = "1W"
    print(tenor, dateRange(startDate, endDate, tenor))

    tenor = "7D"
    print(tenor, dateRange(startDate, endDate, tenor))

    case = "Same startDate"
    print(case, dateRange(startDate, startDate))
    case = "startDate before endDate"
    print(case, dateRange(endDate, startDate))
Esempio n. 3
0
def test_valueCDSIndex():

    # We treat an index as a CDS contract with a flat CDS curve
    tradeDate = Date(7, 2, 2006)
    libor_curve = buildIborCurve(tradeDate)
    issuer_curve = buildIssuerCurve(tradeDate, libor_curve)
    step_in_date = tradeDate.addDays(1)
    valuation_date = step_in_date
    maturity_date = Date(20, 6, 2010)

    cdsRecovery = 0.40
    notional = 10.0 * ONE_MILLION
    long_protection = True
    index_coupon = 0.004

    cdsIndexContract = FinCDS(step_in_date, maturity_date, index_coupon,
                              notional, long_protection)

    #    cdsIndexContract.print(valuation_date)

    testCases.header("LABEL", "VALUE")

    spd = cdsIndexContract.parSpread(valuation_date, issuer_curve,
                                     cdsRecovery) * 10000.0
    testCases.print("PAR SPREAD", spd)

    v = cdsIndexContract.value(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("FULL VALUE", v['full_pv'])
    testCases.print("CLEAN VALUE", v['clean_pv'])

    p = cdsIndexContract.clean_price(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("CLEAN PRICE", p)

    accrued_days = cdsIndexContract.accrued_days()
    testCases.print("ACCRUED DAYS", accrued_days)

    accruedInterest = cdsIndexContract.accruedInterest()
    testCases.print("ACCRUED COUPON", accruedInterest)

    prot_pv = cdsIndexContract.protectionLegPV(valuation_date, issuer_curve,
                                               cdsRecovery)
    testCases.print("PROTECTION LEG PV", prot_pv)

    premPV = cdsIndexContract.premiumLegPV(valuation_date, issuer_curve,
                                           cdsRecovery)
    testCases.print("PREMIUM LEG PV", premPV)

    fullRPV01, cleanRPV01 = cdsIndexContract.riskyPV01(valuation_date,
                                                       issuer_curve)
    testCases.print("FULL  RPV01", fullRPV01)
    testCases.print("CLEAN RPV01", cleanRPV01)
Esempio n. 4
0
def test_Date():

    startDate = Date(1, 1, 2018)

    for numMonths in range(0, 120):
        nextCDSDate = startDate.nextCDSDate(numMonths)
        print(str(startDate), numMonths, str(nextCDSDate))

    startDate = Date(1, 1, 2018)

    for numMonths in range(0, 365):
        startDate = startDate.addDays(1)
        nextIMMDate = startDate.nextIMMDate()
        print(numMonths, str(startDate), str(nextIMMDate))
Esempio n. 5
0
def test_FinDateRange():

    start_date = Date(1, 1, 2010)

    testCases.header("Tenor", "Dates")

    end_date = start_date.addDays(3)
    tenor = "Default"
    testCases.print(tenor, dateRange(start_date, end_date))

    end_date = start_date.addDays(20)
    tenor = "1W"
    testCases.print(tenor, dateRange(start_date, end_date, tenor))

    tenor = "7D"
    testCases.print(tenor, dateRange(start_date, end_date, tenor))

    testCases.header("Case", "Dates")

    case = "Same start_date"
    testCases.print(case, dateRange(start_date, start_date))
    case = "start_date before end_date"
    testCases.print(case, dateRange(end_date, start_date))
Esempio n. 6
0
def test_FinDate():

    start_date = Date(1, 1, 2018)

    assert Date(1, 1, 2018) == Date.fromString('1-1-2018', '%d-%m-%Y')

    testCases.header("DATE", "MONTHS", "CDS DATE")

    for numMonths in range(0, 120):
        nextCDSDate = start_date.nextCDSDate(numMonths)
        testCases.print(str(start_date), numMonths, str(nextCDSDate))

    start_date = Date(1, 1, 2018)

    testCases.header("STARTDATE", "MONTHS", "CDS DATE")

    for numMonths in range(0, 365):
        start_date = start_date.addDays(1)
        nextIMMDate = start_date.nextIMMDate()
        testCases.print(numMonths, str(start_date), str(nextIMMDate))
Esempio n. 7
0
def test_LiborSwap():

    # I have tried to reproduce the example from the blog by Ioannis Rigopoulos
    # https://blog.deriscope.com/index.php/en/excel-interest-rate-swap-price-dual-bootstrapping-curve
    start_date = Date(27, 12, 2017)
    end_date = Date(27, 12, 2067)

    fixedCoupon = 0.015
    fixedFreqType = FrequencyTypes.ANNUAL
    fixedDayCountType = DayCountTypes.THIRTY_E_360

    floatSpread = 0.0
    floatFreqType = FrequencyTypes.SEMI_ANNUAL
    floatDayCountType = DayCountTypes.ACT_360
    firstFixing = -0.00268

    swapCalendarType = CalendarTypes.WEEKEND
    bus_day_adjust_type = BusDayAdjustTypes.FOLLOWING
    date_gen_rule_type = DateGenRuleTypes.BACKWARD
    fixed_legType = FinSwapTypes.RECEIVE

    notional = 10.0 * ONE_MILLION

    swap = FinIborSwap(start_date, end_date, fixed_legType, fixedCoupon,
                       fixedFreqType, fixedDayCountType, notional, floatSpread,
                       floatFreqType, floatDayCountType, swapCalendarType,
                       bus_day_adjust_type, date_gen_rule_type)
    """ Now perform a valuation after the swap has seasoned but with the
    same curve being used for discounting and working out the implied
    future Libor rates. """

    valuation_date = Date(30, 11, 2018)
    settlement_date = valuation_date.addDays(2)
    libor_curve = buildIborSingleCurve(valuation_date)
    v = swap.value(settlement_date, libor_curve, libor_curve, firstFixing)

    v_bbg = 388147.0
    testCases.header("LABEL", "VALUE")
    testCases.print("SWAP_VALUE USING ONE_CURVE", v)
    testCases.print("BLOOMBERG VALUE", v_bbg)
    testCases.print("DIFFERENCE VALUE", v_bbg - v)
Esempio n. 8
0
def test_BondExDividend():
    issue_date = Date(7, 9, 2000)
    maturity_date = Date(7, 9, 2020)
    coupon = 0.05
    freq_type = FrequencyTypes.SEMI_ANNUAL
    accrual_type = DayCountTypes.ACT_ACT_ICMA
    face = 100.0
    exDivDays = 7
    testCases.header("LABEL", "VALUE")

    calendar_type = CalendarTypes.UNITED_KINGDOM
    bond = Bond(issue_date, maturity_date, coupon,
                freq_type, accrual_type, face)
    settlement_date = Date(7, 9, 2003)
    accrued = bond.calc_accrued_interest(settlement_date, exDivDays, calendar_type)
    testCases.print("SettlementDate:", settlement_date)
    testCases.print("Accrued:", accrued)

    ###########################################################################
    testCases.banner("=======================================================")
    testCases.header("SETTLEMENT", "ACCRUED")

    issue_date = Date(7, 9, 2000)
    maturity_date = Date(7, 9, 2020)
    coupon = 0.05
    freq_type = FrequencyTypes.SEMI_ANNUAL
    accrual_type = DayCountTypes.ACT_ACT_ICMA
    face = 100.0
    exDivDays = 7

    calendar_type = CalendarTypes.UNITED_KINGDOM
    bond = Bond(issue_date, maturity_date, coupon,
                freq_type, accrual_type, face)

    settlement_date = Date(25, 8, 2010)

    for _ in range(0, 13):
        settlement_date = settlement_date.addDays(1)
        accrued = bond.calc_accrued_interest(
            settlement_date, exDivDays, calendar_type)
        testCases.print(settlement_date, accrued)
Esempio n. 9
0
def test_CDSDateGeneration():

    # This is the 10 year contract at an off market coupon
    maturity_date = Date(20, 6, 2029)
    cdsCoupon = 0.0100

    tradeDate = Date(9, 8, 2019)
    valuation_date = tradeDate.addDays(1)

    cds_contract = FinCDS(valuation_date, maturity_date, cdsCoupon,
                          ONE_MILLION, True, FrequencyTypes.QUARTERLY,
                          DayCountTypes.ACT_360, CalendarTypes.WEEKEND,
                          BusDayAdjustTypes.FOLLOWING,
                          DateGenRuleTypes.BACKWARD)

    testCases.header("Flow Date", "AccrualFactor", "Flow")
    num_flows = len(cds_contract._adjusted_dates)
    for n in range(0, num_flows):
        testCases.print(str(cds_contract._adjusted_dates[n]),
                        cds_contract._accrual_factors[n],
                        cds_contract._flows[n])
Esempio n. 10
0
def test_full_priceCDSConvergence():

    _, issuer_curve = buildFullIssuerCurve1(0.0, 0.0)

    # This is the 10 year contract at an off market coupon
    maturity_date = Date(20, 6, 2029)
    cdsCoupon = 0.0150
    notional = ONE_MILLION
    long_protection = False
    tradeDate = Date(9, 8, 2019)
    valuation_date = tradeDate.addDays(1)

    cds_contract = FinCDS(valuation_date, maturity_date, cdsCoupon, notional,
                          long_protection)

    cdsRecovery = 0.40

    testCases.header("NumSteps", "Value")
    for n in [10, 50, 100, 500, 1000]:
        v_full = cds_contract.value(valuation_date, issuer_curve, cdsRecovery,
                                    0, 1, n)['full_pv']
        testCases.print(n, v_full)
def test_performCDSIndexHazardRateAdjustment():

    tradeDate = Date(1, 8, 2007)
    step_in_date = tradeDate.addDays(1)
    valuation_date = step_in_date

    libor_curve = buildIborCurve(tradeDate)

    maturity3Y = tradeDate.nextCDSDate(36)
    maturity5Y = tradeDate.nextCDSDate(60)
    maturity7Y = tradeDate.nextCDSDate(84)
    maturity10Y = tradeDate.nextCDSDate(120)

    path = dirname(__file__)
    filename = "CDX_NA_IG_S7_SPREADS.csv"
    full_filename_path = join(path, "data", filename)
    f = open(full_filename_path, 'r')

    data = f.readlines()
    issuer_curves = []

    for row in data[1:]:

        splitRow = row.split(",")
        spd3Y = float(splitRow[1]) / 10000.0
        spd5Y = float(splitRow[2]) / 10000.0
        spd7Y = float(splitRow[3]) / 10000.0
        spd10Y = float(splitRow[4]) / 10000.0
        recovery_rate = float(splitRow[5])

        cds3Y = FinCDS(step_in_date, maturity3Y, spd3Y)
        cds5Y = FinCDS(step_in_date, maturity5Y, spd5Y)
        cds7Y = FinCDS(step_in_date, maturity7Y, spd7Y)
        cds10Y = FinCDS(step_in_date, maturity10Y, spd10Y)
        cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]

        issuer_curve = FinCDSCurve(valuation_date, cds_contracts, libor_curve,
                                   recovery_rate)

        issuer_curves.append(issuer_curve)

    ##########################################################################
    # Now determine the average spread of the index
    ##########################################################################

    cdsIndex = FinCDSIndexPortfolio()

    averageSpd3Y = cdsIndex.averageSpread(valuation_date, step_in_date,
                                          maturity3Y, issuer_curves) * 10000.0

    averageSpd5Y = cdsIndex.averageSpread(valuation_date, step_in_date,
                                          maturity5Y, issuer_curves) * 10000.0

    averageSpd7Y = cdsIndex.averageSpread(valuation_date, step_in_date,
                                          maturity7Y, issuer_curves) * 10000.0

    averageSpd10Y = cdsIndex.averageSpread(
        valuation_date, step_in_date, maturity10Y, issuer_curves) * 10000.0

    testCases.header("LABEL", "VALUE")
    testCases.print("AVERAGE SPD 3Y", averageSpd3Y)
    testCases.print("AVERAGE SPD 5Y", averageSpd5Y)
    testCases.print("AVERAGE SPD 7Y", averageSpd7Y)
    testCases.print("AVERAGE SPD 10Y", averageSpd10Y)
    testCases.banner(
        "===================================================================")

    ##########################################################################
    # Now determine the intrinsic spread of the index to the same maturity dates
    # As the single name CDS contracts
    ##########################################################################

    cdsIndex = FinCDSIndexPortfolio()

    intrinsicSpd3Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity3Y, issuer_curves) * 10000.0

    intrinsicSpd5Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity5Y, issuer_curves) * 10000.0

    intrinsicSpd7Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity7Y, issuer_curves) * 10000.0

    intrinsicSpd10Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity10Y, issuer_curves) * 10000.0

    ##########################################################################
    ##########################################################################

    testCases.header("LABEL", "VALUE")
    testCases.print("INTRINSIC SPD 3Y", intrinsicSpd3Y)
    testCases.print("INTRINSIC SPD 5Y", intrinsicSpd5Y)
    testCases.print("INTRINSIC SPD 7Y", intrinsicSpd7Y)
    testCases.print("INTRINSIC SPD 10Y", intrinsicSpd10Y)
    testCases.banner(
        "===================================================================")

    ##########################################################################
    ##########################################################################

    index_coupons = [0.002, 0.0037, 0.0050, 0.0063]
    indexUpfronts = [0.0, 0.0, 0.0, 0.0]

    indexMaturityDates = [
        Date(20, 12, 2009),
        Date(20, 12, 2011),
        Date(20, 12, 2013),
        Date(20, 12, 2016)
    ]

    indexRecoveryRate = 0.40

    tolerance = 1e-6

    import time
    start = time.time()

    indexPortfolio = FinCDSIndexPortfolio()
    adjustedIssuerCurves = indexPortfolio.hazardRateAdjustIntrinsic(
        valuation_date, issuer_curves, index_coupons, indexUpfronts,
        indexMaturityDates, indexRecoveryRate, tolerance)

    end = time.time()
    testCases.header("TIME")
    testCases.print(end - start)

    #    num_credits = len(issuer_curves)
    #    testCases.print("#","MATURITY","CDS_UNADJ","CDS_ADJ")
    #    for m in range(0,num_credits):
    #        for cds in cds_contracts:
    #            unadjustedSpread = cds.parSpread(valuation_date,issuer_curves[m])
    #            adjustedSpread = cds.parSpread(valuation_date,adjustedIssuerCurves[m])
    #            testCases.print(m,str(cds._maturity_date),"%10.3f"%(unadjustedSpread*10000),"%10.3f" %(adjustedSpread*10000))

    cdsIndex = FinCDSIndexPortfolio()

    intrinsicSpd3Y = cdsIndex.intrinsicSpread(valuation_date, step_in_date,
                                              indexMaturityDates[0],
                                              adjustedIssuerCurves) * 10000.0

    intrinsicSpd5Y = cdsIndex.intrinsicSpread(valuation_date, step_in_date,
                                              indexMaturityDates[1],
                                              adjustedIssuerCurves) * 10000.0

    intrinsicSpd7Y = cdsIndex.intrinsicSpread(valuation_date, step_in_date,
                                              indexMaturityDates[2],
                                              adjustedIssuerCurves) * 10000.0

    intrinsicSpd10Y = cdsIndex.intrinsicSpread(valuation_date, step_in_date,
                                               indexMaturityDates[3],
                                               adjustedIssuerCurves) * 10000.0

    # If the adjustment works then this should equal the index spreads
    testCases.header("LABEL", "VALUE")
    testCases.print("ADJUSTED INTRINSIC SPD 3Y", intrinsicSpd3Y)
    testCases.print("ADJUSTED INTRINSIC SPD 5Y", intrinsicSpd5Y)
    testCases.print("ADJUSTED INTRINSIC SPD 7Y", intrinsicSpd7Y)
    testCases.print("ADJUSTED INTRINSIC SPD 10Y", intrinsicSpd10Y)
Esempio n. 12
0
def test_FinCDSBasket():

    tradeDate = Date(1, 3, 2007)
    step_in_date = tradeDate.addDays(1)
    valuation_date = tradeDate.addDays(1)

    libor_curve = buildIborCurve(tradeDate)

    basketMaturity = Date(20, 12, 2011)

    cdsIndex = FinCDSIndexPortfolio()

    ##########################################################################

    testCases.banner(
        "===================================================================")
    testCases.banner(
        "====================== INHOMOGENEOUS CURVE =========================="
    )
    testCases.banner(
        "===================================================================")

    num_credits = 5
    spd3Y = 0.0012
    spd5Y = 0.0025
    spd7Y = 0.0034
    spd10Y = 0.0046

    testCases.header("LABELS", "VALUE")

    if 1 == 0:
        issuer_curves = loadHomogeneousSpreadCurves(valuation_date,
                                                    libor_curve, spd3Y, spd5Y,
                                                    spd7Y, spd10Y, num_credits)
    else:
        issuer_curves = loadHeterogeneousSpreadCurves(valuation_date,
                                                      libor_curve)
        issuer_curves = issuer_curves[0:num_credits]

    intrinsicSpd = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, basketMaturity, issuer_curves) * 10000.0

    testCases.print("INTRINSIC SPD BASKET MATURITY", intrinsicSpd)

    totalSpd = cdsIndex.totalSpread(valuation_date, step_in_date,
                                    basketMaturity, issuer_curves) * 10000.0

    testCases.print("SUMMED UP SPD BASKET MATURITY", totalSpd)

    minSpd = cdsIndex.minSpread(valuation_date, step_in_date, basketMaturity,
                                issuer_curves) * 10000.0

    testCases.print("MINIMUM SPD BASKET MATURITY", minSpd)

    maxSpd = cdsIndex.maxSpread(valuation_date, step_in_date, basketMaturity,
                                issuer_curves) * 10000.0

    testCases.print("MAXIMUM SPD BASKET MATURITY", maxSpd)

    seed = 1967
    basket = FinCDSBasket(valuation_date, basketMaturity)

    testCases.banner(
        "===================================================================")
    testCases.banner(
        "======================= GAUSSIAN COPULA ===========================")
    testCases.banner(
        "===================================================================")

    testCases.header("TIME", "Trials", "RHO", "NTD", "SPRD", "SPRD_HOMO")

    for ntd in range(1, num_credits + 1):
        for beta in [0.0, 0.5]:
            rho = beta * beta
            betaVector = np.ones(num_credits) * beta
            corrMatrix = corrMatrixGenerator(rho, num_credits)
            for num_trials in [1000]:  # [1000,5000,10000,20000,50000,100000]:
                start = time.time()

                v1 = basket.valueGaussian_MC(valuation_date, ntd,
                                             issuer_curves, corrMatrix,
                                             libor_curve, num_trials, seed)

                v2 = basket.value1FGaussian_Homo(valuation_date, ntd,
                                                 issuer_curves, betaVector,
                                                 libor_curve)

                end = time.time()
                period = (end - start)
                testCases.print(period, num_trials, rho, ntd, v1[2] * 10000,
                                v2[3] * 10000)

    testCases.banner(
        "===================================================================")
    testCases.banner(
        "==================== STUDENT'S-T CONVERGENCE ======================")
    testCases.banner(
        "===================================================================")

    testCases.header("TIME", "TRIALS", "RHO", "DOF", "NTD", "SPRD")

    for beta in [0.0, 0.5]:
        rho = beta**2
        corrMatrix = corrMatrixGenerator(rho, num_credits)
        for ntd in range(1, num_credits + 1):
            for doF in [3, 6]:
                start = time.time()

                v = basket.valueStudentT_MC(valuation_date, ntd, issuer_curves,
                                            corrMatrix, doF, libor_curve,
                                            num_trials, seed)

                end = time.time()
                period = (end - start)
                testCases.print(period, num_trials, rho, doF, ntd,
                                v[2] * 10000)

            start = time.time()
            v = basket.valueGaussian_MC(valuation_date, ntd, issuer_curves,
                                        corrMatrix, libor_curve, num_trials,
                                        seed)
            end = time.time()
            period = (end - start)

            testCases.print(period, num_trials, rho, "GC", ntd, v[2] * 10000)

    testCases.banner(
        "===================================================================")
    testCases.banner(
        "=================== STUDENT'S T WITH DOF = 5 ======================")
    testCases.banner(
        "===================================================================")
    doF = 5
    testCases.header("TIME", "NUMTRIALS", "RHO", "NTD", "SPD")
    for beta in [0.0, 0.5]:
        rho = beta**2
        corrMatrix = corrMatrixGenerator(rho, num_credits)
        for ntd in range(1, num_credits + 1):
            for num_trials in [1000]:
                start = time.time()

                v = basket.valueStudentT_MC(valuation_date, ntd, issuer_curves,
                                            corrMatrix, doF, libor_curve,
                                            num_trials, seed)
                end = time.time()
                period = (end - start)
                testCases.print(period, num_trials, rho, ntd, v[2] * 10000)
Esempio n. 13
0
def test_full_priceCDSwaption():

    # This reproduces example on page 38 of Open Gamma note on CDS Option
    tradeDate = Date(5, 2, 2014)
    _, issuer_curve = buildFullIssuerCurve(tradeDate)
    step_in_date = tradeDate.addDays(1)
    valuation_date = step_in_date
    expiry_date = Date(20, 3, 2014)
    maturity_date = Date(20, 6, 2019)

    cdsRecovery = 0.40
    notional = 100.0
    long_protection = False
    cdsCoupon = 0.0  # NOT KNOWN

    cds_contract = FinCDS(step_in_date,
                         maturity_date,
                         cdsCoupon,
                         notional,
                         long_protection)

    testCases.banner(
        "=============================== CDS ===============================")
#    cds_contract.print(valuation_date)

    testCases.header("LABEL", "VALUE")
    spd = cds_contract.parSpread(
        valuation_date,
        issuer_curve,
        cdsRecovery) * 10000.0
    testCases.print("PAR SPREAD:", spd)

    v = cds_contract.value(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("FULL VALUE", v['full_pv'])
    testCases.print("CLEAN VALUE", v['clean_pv'])

    p = cds_contract.clean_price(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("CLEAN PRICE", p)

    accrued_days = cds_contract.accrued_days()
    testCases.print("ACCRUED DAYS", accrued_days)

    accruedInterest = cds_contract.accruedInterest()
    testCases.print("ACCRUED COUPON", accruedInterest)

    prot_pv = cds_contract.protectionLegPV(
        valuation_date, issuer_curve, cdsRecovery)
    testCases.print("PROTECTION LEG PV", prot_pv)

    premPV = cds_contract.premiumLegPV(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("PREMIUM LEG PV", premPV)

    fullRPV01, cleanRPV01 = cds_contract.riskyPV01(valuation_date, issuer_curve)
    testCases.print("FULL  RPV01", fullRPV01)
    testCases.print("CLEAN RPV01", cleanRPV01)

#    cds_contract.printFlows(issuer_curve)

    testCases.banner(
        "=========================== FORWARD CDS ===========================")

    cds_contract = FinCDS(expiry_date,
                         maturity_date,
                         cdsCoupon,
                         notional,
                         long_protection)

#    cds_contract.print(valuation_date)

    spd = cds_contract.parSpread(
        valuation_date,
        issuer_curve,
        cdsRecovery) * 10000.0
    testCases.print("PAR SPREAD", spd)

    v = cds_contract.value(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("FULL VALUE", v['full_pv'])
    testCases.print("CLEAN VALUE", v['clean_pv'])

    prot_pv = cds_contract.protectionLegPV(
        valuation_date, issuer_curve, cdsRecovery)
    testCases.print("PROTECTION LEG PV", prot_pv)

    premPV = cds_contract.premiumLegPV(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("PREMIUM LEG PV", premPV)

    fullRPV01, cleanRPV01 = cds_contract.riskyPV01(valuation_date, issuer_curve)
    testCases.print("FULL  RPV01", fullRPV01)
    testCases.print("CLEAN RPV01", cleanRPV01)

#    cds_contract.printFlows(issuer_curve)

    testCases.banner(
        "========================== CDS OPTIONS ============================")

    cdsCoupon = 0.01
    volatility = 0.3
    testCases.print("Expiry Date:", str(expiry_date))
    testCases.print("Maturity Date:", str(maturity_date))
    testCases.print("CDS Coupon:", cdsCoupon)

    testCases.header("STRIKE", "FULL VALUE", "IMPLIED VOL")

    for strike in np.linspace(100, 300, 41):

        cdsOption = FinCDSOption(expiry_date,
                                 maturity_date,
                                 strike / 10000.0,
                                 notional)

        v = cdsOption.value(valuation_date,
                            issuer_curve,
                            volatility)

        vol = cdsOption.impliedVolatility(valuation_date,
                                          issuer_curve,
                                          v)

        testCases.print(strike, v, vol)
Esempio n. 14
0
def test_full_priceCDS1():

    mktSpread = 0.040

    testCases.header("Example", "Markit 9 Aug 2019")

    libor_curve, issuer_curve = buildFullIssuerCurve1(0.0, 0.0)

    # This is the 10 year contract at an off market coupon
    maturity_date = Date(20, 6, 2029)
    cdsCoupon = 0.0150
    notional = ONE_MILLION
    long_protection = True
    tradeDate = Date(9, 8, 2019)
    valuation_date = tradeDate.addDays(1)
    effective_date = valuation_date

    cds_contract = FinCDS(effective_date, maturity_date, cdsCoupon, notional,
                          long_protection)

    cdsRecovery = 0.40

    testCases.header("LABEL", "VALUE")
    spd = cds_contract.parSpread(valuation_date, issuer_curve,
                                 cdsRecovery) * 10000.0
    testCases.print("PAR_SPREAD", spd)

    v = cds_contract.value(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("FULL_VALUE", v['full_pv'])
    testCases.print("CLEAN_VALUE", v['clean_pv'])

    p = cds_contract.clean_price(valuation_date, issuer_curve, cdsRecovery)
    testCases.print("CLEAN_PRICE", p)

    # MARKIT PRICE IS 168517

    accrued_days = cds_contract.accrued_days()
    testCases.print("ACCRUED_DAYS", accrued_days)

    accruedInterest = cds_contract.accruedInterest()
    testCases.print("ACCRUED_COUPON", accruedInterest)

    prot_pv = cds_contract.protectionLegPV(valuation_date, issuer_curve,
                                           cdsRecovery)
    testCases.print("PROTECTION_PV", prot_pv)

    premPV = cds_contract.premiumLegPV(valuation_date, issuer_curve,
                                       cdsRecovery)
    testCases.print("PREMIUM_PV", premPV)

    fullRPV01, cleanRPV01 = cds_contract.riskyPV01(valuation_date,
                                                   issuer_curve)
    testCases.print("FULL_RPV01", fullRPV01)
    testCases.print("CLEAN_RPV01", cleanRPV01)

    # cds_contract.printFlows(issuer_curve)

    bump = 1.0 / 10000.0  # 1 bp

    libor_curve, issuer_curve = buildFullIssuerCurve1(bump, 0)
    v_bump = cds_contract.value(valuation_date, issuer_curve, cdsRecovery)
    dv = v_bump['full_pv'] - v['full_pv']
    testCases.print("CREDIT_DV01", dv)

    # Interest Rate Bump
    libor_curve, issuer_curve = buildFullIssuerCurve1(0, bump)
    v_bump = cds_contract.value(valuation_date, issuer_curve, cdsRecovery)
    dv = v_bump['full_pv'] - v['full_pv']
    testCases.print("INTEREST_DV01", dv)

    t = (maturity_date - valuation_date) / gDaysInYear
    z = libor_curve.df(maturity_date)
    r = -np.log(z) / t

    v_approx = cds_contract.valueFastApprox(valuation_date, r, mktSpread,
                                            cdsRecovery)

    testCases.print("FULL APPROX VALUE", v_approx[0])
    testCases.print("CLEAN APPROX VALUE", v_approx[1])
    testCases.print("APPROX CREDIT DV01", v_approx[2])
    testCases.print("APPROX INTEREST DV01", v_approx[3])
Esempio n. 15
0
def test_FinCDSTranche():

    tradeDate = Date(1, 3, 2007)
    step_in_date = tradeDate.addDays(1)
    valuation_date = tradeDate.addDays(1)

    testCases.header("DATE")
    testCases.print(str((tradeDate)))
    testCases.print(str((step_in_date)))
    testCases.print(str((valuation_date)))

    libor_curve = buildIborCurve(tradeDate)

    trancheMaturity = Date(20, 12, 2011)
    tranche1 = FinCDSTranche(valuation_date, trancheMaturity, 0.00, 0.03)
    tranche2 = FinCDSTranche(valuation_date, trancheMaturity, 0.03, 0.06)
    tranche3 = FinCDSTranche(valuation_date, trancheMaturity, 0.06, 0.09)
    tranche4 = FinCDSTranche(valuation_date, trancheMaturity, 0.09, 0.12)
    tranche5 = FinCDSTranche(valuation_date, trancheMaturity, 0.12, 0.22)
    tranche6 = FinCDSTranche(valuation_date, trancheMaturity, 0.22, 0.60)
    tranche7 = FinCDSTranche(valuation_date, trancheMaturity, 0.00, 0.60)
    tranches = [
        tranche1, tranche2, tranche3, tranche4, tranche5, tranche6, tranche7
    ]

    corr1 = 0.30
    corr2 = 0.35
    upfront = 0.0
    spd = 0.0

    cdsIndex = FinCDSIndexPortfolio()

    ##########################################################################

    testCases.banner(
        "===================================================================")
    testCases.banner(
        "====================== HOMOGENEOUS CURVE ==========================")
    testCases.banner(
        "===================================================================")
    num_credits = 125
    spd3Y = 0.0012
    spd5Y = 0.0025
    spd7Y = 0.0034
    spd10Y = 0.0046

    issuer_curves = loadHomogeneousCDSCurves(valuation_date, libor_curve,
                                             spd3Y, spd5Y, spd7Y, spd10Y,
                                             num_credits)

    intrinsicSpd = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, trancheMaturity, issuer_curves) * 10000.0

    testCases.header("LABEL", "VALUE")
    testCases.print("INTRINSIC SPD TRANCHE MATURITY", intrinsicSpd)
    adjustedSpd = intrinsicSpd / 0.6
    testCases.print("ADJUSTED  SPD TRANCHE MATURITY", adjustedSpd)

    testCases.header("METHOD", "TIME", "NumPoints", "K1", "K2", "Sprd")

    for method in FinLossDistributionBuilder:
        for tranche in tranches:
            for num_points in [40]:
                start = time.time()
                v = tranche.valueBC(valuation_date, issuer_curves, upfront,
                                    spd, corr1, corr2, num_points, method)
                end = time.time()
                period = (end - start)
                testCases.print(method, period, num_points, tranche._k1,
                                tranche._k2, v[3] * 10000)

##########################################################################

    testCases.banner(
        "===================================================================")
    testCases.banner(
        "=================== HETEROGENEOUS CURVES ==========================")
    testCases.banner(
        "===================================================================")

    issuer_curves = loadHeterogeneousSpreadCurves(valuation_date, libor_curve)

    intrinsicSpd = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, trancheMaturity, issuer_curves) * 10000.0

    testCases.header("LABEL", "VALUE")
    testCases.print("INTRINSIC SPD TRANCHE MATURITY", intrinsicSpd)
    adjustedSpd = intrinsicSpd / 0.6
    testCases.print("ADJUSTED  SPD TRANCHE MATURITY", adjustedSpd)

    testCases.header("METHOD", "TIME", "NumPoints", "K1", "K2", "Sprd")

    for method in FinLossDistributionBuilder:
        for tranche in tranches:
            for num_points in [40]:
                start = time.time()
                v = tranche.valueBC(valuation_date, issuer_curves, upfront,
                                    spd, corr1, corr2, num_points, method)
                end = time.time()
                period = (end - start)
                testCases.print(method, period, num_points, tranche._k1,
                                tranche._k2, v[3] * 10000)

    testCases.banner(
        "===================================================================")
def test_CDSIndexPortfolio():

    tradeDate = Date(1, 8, 2007)
    step_in_date = tradeDate.addDays(1)
    valuation_date = step_in_date

    libor_curve = buildIborCurve(tradeDate)

    maturity3Y = tradeDate.nextCDSDate(36)
    maturity5Y = tradeDate.nextCDSDate(60)
    maturity7Y = tradeDate.nextCDSDate(84)
    maturity10Y = tradeDate.nextCDSDate(120)

    path = os.path.join(os.path.dirname(__file__),
                        './/data//CDX_NA_IG_S7_SPREADS.csv')
    f = open(path, 'r')
    data = f.readlines()
    f.close()
    issuer_curves = []

    for row in data[1:]:

        splitRow = row.split(",")
        spd3Y = float(splitRow[1]) / 10000.0
        spd5Y = float(splitRow[2]) / 10000.0
        spd7Y = float(splitRow[3]) / 10000.0
        spd10Y = float(splitRow[4]) / 10000.0
        recovery_rate = float(splitRow[5])

        cds3Y = FinCDS(step_in_date, maturity3Y, spd3Y)
        cds5Y = FinCDS(step_in_date, maturity5Y, spd5Y)
        cds7Y = FinCDS(step_in_date, maturity7Y, spd7Y)
        cds10Y = FinCDS(step_in_date, maturity10Y, spd10Y)
        cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]

        issuer_curve = FinCDSCurve(valuation_date, cds_contracts, libor_curve,
                                   recovery_rate)

        issuer_curves.append(issuer_curve)

    ##########################################################################
    # Now determine the average spread of the index
    ##########################################################################

    cdsIndex = FinCDSIndexPortfolio()

    averageSpd3Y = cdsIndex.averageSpread(valuation_date, step_in_date,
                                          maturity3Y, issuer_curves) * 10000.0

    averageSpd5Y = cdsIndex.averageSpread(valuation_date, step_in_date,
                                          maturity5Y, issuer_curves) * 10000.0

    averageSpd7Y = cdsIndex.averageSpread(valuation_date, step_in_date,
                                          maturity7Y, issuer_curves) * 10000.0

    averageSpd10Y = cdsIndex.averageSpread(
        valuation_date, step_in_date, maturity10Y, issuer_curves) * 10000.0

    testCases.header("LABEL", "VALUE")
    testCases.print("AVERAGE SPD 3Y", averageSpd3Y)
    testCases.print("AVERAGE SPD 5Y", averageSpd5Y)
    testCases.print("AVERAGE SPD 7Y", averageSpd7Y)
    testCases.print("AVERAGE SPD 10Y", averageSpd10Y)

    ##########################################################################
    # Now determine the intrinsic spread of the index to the same maturity
    # dates. As the single name CDS contracts
    ##########################################################################

    cdsIndex = FinCDSIndexPortfolio()

    intrinsicSpd3Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity3Y, issuer_curves) * 10000.0

    intrinsicSpd5Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity5Y, issuer_curves) * 10000.0

    intrinsicSpd7Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity7Y, issuer_curves) * 10000.0

    intrinsicSpd10Y = cdsIndex.intrinsicSpread(
        valuation_date, step_in_date, maturity10Y, issuer_curves) * 10000.0

    ##########################################################################
    ##########################################################################

    testCases.header("LABEL", "VALUE")
    testCases.print("INTRINSIC SPD 3Y", intrinsicSpd3Y)
    testCases.print("INTRINSIC SPD 5Y", intrinsicSpd5Y)
    testCases.print("INTRINSIC SPD 7Y", intrinsicSpd7Y)
    testCases.print("INTRINSIC SPD 10Y", intrinsicSpd10Y)
Esempio n. 17
0
def buildFullIssuerCurve1(mktSpreadBump, irBump):

    # https://www.markit.com/markit.jsp?jsppage=pv.jsp
    # YIELD CURVE 8-AUG-2019 SNAP AT 1600

    tradeDate = Date(9, 8, 2019)
    valuation_date = tradeDate.addDays(1)

    m = 1.0  # 0.00000000000

    dcType = DayCountTypes.ACT_360
    depos = []
    depo1 = FinIborDeposit(valuation_date, "1D", m * 0.0220, dcType)
    depos.append(depo1)

    spotDays = 2
    settlement_date = valuation_date.addDays(spotDays)

    maturity_date = settlement_date.addMonths(1)
    depo1 = FinIborDeposit(settlement_date, maturity_date, m * 0.022009,
                           dcType)

    maturity_date = settlement_date.addMonths(2)
    depo2 = FinIborDeposit(settlement_date, maturity_date, m * 0.022138,
                           dcType)

    maturity_date = settlement_date.addMonths(3)
    depo3 = FinIborDeposit(settlement_date, maturity_date, m * 0.021810,
                           dcType)

    maturity_date = settlement_date.addMonths(6)
    depo4 = FinIborDeposit(settlement_date, maturity_date, m * 0.020503,
                           dcType)

    maturity_date = settlement_date.addMonths(12)
    depo5 = FinIborDeposit(settlement_date, maturity_date, m * 0.019930,
                           dcType)

    depos.append(depo1)
    depos.append(depo2)
    depos.append(depo3)
    depos.append(depo4)
    depos.append(depo5)

    fras = []

    swaps = []
    dcType = DayCountTypes.THIRTY_E_360_ISDA
    fixedFreq = FrequencyTypes.SEMI_ANNUAL

    maturity_date = settlement_date.addMonths(24)
    swap1 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.015910 + irBump, fixedFreq, dcType)
    swaps.append(swap1)

    maturity_date = settlement_date.addMonths(36)
    swap2 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.014990 + irBump, fixedFreq, dcType)
    swaps.append(swap2)

    maturity_date = settlement_date.addMonths(48)
    swap3 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.014725 + irBump, fixedFreq, dcType)
    swaps.append(swap3)

    maturity_date = settlement_date.addMonths(60)
    swap4 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.014640 + irBump, fixedFreq, dcType)
    swaps.append(swap4)

    maturity_date = settlement_date.addMonths(72)
    swap5 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.014800 + irBump, fixedFreq, dcType)
    swaps.append(swap5)

    maturity_date = settlement_date.addMonths(84)
    swap6 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.014995 + irBump, fixedFreq, dcType)
    swaps.append(swap6)

    maturity_date = settlement_date.addMonths(96)
    swap7 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.015180 + irBump, fixedFreq, dcType)
    swaps.append(swap7)

    maturity_date = settlement_date.addMonths(108)
    swap8 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.015610 + irBump, fixedFreq, dcType)
    swaps.append(swap8)

    maturity_date = settlement_date.addMonths(120)
    swap9 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                        m * 0.015880 + irBump, fixedFreq, dcType)
    swaps.append(swap9)

    maturity_date = settlement_date.addMonths(144)
    swap10 = FinIborSwap(settlement_date, maturity_date, FinSwapTypes.PAY,
                         m * 0.016430 + irBump, fixedFreq, dcType)
    swaps.append(swap10)

    libor_curve = IborSingleCurve(valuation_date, depos, fras, swaps)

    cdsMarketContracts = []

    cdsCoupon = 0.04 + mktSpreadBump

    maturity_date = valuation_date.nextCDSDate(6)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(12)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(24)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(36)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(48)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(60)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(84)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(120)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    maturity_date = valuation_date.nextCDSDate(180)
    cds = FinCDS(valuation_date, maturity_date, cdsCoupon)
    cdsMarketContracts.append(cds)

    recovery_rate = 0.40

    issuer_curve = FinCDSCurve(valuation_date, cdsMarketContracts, libor_curve,
                               recovery_rate)

    return libor_curve, issuer_curve
Esempio n. 18
0
def test_full_priceCDSIndexOption():

    tradeDate = Date(1, 8, 2007)
    step_in_date = tradeDate.addDays(1)
    valuation_date = step_in_date

    libor_curve = buildIborCurve(tradeDate)

    maturity3Y = tradeDate.nextCDSDate(36)
    maturity5Y = tradeDate.nextCDSDate(60)
    maturity7Y = tradeDate.nextCDSDate(84)
    maturity10Y = tradeDate.nextCDSDate(120)

    path = os.path.join(os.path.dirname(__file__),
                        './/data//CDX_NA_IG_S7_SPREADS.csv')
    f = open(path, 'r')
    data = f.readlines()
    f.close()
    issuer_curves = []

    for row in data[1:]:

        splitRow = row.split(",")
        creditName = splitRow[0]
        spd3Y = float(splitRow[1]) / 10000.0
        spd5Y = float(splitRow[2]) / 10000.0
        spd7Y = float(splitRow[3]) / 10000.0
        spd10Y = float(splitRow[4]) / 10000.0
        recovery_rate = float(splitRow[5])

        cds3Y = FinCDS(step_in_date, maturity3Y, spd3Y)
        cds5Y = FinCDS(step_in_date, maturity5Y, spd5Y)
        cds7Y = FinCDS(step_in_date, maturity7Y, spd7Y)
        cds10Y = FinCDS(step_in_date, maturity10Y, spd10Y)
        cds_contracts = [cds3Y, cds5Y, cds7Y, cds10Y]

        issuer_curve = FinCDSCurve(valuation_date, cds_contracts, libor_curve,
                                   recovery_rate)

        issuer_curves.append(issuer_curve)

    ##########################################################################
    ##########################################################################

    indexUpfronts = [0.0, 0.0, 0.0, 0.0]
    indexMaturityDates = [
        Date(20, 12, 2009),
        Date(20, 12, 2011),
        Date(20, 12, 2013),
        Date(20, 12, 2016)
    ]
    indexRecovery = 0.40

    testCases.banner(
        "======================= CDS INDEX OPTION ==========================")

    index_coupon = 0.004
    volatility = 0.50
    expiry_date = Date(1, 2, 2008)
    maturity_date = Date(20, 12, 2011)
    notional = 10000.0
    tolerance = 1e-6

    testCases.header("TIME", "STRIKE", "INDEX", "PAY", "RECEIVER", "G(K)", "X",
                     "EXPH", "ABPAY", "ABREC")

    for index in np.linspace(20, 60, 10):

        #######################################################################

        cds_contracts = []
        for dt in indexMaturityDates:
            cds = FinCDS(valuation_date, dt, index / 10000.0)
            cds_contracts.append(cds)

        index_curve = FinCDSCurve(valuation_date, cds_contracts, libor_curve,
                                  indexRecovery)

        if 1 == 1:

            indexSpreads = [index / 10000.0] * 4

            indexPortfolio = FinCDSIndexPortfolio()
            adjustedIssuerCurves = indexPortfolio.hazardRateAdjustIntrinsic(
                valuation_date, issuer_curves, indexSpreads, indexUpfronts,
                indexMaturityDates, indexRecovery, tolerance)
        else:

            indexSpread = index / 10000.0
            issuer_curve = buildFlatIssuerCurve(tradeDate, libor_curve,
                                                indexSpread, indexRecovery)

            adjustedIssuerCurves = []
            for iCredit in range(0, 125):
                adjustedIssuerCurves.append(issuer_curve)

        #######################################################################

        for strike in np.linspace(20, 60, 20):

            start = time.time()

            option = FinCDSIndexOption(expiry_date, maturity_date,
                                       index_coupon, strike / 10000.0,
                                       notional)

            v_pay_1, v_rec_1, strikeValue, mu, expH = option.valueAnderson(
                valuation_date, adjustedIssuerCurves, indexRecovery,
                volatility)
            end = time.time()
            elapsed = end - start

            end = time.time()

            v_pay_2, v_rec_2 = option.valueAdjustedBlack(
                valuation_date, index_curve, indexRecovery, libor_curve,
                volatility)

            elapsed = end - start

            testCases.print(elapsed, strike, index, v_pay_1, v_rec_1,
                            strikeValue, mu, expH, v_pay_2, v_rec_2)