Ejemplo n.º 1
0
def heston_helpers(spot, df_option, dtTrade, df_rates):
    """
    Create array of heston options helpers
    """

    DtSettlement = dateToQLDate(dtTrade)
    
    settings = Settings()
    settings.evaluation_date = DtSettlement

    calendar = TARGET()

    # convert data frame (date/value) into zero curve
    # expect the index to be a date, and 1 column of values

    risk_free_ts = dfToZeroCurve(df_rates['iRate'], dtTrade)
    dividend_ts = dfToZeroCurve(df_rates['iDiv'], dtTrade)

    # loop through rows in option data frame, construct
    # helpers for bid/ask

    oneDay = datetime.timedelta(days=1)
    dtExpiry = [dtTrade + int(t*365)*oneDay for t in df_option['TTM']]
    df_option['dtExpiry'] = dtExpiry

    options = []
    for index, row in df_option.T.iteritems():

        strike = row['Strike']
        if (strike/spot.value > 1.3) | (strike/spot.value < .7):
            continue

        days = int(365*row['TTM'])
        maturity = Period(days, Days)

        options.append(
                HestonModelHelper(
                    maturity, calendar, spot.value,
                    strike, SimpleQuote(row['IVBid']),
                    risk_free_ts, dividend_ts,
                    ImpliedVolError))
        
        options.append(
                HestonModelHelper(
                    maturity, calendar, spot.value,
                    strike, SimpleQuote(row['IVAsk']),
                    risk_free_ts, dividend_ts,
                    ImpliedVolError))

    return {'options':options, 'spot': spot}
Ejemplo n.º 2
0
    def test_heston_hw_calibration(self):
        """
        From Quantlib test suite
        """

        print("Testing Heston Hull-White calibration...")

        ## Calibration of a hybrid Heston-Hull-White model using
        ## the finite difference HestonHullWhite pricing engine
        ## Input surface is based on a Heston-Hull-White model with
        ## Hull-White: a = 0.00883, \sigma = 0.00631
        ## Heston    : \nu = 0.12, \kappa = 2.0,
        ##             \theta = 0.09, \sigma = 0.5, \rho=-0.75
        ## Equity Short rate correlation: -0.5

        dc = Actual365Fixed()
        calendar = TARGET()
        todays_date = Date(28, March, 2004)
        settings = Settings()
        settings.evaluation_date = todays_date

        r_ts = flat_rate(todays_date, 0.05, dc)

        ## assuming, that the Hull-White process is already calibrated
        ## on a given set of pure interest rate calibration instruments.

        hw_process = HullWhiteProcess(r_ts, a=0.00883, sigma=0.00631)

        q_ts = flat_rate(todays_date, 0.02, dc)
        s0 = SimpleQuote(100.0)

        # vol surface

        strikes = [50, 75, 90, 100, 110, 125, 150, 200]
        maturities = [1 / 12., 3 / 12., 0.5, 1.0, 2.0, 3.0, 5.0, 7.5, 10]

        vol = [
            0.482627, 0.407617, 0.366682, 0.340110, 0.314266, 0.280241,
            0.252471, 0.325552, 0.464811, 0.393336, 0.354664, 0.329758,
            0.305668, 0.273563, 0.244024, 0.244886, 0.441864, 0.375618,
            0.340464, 0.318249, 0.297127, 0.268839, 0.237972, 0.225553,
            0.407506, 0.351125, 0.322571, 0.305173, 0.289034, 0.267361,
            0.239315, 0.213761, 0.366761, 0.326166, 0.306764, 0.295279,
            0.284765, 0.270592, 0.250702, 0.222928, 0.345671, 0.314748,
            0.300259, 0.291744, 0.283971, 0.273475, 0.258503, 0.235683,
            0.324512, 0.303631, 0.293981, 0.288338, 0.283193, 0.276248,
            0.266271, 0.250506, 0.311278, 0.296340, 0.289481, 0.285482,
            0.281840, 0.276924, 0.269856, 0.258609, 0.303219, 0.291534,
            0.286187, 0.283073, 0.280239, 0.276414, 0.270926, 0.262173
        ]

        start_v0 = 0.2 * 0.2
        start_theta = start_v0
        start_kappa = 0.5
        start_sigma = 0.25
        start_rho = -0.5

        equityShortRateCorr = -0.5

        corrConstraint = HestonHullWhiteCorrelationConstraint(
            equityShortRateCorr)

        heston_process = HestonProcess(r_ts, q_ts, s0, start_v0, start_kappa,
                                       start_theta, start_sigma, start_rho)

        h_model = HestonModel(heston_process)
        h_engine = AnalyticHestonEngine(h_model)

        options = []

        # first calibrate a heston model to get good initial
        # parameters

        for i in range(len(maturities)):
            maturity = Period(int(maturities[i] * 12.0 + 0.5), Months)

            for j, s in enumerate(strikes):

                v = SimpleQuote(vol[i * len(strikes) + j])

                helper = HestonModelHelper(maturity, calendar, s0.value, s, v,
                                           r_ts, q_ts, PriceError)

                helper.set_pricing_engine(h_engine)

                options.append(helper)

        om = LevenbergMarquardt(1e-6, 1e-8, 1e-8)

        # Heston model
        h_model.calibrate(options, om,
                          EndCriteria(400, 40, 1.0e-8, 1.0e-4, 1.0e-8))

        print("Heston calibration")
        print("v0: %f" % h_model.v0)
        print("theta: %f" % h_model.theta)
        print("kappa: %f" % h_model.kappa)
        print("sigma: %f" % h_model.sigma)
        print("rho: %f" % h_model.rho)

        h_process_2 = HestonProcess(r_ts, q_ts, s0, h_model.v0, h_model.kappa,
                                    h_model.theta, h_model.sigma, h_model.rho)

        hhw_model = HestonModel(h_process_2)

        options = []
        for i in range(len(maturities)):

            tGrid = np.max((10.0, maturities[i] * 10.0))
            hhw_engine = FdHestonHullWhiteVanillaEngine(
                hhw_model, hw_process, equityShortRateCorr, tGrid, 61, 13, 9,
                0, True, FdmSchemeDesc.Hundsdorfer())

            hhw_engine.enable_multiple_strikes_caching(strikes)

            maturity = Period(int(maturities[i] * 12.0 + 0.5), Months)

            # multiple strikes engine works best if the first option
            # per maturity has the average strike (because the first
            # option is priced first during the calibration and
            # the first pricing is used to calculate the prices
            # for all strikes

            # list of strikes by distance from moneyness

            indx = np.argsort(np.abs(np.array(strikes) - s0.value))

            for j, tmp in enumerate(indx):
                js = indx[j]
                s = strikes[js]
                v = SimpleQuote(vol[i * len(strikes) + js])
                helper = HestonModelHelper(maturity, calendar, s0.value,
                                           strikes[js], v, r_ts, q_ts,
                                           PriceError)
                helper.set_pricing_engine(hhw_engine)
                options.append(helper)

        vm = LevenbergMarquardt(1e-6, 1e-2, 1e-2)

        hhw_model.calibrate(options, vm,
                            EndCriteria(400, 40, 1.0e-8, 1.0e-4, 1.0e-8),
                            corrConstraint)

        print("Heston HW calibration with FD engine")
        print("v0: %f" % hhw_model.v0)
        print("theta: %f" % hhw_model.theta)
        print("kappa: %f" % hhw_model.kappa)
        print("sigma: %f" % hhw_model.sigma)
        print("rho: %f" % hhw_model.rho)

        relTol = 0.05
        expected_v0 = 0.12
        expected_kappa = 2.0
        expected_theta = 0.09
        expected_sigma = 0.5
        expected_rho = -0.75

        self.assertAlmostEquals(np.abs(hhw_model.v0 - expected_v0) /
                                expected_v0,
                                0,
                                delta=relTol)

        self.assertAlmostEquals(np.abs(hhw_model.theta - expected_theta) /
                                expected_theta,
                                0,
                                delta=relTol)

        self.assertAlmostEquals(np.abs(hhw_model.kappa - expected_kappa) /
                                expected_kappa,
                                0,
                                delta=relTol)

        self.assertAlmostEquals(np.abs(hhw_model.sigma - expected_sigma) /
                                expected_sigma,
                                0,
                                delta=relTol)

        self.assertAlmostEquals(np.abs(hhw_model.rho - expected_rho) /
                                expected_rho,
                                0,
                                delta=relTol)
Ejemplo n.º 3
0
def heston_helpers(df_option, dtTrade=None, df_rates=None, ival=None):
    """
    Create array of heston options helpers
    """

    if dtTrade is None:
        dtTrade = df_option['dtTrade'][0]
    DtSettlement = pydate_to_qldate(dtTrade)

    settings = Settings()
    settings.evaluation_date = DtSettlement

    calendar = TARGET()

    if df_rates is None:
        df_tmp = DataFrame.filter(df_option, items=['dtExpiry', 'IR', 'IDIV'])
        grouped = df_tmp.groupby('dtExpiry')
        df_rates = grouped.agg(lambda x: x[0])

    # convert data frame (date/value) into zero curve
    # expect the index to be a date, and 1 column of values

    risk_free_ts = df_to_zero_curve(df_rates['R'], dtTrade)
    dividend_ts = df_to_zero_curve(df_rates['D'], dtTrade)

    # back out the spot from any forward
    iRate = df_option['R'][0]
    iDiv = df_option['D'][0]
    TTM = df_option['T'][0]
    Fwd = df_option['F'][0]
    spot = SimpleQuote(Fwd * np.exp(-(iRate - iDiv) * TTM))
    print('Spot: %f risk-free rate: %f div. yield: %f' % \
          (spot.value, iRate, iDiv))

    # loop through rows in option data frame, construct
    # helpers for bid/ask

    oneDay = datetime.timedelta(days=1)
    dtExpiry = [dtTrade + int(t * 365) * oneDay for t in df_option['T']]
    df_option['dtExpiry'] = dtExpiry

    options = []
    for index, row in df_option.T.iteritems():

        strike = row['K']
        if (strike / spot.value > 1.3) | (strike / spot.value < .7):
            continue

        days = int(365 * row['T'])
        maturity = Period(days, Days)

        options.append(
            HestonModelHelper(maturity, calendar, spot.value, strike,
                              SimpleQuote(row['VB']), risk_free_ts,
                              dividend_ts, ImpliedVolError))

        options.append(
            HestonModelHelper(maturity, calendar, spot.value, strike,
                              SimpleQuote(row['VA']), risk_free_ts,
                              dividend_ts, ImpliedVolError))

    return {'options': options, 'spot': spot}
Ejemplo n.º 4
0
    def test_black_calibration(self):

        # calibrate a Heston model to a constant volatility surface without
        # smile. expected result is a vanishing volatility of the volatility.
        # In addition theta and v0 should be equal to the constant variance

        todays_date = today()

        self.settings.evaluation_date = todays_date

        daycounter = Actual360()
        calendar = NullCalendar()

        risk_free_ts = flat_rate(0.04, daycounter)
        dividend_ts = flat_rate(0.50, daycounter)

        option_maturities = [
            Period(1, Months),
            Period(2, Months),
            Period(3, Months),
            Period(6, Months),
            Period(9, Months),
            Period(1, Years),
            Period(2, Years)
        ]

        options = []

        s0 = SimpleQuote(1.0)
        vol = SimpleQuote(0.1)

        volatility = vol.value

        for maturity in option_maturities:
            for moneyness in np.arange(-1.0, 2.0, 1.):
                tau = daycounter.year_fraction(
                    risk_free_ts.reference_date,
                    calendar.advance(
                        risk_free_ts.reference_date,
                        period=maturity)
                )
                forward_price = s0.value * dividend_ts.discount(tau) / \
                                risk_free_ts.discount(tau)
                strike_price = forward_price * np.exp(
                    -moneyness * volatility * np.sqrt(tau)
                )
                options.append(
                    HestonModelHelper(
                        maturity, calendar, s0.value, strike_price, vol,
                        risk_free_ts, dividend_ts
                    )
                )

        for sigma in np.arange(0.1, 0.7, 0.2):
            v0    = 0.01
            kappa = 0.2
            theta = 0.02
            rho   = -0.75

            process = HestonProcess(
                risk_free_ts, dividend_ts, s0, v0, kappa, theta, sigma, rho
            )

            self.assertEqual(v0, process.v0)
            self.assertEqual(kappa, process.kappa)
            self.assertEqual(theta, process.theta)
            self.assertEqual(sigma, process.sigma)
            self.assertEqual(rho, process.rho)
            self.assertEqual(1.0, process.s0.value)

            model = HestonModel(process)
            engine = AnalyticHestonEngine(model, 96)

            for option in options:
                option.set_pricing_engine(engine)

            optimisation_method = LevenbergMarquardt(1e-8, 1e-8, 1e-8)

            end_criteria = EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8)
            model.calibrate(options, optimisation_method, end_criteria)

            tolerance = 3.0e-3

            self.assertFalse(model.sigma > tolerance)

            self.assertAlmostEqual(
                model.kappa * model.theta,
                model.kappa * volatility ** 2,
                delta=tolerance
            )
            self.assertAlmostEqual(model.v0, volatility ** 2, delta=tolerance)
Ejemplo n.º 5
0
    def test_DAX_calibration(self):

        # this example is taken from A. Sepp
        # Pricing European-Style Options under Jump Diffusion Processes
        # with Stochstic Volatility: Applications of Fourier Transform
        # http://math.ut.ee/~spartak/papers/stochjumpvols.pdf

        settlement_date = Date(5, July, 2002)

        self.settings.evaluation_date = settlement_date

        daycounter = Actual365Fixed()
        calendar = TARGET()

        t = [13, 41, 75, 165, 256, 345, 524, 703]
        r = [0.0357,0.0349,0.0341,0.0355,0.0359,0.0368,0.0386,0.0401]

        dates = [settlement_date] + [settlement_date + val for val in t]
        rates = [0.0357] + r

        risk_free_ts = ZeroCurve(dates, rates, daycounter)
        dividend_ts = FlatForward(
            settlement_date, forward=0.0, daycounter=daycounter
        )

        v = [
            0.6625,0.4875,0.4204,0.3667,0.3431,0.3267,0.3121,0.3121,
            0.6007,0.4543,0.3967,0.3511,0.3279,0.3154,0.2984,0.2921,
            0.5084,0.4221,0.3718,0.3327,0.3155,0.3027,0.2919,0.2889,
            0.4541,0.3869,0.3492,0.3149,0.2963,0.2926,0.2819,0.2800,
            0.4060,0.3607,0.3330,0.2999,0.2887,0.2811,0.2751,0.2775,
            0.3726,0.3396,0.3108,0.2781,0.2788,0.2722,0.2661,0.2686,
            0.3550,0.3277,0.3012,0.2781,0.2781,0.2661,0.2661,0.2681,
            0.3428,0.3209,0.2958,0.2740,0.2688,0.2627,0.2580,0.2620,
            0.3302,0.3062,0.2799,0.2631,0.2573,0.2533,0.2504,0.2544,
            0.3343,0.2959,0.2705,0.2540,0.2504,0.2464,0.2448,0.2462,
            0.3460,0.2845,0.2624,0.2463,0.2425,0.2385,0.2373,0.2422,
            0.3857,0.2860,0.2578,0.2399,0.2357,0.2327,0.2312,0.2351,
            0.3976,0.2860,0.2607,0.2356,0.2297,0.2268,0.2241,0.2320
        ]

        s0 = SimpleQuote(4468.17)
        strikes = [
            3400, 3600, 3800, 4000, 4200, 4400, 4500, 4600, 4800, 5000, 5200,
            5400, 5600
        ]

        options = []

        for s, strike in enumerate(strikes):
            for m in range(len(t)):
                vol = SimpleQuote(v[s * 8 + m])
                # round to weeks
                maturity = Period((int)((t[m] + 3) / 7.), Weeks)
                options.append(
                    HestonModelHelper(
                        maturity, calendar, s0.value, strike, vol,
                        risk_free_ts, dividend_ts,
                        ImpliedVolError
                    )
                )

        v0    = 0.1
        kappa = 1.0
        theta = 0.1
        sigma = 0.5
        rho   = -0.5

        process = HestonProcess(
            risk_free_ts, dividend_ts, s0, v0, kappa, theta, sigma, rho
        )

        model = HestonModel(process)

        engine = AnalyticHestonEngine(model, 64)

        for option in options:
            option.set_pricing_engine(engine)

        om = LevenbergMarquardt(1e-8, 1e-8, 1e-8)

        model.calibrate(
            options, om, EndCriteria(400, 40, 1.0e-8, 1.0e-8, 1.0e-8)
        )

        sse = 0
        for i in range(len(strikes) * len(t)):
            diff = options[i].calibration_error() * 100.0
            sse += diff * diff

        expected = 177.2  # see article by A. Sepp.
        self.assertAlmostEqual(expected, sse, delta=1.0)
Ejemplo n.º 6
0
    def test_heston_hw_calibration(self):
        """
        From Quantlib test suite
        """

        print("Testing Heston Hull-White calibration...")

        ## Calibration of a hybrid Heston-Hull-White model using
        ## the finite difference HestonHullWhite pricing engine
        ## Input surface is based on a Heston-Hull-White model with
        ## Hull-White: a = 0.00883, \sigma = 0.00631
        ## Heston    : \nu = 0.12, \kappa = 2.0,
        ##             \theta = 0.09, \sigma = 0.5, \rho=-0.75
        ## Equity Short rate correlation: -0.5

        dc = Actual365Fixed()
        calendar = TARGET()
        todays_date = Date(28, March, 2004)
        settings = Settings()
        settings.evaluation_date = todays_date

        r_ts = flat_rate(todays_date, 0.05, dc)

        ## assuming, that the Hull-White process is already calibrated
        ## on a given set of pure interest rate calibration instruments.

        hw_process = HullWhiteProcess(r_ts, a=0.00883, sigma=0.00631)

        q_ts = flat_rate(todays_date, 0.02, dc)
        s0 = SimpleQuote(100.0)

        # vol surface

        strikes    = [50, 75, 90, 100, 110, 125, 150, 200]
        maturities = [1 / 12., 3 / 12., 0.5, 1.0, 2.0, 3.0, 5.0, 7.5, 10]

        vol = [
        0.482627,0.407617,0.366682,0.340110,0.314266,0.280241,0.252471,0.325552,
        0.464811,0.393336,0.354664,0.329758,0.305668,0.273563,0.244024,0.244886,
        0.441864,0.375618,0.340464,0.318249,0.297127,0.268839,0.237972,0.225553,
        0.407506,0.351125,0.322571,0.305173,0.289034,0.267361,0.239315,0.213761,
        0.366761,0.326166,0.306764,0.295279,0.284765,0.270592,0.250702,0.222928,
        0.345671,0.314748,0.300259,0.291744,0.283971,0.273475,0.258503,0.235683,
        0.324512,0.303631,0.293981,0.288338,0.283193,0.276248,0.266271,0.250506,
        0.311278,0.296340,0.289481,0.285482,0.281840,0.276924,0.269856,0.258609,
        0.303219,0.291534,0.286187,0.283073,0.280239,0.276414,0.270926,0.262173]

        start_v0    = 0.2 * 0.2
        start_theta = start_v0
        start_kappa = 0.5
        start_sigma = 0.25
        start_rho   = -0.5

        equityShortRateCorr = -0.5

        corrConstraint = HestonHullWhiteCorrelationConstraint(
            equityShortRateCorr)

        heston_process = HestonProcess(r_ts, q_ts, s0, start_v0, start_kappa,
                                       start_theta, start_sigma, start_rho)

        h_model = HestonModel(heston_process)
        h_engine = AnalyticHestonEngine(h_model)

        options = []

        # first calibrate a heston model to get good initial
        # parameters

        for i in range(len(maturities)):
            maturity = Period(int(maturities[i] * 12.0 + 0.5), Months)

            for j, s in enumerate(strikes):

                v = SimpleQuote(vol[i * len(strikes) + j])

                helper = HestonModelHelper(maturity, calendar, s0.value,
                                           s, v, r_ts, q_ts,
                                           PriceError)

                helper.set_pricing_engine(h_engine)

                options.append(helper)

        om = LevenbergMarquardt(1e-6, 1e-8, 1e-8)

        # Heston model
        h_model.calibrate(options, om,
                          EndCriteria(400, 40, 1.0e-8,
                                      1.0e-4, 1.0e-8))

        print("Heston calibration")
        print("v0: %f" % h_model.v0)
        print("theta: %f" % h_model.theta)
        print("kappa: %f" % h_model.kappa)
        print("sigma: %f" % h_model.sigma)
        print("rho: %f" % h_model.rho)

        h_process_2 = HestonProcess(r_ts, q_ts, s0, h_model.v0,
                                    h_model.kappa,
                                    h_model.theta,
                                    h_model.sigma,
                                    h_model.rho)

        hhw_model = HestonModel(h_process_2)

        options = []
        for i in range(len(maturities)):

            tGrid = np.max((10.0, maturities[i] * 10.0))
            hhw_engine = FdHestonHullWhiteVanillaEngine(
                hhw_model, hw_process,
                equityShortRateCorr,
                tGrid, 61, 13, 9, 0, True, FdmSchemeDesc.Hundsdorfer())

            hhw_engine.enable_multiple_strikes_caching(strikes)

            maturity = Period(int(maturities[i] * 12.0 + 0.5), Months)

            # multiple strikes engine works best if the first option
            # per maturity has the average strike (because the first
            # option is priced first during the calibration and
            # the first pricing is used to calculate the prices
            # for all strikes

            # list of strikes by distance from moneyness

            indx = np.argsort(np.abs(np.array(strikes) - s0.value))

            for j, tmp in enumerate(indx):
                js = indx[j]
                s = strikes[js]
                v = SimpleQuote(vol[i * len(strikes) + js])
                helper = HestonModelHelper(maturity,
                                           calendar, s0.value,
                                           strikes[js], v, r_ts, q_ts,
                                           PriceError)
                helper.set_pricing_engine(hhw_engine)
                options.append(helper)

        vm = LevenbergMarquardt(1e-6, 1e-2, 1e-2)

        hhw_model.calibrate(options, vm,
                            EndCriteria(400, 40, 1.0e-8, 1.0e-4, 1.0e-8),
                            corrConstraint)

        print("Heston HW calibration with FD engine")
        print("v0: %f" % hhw_model.v0)
        print("theta: %f" % hhw_model.theta)
        print("kappa: %f" % hhw_model.kappa)
        print("sigma: %f" % hhw_model.sigma)
        print("rho: %f" % hhw_model.rho)

        relTol = 0.05
        expected_v0 = 0.12
        expected_kappa = 2.0
        expected_theta = 0.09
        expected_sigma = 0.5
        expected_rho = -0.75

        self.assertAlmostEqual(
            np.abs(hhw_model.v0 - expected_v0) / expected_v0, 0,
            delta=relTol)

        self.assertAlmostEqual(
            np.abs(hhw_model.theta - expected_theta) / expected_theta, 0,
            delta=relTol)

        self.assertAlmostEqual(
            np.abs(hhw_model.kappa - expected_kappa) / expected_kappa, 0,
            delta=relTol)

        self.assertAlmostEqual(
            np.abs(hhw_model.sigma - expected_sigma) / expected_sigma, 0,
            delta=relTol)

        self.assertAlmostEqual(
            np.abs(hhw_model.rho - expected_rho) / expected_rho, 0,
            delta=relTol)