public virtual void recovery_test_blackSurface()
        {
            SurfaceIborCapletFloorletVolatilityBootstrapDefinition definition = SurfaceIborCapletFloorletVolatilityBootstrapDefinition.of(IborCapletFloorletVolatilitiesName.of("test"), USD_LIBOR_3M, ACT_ACT_ISDA, LINEAR, LINEAR);
            DoubleArray   strikes = createBlackStrikes();
            RawOptionData data    = RawOptionData.of(createBlackMaturities(), strikes, ValueType.STRIKE, createFullBlackDataMatrix(), ValueType.BLACK_VOLATILITY);
            IborCapletFloorletVolatilityCalibrationResult   res    = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
            BlackIborCapletFloorletExpiryStrikeVolatilities resVol = (BlackIborCapletFloorletExpiryStrikeVolatilities)res.Volatilities;

            for (int i = 0; i < strikes.size(); ++i)
            {
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, resVol).Amount;
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL);
                }
            }
            assertEquals(res.ChiSquare, 0d);
            assertEquals(resVol.Index, USD_LIBOR_3M);
            assertEquals(resVol.Name, definition.Name);
            assertEquals(resVol.ValuationDateTime, CALIBRATION_TIME);
            InterpolatedNodalSurface surface = (InterpolatedNodalSurface)resVol.Surface;

            for (int i = 0; i < surface.ParameterCount; ++i)
            {
                GenericVolatilitySurfacePeriodParameterMetadata metadata = (GenericVolatilitySurfacePeriodParameterMetadata)surface.getParameterMetadata(i);
                assertEquals(metadata.Strike.Value, surface.YValues.get(i));
            }
        }
        public virtual void test_recovery_black_fixedRho()
        {
            SabrIborCapletFloorletVolatilityBootstrapDefinition definition = SabrIborCapletFloorletVolatilityBootstrapDefinition.ofFixedRho(IborCapletFloorletVolatilitiesName.of("test"), USD_LIBOR_3M, ACT_ACT_ISDA, 0.0, CurveInterpolators.STEP_UPPER, CurveExtrapolators.FLAT, CurveExtrapolators.FLAT, SabrHaganVolatilityFunctionProvider.DEFAULT);
            DoubleMatrix  volData    = createFullBlackDataMatrix();
            double        errorValue = 1.0e-3;
            DoubleMatrix  error      = DoubleMatrix.filled(volData.rowCount(), volData.columnCount(), errorValue);
            RawOptionData data       = RawOptionData.of(createBlackMaturities(), createBlackStrikes(), ValueType.STRIKE, volData, error, ValueType.BLACK_VOLATILITY);
            IborCapletFloorletVolatilityCalibrationResult res     = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
            SabrParametersIborCapletFloorletVolatilities  resVols = (SabrParametersIborCapletFloorletVolatilities)res.Volatilities;
            double expSq = 0d;

            for (int i = 0; i < NUM_BLACK_STRIKES; ++i)
            {
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_SABR.presentValue(caps[j], RATES_PROVIDER, resVols).Amount;
                    expSq += Math.Pow((priceOrg - priceCalib) / priceOrg / errorValue, 2);
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL * 3d);
                }
            }
            assertEquals(res.ChiSquare, expSq, expSq * 1.0e-14);
            assertEquals(resVols.Index, USD_LIBOR_3M);
            assertEquals(resVols.Name, definition.Name);
            assertEquals(resVols.ValuationDateTime, CALIBRATION_TIME);
            assertEquals(resVols.Parameters.ShiftCurve, definition.ShiftCurve);
            assertEquals(resVols.Parameters.RhoCurve, definition.RhoCurve.get());
        }
Example #3
0
        public virtual void recovery_test_black_fixedRho()
        {
            double rho = 0.15;
            SabrIborCapletFloorletVolatilityCalibrationDefinition definition = SabrIborCapletFloorletVolatilityCalibrationDefinition.ofFixedRho(NAME, USD_LIBOR_3M, ACT_ACT_ISDA, rho, ALPHA_KNOTS, BETA_RHO_KNOTS, NU_KNOTS, DOUBLE_QUADRATIC, FLAT, FLAT, HAGAN);
            ImmutableList <Period> maturities = createBlackMaturities();
            DoubleArray            strikes    = createBlackStrikes();
            DoubleMatrix           volData    = createFullBlackDataMatrix();
            DoubleMatrix           error      = DoubleMatrix.filled(volData.rowCount(), volData.columnCount(), 1.0e-3);
            RawOptionData          data       = RawOptionData.of(maturities, strikes, ValueType.STRIKE, volData, error, ValueType.BLACK_VOLATILITY);
            IborCapletFloorletVolatilityCalibrationResult res     = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
            SabrParametersIborCapletFloorletVolatilities  resVols = (SabrParametersIborCapletFloorletVolatilities)res.Volatilities;

            for (int i = 0; i < NUM_BLACK_STRIKES; ++i)
            {
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_SABR.presentValue(caps[j], RATES_PROVIDER, resVols).Amount;
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL * 5d);
                }
            }
            assertEquals(resVols.Index, USD_LIBOR_3M);
            assertEquals(resVols.Name, definition.Name);
            assertEquals(resVols.ValuationDateTime, CALIBRATION_TIME);
            assertEquals(resVols.ParameterCount, ALPHA_KNOTS.size() + BETA_RHO_KNOTS.size() + NU_KNOTS.size() + 2);     // beta, shift counted
            assertEquals(resVols.Parameters.ShiftCurve, definition.ShiftCurve);
            assertEquals(resVols.Parameters.RhoCurve, definition.RhoCurve.get());
        }
        public virtual void recovery_test_blackCurve()
        {
            SurfaceIborCapletFloorletVolatilityBootstrapDefinition definition = SurfaceIborCapletFloorletVolatilityBootstrapDefinition.of(IborCapletFloorletVolatilitiesName.of("test"), USD_LIBOR_3M, ACT_ACT_ISDA, LINEAR, LINEAR);
            DoubleArray strikes = createBlackStrikes();

            for (int i = 0; i < strikes.size(); ++i)
            {
                Pair <IList <Period>, DoubleMatrix> trimedData = trimData(createBlackMaturities(), createBlackDataMatrixForStrike(i));
                RawOptionData data = RawOptionData.of(trimedData.First, DoubleArray.of(strikes.get(i)), ValueType.STRIKE, trimedData.Second, ValueType.BLACK_VOLATILITY);
                IborCapletFloorletVolatilityCalibrationResult           res         = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
                BlackIborCapletFloorletExpiryStrikeVolatilities         resVol      = (BlackIborCapletFloorletExpiryStrikeVolatilities)res.Volatilities;
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, resVol).Amount;
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL);
                }
            }
        }
        public virtual void recovery_test_shiftedBlack()
        {
            double        lambdaT    = 0.07;
            double        lambdaK    = 0.07;
            double        error      = 1.0e-5;
            ConstantCurve shiftCurve = ConstantCurve.of("Black shift", 0.02);
            DirectIborCapletFloorletVolatilityDefinition definition = DirectIborCapletFloorletVolatilityDefinition.of(NAME, USD_LIBOR_3M, ACT_ACT_ISDA, lambdaT, lambdaK, INTERPOLATOR, shiftCurve);
            ImmutableList <Period> maturities  = createBlackMaturities();
            DoubleArray            strikes     = createBlackStrikes();
            DoubleMatrix           errorMatrix = DoubleMatrix.filled(maturities.size(), strikes.size(), error);
            RawOptionData          data        = RawOptionData.of(maturities, strikes, STRIKE, createFullBlackDataMatrix(), errorMatrix, BLACK_VOLATILITY);
            IborCapletFloorletVolatilityCalibrationResult          res     = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
            ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities resVols = (ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities)res.Volatilities;

            for (int i = 0; i < NUM_BLACK_STRIKES; ++i)
            {
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, resVols).Amount;
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL);
                }
            }
            assertTrue(res.ChiSquare > 0d);
            assertEquals(resVols.Index, USD_LIBOR_3M);
            assertEquals(resVols.Name, definition.Name);
            assertEquals(resVols.ValuationDateTime, CALIBRATION_TIME);
            assertEquals(resVols.ShiftCurve, definition.ShiftCurve.get());
        }
Example #6
0
        public virtual void recovery_test_flat()
        {
            DoubleArray initial = DoubleArray.of(0.4, 0.95, 0.5, 0.05);
            SabrIborCapletFloorletVolatilityCalibrationDefinition definition = SabrIborCapletFloorletVolatilityCalibrationDefinition.ofFixedBeta(NAME, USD_LIBOR_3M, ACT_ACT_ISDA, ALPHA_KNOTS, BETA_RHO_KNOTS, NU_KNOTS, initial, LINEAR, FLAT, FLAT, HAGAN);
            DoubleArray   strikes = createBlackStrikes();
            RawOptionData data    = RawOptionData.of(createBlackMaturities(), strikes, ValueType.STRIKE, createFullFlatBlackDataMatrix(), ValueType.BLACK_VOLATILITY);
            IborCapletFloorletVolatilityCalibrationResult res    = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
            SabrIborCapletFloorletVolatilities            resVol = (SabrIborCapletFloorletVolatilities)res.Volatilities;

            for (int i = 0; i < NUM_BLACK_STRIKES; ++i)
            {
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsFlatBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_SABR.presentValue(caps[j], RATES_PROVIDER, resVol).Amount;
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL);
                }
            }
        }
Example #7
0
        //-------------------------------------------------------------------------
        public SurfaceMetadata createMetadata(RawOptionData capFloorData)
        {
            IList <GenericVolatilitySurfacePeriodParameterMetadata> list = new List <GenericVolatilitySurfacePeriodParameterMetadata>();
            ImmutableList <Period> expiries = capFloorData.Expiries;
            int         nExpiries           = expiries.size();
            DoubleArray strikes             = capFloorData.Strikes;
            int         nStrikes            = strikes.size();

            for (int i = 0; i < nExpiries; ++i)
            {
                for (int j = 0; j < nStrikes; ++j)
                {
                    if (Double.isFinite(capFloorData.Data.get(i, j)))
                    {
                        list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(expiries.get(i), SimpleStrike.of(strikes.get(j))));
                    }
                }
            }
            SurfaceMetadata metadata;

            if (capFloorData.DataType.Equals(ValueType.BLACK_VOLATILITY))
            {
                metadata = Surfaces.blackVolatilityByExpiryStrike(name.Name, dayCount);
            }
            else if (capFloorData.DataType.Equals(ValueType.NORMAL_VOLATILITY))
            {
                metadata = Surfaces.normalVolatilityByExpiryStrike(name.Name, dayCount);
            }
            else
            {
                throw new System.ArgumentException("Data type not supported");
            }
            return(metadata.withParameterMetadata(list));
        }
        public virtual void test_createMetadata()
        {
            SabrIborCapletFloorletVolatilityCalibrationDefinition @base = SabrIborCapletFloorletVolatilityCalibrationDefinition.ofFixedBeta(NAME, USD_LIBOR_3M, ACT_365F, BETA_RHO, ALPHA_KNOTS, BETA_RHO_KNOTS, NU_KNOTS, DOUBLE_QUADRATIC, FLAT, LINEAR, HAGAN);

            assertEquals(@base.createMetadata(SAMPLE_BLACK), Surfaces.blackVolatilityByExpiryStrike(NAME.Name, ACT_365F));
            assertEquals(@base.createMetadata(SAMPLE_NORMAL), Surfaces.normalVolatilityByExpiryStrike(NAME.Name, ACT_365F));
            assertThrowsIllegalArg(() => @base.createMetadata(RawOptionData.of(EXPIRIES, STRIKES, STRIKE, DATA, ValueType.PRICE)));
        }
        static ShiftedBlackIborCapletFloorletExpiryStrikeVolatilitiesTest()
        {
            IList <GenericVolatilitySurfaceYearFractionParameterMetadata> list = new List <GenericVolatilitySurfaceYearFractionParameterMetadata>();
            int nData = TIME.size();

            for (int i = 0; i < nData; ++i)
            {
                GenericVolatilitySurfaceYearFractionParameterMetadata parameterMetadata = GenericVolatilitySurfaceYearFractionParameterMetadata.of(TIME.get(i), SimpleStrike.of(STRIKE.get(i)));
                list.Add(parameterMetadata);
            }
            METADATA = Surfaces.blackVolatilityByExpiryStrike("CAP_VOL", ACT_365F).withParameterMetadata(list);
        }
Example #10
0
        //-------------------------------------------------------------------------
        public SurfaceMetadata createMetadata(RawOptionData capFloorData)
        {
            SurfaceMetadata metadata;

            if (capFloorData.DataType.Equals(BLACK_VOLATILITY))
            {
                metadata = Surfaces.blackVolatilityByExpiryStrike(name.Name, dayCount);
            }
            else if (capFloorData.DataType.Equals(NORMAL_VOLATILITY))
            {
                metadata = Surfaces.normalVolatilityByExpiryStrike(name.Name, dayCount);
            }
            else
            {
                throw new System.ArgumentException("Data type not supported");
            }
            return(metadata);
        }
Example #11
0
        public virtual void test_createMetadata_black()
        {
            SurfaceIborCapletFloorletVolatilityBootstrapDefinition @base = SurfaceIborCapletFloorletVolatilityBootstrapDefinition.of(NAME, USD_LIBOR_3M, ACT_ACT_ISDA, LINEAR, DOUBLE_QUADRATIC);
            RawOptionData capData = RawOptionData.of(ImmutableList.of(Period.ofYears(1), Period.ofYears(5)), DoubleArray.of(0.005, 0.01, 0.015), ValueType.STRIKE, DoubleMatrix.copyOf(new double[][]
            {
                new double[] { 0.15, 0.12, 0.13 },
                new double[] { 0.1, 0.08, 0.09 }
            }), ValueType.BLACK_VOLATILITY);
            IList <GenericVolatilitySurfacePeriodParameterMetadata> list = new List <GenericVolatilitySurfacePeriodParameterMetadata>();

            list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(Period.ofYears(1), SimpleStrike.of(0.005)));
            list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(Period.ofYears(1), SimpleStrike.of(0.01)));
            list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(Period.ofYears(1), SimpleStrike.of(0.015)));
            list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(Period.ofYears(5), SimpleStrike.of(0.005)));
            list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(Period.ofYears(5), SimpleStrike.of(0.01)));
            list.Add(GenericVolatilitySurfacePeriodParameterMetadata.of(Period.ofYears(5), SimpleStrike.of(0.015)));
            SurfaceMetadata expected = Surfaces.blackVolatilityByExpiryStrike(NAME.Name, ACT_ACT_ISDA).withParameterMetadata(list);
            SurfaceMetadata computed = @base.createMetadata(capData);

            assertEquals(computed, expected);
        }
        public virtual void test_recovery_flatVol()
        {
            double beta = 0.8;
            SabrIborCapletFloorletVolatilityBootstrapDefinition definition = SabrIborCapletFloorletVolatilityBootstrapDefinition.ofFixedBeta(IborCapletFloorletVolatilitiesName.of("test"), USD_LIBOR_3M, ACT_ACT_ISDA, beta, CurveInterpolators.STEP_UPPER, CurveExtrapolators.FLAT, CurveExtrapolators.FLAT, SabrHaganVolatilityFunctionProvider.DEFAULT);
            RawOptionData data = RawOptionData.of(createBlackMaturities(), createBlackStrikes(), ValueType.STRIKE, createFullFlatBlackDataMatrix(), ValueType.BLACK_VOLATILITY);
            IborCapletFloorletVolatilityCalibrationResult res     = CALIBRATOR.calibrate(definition, CALIBRATION_TIME, data, RATES_PROVIDER);
            SabrParametersIborCapletFloorletVolatilities  resVols = (SabrParametersIborCapletFloorletVolatilities)res.Volatilities;

            for (int i = 0; i < NUM_BLACK_STRIKES; ++i)
            {
                Pair <IList <ResolvedIborCapFloorLeg>, IList <double> > capsAndVols = getCapsFlatBlackVols(i);
                IList <ResolvedIborCapFloorLeg> caps = capsAndVols.First;
                IList <double> vols  = capsAndVols.Second;
                int            nCaps = caps.Count;
                for (int j = 0; j < nCaps; ++j)
                {
                    ConstantSurface volSurface = ConstantSurface.of(Surfaces.blackVolatilityByExpiryStrike("test", ACT_ACT_ISDA), vols[j]);
                    BlackIborCapletFloorletExpiryStrikeVolatilities constVol = BlackIborCapletFloorletExpiryStrikeVolatilities.of(USD_LIBOR_3M, CALIBRATION_TIME, volSurface);
                    double priceOrg   = LEG_PRICER_BLACK.presentValue(caps[j], RATES_PROVIDER, constVol).Amount;
                    double priceCalib = LEG_PRICER_SABR.presentValue(caps[j], RATES_PROVIDER, resVols).Amount;
                    assertEquals(priceOrg, priceCalib, Math.Max(priceOrg, 1d) * TOL);
                }
            }
        }
Example #13
0
        //-------------------------------------------------------------------------
        public override IborCapletFloorletVolatilityCalibrationResult calibrate(IborCapletFloorletVolatilityDefinition definition, ZonedDateTime calibrationDateTime, RawOptionData capFloorData, RatesProvider ratesProvider)
        {
            ArgChecker.isTrue(ratesProvider.ValuationDate.Equals(calibrationDateTime.toLocalDate()), "valuationDate of ratesProvider should be coherent to calibrationDateTime");
            ArgChecker.isTrue(definition is DirectIborCapletFloorletVolatilityDefinition, "definition should be DirectIborCapletFloorletVolatilityDefinition");
            DirectIborCapletFloorletVolatilityDefinition directDefinition = (DirectIborCapletFloorletVolatilityDefinition)definition;
            // unpack cap data, create node caps
            IborIndex index           = directDefinition.Index;
            LocalDate calibrationDate = calibrationDateTime.toLocalDate();
            LocalDate baseDate        = index.EffectiveDateOffset.adjust(calibrationDate, ReferenceData);
            LocalDate startDate       = baseDate.plus(index.Tenor);

            System.Func <Surface, IborCapletFloorletVolatilities> volatilitiesFunction = this.volatilitiesFunction(directDefinition, calibrationDateTime, capFloorData);
            SurfaceMetadata metadata   = directDefinition.createMetadata(capFloorData);
            IList <Period>  expiries   = capFloorData.Expiries;
            DoubleArray     strikes    = capFloorData.Strikes;
            int             nExpiries  = expiries.Count;
            IList <double>  timeList   = new List <double>();
            IList <double>  strikeList = new List <double>();
            IList <double>  volList    = new List <double>();
            IList <ResolvedIborCapFloorLeg> capList = new List <ResolvedIborCapFloorLeg>();
            IList <double> priceList   = new List <double>();
            IList <double> errorList   = new List <double>();
            DoubleMatrix   errorMatrix = capFloorData.Error.orElse(DoubleMatrix.filled(nExpiries, strikes.size(), 1d));

            int[] startIndex = new int[nExpiries + 1];
            for (int i = 0; i < nExpiries; ++i)
            {
                LocalDate   endDate           = baseDate.plus(expiries[i]);
                DoubleArray volatilityForTime = capFloorData.Data.row(i);
                DoubleArray errorForTime      = errorMatrix.row(i);
                reduceRawData(directDefinition, ratesProvider, capFloorData.Strikes, volatilityForTime, errorForTime, startDate, endDate, metadata, volatilitiesFunction, timeList, strikeList, volList, capList, priceList, errorList);
                startIndex[i + 1] = volList.Count;
                ArgChecker.isTrue(startIndex[i + 1] > startIndex[i], "no valid option data for {}", expiries[i]);
            }
            // create caplet nodes and initial caplet vol surface
            ResolvedIborCapFloorLeg cap = capList[capList.Count - 1];
            int         nCaplets        = cap.CapletFloorletPeriods.size();
            DoubleArray capletExpiries  = DoubleArray.of(nCaplets, n => directDefinition.DayCount.relativeYearFraction(calibrationDate, cap.CapletFloorletPeriods.get(n).FixingDateTime.toLocalDate()));
            Triple <DoubleArray, DoubleArray, DoubleArray> capletNodes;
            DoubleArray initialVols = DoubleArray.copyOf(volList);

            if (directDefinition.ShiftCurve.Present)
            {
                metadata = Surfaces.blackVolatilityByExpiryStrike(directDefinition.Name.Name, directDefinition.DayCount);
                Curve shiftCurve = directDefinition.ShiftCurve.get();
                if (capFloorData.DataType.Equals(NORMAL_VOLATILITY))
                {
                    initialVols = DoubleArray.of(capList.Count, n => volList[n] / (ratesProvider.iborIndexRates(index).rate(capList[n].FinalPeriod.IborRate.Observation) + shiftCurve.yValue(timeList[n])));
                }
                InterpolatedNodalSurface capVolSurface = InterpolatedNodalSurface.of(metadata, DoubleArray.copyOf(timeList), DoubleArray.copyOf(strikeList), initialVols, INTERPOLATOR);
                capletNodes          = createCapletNodes(capVolSurface, capletExpiries, strikes, directDefinition.ShiftCurve.get());
                volatilitiesFunction = createShiftedBlackVolatilitiesFunction(index, calibrationDateTime, shiftCurve);
            }
            else
            {
                InterpolatedNodalSurface capVolSurface = InterpolatedNodalSurface.of(metadata, DoubleArray.copyOf(timeList), DoubleArray.copyOf(strikeList), initialVols, INTERPOLATOR);
                capletNodes = createCapletNodes(capVolSurface, capletExpiries, strikes);
            }
            InterpolatedNodalSurface baseSurface   = InterpolatedNodalSurface.of(metadata, capletNodes.First, capletNodes.Second, capletNodes.Third, INTERPOLATOR);
            DoubleMatrix             penaltyMatrix = directDefinition.computePenaltyMatrix(strikes, capletExpiries);
            // solve least square
            LeastSquareResults       res        = solver.solve(DoubleArray.copyOf(priceList), DoubleArray.copyOf(errorList), getPriceFunction(capList, ratesProvider, volatilitiesFunction, baseSurface), getJacobianFunction(capList, ratesProvider, volatilitiesFunction, baseSurface), capletNodes.Third, penaltyMatrix, POSITIVE);
            InterpolatedNodalSurface resSurface = InterpolatedNodalSurface.of(metadata, capletNodes.First, capletNodes.Second, res.FitParameters, directDefinition.Interpolator);

            return(IborCapletFloorletVolatilityCalibrationResult.ofLeastSquare(volatilitiesFunction(resSurface), res.ChiSq));
        }
Example #14
0
        static FxOptionVolatilitiesMarketDataFunctionTest()
        {
            ImmutableList.Builder <FxOptionVolatilitiesNode>        volNodeBuilder             = ImmutableList.builder();
            ImmutableMap.Builder <QuoteId, double>                  marketQuoteBuilder         = ImmutableMap.builder();
            ImmutableMap.Builder <QuoteId, MarketDataBox <double> > scenarioMarketQuoteBuilder = ImmutableMap.builder();
            ImmutableList.Builder <FixedOvernightSwapCurveNode>     usdNodeBuilder             = ImmutableList.builder();
            ImmutableList.Builder <FxSwapCurveNode>                 gbpNodeBuilder             = ImmutableList.builder();
            for (int i = 0; i < VOL_TENORS.Count; ++i)
            {
                for (int j = 0; j < STRIKES.Count; ++j)
                {
                    QuoteId quoteId = QuoteId.of(StandardId.of("OG", VOL_TENORS[i].ToString() + "_" + STRIKES[j].Label + "_" + VALUE_TYPES[j].ToString()));
                    volNodeBuilder.add(FxOptionVolatilitiesNode.of(GBP_USD, SPOT_OFFSET, BDA, VALUE_TYPES[j], quoteId, VOL_TENORS[i], STRIKES[j]));
                    marketQuoteBuilder.put(quoteId, VOL_QUOTES[i][j]);
                    scenarioMarketQuoteBuilder.put(quoteId, MarketDataBox.ofScenarioValues(VOL_QUOTES[i][j], VOL_QUOTES_1[i][j]));
                }
            }
            for (int i = 0; i < USD_QUOTES.Count; ++i)
            {
                QuoteId quoteId = QuoteId.of(StandardId.of("OG", USD.ToString() + "-OIS-" + USD_TENORS[i].ToString()));
                usdNodeBuilder.add(FixedOvernightSwapCurveNode.of(FixedOvernightSwapTemplate.of(USD_TENORS[i], FixedOvernightSwapConventions.USD_FIXED_TERM_FED_FUND_OIS), quoteId));
                marketQuoteBuilder.put(quoteId, USD_QUOTES[i]);
                scenarioMarketQuoteBuilder.put(quoteId, MarketDataBox.ofScenarioValues(USD_QUOTES[i], USD_QUOTES_1[i]));
            }
            for (int i = 0; i < GBP_QUOTES.Count; ++i)
            {
                QuoteId quoteId = QuoteId.of(StandardId.of("OG", GBP_USD.ToString() + "-FX-" + GBP_PERIODS[i].ToString()));
                gbpNodeBuilder.add(FxSwapCurveNode.of(FxSwapTemplate.of(GBP_PERIODS[i], FxSwapConventions.GBP_USD), quoteId));
                marketQuoteBuilder.put(quoteId, GBP_QUOTES[i]);
                scenarioMarketQuoteBuilder.put(quoteId, MarketDataBox.ofScenarioValues(GBP_QUOTES[i], GBP_QUOTES_1[i]));
            }
            VOL_NODES              = volNodeBuilder.build();
            USD_NODES              = usdNodeBuilder.build();
            GBP_NODES              = gbpNodeBuilder.build();
            MARKET_QUOTES          = marketQuoteBuilder.build();
            SCENARIO_MARKET_QUOTES = scenarioMarketQuoteBuilder.build();
            IList <double> expiry  = VOL_TENORS.Select(t => ACT_365F.relativeYearFraction(VALUATION_DATE, BDA.adjust(SPOT_OFFSET.adjust(VALUATION_DATE, REF_DATA).plus(t), REF_DATA))).ToList();
            int            nSmiles = expiry.Count;

            double[] atm = new double[nSmiles];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] rr = new double[nSmiles][2];
            double[][] rr = RectangularArrays.ReturnRectangularDoubleArray(nSmiles, 2);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] str = new double[nSmiles][2];
            double[][] str = RectangularArrays.ReturnRectangularDoubleArray(nSmiles, 2);
            for (int i = 0; i < nSmiles; ++i)
            {
                atm[i]    = VOL_QUOTES[i][0];
                rr[i][0]  = VOL_QUOTES[i][1];
                rr[i][1]  = VOL_QUOTES[i][3];
                str[i][0] = VOL_QUOTES[i][2];
                str[i][1] = VOL_QUOTES[i][4];
            }
            InterpolatedStrikeSmileDeltaTermStructure term = InterpolatedStrikeSmileDeltaTermStructure.of(DoubleArray.copyOf(expiry), DoubleArray.of(0.1, 0.25), DoubleArray.copyOf(atm), DoubleMatrix.copyOf(rr), DoubleMatrix.copyOf(str), ACT_365F, LINEAR, FLAT, FLAT, PCHIP, FLAT, FLAT);

            EXP_VOLS = BlackFxOptionSmileVolatilities.of(VOL_NAME, GBP_USD, VALUATION_DATE.atTime(VALUATION_TIME).atZone(ZONE), term);
            for (int i = 0; i < nSmiles; ++i)
            {
                atm[i]    = VOL_QUOTES_1[i][0];
                rr[i][0]  = VOL_QUOTES_1[i][1];
                rr[i][1]  = VOL_QUOTES_1[i][3];
                str[i][0] = VOL_QUOTES_1[i][2];
                str[i][1] = VOL_QUOTES_1[i][4];
            }
            InterpolatedStrikeSmileDeltaTermStructure term1 = InterpolatedStrikeSmileDeltaTermStructure.of(DoubleArray.copyOf(expiry), DoubleArray.of(0.1, 0.25), DoubleArray.copyOf(atm), DoubleMatrix.copyOf(rr), DoubleMatrix.copyOf(str), ACT_365F, LINEAR, FLAT, FLAT, PCHIP, FLAT, FLAT);

            EXP_VOLS_1 = BlackFxOptionSmileVolatilities.of(VOL_NAME, GBP_USD, VALUATION_DATE_1.atTime(VALUATION_TIME_1).atZone(ZONE), term1);
            ImmutableList.Builder <FxOptionVolatilitiesNode> nodeBuilder  = ImmutableList.builder();
            ImmutableMap.Builder <QuoteId, double>           quoteBuilder = ImmutableMap.builder();
            for (int i = 0; i < SURFACE_TENORS.Count; ++i)
            {
                for (int j = 0; j < SURFACE_STRIKES.Count; ++j)
                {
                    QuoteId quoteId = QuoteId.of(StandardId.of("OG", GBP_USD.ToString() + "_" + SURFACE_TENORS[i].ToString() + "_" + SURFACE_STRIKES[j]));
                    quoteBuilder.put(quoteId, SURFACE_VOL_QUOTES[i][j]);
                    nodeBuilder.add(FxOptionVolatilitiesNode.of(GBP_USD, SPOT_OFFSET, BDA, ValueType.BLACK_VOLATILITY, quoteId, SURFACE_TENORS[i], SimpleStrike.of(SURFACE_STRIKES[j])));
                }
            }
            SURFACE_NODES  = nodeBuilder.build();
            SURFACE_QUOTES = quoteBuilder.build();
            IList <double> expiry = new List <double>();
            IList <double> strike = new List <double>();
            IList <double> vols   = new List <double>();

            for (int i = 0; i < SURFACE_TENORS.Count; ++i)
            {
                for (int j = 0; j < SURFACE_STRIKES.Count; ++j)
                {
                    double yearFraction = ACT_365F.relativeYearFraction(VALUATION_DATE, BDA.adjust(SPOT_OFFSET.adjust(VALUATION_DATE, REF_DATA).plus(SURFACE_TENORS[i]), REF_DATA));
                    expiry.Add(yearFraction);
                    strike.Add(SURFACE_STRIKES[j]);
                    vols.Add(SURFACE_VOL_QUOTES[i][j]);
                }
            }
            SurfaceInterpolator      interp  = GridSurfaceInterpolator.of(LINEAR, PCHIP);
            InterpolatedNodalSurface surface = InterpolatedNodalSurface.ofUnsorted(Surfaces.blackVolatilityByExpiryStrike(VOL_NAME.Name, ACT_365F), DoubleArray.copyOf(expiry), DoubleArray.copyOf(strike), DoubleArray.copyOf(vols), interp);

            SURFACE_EXP_VOLS = BlackFxOptionSurfaceVolatilities.of(VOL_NAME, GBP_USD, VALUATION_DATE.atTime(VALUATION_TIME).atZone(ZONE), surface);
        }
        public virtual void test_volatilities()
        {
            BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification @base = BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification.builder().name(VOL_NAME).currencyPair(GBP_USD).dayCount(ACT_365F).nodes(NODES).timeInterpolator(PCHIP).strikeInterpolator(DOUBLE_QUADRATIC).build();
            LocalDate     date       = LocalDate.of(2017, 9, 25);
            ZonedDateTime dateTime   = date.atStartOfDay().atZone(ZoneId.of("Europe/London"));
            DoubleArray   parameters = DoubleArray.of(0.19, 0.15, 0.13, 0.14, 0.14, 0.11, 0.09, 0.09, 0.11, 0.09, 0.07, 0.07);
            BlackFxOptionSurfaceVolatilities computed = @base.volatilities(dateTime, parameters, REF_DATA);
            DaysAdjustment expOffset = DaysAdjustment.ofBusinessDays(-2, NY_LO);

            double[] expiries = new double[STRIKES.Count * TENORS.Count];
            double[] strikes  = new double[STRIKES.Count * TENORS.Count];
            ImmutableList.Builder <ParameterMetadata> paramMetadata = ImmutableList.builder();
            for (int i = 0; i < TENORS.Count; ++i)
            {
                double expiry = ACT_365F.relativeYearFraction(date, expOffset.adjust(BDA.adjust(SPOT_OFFSET.adjust(date, REF_DATA).plus(TENORS[i]), REF_DATA), REF_DATA));
                for (int j = 0; j < STRIKES.Count; ++j)
                {
                    paramMetadata.add(FxVolatilitySurfaceYearFractionParameterMetadata.of(expiry, SimpleStrike.of(STRIKES[j]), GBP_USD));
                    expiries[STRIKES.Count * i + j] = expiry;
                    strikes[STRIKES.Count * i + j]  = STRIKES[j];
                }
            }
            InterpolatedNodalSurface         surface  = InterpolatedNodalSurface.ofUnsorted(Surfaces.blackVolatilityByExpiryStrike(VOL_NAME.Name, ACT_365F).withParameterMetadata(paramMetadata.build()), DoubleArray.ofUnsafe(expiries), DoubleArray.ofUnsafe(strikes), parameters, GridSurfaceInterpolator.of(PCHIP, DOUBLE_QUADRATIC));
            BlackFxOptionSurfaceVolatilities expected = BlackFxOptionSurfaceVolatilities.of(VOL_NAME, GBP_USD, dateTime, surface);

            assertEquals(computed, expected);
        }
        //-------------------------------------------------------------------------
        public override IborCapletFloorletVolatilityCalibrationResult calibrate(IborCapletFloorletVolatilityDefinition definition, ZonedDateTime calibrationDateTime, RawOptionData capFloorData, RatesProvider ratesProvider)
        {
            ArgChecker.isTrue(ratesProvider.ValuationDate.Equals(calibrationDateTime.toLocalDate()), "valuationDate of ratesProvider should be coherent to calibrationDateTime");
            ArgChecker.isTrue(definition is SurfaceIborCapletFloorletVolatilityBootstrapDefinition, "definition should be SurfaceIborCapletFloorletVolatilityBootstrapDefinition");
            SurfaceIborCapletFloorletVolatilityBootstrapDefinition bsDefinition = (SurfaceIborCapletFloorletVolatilityBootstrapDefinition)definition;
            IborIndex index           = bsDefinition.Index;
            LocalDate calibrationDate = calibrationDateTime.toLocalDate();
            LocalDate baseDate        = index.EffectiveDateOffset.adjust(calibrationDate, ReferenceData);
            LocalDate startDate       = baseDate.plus(index.Tenor);

            System.Func <Surface, IborCapletFloorletVolatilities> volatilitiesFunction = this.volatilitiesFunction(bsDefinition, calibrationDateTime, capFloorData);
            SurfaceMetadata metadata                = bsDefinition.createMetadata(capFloorData);
            IList <Period>  expiries                = capFloorData.Expiries;
            int             nExpiries               = expiries.Count;
            DoubleArray     strikes                 = capFloorData.Strikes;
            DoubleMatrix    errorsMatrix            = capFloorData.Error.orElse(DoubleMatrix.filled(nExpiries, strikes.size(), 1d));
            IList <double>  timeList                = new List <double>();
            IList <double>  strikeList              = new List <double>();
            IList <double>  volList                 = new List <double>();
            IList <ResolvedIborCapFloorLeg> capList = new List <ResolvedIborCapFloorLeg>();
            IList <double> priceList                = new List <double>();
            IList <double> errorList                = new List <double>();

            int[] startIndex = new int[nExpiries + 1];
            for (int i = 0; i < nExpiries; ++i)
            {
                LocalDate   endDate        = baseDate.plus(expiries[i]);
                DoubleArray volatilityData = capFloorData.Data.row(i);
                DoubleArray errors         = errorsMatrix.row(i);
                reduceRawData(bsDefinition, ratesProvider, strikes, volatilityData, errors, startDate, endDate, metadata, volatilitiesFunction, timeList, strikeList, volList, capList, priceList, errorList);
                startIndex[i + 1] = volList.Count;
                ArgChecker.isTrue(startIndex[i + 1] > startIndex[i], "no valid option data for {}", expiries[i]);
            }
            int nTotal = startIndex[nExpiries];
            IborCapletFloorletVolatilities vols;
            int           start;
            ZonedDateTime prevExpiry;
            DoubleArray   initialVol = DoubleArray.copyOf(volList);

            if (bsDefinition.ShiftCurve.Present)
            {
                Curve       shiftCurve    = bsDefinition.ShiftCurve.get();
                DoubleArray strikeShifted = DoubleArray.of(nTotal, n => strikeList[n] + shiftCurve.yValue(timeList[n]));
                if (capFloorData.DataType.Equals(NORMAL_VOLATILITY))
                {   // correct initial surface
                    metadata   = Surfaces.blackVolatilityByExpiryStrike(bsDefinition.Name.Name, bsDefinition.DayCount).withParameterMetadata(metadata.ParameterMetadata.get());
                    initialVol = DoubleArray.of(nTotal, n => volList[n] / (ratesProvider.iborIndexRates(index).rate(capList[n].FinalPeriod.IborRate.Observation) + shiftCurve.yValue(timeList[n])));
                }
                InterpolatedNodalSurface surface = InterpolatedNodalSurface.of(metadata, DoubleArray.copyOf(timeList), strikeShifted, initialVol, bsDefinition.Interpolator);
                vols       = ShiftedBlackIborCapletFloorletExpiryStrikeVolatilities.of(index, calibrationDateTime, surface, bsDefinition.ShiftCurve.get());
                start      = 0;
                prevExpiry = calibrationDateTime.minusDays(1L);   // included if calibrationDateTime == fixingDateTime
            }
            else
            {
                InterpolatedNodalSurface surface = InterpolatedNodalSurface.of(metadata, DoubleArray.copyOf(timeList), DoubleArray.copyOf(strikeList), initialVol, bsDefinition.Interpolator);
                vols       = volatilitiesFunction(surface);
                start      = 1;
                prevExpiry = capList[startIndex[1] - 1].FinalFixingDateTime;
            }
            for (int i = start; i < nExpiries; ++i)
            {
                for (int j = startIndex[i]; j < startIndex[i + 1]; ++j)
                {
                    System.Func <double, double[]> func   = getValueVegaFunction(capList[j], ratesProvider, vols, prevExpiry, j);
                    GenericImpliedVolatiltySolver  solver = new GenericImpliedVolatiltySolver(func);
                    double priceFixed = i == 0 ? 0d : this.priceFixed(capList[j], ratesProvider, vols, prevExpiry);
                    double capletVol  = solver.impliedVolatility(priceList[j] - priceFixed, initialVol.get(j));
                    vols = vols.withParameter(j, capletVol);
                }
                prevExpiry = capList[startIndex[i + 1] - 1].FinalFixingDateTime;
            }
            return(IborCapletFloorletVolatilityCalibrationResult.ofRootFind(vols));
        }