Esempio n. 1
0
        public virtual void sensitivity_single_curve()
        {
            CrossGammaParameterSensitivities forward  = FORWARD.calculateCrossGammaIntraCurve(RatesProviderDataSets.SINGLE_USD, this.sensiFn);
            CrossGammaParameterSensitivities central  = CENTRAL.calculateCrossGammaIntraCurve(RatesProviderDataSets.SINGLE_USD, this.sensiFn);
            CrossGammaParameterSensitivities backward = BACKWARD.calculateCrossGammaIntraCurve(RatesProviderDataSets.SINGLE_USD, this.sensiFn);
            DoubleArray times = RatesProviderDataSets.TIMES_1;

            foreach (CrossGammaParameterSensitivities sensi in new CrossGammaParameterSensitivities[] { forward, central, backward })
            {
                CurrencyParameterSensitivities diagonalComputed = sensi.diagonal();
                assertEquals(sensi.size(), 1);
                assertEquals(diagonalComputed.size(), 1);
                DoubleMatrix s = sensi.Sensitivities.get(0).Sensitivity;
                assertEquals(s.columnCount(), times.size());
                for (int i = 0; i < times.size(); i++)
                {
                    for (int j = 0; j < times.size(); j++)
                    {
                        double expected = 32d * times.get(i) * times.get(j);
                        assertEquals(s.get(i, j), expected, Math.Max(Math.Abs(expected), 1d) * EPS);
                    }
                }
            }
            // no difference for single curve
            CrossGammaParameterSensitivities forwardCross = FORWARD.calculateCrossGammaCrossCurve(RatesProviderDataSets.SINGLE_USD, this.sensiFn);

            assertTrue(forward.equalWithTolerance(forwardCross, TOL));
            CrossGammaParameterSensitivities centralCross = CENTRAL.calculateCrossGammaCrossCurve(RatesProviderDataSets.SINGLE_USD, this.sensiFn);

            assertTrue(central.equalWithTolerance(centralCross, TOL));
            CrossGammaParameterSensitivities backwardCross = BACKWARD.calculateCrossGammaCrossCurve(RatesProviderDataSets.SINGLE_USD, this.sensiFn);

            assertTrue(backward.equalWithTolerance(backwardCross, TOL));
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void sensitivity_single_curve()
        public virtual void sensitivity_single_curve()
        {
            CurrencyParameterSensitivities sensiComputed = FD_CALCULATOR.sensitivity(RatesProviderDataSets.SINGLE_USD, this.fn);
            DoubleArray times = RatesProviderDataSets.TIMES_1;

            assertEquals(sensiComputed.size(), 1);
            DoubleArray s = sensiComputed.Sensitivities.get(0).Sensitivity;

            assertEquals(s.size(), times.size());
            for (int i = 0; i < times.size(); i++)
            {
                assertEquals(s.get(i), times.get(i) * 4.0d, TOLERANCE_DELTA);
            }
        }
        //-------------------------------------------------------------------------
        //-------------------------------------------------------------------------
        public virtual void test_parameterSensitivity()
        {
            ZeroRatePeriodicDiscountFactors test = ZeroRatePeriodicDiscountFactors.of(GBP, DATE_VAL, CURVE);
            double sensiValue         = 25d;
            ZeroRateSensitivity point = test.zeroRatePointSensitivity(DATE_AFTER);

            point = point.multipliedBy(sensiValue);
            CurrencyParameterSensitivities sensiObject = test.parameterSensitivity(point);

            assertEquals(sensiObject.size(), 1);
            CurrencyParameterSensitivity sensi1 = sensiObject.Sensitivities.get(0);

            assertEquals(sensi1.Currency, GBP);
        }
        public CurrencyParameterSensitivity singleDiscountCurveParameterSensitivity(PointSensitivities pointSensitivities, Currency currency)
        {
            CurrencyParameterSensitivities sens = CurrencyParameterSensitivities.empty();

            foreach (PointSensitivity point in pointSensitivities.Sensitivities)
            {
                if (point is ZeroRateSensitivity)
                {
                    ZeroRateSensitivity pt = (ZeroRateSensitivity)point;
                    if (pt.Currency.Equals(currency))
                    {
                        CreditDiscountFactors factors = discountFactors(pt.CurveCurrency);
                        sens = sens.combinedWith(factors.parameterSensitivity(pt));
                    }
                }
            }
            ArgChecker.isTrue(sens.size() == 1, "sensitivity must be unique");
            return(sens.Sensitivities.get(0));
        }
        public CurrencyParameterSensitivity singleCreditCurveParameterSensitivity(PointSensitivities pointSensitivities, StandardId legalEntityId, Currency currency)
        {
            CurrencyParameterSensitivities sens = CurrencyParameterSensitivities.empty();

            foreach (PointSensitivity point in pointSensitivities.Sensitivities)
            {
                if (point is CreditCurveZeroRateSensitivity)
                {
                    CreditCurveZeroRateSensitivity pt = (CreditCurveZeroRateSensitivity)point;
                    if (pt.LegalEntityId.Equals(legalEntityId) && pt.Currency.Equals(currency))
                    {
                        LegalEntitySurvivalProbabilities factors = survivalProbabilities(pt.LegalEntityId, pt.CurveCurrency);
                        sens = sens.combinedWith(factors.parameterSensitivity(pt));
                    }
                }
            }
            ArgChecker.isTrue(sens.size() == 1, "sensitivity must be unique");
            return(sens.Sensitivities.get(0));
        }
        //-------------------------------------------------------------------------
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void sensitivity_credit_isda()
        public virtual void sensitivity_credit_isda()
        {
            LocalDate                         valuationDate = LocalDate.of(2014, 1, 3);
            CreditRatesProvider               rates         = CreditRatesProviderDataSets.createCreditRatesProvider(valuationDate);
            CurrencyParameterSensitivities    sensiComputed = FD_CALCULATOR.sensitivity(rates, this.creditFunction);
            IList <IsdaCreditDiscountFactors> curves        = CreditRatesProviderDataSets.getAllDiscountFactors(valuationDate);

            assertEquals(sensiComputed.size(), curves.Count);
            foreach (IsdaCreditDiscountFactors curve in curves)
            {
                DoubleArray time = curve.ParameterKeys;
                DoubleArray sensiValueComputed = sensiComputed.getSensitivity(curve.Curve.Name, USD).Sensitivity;
                assertEquals(sensiValueComputed.size(), time.size());
                for (int i = 0; i < time.size(); i++)
                {
                    assertEquals(time.get(i), sensiValueComputed.get(i), TOLERANCE_DELTA);
                }
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void sensitivity_legalEntity_Simple()
        public virtual void sensitivity_legalEntity_Simple()
        {
            CurrencyParameterSensitivities sensiComputed = FD_CALCULATOR.sensitivity(LegalEntityDiscountingProviderDataSets.ISSUER_REPO_SIMPLE, this.fn);
            DoubleArray timeIssuer = LegalEntityDiscountingProviderDataSets.ISSUER_TIME_USD;
            DoubleArray timesRepo  = LegalEntityDiscountingProviderDataSets.REPO_TIME_USD;

            assertEquals(sensiComputed.size(), 2);
            DoubleArray sensiIssuer = sensiComputed.getSensitivity(LegalEntityDiscountingProviderDataSets.META_SIMPLE_ISSUER_USD.CurveName, USD).Sensitivity;

            assertEquals(sensiIssuer.size(), timeIssuer.size());
            for (int i = 0; i < timeIssuer.size(); i++)
            {
                assertEquals(timeIssuer.get(i), sensiIssuer.get(i), TOLERANCE_DELTA);
            }
            DoubleArray sensiRepo = sensiComputed.getSensitivity(LegalEntityDiscountingProviderDataSets.META_SIMPLE_REPO_USD.CurveName, USD).Sensitivity;

            assertEquals(sensiRepo.size(), timesRepo.size());
            for (int i = 0; i < timesRepo.size(); i++)
            {
                assertEquals(timesRepo.get(i), sensiRepo.get(i), TOLERANCE_DELTA);
            }
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void sensitivity_multi_curve()
        public virtual void sensitivity_multi_curve()
        {
            CurrencyParameterSensitivities sensiComputed = FD_CALCULATOR.sensitivity(RatesProviderDataSets.MULTI_CPI_USD, this.fn);
            DoubleArray times1 = RatesProviderDataSets.TIMES_1;
            DoubleArray times2 = RatesProviderDataSets.TIMES_2;
            DoubleArray times3 = RatesProviderDataSets.TIMES_3;
            DoubleArray times4 = RatesProviderDataSets.TIMES_4;

            assertEquals(sensiComputed.size(), 4);
            DoubleArray s1 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_DSC_NAME, USD).Sensitivity;

            assertEquals(s1.size(), times1.size());
            for (int i = 0; i < times1.size(); i++)
            {
                assertEquals(times1.get(i) * 2.0d, s1.get(i), TOLERANCE_DELTA);
            }
            DoubleArray s2 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_L3_NAME, USD).Sensitivity;

            assertEquals(s2.size(), times2.size());
            for (int i = 0; i < times2.size(); i++)
            {
                assertEquals(times2.get(i), s2.get(i), TOLERANCE_DELTA);
            }
            DoubleArray s3 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_L6_NAME, USD).Sensitivity;

            assertEquals(s3.size(), times3.size());
            for (int i = 0; i < times3.size(); i++)
            {
                assertEquals(times3.get(i), s3.get(i), TOLERANCE_DELTA);
            }
            DoubleArray s4 = sensiComputed.getSensitivity(RatesProviderDataSets.USD_CPI_NAME, USD).Sensitivity;

            assertEquals(s4.size(), times4.size());
            for (int i = 0; i < times4.size(); i++)
            {
                assertEquals(times4.get(i), s4.get(i), TOLERANCE_DELTA);
            }
        }
        //-------------------------------------------------------------------------
        public virtual void calibration_transition_coherence_par_rate()
        {
            RatesProvider provider = CalibrationEurStandard.calibrateEurStandard(VAL_DATE, DSC_MARKET_QUOTES, DSC_OIS_TENORS, FWD3_FIXING_QUOTE, FWD3_FRA_QUOTES, FWD3_IRS_QUOTES, FWD3_FRA_TENORS, FWD3_IRS_TENORS, FWD6_FIXING_QUOTE, FWD6_FRA_QUOTES, FWD6_IRS_QUOTES, FWD6_FRA_TENORS, FWD6_IRS_TENORS);

            /* Curve Discounting/EUR-EONIA */
            string[] dscIdValues = CalibrationEurStandard.dscIdValues(DSC_OIS_TENORS);
            /* Curve EUR-EURIBOR-3M */
            double[] fwd3MarketQuotes = CalibrationEurStandard.fwdMarketQuotes(FWD3_FIXING_QUOTE, FWD3_FRA_QUOTES, FWD3_IRS_QUOTES);
            string[] fwd3IdValue      = CalibrationEurStandard.fwdIdValue(3, FWD3_FIXING_QUOTE, FWD3_FRA_QUOTES, FWD3_IRS_QUOTES, FWD3_FRA_TENORS, FWD3_IRS_TENORS);
            /* Curve EUR-EURIBOR-6M */
            double[] fwd6MarketQuotes = CalibrationEurStandard.fwdMarketQuotes(FWD6_FIXING_QUOTE, FWD6_FRA_QUOTES, FWD6_IRS_QUOTES);
            string[] fwd6IdValue      = CalibrationEurStandard.fwdIdValue(6, FWD6_FIXING_QUOTE, FWD6_FRA_QUOTES, FWD6_IRS_QUOTES, FWD6_FRA_TENORS, FWD6_IRS_TENORS);
            /* All quotes for the curve calibration */
            MarketData allQuotes = CalibrationEurStandard.allQuotes(VAL_DATE, DSC_MARKET_QUOTES, dscIdValues, fwd3MarketQuotes, fwd3IdValue, fwd6MarketQuotes, fwd6IdValue);
            /* All nodes by groups. */
            RatesCurveGroupDefinition config = CalibrationEurStandard.config(DSC_OIS_TENORS, dscIdValues, FWD3_FRA_TENORS, FWD3_IRS_TENORS, fwd3IdValue, FWD6_FRA_TENORS, FWD6_IRS_TENORS, fwd6IdValue);

            ImmutableList <CurveDefinition> definitions = config.CurveDefinitions;
            // Test PV Dsc
            ImmutableList <CurveNode> dscNodes  = definitions.get(0).Nodes;
            IList <ResolvedTrade>     dscTrades = new List <ResolvedTrade>();

            for (int i = 0; i < dscNodes.size(); i++)
            {
                dscTrades.Add(dscNodes.get(i).resolvedTrade(1d, allQuotes, REF_DATA));
            }
            // OIS
            for (int loopnode = 0; loopnode < DSC_MARKET_QUOTES.Length; loopnode++)
            {
                PointSensitivities             pts = SWAP_PRICER.parRateSensitivity(((ResolvedSwapTrade)dscTrades[loopnode]).Product, provider).build();
                CurrencyParameterSensitivities ps  = provider.parameterSensitivity(pts);
                CurrencyParameterSensitivities mqs = MQC.sensitivity(ps, provider);
                assertEquals(mqs.size(), 3);   // Calibration of all curves simultaneously
                CurrencyParameterSensitivity mqsDsc = mqs.getSensitivity(CalibrationEurStandard.DSCON_CURVE_NAME, EUR);
                assertTrue(mqsDsc.MarketDataName.Equals(CalibrationEurStandard.DSCON_CURVE_NAME));
                assertTrue(mqsDsc.Currency.Equals(EUR));
                DoubleArray mqsData = mqsDsc.Sensitivity;
                assertEquals(mqsData.size(), DSC_MARKET_QUOTES.Length);
                for (int i = 0; i < mqsData.size(); i++)
                {
                    assertEquals(mqsData.get(i), (i == loopnode) ? 1.0 : 0.0, TOLERANCE_DELTA);
                }
            }
            // Test PV Fwd3
            ImmutableList <CurveNode> fwd3Nodes  = definitions.get(1).Nodes;
            IList <ResolvedTrade>     fwd3Trades = new List <ResolvedTrade>();

            for (int i = 0; i < fwd3Nodes.size(); i++)
            {
                fwd3Trades.Add(fwd3Nodes.get(i).resolvedTrade(1d, allQuotes, REF_DATA));
            }
            for (int loopnode = 0; loopnode < fwd3MarketQuotes.Length; loopnode++)
            {
                PointSensitivities pts = null;
                if (fwd3Trades[loopnode] is ResolvedIborFixingDepositTrade)
                {
                    pts = PRICER_FIXING.parSpreadSensitivity(((ResolvedIborFixingDepositTrade)fwd3Trades[loopnode]).Product, provider);
                }
                if (fwd3Trades[loopnode] is ResolvedFraTrade)
                {
                    pts = PRICER_FRA.parSpreadSensitivity(((ResolvedFraTrade)fwd3Trades[loopnode]).Product, provider);
                }
                if (fwd3Trades[loopnode] is ResolvedSwapTrade)
                {
                    pts = SWAP_PRICER.parSpreadSensitivity(((ResolvedSwapTrade)fwd3Trades[loopnode]).Product, provider).build();
                }
                CurrencyParameterSensitivities ps  = provider.parameterSensitivity(pts);
                CurrencyParameterSensitivities mqs = MQC.sensitivity(ps, provider);
                assertEquals(mqs.size(), 3);   // Calibration of all curves simultaneously
                CurrencyParameterSensitivity mqsDsc  = mqs.getSensitivity(CalibrationEurStandard.DSCON_CURVE_NAME, EUR);
                CurrencyParameterSensitivity mqsFwd3 = mqs.getSensitivity(CalibrationEurStandard.FWD3_CURVE_NAME, EUR);
                DoubleArray mqsDscData = mqsDsc.Sensitivity;
                assertEquals(mqsDscData.size(), DSC_MARKET_QUOTES.Length);
                for (int i = 0; i < mqsDscData.size(); i++)
                {
                    assertEquals(mqsDscData.get(i), 0.0, TOLERANCE_DELTA);
                }
                DoubleArray mqsFwd3Data = mqsFwd3.Sensitivity;
                assertEquals(mqsFwd3Data.size(), fwd3MarketQuotes.Length);
                for (int i = 0; i < mqsFwd3Data.size(); i++)
                {
                    assertEquals(mqsFwd3Data.get(i), (i == loopnode) ? 1.0 : 0.0, TOLERANCE_DELTA);
                }
            }
            // Test PV Fwd6
            ImmutableList <CurveNode> fwd6Nodes  = definitions.get(2).Nodes;
            IList <ResolvedTrade>     fwd6Trades = new List <ResolvedTrade>();

            for (int i = 0; i < fwd6Nodes.size(); i++)
            {
                fwd6Trades.Add(fwd6Nodes.get(i).resolvedTrade(1d, allQuotes, REF_DATA));
            }
            for (int loopnode = 0; loopnode < fwd6MarketQuotes.Length; loopnode++)
            {
                PointSensitivities pts = null;
                if (fwd6Trades[loopnode] is ResolvedIborFixingDepositTrade)
                {
                    pts = PRICER_FIXING.parSpreadSensitivity(((ResolvedIborFixingDepositTrade)fwd6Trades[loopnode]).Product, provider);
                }
                if (fwd6Trades[loopnode] is ResolvedFraTrade)
                {
                    pts = PRICER_FRA.parSpreadSensitivity(((ResolvedFraTrade)fwd6Trades[loopnode]).Product, provider);
                }
                if (fwd6Trades[loopnode] is ResolvedSwapTrade)
                {
                    pts = SWAP_PRICER.parSpreadSensitivity(((ResolvedSwapTrade)fwd6Trades[loopnode]).Product, provider).build();
                }
                CurrencyParameterSensitivities ps  = provider.parameterSensitivity(pts);
                CurrencyParameterSensitivities mqs = MQC.sensitivity(ps, provider);
                assertEquals(mqs.size(), 3);
                CurrencyParameterSensitivity mqsDsc  = mqs.getSensitivity(CalibrationEurStandard.DSCON_CURVE_NAME, EUR);
                CurrencyParameterSensitivity mqsFwd3 = mqs.getSensitivity(CalibrationEurStandard.FWD3_CURVE_NAME, EUR);
                CurrencyParameterSensitivity mqsFwd6 = mqs.getSensitivity(CalibrationEurStandard.FWD6_CURVE_NAME, EUR);
                DoubleArray mqsDscData = mqsDsc.Sensitivity;
                assertEquals(mqsDscData.size(), DSC_MARKET_QUOTES.Length);
                for (int i = 0; i < mqsDscData.size(); i++)
                {
                    assertEquals(mqsDscData.get(i), 0.0, TOLERANCE_DELTA);
                }
                DoubleArray mqsFwd3Data = mqsFwd3.Sensitivity;
                assertEquals(mqsFwd3Data.size(), fwd3MarketQuotes.Length);
                for (int i = 0; i < mqsFwd3Data.size(); i++)
                {
                    assertEquals(mqsFwd3Data.get(i), 0.0, TOLERANCE_DELTA);
                }
                DoubleArray mqsFwd6Data = mqsFwd6.Sensitivity;
                assertEquals(mqsFwd6Data.size(), fwd6MarketQuotes.Length);
                for (int i = 0; i < mqsFwd6Data.size(); i++)
                {
                    assertEquals(mqsFwd6Data.get(i), (i == loopnode) ? 1.0 : 0.0, TOLERANCE_DELTA);
                }
            }
        }
        //-------------------------------------------------------------------------
        /// <summary>
        /// Runs the calibration of SABR on swaptions and print on the console the present value, bucketed PV01 and
        /// the bucketed Vega of a 18M x 4Y swaption.
        /// </summary>
        /// <param name="args">  -s to use the spares data </param>
        public static void Main(string[] args)
        {
            long start, end;

            // Swaption description
            BuySell          payer            = BuySell.BUY;
            Period           expiry           = Period.ofMonths(18);
            double           notional         = 1_000_000;
            double           strike           = 0.0100;
            Tenor            tenor            = Tenor.TENOR_4Y;
            LocalDate        expiryDate       = EUR_FIXED_1Y_EURIBOR_6M.FloatingLeg.StartDateBusinessDayAdjustment.adjust(CALIBRATION_DATE.plus(expiry), REF_DATA);
            SwapTrade        underlying       = EUR_FIXED_1Y_EURIBOR_6M.createTrade(expiryDate, tenor, payer, notional, strike, REF_DATA);
            Swaption         swaption         = Swaption.builder().expiryDate(AdjustableDate.of(expiryDate)).expiryTime(LocalTime.of(11, 0x0)).expiryZone(ZoneId.of("Europe/Berlin")).underlying(underlying.Product).longShort(LongShort.LONG).swaptionSettlement(PhysicalSwaptionSettlement.DEFAULT).build();
            ResolvedSwaption resolvedSwaption = swaption.resolve(REF_DATA);

            // select data
            TenorRawOptionData data = DATA_FULL;

            if (args.Length > 0)
            {
                if (args[0].Equals("-s"))
                {
                    data = DATA_SPARSE;
                }
            }

            start = DateTimeHelper.CurrentUnixTimeMillis();
            // Curve calibration
            RatesProvider multicurve = CALIBRATOR.calibrate(CONFIGS, MARKET_QUOTES, REF_DATA);

            end = DateTimeHelper.CurrentUnixTimeMillis();
            Console.WriteLine("Curve calibration time: " + (end - start) + " ms.");

            // SABR calibration
            start = DateTimeHelper.CurrentUnixTimeMillis();
            double          beta                    = 0.50;
            SurfaceMetadata betaMetadata            = DefaultSurfaceMetadata.builder().xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).zValueType(ValueType.SABR_BETA).surfaceName("Beta").build();
            Surface         betaSurface             = ConstantSurface.of(betaMetadata, beta);
            double          shift                   = 0.0300;
            Surface         shiftSurface            = ConstantSurface.of("SABR-Shift", shift);
            SabrParametersSwaptionVolatilities sabr = SABR_CALIBRATION.calibrateWithFixedBetaAndShift(DEFINITION, CALIBRATION_TIME, data, multicurve, betaSurface, shiftSurface);

            end = DateTimeHelper.CurrentUnixTimeMillis();
            Console.WriteLine("SABR calibration time: " + (end - start) + " ms.");

            // Price and risk
            Console.WriteLine("Risk measures: ");
            start = DateTimeHelper.CurrentUnixTimeMillis();
            CurrencyAmount pv = SWAPTION_PRICER.presentValue(resolvedSwaption, multicurve, sabr);

            Console.WriteLine("  |-> PV: " + pv.ToString());

            PointSensitivities             deltaPts      = SWAPTION_PRICER.presentValueSensitivityRatesStickyModel(resolvedSwaption, multicurve, sabr).build();
            CurrencyParameterSensitivities deltaBucketed = multicurve.parameterSensitivity(deltaPts);

            Console.WriteLine("  |-> Delta bucketed: " + deltaBucketed.ToString());

            PointSensitivities vegaPts = SWAPTION_PRICER.presentValueSensitivityModelParamsSabr(resolvedSwaption, multicurve, sabr).build();

            Console.WriteLine("  |-> Vega point: " + vegaPts.ToString());

            CurrencyParameterSensitivities vegaBucketed = sabr.parameterSensitivity(vegaPts);

            for (int i = 0; i < vegaBucketed.size(); i++)
            {
                Console.WriteLine("  |-> Vega bucketed: " + vegaBucketed.Sensitivities.get(i));
            }

            end = DateTimeHelper.CurrentUnixTimeMillis();
            Console.WriteLine("PV and risk time: " + (end - start) + " ms.");
        }