@Test(enabled = false)
 /** Tests the clean, dirty and yield vs external hard-coded values. */
 public void priceYieldExternalValues1() {
   final double m1 = 1000000; // Notional of the external figures.
   final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 16); // Spot 18-Aug-2011
   final InflationIssuerProviderDiscount market =
       MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
   final double cleanRealPrice = 1.00;
   final BondCapitalIndexedSecurity<Coupon> bond_110817 =
       BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
   final double referenceIndexExpected = 225.83129;
   final MultiCurrencyAmount netAmountSettle =
       bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
   final double referenceIndexComputed =
       netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
           * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
           / bond_110817.getSettlement().getNotional();
   assertEquals(
       "Inflation Capital Indexed bond: index",
       referenceIndexExpected,
       referenceIndexComputed,
       1.0E-5);
   final double indexRatioExpected = 1.13782;
   final MultiCurrencyAmount indexRatioCalculated =
       bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
   assertEquals(
       "Inflation Capital Indexed bond: indexRatio",
       indexRatioExpected,
       indexRatioCalculated.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount()
           / NOTIONAL_TIPS_1,
       1.0E-5);
   final double yieldExpected = 1.999644 / 100.0;
   final double dirtyRealPriceComputed =
       METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
   final double yieldComputed =
       METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
   assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
   final double accruedExpected = 2102.49;
   final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
   final double accruedReal = bond_110817.getAccruedInterest();
   assertEquals(
       "Inflation Capital Indexed bond: accrued",
       accruedRealExpected,
       accruedReal / NOTIONAL_TIPS_1,
       1.0E-8);
   final double netAmountExpected = 1139922.49; // For 1m; uses the rounding rules.
   final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
   assertEquals(
       "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
   final MultiCurrencyAmount netAmount =
       METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
   assertEquals(
       "Inflation Capital Indexed bond: net amount",
       netAmountExpected,
       netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
       2.0E+0); // The difference is due to rounding.
 }
/**
 * Tests for the methods related to interest rate securities pricing with Hull-White model convexity
 * adjustment.
 */
@Test(groups = TestGroup.UNIT)
public class InterestRateFutureSecurityHullWhiteMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex[] INDEX_LIST =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd();
  private static final IborIndex EURIBOR3M = INDEX_LIST[0];
  private static final Currency EUR = EURIBOR3M.getCurrency();
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();
  // Future
  private static final ZonedDateTime SPOT_LAST_TRADING_DATE = DateUtils.getUTCDate(2012, 9, 19);
  private static final ZonedDateTime LAST_TRADING_DATE =
      ScheduleCalculator.getAdjustedDate(SPOT_LAST_TRADING_DATE, -EURIBOR3M.getSpotLag(), CALENDAR);
  private static final double NOTIONAL = 1000000.0; // 1m
  private static final double FUTURE_FACTOR = 0.25;
  private static final String NAME = "ERU2";

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2011, 5, 12);
  private static final InterestRateFutureSecurityDefinition ERU2_DEFINITION =
      new InterestRateFutureSecurityDefinition(
          LAST_TRADING_DATE, EURIBOR3M, NOTIONAL, FUTURE_FACTOR, NAME, CALENDAR);

  private static final InterestRateFutureSecurity ERU2 =
      ERU2_DEFINITION.toDerivative(REFERENCE_DATE);

  private static final double MEAN_REVERSION = 0.01;
  private static final double[] VOLATILITY = new double[] {0.01, 0.011, 0.012, 0.013, 0.014};
  private static final double[] VOLATILITY_TIME = new double[] {0.5, 1.0, 2.0, 5.0};
  private static final HullWhiteOneFactorPiecewiseConstantParameters MODEL_PARAMETERS =
      new HullWhiteOneFactorPiecewiseConstantParameters(
          MEAN_REVERSION, VOLATILITY, VOLATILITY_TIME);

  private static final HullWhiteOneFactorProviderDiscount HW_MULTICURVES =
      new HullWhiteOneFactorProviderDiscount(MULTICURVES, MODEL_PARAMETERS, EUR);
  private static final HullWhiteOneFactorPiecewiseConstantInterestRateModel MODEL =
      new HullWhiteOneFactorPiecewiseConstantInterestRateModel();

  private static final InterestRateFutureSecurityHullWhiteMethod METHOD_IRFUT_HW =
      InterestRateFutureSecurityHullWhiteMethod.getInstance();

  private static final MarketQuoteHullWhiteCalculator MQHWC =
      MarketQuoteHullWhiteCalculator.getInstance();
  private static final MarketQuoteCurveSensitivityHullWhiteCalculator MQCSHWC =
      MarketQuoteCurveSensitivityHullWhiteCalculator.getInstance();
  private static final ConvexityAdjustmentHullWhiteCalculator CAHWC =
      ConvexityAdjustmentHullWhiteCalculator.getInstance();
  private static final ParRateHullWhiteCalculator PRHWC = ParRateHullWhiteCalculator.getInstance();

  private static final double SHIFT_FD = 1.0E-6;
  private static final SimpleParameterSensitivityParameterCalculator<
          HullWhiteOneFactorProviderInterface>
      SPSHWC = new SimpleParameterSensitivityParameterCalculator<>(MQCSHWC);
  private static final SimpleParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator
      SPSHWC_FD =
          new SimpleParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(MQHWC, SHIFT_FD);

  private static final double TOLERANCE_PRICE = 1.0E-10;
  private static final double TOLERANCE_PRICE_DELTA = 1.0E-8;

  @Test
  /** Test the price computed from the curves and HW parameters. */
  public void price() {
    final double price = METHOD_IRFUT_HW.price(ERU2, HW_MULTICURVES);
    final double forward =
        MULTICURVES.getSimplyCompoundForwardRate(
            EURIBOR3M,
            ERU2.getFixingPeriodStartTime(),
            ERU2.getFixingPeriodEndTime(),
            ERU2.getFixingPeriodAccrualFactor());
    final double factor =
        MODEL.futuresConvexityFactor(
            MODEL_PARAMETERS,
            ERU2.getTradingLastTime(),
            ERU2.getFixingPeriodStartTime(),
            ERU2.getFixingPeriodEndTime());
    final double expectedPrice =
        1.0 - factor * forward + (1 - factor) / ERU2.getFixingPeriodAccrualFactor();
    assertEquals(
        "InterestRateFutureSecurityHullWhiteProviderMethod: price",
        expectedPrice,
        price,
        TOLERANCE_PRICE);
  }

  @Test
  /** Test the par rate computed from the curves and HW parameters. Par rate = 1-price. */
  public void parRate() {
    final double price = METHOD_IRFUT_HW.price(ERU2, HW_MULTICURVES);
    final double parRateExpected = 1.0d - price;
    final double parRateComputed = METHOD_IRFUT_HW.parRate(ERU2, HW_MULTICURVES);
    assertEquals(
        "InterestRateFutureSecurityHullWhiteProviderMethod: parRate",
        parRateExpected,
        parRateComputed,
        TOLERANCE_PRICE);
  }

  @Test
  /** Test the par rate computed from the method and the calculator. */
  public void parRateMethodVsCalculator() {
    final double parRateMethod = METHOD_IRFUT_HW.parRate(ERU2, HW_MULTICURVES);
    final double parRateCalculator = ERU2.accept(PRHWC, HW_MULTICURVES);
    assertEquals(
        "InterestRateFutureSecurityHullWhiteProviderMethod: parRate",
        parRateMethod,
        parRateCalculator,
        TOLERANCE_PRICE);
  }

  @Test
  /** Test the price as "MarketQuote" */
  public void marketQuote() {
    final double priceMethod = METHOD_IRFUT_HW.price(ERU2, HW_MULTICURVES);
    final double marketQuote = ERU2.accept(MQHWC, HW_MULTICURVES);
    assertEquals(
        "InterestRateFutureSecurityHullWhiteProviderMethod: price",
        priceMethod,
        marketQuote,
        TOLERANCE_PRICE);
  }

  @Test
  /** Test the convexity adjustment */
  public void convexityAdjustment() {
    final double price = METHOD_IRFUT_HW.price(ERU2, HW_MULTICURVES);
    final double forward =
        MULTICURVES.getSimplyCompoundForwardRate(
            EURIBOR3M,
            ERU2.getFixingPeriodStartTime(),
            ERU2.getFixingPeriodEndTime(),
            ERU2.getFixingPeriodAccrualFactor());
    final double convexityAdjustment = METHOD_IRFUT_HW.convexityAdjustment(ERU2, HW_MULTICURVES);
    assertEquals(
        "InterestRateFutureSecurityHullWhiteProviderMethod: convexity adjustment",
        price - (1.0d - forward),
        convexityAdjustment,
        TOLERANCE_PRICE);
    final double caCalculator = ERU2.accept(CAHWC, HW_MULTICURVES);
    assertEquals(
        "DeliverableSwapFuturesSecurityDefinition: convexity adjustment",
        caCalculator,
        convexityAdjustment,
        TOLERANCE_PRICE);
  }

  @Test
  /** Test the price curve sensitivity versus a finite difference computation. */
  public void priceCurveSensitivity() {
    final SimpleParameterSensitivity pcsExact =
        SPSHWC.calculateSensitivity(ERU2, HW_MULTICURVES, MULTICURVES.getAllNames());
    final SimpleParameterSensitivity pcsFD = SPSHWC_FD.calculateSensitivity(ERU2, HW_MULTICURVES);
    AssertSensitivityObjects.assertEquals(
        "DeliverableSwapFuturesSecurityHullWhiteMethod: priceCurveSensitivity",
        pcsExact,
        pcsFD,
        TOLERANCE_PRICE_DELTA);
  }
}
/** Tests related to the pricing of physical delivery swaption in Hull-White one factor model. */
public class SwaptionPhysicalFixedIborHullWhiteMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex EURIBOR6M =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd()[1];

  private static final Currency EUR = EURIBOR6M.getCurrency();
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();

  private static final HullWhiteOneFactorPiecewiseConstantParameters HW_PARAMETERS =
      HullWhiteDataSets.createHullWhiteParameters();
  private static final HullWhiteOneFactorProviderDiscount HW_MULTICURVES =
      new HullWhiteOneFactorProviderDiscount(MULTICURVES, HW_PARAMETERS, EUR);

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2011, 7, 7);
  // Swaption 5Yx5Y
  private static final int SPOT_LAG = EURIBOR6M.getSpotLag();
  private static final int SWAP_TENOR_YEAR = 5;
  private static final Period SWAP_TENOR = Period.ofYears(SWAP_TENOR_YEAR);
  private static final GeneratorSwapFixedIbor EUR1YEURIBOR6M =
      GeneratorSwapFixedIborMaster.getInstance().getGenerator("EUR1YEURIBOR6M", CALENDAR);
  private static final ZonedDateTime EXPIRY_DATE = DateUtils.getUTCDate(2016, 7, 7);
  private static final boolean IS_LONG = true;
  private static final ZonedDateTime SETTLEMENT_DATE =
      ScheduleCalculator.getAdjustedDate(EXPIRY_DATE, SPOT_LAG, CALENDAR);
  private static final double NOTIONAL = 100000000; // 100m
  private static final double RATE = 0.0175;
  private static final boolean FIXED_IS_PAYER = true;
  private static final SwapFixedIborDefinition SWAP_PAYER_DEFINITION =
      SwapFixedIborDefinition.from(
          SETTLEMENT_DATE, SWAP_TENOR, EUR1YEURIBOR6M, NOTIONAL, RATE, FIXED_IS_PAYER);
  private static final SwapFixedIborDefinition SWAP_RECEIVER_DEFINITION =
      SwapFixedIborDefinition.from(
          SETTLEMENT_DATE, SWAP_TENOR, EUR1YEURIBOR6M, NOTIONAL, RATE, !FIXED_IS_PAYER);

  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_LONG_PAYER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_PAYER_DEFINITION, IS_LONG);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_LONG_RECEIVER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_RECEIVER_DEFINITION, IS_LONG);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_SHORT_PAYER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_PAYER_DEFINITION, !IS_LONG);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_SHORT_RECEIVER_DEFINITION =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_RECEIVER_DEFINITION, !IS_LONG);

  private static final SwapFixedCoupon<Coupon> SWAP_RECEIVER =
      SWAP_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_LONG_PAYER =
      SWAPTION_LONG_PAYER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_LONG_RECEIVER =
      SWAPTION_LONG_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_SHORT_PAYER =
      SWAPTION_SHORT_PAYER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final SwaptionPhysicalFixedIbor SWAPTION_SHORT_RECEIVER =
      SWAPTION_SHORT_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);

  // Calculator
  private static final SwaptionPhysicalFixedIborHullWhiteMethod METHOD_HW =
      SwaptionPhysicalFixedIborHullWhiteMethod.getInstance();
  private static final SwapFixedCouponDiscountingMethod METHOD_SWAP =
      SwapFixedCouponDiscountingMethod.getInstance();

  private static final CashFlowEquivalentCalculator CFEC =
      CashFlowEquivalentCalculator.getInstance();
  private static final ParRateDiscountingCalculator PRDC =
      ParRateDiscountingCalculator.getInstance();
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingCalculator.getInstance();
  private static final PresentValueHullWhiteCalculator PVHWC =
      PresentValueHullWhiteCalculator.getInstance();
  private static final PresentValueCurveSensitivityHullWhiteCalculator PVCSHWC =
      PresentValueCurveSensitivityHullWhiteCalculator.getInstance();

  private static final double SHIFT = 1.0E-6;
  private static final ParameterSensitivityParameterCalculator<HullWhiteOneFactorProviderInterface>
      PS_HW_C = new ParameterSensitivityParameterCalculator<>(PVCSHWC);
  private static final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator PS_HW_FDC =
      new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(PVHWC, SHIFT);

  private static final SwaptionPhysicalFixedIborHullWhiteNumericalIntegrationMethod
      METHOD_HW_INTEGRATION =
          SwaptionPhysicalFixedIborHullWhiteNumericalIntegrationMethod.getInstance();
  private static final SwaptionPhysicalFixedIborHullWhiteApproximationMethod
      METHOD_HW_APPROXIMATION = SwaptionPhysicalFixedIborHullWhiteApproximationMethod.getInstance();
  private static final int NB_PATH = 12500;
  private static final HullWhiteMonteCarloMethod METHOD_HW_MONTECARLO =
      new HullWhiteMonteCarloMethod(new NormalRandomNumberGenerator(0.0, 1.0), NB_PATH);

  private static final HullWhiteOneFactorPiecewiseConstantInterestRateModel MODEL =
      new HullWhiteOneFactorPiecewiseConstantInterestRateModel();
  private static final ProbabilityDistribution<Double> NORMAL = new NormalDistribution(0, 1);

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA =
      1.0E+0; // Testing note: Sensitivity is for a movement of 1. 1E+2 = 1 cent for a 1 bp move.

  @Test
  /** Test the present value. */
  public void presentValueExplicit() {
    final MultipleCurrencyAmount pv = METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final double timeToExpiry = SWAPTION_LONG_PAYER.getTimeToExpiry();
    final AnnuityPaymentFixed cfe =
        CFEC.visitSwap(SWAPTION_LONG_PAYER.getUnderlyingSwap(), MULTICURVES);
    final int numberOfPayments = cfe.getNumberOfPayments();
    final double alpha[] = new double[numberOfPayments];
    final double disccf[] = new double[numberOfPayments];
    for (int loopcf = 0; loopcf < numberOfPayments; loopcf++) {
      alpha[loopcf] =
          MODEL.alpha(
              HW_PARAMETERS,
              0.0,
              timeToExpiry,
              timeToExpiry,
              cfe.getNthPayment(loopcf).getPaymentTime());
      disccf[loopcf] =
          MULTICURVES.getDiscountFactor(EUR, cfe.getNthPayment(loopcf).getPaymentTime())
              * cfe.getNthPayment(loopcf).getAmount();
    }
    final double kappa = MODEL.kappa(disccf, alpha);
    double pvExpected = 0.0;
    for (int loopcf = 0; loopcf < numberOfPayments; loopcf++) {
      pvExpected += disccf[loopcf] * NORMAL.getCDF(-kappa - alpha[loopcf]);
    }
    assertEquals(
        "Swaption physical - Hull-White - present value", pvExpected, pv.getAmount(EUR), 1E-2);
    final MultipleCurrencyAmount pv2 =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, cfe, HW_MULTICURVES);
    assertEquals("Swaption physical - Hull-White - present value", pv, pv2);
  }

  @Test
  /** Tests long/short parity. */
  public void longShortParityExplicit() {
    final MultipleCurrencyAmount pvLong =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvShort =
        METHOD_HW.presentValue(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - long/short parity",
        pvLong.getAmount(EUR),
        -pvShort.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Tests payer/receiver/swap parity. */
  public void payerReceiverParityExplicit() {
    final MultipleCurrencyAmount pvReceiverLong =
        METHOD_HW.presentValue(SWAPTION_LONG_RECEIVER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerShort =
        METHOD_HW.presentValue(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvSwap = SWAP_RECEIVER.accept(PVDC, MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - payer/receiver/swap parity",
        pvReceiverLong.getAmount(EUR) + pvPayerShort.getAmount(EUR),
        pvSwap.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Tests the method against the present value calculator. */
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = SWAPTION_LONG_PAYER.accept(PVHWC, HW_MULTICURVES);
    assertEquals(
        "SwaptionPhysicalFixedIborSABRMethod: present value : method and calculator",
        pvMethod,
        pvCalculator);
  }

  @Test
  /** Compare explicit formula with numerical integration. */
  public void presentValueNumericalIntegration() {
    final MultipleCurrencyAmount pvPayerLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvPayerLongExplicit.getAmount(EUR),
        pvPayerLongIntegration.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvPayerShortExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerShortIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvPayerShortExplicit.getAmount(EUR),
        pvPayerShortIntegration.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvReceiverLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvReceiverLongIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvReceiverLongExplicit.getAmount(EUR),
        pvReceiverLongIntegration.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvReceiverShortExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvReceiverShortIntegration =
        METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvReceiverShortExplicit.getAmount(EUR),
        pvReceiverShortIntegration.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Compare explicit formula with approximated formula. */
  public void presentValueApproximation() {
    final BlackImpliedVolatilityFormula implied = new BlackImpliedVolatilityFormula();
    final double forward =
        SWAPTION_LONG_PAYER
            .getUnderlyingSwap()
            .accept(ParRateDiscountingCalculator.getInstance(), MULTICURVES);
    final double pvbp =
        METHOD_SWAP.presentValueBasisPoint(SWAPTION_LONG_PAYER.getUnderlyingSwap(), MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongApproximation =
        METHOD_HW_APPROXIMATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final BlackFunctionData data = new BlackFunctionData(forward, pvbp, 0.20);
    final double volExplicit =
        implied.getImpliedVolatility(data, SWAPTION_LONG_PAYER, pvPayerLongExplicit.getAmount(EUR));
    final double volApprox =
        implied.getImpliedVolatility(
            data, SWAPTION_LONG_PAYER, pvPayerLongApproximation.getAmount(EUR));
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/approximation",
        pvPayerLongExplicit.getAmount(EUR),
        pvPayerLongApproximation.getAmount(EUR),
        5.0E+2);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/approximation",
        volExplicit,
        volApprox,
        2.5E-4); // 0.025%
    final MultipleCurrencyAmount pvReceiverLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvReceiverLongApproximation =
        METHOD_HW_APPROXIMATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - present value - explicit/numerical integration",
        pvReceiverLongExplicit.getAmount(EUR),
        pvReceiverLongApproximation.getAmount(EUR),
        5.0E+2);
  }

  @Test
  /** Approximation analysis. */
  public void presentValueApproximationAnalysis() {
    final NormalImpliedVolatilityFormula implied = new NormalImpliedVolatilityFormula();
    final int nbStrike = 20;
    final double[] pvExplicit = new double[nbStrike + 1];
    final double[] pvApproximation = new double[nbStrike + 1];
    final double[] strike = new double[nbStrike + 1];
    final double[] volExplicit = new double[nbStrike + 1];
    final double[] volApprox = new double[nbStrike + 1];
    final double strikeRange = 0.010;
    final SwapFixedCoupon<Coupon> swap = SWAP_PAYER_DEFINITION.toDerivative(REFERENCE_DATE);
    final double forward = swap.accept(PRDC, MULTICURVES);
    final double pvbp = METHOD_SWAP.presentValueBasisPoint(swap, MULTICURVES);
    for (int loopstrike = 0; loopstrike <= nbStrike; loopstrike++) {
      strike[loopstrike] =
          forward
              - strikeRange
              + 3
                  * strikeRange
                  * loopstrike
                  / nbStrike; // From forward-strikeRange to forward+2*strikeRange
      final SwapFixedIborDefinition swapDefinition =
          SwapFixedIborDefinition.from(
              SETTLEMENT_DATE,
              SWAP_TENOR,
              EUR1YEURIBOR6M,
              NOTIONAL,
              strike[loopstrike],
              FIXED_IS_PAYER);
      final SwaptionPhysicalFixedIborDefinition swaptionDefinition =
          SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, swapDefinition, IS_LONG);
      final SwaptionPhysicalFixedIbor swaption = swaptionDefinition.toDerivative(REFERENCE_DATE);
      pvExplicit[loopstrike] = METHOD_HW.presentValue(swaption, HW_MULTICURVES).getAmount(EUR);
      pvApproximation[loopstrike] =
          METHOD_HW_APPROXIMATION.presentValue(swaption, HW_MULTICURVES).getAmount(EUR);
      final NormalFunctionData data = new NormalFunctionData(forward, pvbp, 0.01);
      volExplicit[loopstrike] =
          implied.getImpliedVolatility(data, swaption, pvExplicit[loopstrike]);
      volApprox[loopstrike] =
          implied.getImpliedVolatility(data, swaption, pvApproximation[loopstrike]);
      assertEquals(
          "Swaption physical - Hull-White - implied volatility - explicit/approximation",
          volExplicit[loopstrike],
          volApprox[loopstrike],
          1.0E-3); // 0.10%
    }
  }

  @Test(enabled = true)
  /** Compare explicit formula with Monte-Carlo and long/short and payer/receiver parities. */
  public void presentValueMonteCarlo() {
    HullWhiteMonteCarloMethod methodMC;
    methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);
    // Seed fixed to the DEFAULT_SEED for testing purposes.
    final MultipleCurrencyAmount pvPayerLongExplicit =
        METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyAmount pvPayerLongMC =
        methodMC.presentValue(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo",
        pvPayerLongExplicit.getAmount(EUR),
        pvPayerLongMC.getAmount(EUR),
        1.0E+4);
    final double pvMCPreviousRun = 4221400.891;
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo",
        pvMCPreviousRun,
        pvPayerLongMC.getAmount(EUR),
        TOLERANCE_PV);
    methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);
    final MultipleCurrencyAmount pvPayerShortMC =
        methodMC.presentValue(SWAPTION_SHORT_PAYER, EUR, HW_MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo",
        -pvPayerLongMC.getAmount(EUR),
        pvPayerShortMC.getAmount(EUR),
        TOLERANCE_PV);
    final MultipleCurrencyAmount pvReceiverLongMC =
        methodMC.presentValue(SWAPTION_LONG_RECEIVER, EUR, HW_MULTICURVES);
    final MultipleCurrencyAmount pvSwap = SWAP_RECEIVER.accept(PVDC, MULTICURVES);
    assertEquals(
        "Swaption physical - Hull-White - Monte Carlo - payer/receiver/swap parity",
        pvReceiverLongMC.getAmount(EUR) + pvPayerShortMC.getAmount(EUR),
        pvSwap.getAmount(EUR),
        1.0E+5);
  }

  @Test
  /** Tests the Hull-White parameters sensitivity for the explicit formula. */
  public void presentValueHullWhiteSensitivityExplicit() {
    final double[] hwSensitivity =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final int nbVolatility = HW_PARAMETERS.getVolatility().length;
    final double shiftVol = 1.0E-6;
    final double[] volatilityBumped = new double[nbVolatility];
    System.arraycopy(HW_PARAMETERS.getVolatility(), 0, volatilityBumped, 0, nbVolatility);
    final double[] volatilityTime = new double[nbVolatility - 1];
    System.arraycopy(HW_PARAMETERS.getVolatilityTime(), 1, volatilityTime, 0, nbVolatility - 1);
    final double[] pvBumpedPlus = new double[nbVolatility];
    final double[] pvBumpedMinus = new double[nbVolatility];
    final HullWhiteOneFactorPiecewiseConstantParameters parametersBumped =
        new HullWhiteOneFactorPiecewiseConstantParameters(
            HW_PARAMETERS.getMeanReversion(), volatilityBumped, volatilityTime);
    final HullWhiteOneFactorProviderDiscount bundleBumped =
        new HullWhiteOneFactorProviderDiscount(MULTICURVES, parametersBumped, EUR);
    for (int loopvol = 0; loopvol < nbVolatility; loopvol++) {
      volatilityBumped[loopvol] += shiftVol;
      parametersBumped.setVolatility(volatilityBumped);
      pvBumpedPlus[loopvol] =
          METHOD_HW.presentValue(SWAPTION_LONG_PAYER, bundleBumped).getAmount(EUR);
      volatilityBumped[loopvol] -= 2 * shiftVol;
      parametersBumped.setVolatility(volatilityBumped);
      pvBumpedMinus[loopvol] =
          METHOD_HW.presentValue(SWAPTION_LONG_PAYER, bundleBumped).getAmount(EUR);
      assertEquals(
          "Swaption - Hull-White sensitivity adjoint: derivative "
              + loopvol
              + " - difference:"
              + ((pvBumpedPlus[loopvol] - pvBumpedMinus[loopvol]) / (2 * shiftVol)
                  - hwSensitivity[loopvol]),
          (pvBumpedPlus[loopvol] - pvBumpedMinus[loopvol]) / (2 * shiftVol),
          hwSensitivity[loopvol],
          TOLERANCE_PV_DELTA);
      volatilityBumped[loopvol] = HW_PARAMETERS.getVolatility()[loopvol];
    }
  }

  @Test
  /** Tests long/short parity. */
  public void presentValueHullWhiteSensitivitylongShortParityExplicit() {
    final double[] pvhwsLong =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final double[] pvhwsShort =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    for (int loophw = 0; loophw < pvhwsLong.length; loophw++) {
      assertEquals(
          "Swaption physical - Hull-White - presentValueHullWhiteSensitivity - long/short parity",
          pvhwsLong[loophw],
          -pvhwsShort[loophw],
          TOLERANCE_PV_DELTA);
    }
  }

  @Test
  /** Tests payer/receiver/swap parity. */
  public void presentValueHullWhiteSensitivitypayerReceiverParityExplicit() {
    final double[] pvhwsReceiverLong =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_RECEIVER, HW_MULTICURVES);
    final double[] pvhwsPayerShort =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    for (int loophw = 0; loophw < pvhwsReceiverLong.length; loophw++) {
      assertEquals(
          "Swaption physical - Hull-White - present value - payer/receiver/swap parity",
          0,
          pvhwsReceiverLong[loophw] + pvhwsPayerShort[loophw],
          TOLERANCE_PV_DELTA);
    }
  }

  @Test
  /** Tests present value curve sensitivity when the valuation date is on trade date. */
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsExact =
        PS_HW_C.calculateSensitivity(
            SWAPTION_SHORT_RECEIVER,
            HW_MULTICURVES,
            HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsFD =
        PS_HW_FDC.calculateSensitivity(SWAPTION_SHORT_RECEIVER, HW_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "SwaptionPhysicalFixedIborSABRMethod: presentValueCurveSensitivity ",
        pvpsExact,
        pvpsFD,
        TOLERANCE_PV_DELTA);
  }

  @Test(enabled = false)
  /** Tests present value curve sensitivity when the valuation date is on trade date. */
  public void presentValueCurveSensitivityStability() {
    // 5Yx5Y
    final MultipleCurrencyParameterSensitivity pvpsExact =
        PS_HW_C.calculateSensitivity(
            SWAPTION_SHORT_RECEIVER,
            HW_MULTICURVES,
            HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final double derivativeExact = pvpsExact.totalSensitivity(MULTICURVES.getFxRates(), EUR);
    final double startingShift = 1.0E-4;
    final double ratio = Math.sqrt(2.0);
    final int nbShift = 55;
    final double[] eps = new double[nbShift + 1];
    final double[] derivative_FD = new double[nbShift];
    final double[] diff = new double[nbShift];
    eps[0] = startingShift;
    for (int loopshift = 0; loopshift < nbShift; loopshift++) {
      final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator fdShift =
          new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(PVHWC, eps[loopshift]);
      final MultipleCurrencyParameterSensitivity pvpsFD =
          fdShift.calculateSensitivity(SWAPTION_SHORT_RECEIVER, HW_MULTICURVES);
      derivative_FD[loopshift] = pvpsFD.totalSensitivity(MULTICURVES.getFxRates(), EUR);
      diff[loopshift] = derivative_FD[loopshift] - derivativeExact;
      eps[loopshift + 1] = eps[loopshift] / ratio;
    }
    // 1Mx5Y
    final Period expirationPeriod =
        Period.ofDays(
            1); // Period.ofDays(1); Period.ofDays(7); Period.ofMonths(1); Period.ofYears(1);
    // Period.ofYears(10);
    final ZonedDateTime expiryDateExp =
        ScheduleCalculator.getAdjustedDate(REFERENCE_DATE, expirationPeriod, EURIBOR6M, CALENDAR);
    final ZonedDateTime settlementDateExp =
        ScheduleCalculator.getAdjustedDate(expiryDateExp, SPOT_LAG, CALENDAR);
    final double ATM = 0.0151; //  1W: 1.52% - 1M: 1.52% - 1Y: 1.51% - 10Y: 1.51%
    final SwapFixedIborDefinition swapExpx5YDefinition =
        SwapFixedIborDefinition.from(
            settlementDateExp, SWAP_TENOR, EUR1YEURIBOR6M, NOTIONAL, ATM, !FIXED_IS_PAYER);
    final SwaptionPhysicalFixedIborDefinition swaptionExpx5YDefinition =
        SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, swapExpx5YDefinition, !IS_LONG);
    final SwaptionPhysicalFixedIbor swaptionExpx5Y =
        swaptionExpx5YDefinition.toDerivative(REFERENCE_DATE);
    //    final double forward = swaptionExpx5Y.getUnderlyingSwap().accept(PRDC, MULTICURVES);
    final MultipleCurrencyParameterSensitivity pvpsExactExp =
        PS_HW_C.calculateSensitivity(
            swaptionExpx5Y, HW_MULTICURVES, HW_MULTICURVES.getMulticurveProvider().getAllNames());
    final double derivativeExactExp = pvpsExactExp.totalSensitivity(MULTICURVES.getFxRates(), EUR);
    final double[] derivative_FDExp = new double[nbShift];
    final double[] diffExp = new double[nbShift];
    for (int loopshift = 0; loopshift < nbShift; loopshift++) {
      final ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator fdShift =
          new ParameterSensitivityHullWhiteDiscountInterpolatedFDCalculator(PVHWC, eps[loopshift]);
      final MultipleCurrencyParameterSensitivity pvpsFD =
          fdShift.calculateSensitivity(swaptionExpx5Y, HW_MULTICURVES);
      derivative_FDExp[loopshift] = pvpsFD.totalSensitivity(MULTICURVES.getFxRates(), EUR);
      diffExp[loopshift] = derivative_FDExp[loopshift] - derivativeExactExp;
    }
    //    int t = 0;
    //    t++;
  }

  @Test
  /** Tests long/short parity. */
  public void presentValueCurveSensitivityLongShortParityExplicit() {
    final MultipleCurrencyMulticurveSensitivity pvhwsLong =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvhwsShort =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption physical - Hull-White - presentValueCurveSensitivity - long/short parity",
        pvhwsLong,
        pvhwsShort.multipliedBy(-1.0),
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests payer/receiver/swap parity. */
  public void presentValueCurveSensitivityPayerReceiverParityExplicit() {
    final MultipleCurrencyMulticurveSensitivity pvhwsReceiverLong =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_RECEIVER, HW_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvhwsPayerShort =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_SHORT_PAYER, HW_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvSwap = SWAP_RECEIVER.accept(PVCSDC, MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption physical - Hull-White - presentValueCurveSensitivity - payer/receiver/swap parity",
        pvSwap.cleaned(TOLERANCE_PV_DELTA),
        pvhwsReceiverLong.plus(pvhwsPayerShort).cleaned(TOLERANCE_PV_DELTA),
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests the curve sensitivity in Monte Carlo approach. */
  public void presentValueCurveSensitivityMonteCarlo() {
    final double toleranceDelta = 1.0E+6; // 100 USD by bp
    final MultipleCurrencyMulticurveSensitivity pvcsExplicit =
        METHOD_HW
            .presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES)
            .cleaned(TOLERANCE_PV_DELTA);
    final HullWhiteMonteCarloMethod methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);
    final MultipleCurrencyMulticurveSensitivity pvcsMC =
        methodMC
            .presentValueCurveSensitivity(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES)
            .cleaned(TOLERANCE_PV_DELTA);
    AssertSensivityObjects.assertEquals(
        "Swaption physical - Hull-White - presentValueCurveSensitivity - payer/receiver/swap parity",
        pvcsExplicit,
        pvcsMC,
        toleranceDelta);
  }

  @Test(enabled = false)
  /** Tests of performance. "enabled = false" for the standard testing. */
  public void performance() {
    long startTime, endTime;
    final int nbTest = 1000;
    MultipleCurrencyAmount pvPayerLongExplicit = MultipleCurrencyAmount.of(EUR, 0.0);
    MultipleCurrencyAmount pvPayerLongIntegration = MultipleCurrencyAmount.of(EUR, 0.0);
    MultipleCurrencyAmount pvPayerLongApproximation = MultipleCurrencyAmount.of(EUR, 0.0);
    @SuppressWarnings("unused")
    MultipleCurrencyAmount pvPayerLongMC = MultipleCurrencyAmount.of(EUR, 0.0);
    double[] pvhws =
        METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    MultipleCurrencyMulticurveSensitivity pvcs =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongExplicit = METHOD_HW.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest + " pv swaption Hull-White explicit method: " + (endTime - startTime) + " ms");
    // Performance note: HW price: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 380 ms for
    // 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvhws = METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " HW sensitivity swaption Hull-White explicit method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: HW sensitivity (3): 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon:
    // 430 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvcs = METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " curve sensitivity swaption Hull-White explicit method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: curve sensitivity (40): 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 855 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvhws = METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
      pvcs = METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
      pvhws = METHOD_HW.presentValueHullWhiteSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " price/delta/vega swaption Hull-White explicit method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: present value/delta/vega: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 1730 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongIntegration =
          METHOD_HW_INTEGRATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " swaption Hull-White numerical integration method: "
            + (endTime - startTime)
            + " ms");
    // Performance note: HW numerical integration: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 1700 ms for 10000 swaptions.
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongApproximation =
          METHOD_HW_APPROXIMATION.presentValue(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest + " swaption Hull-White approximation method: " + (endTime - startTime) + " ms");
    // Performance note: HW approximation: 19-Nov-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 250
    // ms for 10000 swaptions.

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvPayerLongMC = METHOD_HW_MONTECARLO.presentValue(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " swaption Hull-White Monte Carlo method ("
            + NB_PATH
            + " paths): "
            + (endTime - startTime)
            + " ms");
    // Performance note: HW approximation: 18-Aug-11: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 9200
    // ms for 1000 swaptions (12500 paths).

    final double difference =
        pvPayerLongExplicit.getAmount(EUR) - pvPayerLongIntegration.getAmount(EUR);
    final double difference2 =
        pvPayerLongExplicit.getAmount(EUR) - pvPayerLongApproximation.getAmount(EUR);
    //      double difference3 = pvPayerLongExplicit.getAmount(CUR) - pvPayerLongMC.getAmount(CUR);
    System.out.println("Difference explicit-integration: " + difference);
    System.out.println("Difference explicit-approximation: " + difference2);
    //      System.out.println("Difference explicit-Monte Carlo: " + difference3);
    System.out.println("Curve sensitivity: " + pvcs.toString());
    System.out.println("HW sensitivity: " + Arrays.toString(pvhws));
  }

  @Test(enabled = false)
  /** Tests of performance. "enabled = false" for the standard testing. */
  public void performanceCurveSensitivity() {
    long startTime, endTime;
    final int nbTest = 25;
    MultipleCurrencyAmount pvMC = MultipleCurrencyAmount.of(EUR, 0.0);
    final MultipleCurrencyMulticurveSensitivity pvcsExplicit =
        METHOD_HW.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, HW_MULTICURVES);
    MultipleCurrencyMulticurveSensitivity pvcsMC = pvcsExplicit;
    final HullWhiteMonteCarloMethod methodMC =
        new HullWhiteMonteCarloMethod(
            new NormalRandomNumberGenerator(0.0, 1.0, new MersenneTwister()), NB_PATH);

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvMC = METHOD_HW_MONTECARLO.presentValue(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " swaption Hull-White Monte Carlo method ("
            + NB_PATH
            + " paths): "
            + (endTime - startTime)
            + " ms / price:"
            + pvMC.toString());
    // Performance note: HW approximation: 03-Dec-2012: On Mac Pro 3.2 GHz Quad-Core Intel Xeon: 250
    // ms for 25 swaptions (12500 paths).
    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      pvcsMC = methodMC.presentValueCurveSensitivity(SWAPTION_LONG_PAYER, EUR, HW_MULTICURVES);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        nbTest
            + " curve sensitivity swaption Hull-White MC method: ("
            + NB_PATH
            + " paths) "
            + (endTime - startTime)
            + " ms / risk:"
            + pvcsMC.toString());
    // Performance note: curve sensitivity (40): 03-Dec-2012: On Mac Pro 3.2 GHz Quad-Core Intel
    // Xeon: 600 ms for 25 swaptions (12500 paths).

  }
}
/** Build of inflation curve in several blocks with relevant Jacobian matrice. */
public class InflationBuildingCurveSimpleTestEUR {

  private static final Interpolator1D INTERPOLATOR_LINEAR =
      CombinedInterpolatorExtrapolatorFactory.getInterpolator(
          Interpolator1DFactory.LOG_LINEAR,
          Interpolator1DFactory.FLAT_EXTRAPOLATOR,
          Interpolator1DFactory.FLAT_EXTRAPOLATOR);

  private static final LastTimeCalculator MATURITY_CALCULATOR = LastTimeCalculator.getInstance();
  private static final double TOLERANCE_ROOT = 1.0E-10;
  private static final int STEP_MAX = 100;

  private static final Currency EUR = Currency.EUR;

  private static final double NOTIONAL = 1.0;

  private static final GeneratorSwapFixedInflationZeroCoupon GENERATOR_INFLATION_SWAP =
      GeneratorSwapFixedInflationMaster.getInstance().getGenerator("EURHICP");
  private static final IndexPrice EUR_HICP = GENERATOR_INFLATION_SWAP.getIndexPrice();

  private static final ZonedDateTime NOW = DateUtils.getUTCDate(2012, 9, 28);

  private static final ZonedDateTimeDoubleTimeSeries TS_PRICE_INDEX_USD_WITH_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {
            DateUtils.getUTCDate(2011, 9, 27), DateUtils.getUTCDate(2011, 9, 28)
          },
          new double[] {200, 200});
  private static final ZonedDateTimeDoubleTimeSeries TS_PRICE_INDEX_USD_WITHOUT_TODAY =
      ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
          new ZonedDateTime[] {DateUtils.getUTCDate(2011, 9, 27)}, new double[] {100});

  @SuppressWarnings("rawtypes")
  private static final DoubleTimeSeries[] TS_FIXED_PRICE_INDEX_USD_WITH_TODAY =
      new DoubleTimeSeries[] {TS_PRICE_INDEX_USD_WITH_TODAY};

  @SuppressWarnings("rawtypes")
  private static final DoubleTimeSeries[] TS_FIXED_PRICE_INDEX_USD_WITHOUT_TODAY =
      new DoubleTimeSeries[] {TS_PRICE_INDEX_USD_WITHOUT_TODAY};

  private static final String CURVE_NAME_HICP_EUR = "EUR HICP";

  /** Market values for the HICP EUR curve */
  public static final double[] HICP_EUR_MARKET_QUOTES =
      new double[] {
        0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200, 0.0200,
        0.0200, 0.0200, 0.0200, 0.0200
      };

  /** Generators for the HICP EUR curve */
  private static final GeneratorInstrument<? extends GeneratorAttribute>[] HICP_EUR_GENERATORS =
      new GeneratorInstrument<?>[] {
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP,
        GENERATOR_INFLATION_SWAP
      };
  /** Tenors for the HICP EUR curve */
  private static final Period[] HICP_EUR_TENOR =
      new Period[] {
        Period.ofYears(1),
        Period.ofYears(2),
        Period.ofYears(3),
        Period.ofYears(4),
        Period.ofYears(5),
        Period.ofYears(6),
        Period.ofYears(7),
        Period.ofYears(8),
        Period.ofYears(9),
        Period.ofYears(10),
        Period.ofYears(12),
        Period.ofYears(15),
        Period.ofYears(20),
        Period.ofYears(25),
        Period.ofYears(30)
      };

  private static final GeneratorAttributeIR[] HICP_EUR_ATTR =
      new GeneratorAttributeIR[HICP_EUR_TENOR.length];

  static {
    for (int loopins = 0; loopins < HICP_EUR_TENOR.length; loopins++) {
      HICP_EUR_ATTR[loopins] = new GeneratorAttributeIR(HICP_EUR_TENOR[loopins]);
    }
  }

  /** Standard EUR HICP curve instrument definitions */
  private static final InstrumentDefinition<?>[] DEFINITIONS_HICP_EUR;

  /** Units of curves */
  private static final int[] NB_UNITS = new int[] {1};

  private static final int NB_BLOCKS = NB_UNITS.length;
  private static final InstrumentDefinition<?>[][][][] DEFINITIONS_UNITS =
      new InstrumentDefinition<?>[NB_BLOCKS][][][];
  private static final GeneratorPriceIndexCurve[][][] GENERATORS_UNITS =
      new GeneratorPriceIndexCurve[NB_BLOCKS][][];
  private static final String[][][] NAMES_UNITS = new String[NB_BLOCKS][][];

  private static final MulticurveProviderDiscount eurMulticurveProviderDiscount =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd().copy();
  private static final InflationProviderDiscount KNOWN_DATA =
      new InflationProviderDiscount(eurMulticurveProviderDiscount);

  private static final LinkedHashMap<String, IndexPrice[]> EUR_HICP_MAP = new LinkedHashMap<>();

  static {
    DEFINITIONS_HICP_EUR =
        getDefinitions(HICP_EUR_MARKET_QUOTES, HICP_EUR_GENERATORS, HICP_EUR_ATTR);

    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      DEFINITIONS_UNITS[loopblock] = new InstrumentDefinition<?>[NB_UNITS[loopblock]][][];
      GENERATORS_UNITS[loopblock] = new GeneratorPriceIndexCurve[NB_UNITS[loopblock]][];
      NAMES_UNITS[loopblock] = new String[NB_UNITS[loopblock]][];
    }
    DEFINITIONS_UNITS[0][0] = new InstrumentDefinition<?>[][] {DEFINITIONS_HICP_EUR};

    final GeneratorPriceIndexCurve genIntLin =
        new GeneratorPriceIndexCurveInterpolated(MATURITY_CALCULATOR, INTERPOLATOR_LINEAR);
    GENERATORS_UNITS[0][0] = new GeneratorPriceIndexCurve[] {genIntLin};

    NAMES_UNITS[0][0] = new String[] {CURVE_NAME_HICP_EUR};

    EUR_HICP_MAP.put(CURVE_NAME_HICP_EUR, new IndexPrice[] {EUR_HICP});
  }

  private static final String NOT_USED = "Not used";
  private static final String[] NOT_USED_2 = {NOT_USED, NOT_USED};

  public static InstrumentDefinition<?>[] getDefinitions(
      final double[] marketQuotes,
      final GeneratorInstrument[] generators,
      final GeneratorAttribute[] attribute) {
    final InstrumentDefinition<?>[] definitions = new InstrumentDefinition<?>[marketQuotes.length];
    for (int loopmv = 0; loopmv < marketQuotes.length; loopmv++) {
      definitions[loopmv] =
          generators[loopmv].generateInstrument(
              NOW, marketQuotes[loopmv], NOTIONAL, attribute[loopmv]);
    }
    return definitions;
  }

  private static List<Pair<InflationProviderDiscount, CurveBuildingBlockBundle>>
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK =
          new ArrayList<Pair<InflationProviderDiscount, CurveBuildingBlockBundle>>();

  // Calculator
  private static final PresentValueDiscountingInflationCalculator PVIC =
      PresentValueDiscountingInflationCalculator.getInstance();
  private static final ParSpreadInflationMarketQuoteDiscountingCalculator PSIMQC =
      ParSpreadInflationMarketQuoteDiscountingCalculator.getInstance();
  private static final ParSpreadInflationMarketQuoteCurveSensitivityDiscountingCalculator PSIMQCSC =
      ParSpreadInflationMarketQuoteCurveSensitivityDiscountingCalculator.getInstance();

  private static final InflationDiscountBuildingRepository CURVE_BUILDING_REPOSITORY =
      new InflationDiscountBuildingRepository(TOLERANCE_ROOT, TOLERANCE_ROOT, STEP_MAX);

  private static final double TOLERANCE_CAL = 1.0E-9;

  @BeforeSuite
  static void initClass() {
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.add(
          makeCurvesFromDefinitions(
              DEFINITIONS_UNITS[loopblock],
              GENERATORS_UNITS[loopblock],
              NAMES_UNITS[loopblock],
              KNOWN_DATA,
              PSIMQC,
              PSIMQCSC,
              false));
    }
  }

  @Test(enabled = false)
  public void performance() {
    long startTime, endTime;
    final int nbTest = 1000;

    startTime = System.currentTimeMillis();
    for (int looptest = 0; looptest < nbTest; looptest++) {
      makeCurvesFromDefinitions(
          DEFINITIONS_UNITS[0],
          GENERATORS_UNITS[0],
          NAMES_UNITS[0],
          KNOWN_DATA,
          PSIMQC,
          PSIMQCSC,
          false);
    }
    endTime = System.currentTimeMillis();
    System.out.println(
        "InflationBuildingCurveSimpleTestEUR - "
            + nbTest
            + " curve construction Price index EUR 1 units: "
            + (endTime - startTime)
            + " ms");
    // Performance note: curve construction Price index EUR 1 units: 27-Mar-13: On Dell Precision
    // T1850 3.5 GHz Quad-Core Intel Xeon: 2816 ms for 1000 sets.
  }

  @Test
  public void curveConstructionGeneratorOtherBlocks() {
    for (int loopblock = 0; loopblock < NB_BLOCKS; loopblock++) {
      curveConstructionTest(
          DEFINITIONS_UNITS[loopblock],
          CURVES_PAR_SPREAD_MQ_WITHOUT_TODAY_BLOCK.get(loopblock).getFirst(),
          false,
          loopblock);
    }
  }

  public void curveConstructionTest(
      final InstrumentDefinition<?>[][][] definitions,
      final InflationProviderDiscount curves,
      final boolean withToday,
      final int block) {
    final int nbBlocks = definitions.length;
    for (int loopblock = 0; loopblock < nbBlocks; loopblock++) {
      final InstrumentDerivative[][] instruments =
          convert(definitions[loopblock], loopblock, withToday);
      final double[][] pv = new double[instruments.length][];
      for (int loopcurve = 0; loopcurve < instruments.length; loopcurve++) {
        pv[loopcurve] = new double[instruments[loopcurve].length];
        for (int loopins = 0; loopins < instruments[loopcurve].length; loopins++) {
          pv[loopcurve][loopins] =
              curves
                  .getFxRates()
                  .convert(instruments[loopcurve][loopins].accept(PVIC, curves), EUR)
                  .getAmount();
          assertEquals(
              "Curve construction: block "
                  + block
                  + ", unit "
                  + loopblock
                  + " - instrument "
                  + loopins,
              0,
              pv[loopcurve][loopins],
              TOLERANCE_CAL);
        }
      }
    }
  }

  private static Pair<InflationProviderDiscount, CurveBuildingBlockBundle>
      makeCurvesFromDefinitions(
          final InstrumentDefinition<?>[][][] definitions,
          final GeneratorPriceIndexCurve[][] curveGenerators,
          final String[][] curveNames,
          final InflationProviderDiscount knownData,
          final InstrumentDerivativeVisitor<InflationProviderInterface, Double> calculator,
          final InstrumentDerivativeVisitor<InflationProviderInterface, InflationSensitivity>
              sensitivityCalculator,
          final boolean withToday) {
    final int nbUnits = curveGenerators.length;
    final double[][] parametersGuess = new double[nbUnits][];
    final GeneratorPriceIndexCurve[][] generatorFinal = new GeneratorPriceIndexCurve[nbUnits][];
    final InstrumentDerivative[][][] instruments = new InstrumentDerivative[nbUnits][][];
    for (int loopunit = 0; loopunit < nbUnits; loopunit++) {
      generatorFinal[loopunit] = new GeneratorPriceIndexCurve[curveGenerators[loopunit].length];
      int nbInsUnit = 0;
      for (int loopcurve = 0; loopcurve < curveGenerators[loopunit].length; loopcurve++) {
        nbInsUnit += definitions[loopunit][loopcurve].length;
      }
      parametersGuess[loopunit] = new double[nbInsUnit];
      int startCurve = 0; // First parameter index of the curve in the unit.
      instruments[loopunit] = convert(definitions[loopunit], loopunit, withToday);
      for (int loopcurve = 0; loopcurve < curveGenerators[loopunit].length; loopcurve++) {
        generatorFinal[loopunit][loopcurve] =
            curveGenerators[loopunit][loopcurve].finalGenerator(instruments[loopunit][loopcurve]);
        final double[] guessCurve =
            generatorFinal[loopunit][loopcurve].initialGuess(
                initialGuess(definitions[loopunit][loopcurve]));
        System.arraycopy(
            guessCurve,
            0,
            parametersGuess[loopunit],
            startCurve,
            instruments[loopunit][loopcurve].length);
        startCurve += instruments[loopunit][loopcurve].length;
      }
    }
    return CURVE_BUILDING_REPOSITORY.makeCurvesFromDerivatives(
        instruments,
        generatorFinal,
        curveNames,
        parametersGuess,
        knownData,
        EUR_HICP_MAP,
        calculator,
        sensitivityCalculator);
  }

  @SuppressWarnings("unchecked")
  private static InstrumentDerivative[][] convert(
      final InstrumentDefinition<?>[][] definitions, final int unit, final boolean withToday) {
    //    int nbDef = 0;
    //    for (final InstrumentDefinition<?>[] definition : definitions) {
    //      nbDef += definition.length;
    //    }
    final InstrumentDerivative[][] instruments = new InstrumentDerivative[definitions.length][];
    for (int loopcurve = 0; loopcurve < definitions.length; loopcurve++) {
      instruments[loopcurve] = new InstrumentDerivative[definitions[loopcurve].length];
      int loopins = 0;
      for (final InstrumentDefinition<?> instrument : definitions[loopcurve]) {
        InstrumentDerivative ird;
        if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {
          /* ird = ((SwapFixedInflationZeroCouponDefinition) instrument).toDerivative(NOW, getTSSwapFixedInflation(withToday, unit), NOT_USED_2);*/
          final Annuity<? extends Payment> ird1 =
              ((SwapFixedInflationZeroCouponDefinition) instrument)
                  .getFirstLeg()
                  .toDerivative(NOW, NOT_USED_2);
          final Annuity<? extends Payment> ird2 =
              ((SwapFixedInflationZeroCouponDefinition) instrument)
                  .getSecondLeg()
                  .toDerivative(NOW, TS_PRICE_INDEX_USD_WITH_TODAY, NOT_USED_2);
          ird = new Swap<>(ird1, ird2);
        } else {
          ird = instrument.toDerivative(NOW, NOT_USED_2);
        }
        instruments[loopcurve][loopins++] = ird;
      }
    }
    return instruments;
  }

  @SuppressWarnings("rawtypes")
  private static DoubleTimeSeries[] getTSSwapFixedInflation(
      final Boolean withToday, final Integer unit) {
    switch (unit) {
      case 0:
        return withToday
            ? TS_FIXED_PRICE_INDEX_USD_WITH_TODAY
            : TS_FIXED_PRICE_INDEX_USD_WITHOUT_TODAY;
      case 1:
        return withToday
            ? TS_FIXED_PRICE_INDEX_USD_WITH_TODAY
            : TS_FIXED_PRICE_INDEX_USD_WITHOUT_TODAY;
      default:
        throw new IllegalArgumentException(unit.toString());
    }
  }

  private static double[] initialGuess(final InstrumentDefinition<?>[] definitions) {
    final double[] result = new double[definitions.length];
    int loopr = 0;
    for (final InstrumentDefinition<?> definition : definitions) {
      result[loopr++] = initialGuess(definition);
    }
    return result;
  }

  private static double initialGuess(final InstrumentDefinition<?> instrument) {
    if (instrument instanceof SwapFixedONDefinition) {
      return ((SwapFixedONDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
    }
    if (instrument instanceof SwapFixedIborDefinition) {
      return ((SwapFixedIborDefinition) instrument).getFixedLeg().getNthPayment(0).getRate();
    }
    if (instrument instanceof SwapFixedInflationZeroCouponDefinition) {

      if (((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().getNthPayment(0)
          instanceof CouponInflationZeroCouponMonthlyDefinition) {
        return ((CouponInflationZeroCouponMonthlyDefinition)
                ((SwapFixedInflationZeroCouponDefinition) instrument)
                    .getFirstLeg()
                    .getNthPayment(0))
            .getIndexStartValue();
      }
      if (((SwapFixedInflationZeroCouponDefinition) instrument).getFirstLeg().getNthPayment(0)
          instanceof CouponInflationZeroCouponInterpolationDefinition) {
        return ((CouponInflationZeroCouponInterpolationDefinition)
                ((SwapFixedInflationZeroCouponDefinition) instrument)
                    .getFirstLeg()
                    .getNthPayment(0))
            .getIndexStartValue();
      }
      return 100;
    }
    if (instrument instanceof ForwardRateAgreementDefinition) {
      return ((ForwardRateAgreementDefinition) instrument).getRate();
    }
    if (instrument instanceof CashDefinition) {
      return ((CashDefinition) instrument).getRate();
    }
    return 1;
  }
}
  @Test
  /**
   * Tests the toDerivative method on the payment date. valuation is at noon, payment set at
   * midnight...
   */
  public void toDerivativeJustAfterPayment() {
    final ZonedDateTime referenceDate = DateUtils.getUTCDate(2011, 9, 19);
    final ZonedDateTime valuationTimeIsNoon = DateUtils.getUTCDate(2011, 9, 19, 12, 0);
    assertTrue(
        "valuationTimeIsNoon used to be after paymentDate, which was midnight. Confirm behaviour",
        valuationTimeIsNoon.isAfter(ON_COMPOUNDED_COUPON_DEFINITION.getPaymentDate()));
    final double fixingRate = 0.01;
    final DoubleTimeSeries<ZonedDateTime> fixingTS =
        ImmutableZonedDateTimeDoubleTimeSeries.ofUTC(
            new ZonedDateTime[] {
              DateUtils.getUTCDate(2011, 9, 7),
              DateUtils.getUTCDate(2011, 9, 8),
              DateUtils.getUTCDate(2011, 9, 9),
              DateUtils.getUTCDate(2011, 9, 12),
              DateUtils.getUTCDate(2011, 9, 13),
              DateUtils.getUTCDate(2011, 9, 14),
              DateUtils.getUTCDate(2011, 9, 15)
            },
            new double[] {
              fixingRate, fixingRate, fixingRate, fixingRate, fixingRate, fixingRate, fixingRate
            });
    final Payment cpnConverted =
        ON_COMPOUNDED_COUPON_DEFINITION.toDerivative(valuationTimeIsNoon, fixingTS);
    final double paymentTime =
        -TimeCalculator.getTimeBetween(
            referenceDate, EUR_PAYMENT_DATE, EUR_DAY_COUNT, EUR_CALENDAR);
    final double notionalAccrued =
        NOTIONAL
            * Math.pow(
                1 + fixingRate, ON_COMPOUNDED_COUPON_DEFINITION.getFixingPeriodAccrualFactors()[0])
            * Math.pow(
                1 + fixingRate, ON_COMPOUNDED_COUPON_DEFINITION.getFixingPeriodAccrualFactors()[1])
            * Math.pow(
                1 + fixingRate, ON_COMPOUNDED_COUPON_DEFINITION.getFixingPeriodAccrualFactors()[2])
            * Math.pow(
                1 + fixingRate, ON_COMPOUNDED_COUPON_DEFINITION.getFixingPeriodAccrualFactors()[3])
            * Math.pow(
                1 + fixingRate, ON_COMPOUNDED_COUPON_DEFINITION.getFixingPeriodAccrualFactors()[4]);
    final CouponFixed cpnExpected =
        new CouponFixed(
            EUR_CUR,
            paymentTime,
            EUR_PAYMENT_YEAR_FRACTION,
            NOTIONAL,
            (notionalAccrued / NOTIONAL - 1.0) / EUR_PAYMENT_YEAR_FRACTION);
    assertEquals("CouponONCompounded definition: toDerivative", cpnExpected, cpnConverted);

    // Test pricing, too. Notice that the value of a coupon on its payment date is non-zero
    final MulticurveProviderDiscount curves =
        MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
    final MultipleCurrencyAmount pvConverted =
        com.opengamma.analytics.financial.interestrate.payments.provider
            .CouponFixedDiscountingMethod.getInstance()
            .presentValue((CouponFixed) cpnConverted, curves);
    final MultipleCurrencyAmount pvExpected =
        com.opengamma.analytics.financial.interestrate.payments.provider
            .CouponFixedDiscountingMethod.getInstance()
            .presentValue(cpnExpected, curves);
    assertEquals("CouponONCompounded definition: toDerivative", pvConverted, pvExpected);
    assertEquals(
        "CouponONCompounded definition: toDerivative",
        pvConverted,
        MultipleCurrencyAmount.of(EUR_CUR, 19744.6689499392));
  }
/** Test the swaps with multiple legs present value and related figures. */
@Test(groups = TestGroup.UNIT)
public class SwapMultilegCalculatorTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();

  private static final Calendar TARGET = new MondayToFridayCalendar("TRAGET");
  private static final IndexIborMaster INDEX_MASTER = IndexIborMaster.getInstance();
  private static final IborIndex EURIBOR3M = INDEX_MASTER.getIndex("EURIBOR3M");
  private static final IborIndex EURIBOR6M = INDEX_MASTER.getIndex("EURIBOR6M");
  private static final GeneratorSwapFixedIborMaster SWAP_MASTER =
      GeneratorSwapFixedIborMaster.getInstance();
  private static final GeneratorSwapFixedIbor EUR1YEURIBOR6M =
      SWAP_MASTER.getGenerator("EUR1YEURIBOR6M", TARGET);
  private static final Period ANNUITY_TENOR = Period.ofYears(2);
  private static final Currency EUR = EURIBOR3M.getCurrency();

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2013, 3, 20);
  private static final ZonedDateTime SETTLEMENT_DATE = DateUtils.getUTCDate(2013, 10, 16);
  private static final double NOTIONAL = 100000000; // 100 m
  private static final double SPREAD = 0.0010; // 10 bps
  private static final StubType STUB = StubType.SHORT_START;

  // Swap represeting a EUR basis swap: 1 spread leg and 2 Euribor leg.
  private static final boolean IS_PAYER_SPREAD = true;
  private static final ZonedDateTime MATURITY_DATE = SETTLEMENT_DATE.plus(ANNUITY_TENOR);
  private static final int NB_LEGS = 3;

  @SuppressWarnings("rawtypes")
  private static final AnnuityDefinition[] LEGS_DEFINITION = new AnnuityDefinition[NB_LEGS];

  static {
    LEGS_DEFINITION[0] =
        AnnuityDefinitionBuilder.couponFixed(
            EUR,
            SETTLEMENT_DATE,
            MATURITY_DATE,
            EUR1YEURIBOR6M.getFixedLegPeriod(),
            TARGET,
            EUR1YEURIBOR6M.getFixedLegDayCount(),
            EUR1YEURIBOR6M.getBusinessDayConvention(),
            EUR1YEURIBOR6M.isEndOfMonth(),
            NOTIONAL,
            SPREAD,
            IS_PAYER_SPREAD,
            STUB,
            0);
    LEGS_DEFINITION[1] =
        AnnuityDefinitionBuilder.couponIbor(
            SETTLEMENT_DATE,
            MATURITY_DATE,
            EURIBOR3M.getTenor(),
            NOTIONAL,
            EURIBOR3M,
            IS_PAYER_SPREAD,
            EURIBOR3M.getDayCount(),
            EURIBOR3M.getBusinessDayConvention(),
            EURIBOR3M.isEndOfMonth(),
            TARGET,
            STUB,
            0);
    LEGS_DEFINITION[2] =
        AnnuityDefinitionBuilder.couponIbor(
            SETTLEMENT_DATE,
            MATURITY_DATE,
            EURIBOR6M.getTenor(),
            NOTIONAL,
            EURIBOR6M,
            !IS_PAYER_SPREAD,
            EURIBOR6M.getDayCount(),
            EURIBOR6M.getBusinessDayConvention(),
            EURIBOR6M.isEndOfMonth(),
            TARGET,
            STUB,
            0);
  }

  @SuppressWarnings("unchecked")
  private static final SwapMultilegDefinition SWAP_MULTI_LEG_DEFINITION =
      new SwapMultilegDefinition(LEGS_DEFINITION);

  private static final SwapMultileg SWAP_MULTI_LEG =
      SWAP_MULTI_LEG_DEFINITION.toDerivative(REFERENCE_DATE);

  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingCalculator.getInstance();
  private static final ParSpreadMarketQuoteDiscountingCalculator PSMQDC =
      ParSpreadMarketQuoteDiscountingCalculator.getInstance();
  private static final ParSpreadMarketQuoteCurveSensitivityDiscountingCalculator PSMQCSDC =
      ParSpreadMarketQuoteCurveSensitivityDiscountingCalculator.getInstance();
  private static final PresentValueMarketQuoteSensitivityDiscountingCalculator PVMQSC =
      PresentValueMarketQuoteSensitivityDiscountingCalculator.getInstance();
  private static final PresentValueMarketQuoteSensitivityCurveSensitivityDiscountingCalculator
      PVMQSCSC =
          PresentValueMarketQuoteSensitivityCurveSensitivityDiscountingCalculator.getInstance();

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E-2;
  private static final double TOLERANCE_RATE = 1.0E-8;
  private static final double TOLERANCE_RATE_DELTA = 1.0E-8;

  @Test
  public void presentValueDiscountingCalculator() {
    final MultipleCurrencyAmount pvSwap = SWAP_MULTI_LEG.accept(PVDC, MULTICURVES);
    MultipleCurrencyAmount pvLegs = MultipleCurrencyAmount.of(EUR, 0.0);
    for (int loopleg = 0; loopleg < NB_LEGS; loopleg++) {
      pvLegs = pvLegs.plus(SWAP_MULTI_LEG.getLegs()[loopleg].accept(PVDC, MULTICURVES));
    }
    assertEquals(
        "SwapMultileg: presentValueDiscountingCalculator",
        pvSwap.getAmount(EUR),
        pvLegs.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  public void presentValueCurveSensitivityDiscountingCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsSwap =
        SWAP_MULTI_LEG.accept(PVCSDC, MULTICURVES);
    MultipleCurrencyMulticurveSensitivity pvcsLegs =
        SWAP_MULTI_LEG.getLegs()[0].accept(PVCSDC, MULTICURVES);
    for (int loopleg = 1; loopleg < NB_LEGS; loopleg++) {
      pvcsLegs = pvcsLegs.plus(SWAP_MULTI_LEG.getLegs()[loopleg].accept(PVCSDC, MULTICURVES));
    }
    AssertSensitivityObjects.assertEquals(
        "SwapMultileg: presentValueCurveSensitivityDiscountingCalculator",
        pvcsLegs,
        pvcsSwap,
        TOLERANCE_PV_DELTA);
  }

  @Test
  public void parSpreadMarketQuoteDiscountingCalculator() {
    final double psmq = SWAP_MULTI_LEG.accept(PSMQDC, MULTICURVES);
    final double pv =
        -MULTICURVES
            .getFxRates()
            .convert(
                SWAP_MULTI_LEG.accept(PVDC, MULTICURVES), SWAP_MULTI_LEG.getLegs()[0].getCurrency())
            .getAmount();
    final double pvbp = SWAP_MULTI_LEG.getLegs()[0].accept(PVMQSC, MULTICURVES);
    assertEquals(
        "SwapMultileg: parSpreadMarketQuoteDiscountingCalculator", psmq, pv / pvbp, TOLERANCE_RATE);
  }

  @Test
  public void parSpreadMarketQuoteCurveSensitivityDiscountingCalculator() {
    final double pv =
        MULTICURVES
            .getFxRates()
            .convert(
                SWAP_MULTI_LEG.accept(PVDC, MULTICURVES), SWAP_MULTI_LEG.getLegs()[0].getCurrency())
            .getAmount();
    final double pvbp = SWAP_MULTI_LEG.getLegs()[0].accept(PVMQSC, MULTICURVES);
    final MulticurveSensitivity pvcs =
        SWAP_MULTI_LEG
            .accept(PVCSDC, MULTICURVES)
            .converted(EUR, MULTICURVES.getFxRates())
            .getSensitivity(EUR);
    final MulticurveSensitivity pvbpcs = SWAP_MULTI_LEG.getLegs()[0].accept(PVMQSCSC, MULTICURVES);
    final MulticurveSensitivity psmqcsExpected =
        pvcs.multipliedBy(-1.0d / pvbp).plus(pvbpcs.multipliedBy(pv / (pvbp * pvbp))).cleaned();
    final MulticurveSensitivity psmqcs = SWAP_MULTI_LEG.accept(PSMQCSDC, MULTICURVES).cleaned();
    AssertSensitivityObjects.assertEquals(
        "SwapMultileg: presentValueCurveSensitivityDiscountingCalculator",
        psmqcs,
        psmqcsExpected,
        TOLERANCE_RATE_DELTA);
  }
}
/**
 * Tests related to the pricing methods for Ibor coupon in the discounting method with data in
 * MarketBundle.
 */
public class CouponIborDiscountingProviderMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex[] IBOR_INDEXES =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd();
  private static final IborIndex EURIBOR3M = IBOR_INDEXES[0];
  private static final Currency EUR = EURIBOR3M.getCurrency();
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();

  private static final DayCount DAY_COUNT_COUPON =
      DayCountFactory.INSTANCE.getDayCount("Actual/365");
  private static final ZonedDateTime ACCRUAL_START_DATE = DateUtils.getUTCDate(2011, 5, 23);
  private static final ZonedDateTime ACCRUAL_END_DATE = DateUtils.getUTCDate(2011, 8, 22);
  private static final double ACCRUAL_FACTOR =
      DAY_COUNT_COUPON.getDayCountFraction(ACCRUAL_START_DATE, ACCRUAL_END_DATE);
  private static final double NOTIONAL = 1000000; // 1m
  private static final CouponIborDefinition CPN_IBOR_DEFINITION =
      CouponIborDefinition.from(
          ACCRUAL_START_DATE, ACCRUAL_END_DATE, ACCRUAL_FACTOR, NOTIONAL, EURIBOR3M, CALENDAR);

  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2010, 12, 27);
  private static final CouponIbor CPN_IBOR =
      (CouponIbor) CPN_IBOR_DEFINITION.toDerivative(REFERENCE_DATE);

  private static final CouponIborDiscountingMethod METHOD_CPN_IBOR =
      CouponIborDiscountingMethod.getInstance();
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();
  private static final PresentValueCurveSensitivityDiscountingCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingCalculator.getInstance();

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;

  @Test
  public void presentValueMarketDiscount() {
    final MultipleCurrencyAmount pvComputed = METHOD_CPN_IBOR.presentValue(CPN_IBOR, MULTICURVES);
    final double forward =
        MULTICURVES.getForwardRate(
            EURIBOR3M,
            CPN_IBOR.getFixingPeriodStartTime(),
            CPN_IBOR.getFixingPeriodEndTime(),
            CPN_IBOR.getFixingAccrualFactor());
    final double df =
        MULTICURVES.getDiscountFactor(EURIBOR3M.getCurrency(), CPN_IBOR.getPaymentTime());
    final double pvExpected = NOTIONAL * ACCRUAL_FACTOR * forward * df;
    assertEquals(
        "CouponIborDiscountingMarketMethod: present value",
        pvExpected,
        pvComputed.getAmount(EURIBOR3M.getCurrency()),
        TOLERANCE_PV);
  }

  @Test
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod = METHOD_CPN_IBOR.presentValue(CPN_IBOR, MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = CPN_IBOR.accept(PVDC, MULTICURVES);
    assertEquals(
        "CouponFixedDiscountingMarketMethod: present value",
        pvMethod.getAmount(EUR),
        pvCalculator.getAmount(EUR),
        TOLERANCE_PV);
  }

  // Testing note: the presentValueMarketSensitivity is tested in
  // ParameterSensitivityProviderCalculatorTest

  @Test
  public void presentValueMarketSensitivityMethodVsCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsMethod =
        METHOD_CPN_IBOR.presentValueCurveSensitivity(CPN_IBOR, MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvcsCalculator =
        CPN_IBOR.accept(PVCSDC, MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "CouponFixedDiscountingMarketMethod: presentValueMarketSensitivity",
        pvcsMethod,
        pvcsCalculator,
        TOLERANCE_PV_DELTA);
  }
}
/**
 * Test class for the replication method for CMS caplet/floorlet using a SABR smile with
 * extrapolation.
 */
@Test
public class CapFloorCMSSABRExtrapolationRightReplicationMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex EURIBOR6M =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd()[1];
  private static final Currency EUR = EURIBOR6M.getCurrency();
  private static final HolidayCalendar CALENDAR =
      MulticurveProviderDiscountDataSets.getEURCalendar();

  private static final SABRInterestRateParameters SABR_PARAMETER = SABRDataSets.createSABR1();
  private static final GeneratorSwapFixedIbor EUR1YEURIBOR6M =
      GeneratorSwapFixedIborMaster.getInstance().getGenerator("EUR1YEURIBOR6M", CALENDAR);
  private static final SABRSwaptionProviderDiscount SABR_MULTICURVES =
      new SABRSwaptionProviderDiscount(MULTICURVES, SABR_PARAMETER, EUR1YEURIBOR6M);

  // Swap 5Y
  private static final BusinessDayConvention BUSINESS_DAY =
      BusinessDayConventions.MODIFIED_FOLLOWING;
  private static final boolean IS_EOM = true;
  private static final Period ANNUITY_TENOR = Period.ofYears(5);
  private static final ZonedDateTime SETTLEMENT_DATE = DateUtils.getUTCDate(2020, 4, 28);
  // Fixed leg: Semi-annual bond
  private static final Period FIXED_PAYMENT_PERIOD = Period.ofMonths(6);
  private static final DayCount FIXED_DAY_COUNT = DayCounts.THIRTY_U_360;
  private static final double RATE = 0.0325;
  private static final boolean FIXED_IS_PAYER = true;
  private static final AnnuityCouponFixedDefinition FIXED_ANNUITY =
      AnnuityCouponFixedDefinition.from(
          EUR,
          SETTLEMENT_DATE,
          ANNUITY_TENOR,
          FIXED_PAYMENT_PERIOD,
          CALENDAR,
          FIXED_DAY_COUNT,
          BUSINESS_DAY,
          IS_EOM,
          1.0,
          RATE,
          FIXED_IS_PAYER);
  // Ibor leg: quarterly money
  private static final AnnuityCouponIborDefinition IBOR_ANNUITY =
      AnnuityCouponIborDefinition.from(
          SETTLEMENT_DATE, ANNUITY_TENOR, 1.0, EURIBOR6M, !FIXED_IS_PAYER, CALENDAR);
  // CMS coupon construction
  private static final IndexSwap CMS_INDEX =
      new IndexSwap(FIXED_PAYMENT_PERIOD, FIXED_DAY_COUNT, EURIBOR6M, ANNUITY_TENOR, CALENDAR);
  private static final SwapFixedIborDefinition SWAP_DEFINITION =
      new SwapFixedIborDefinition(FIXED_ANNUITY, IBOR_ANNUITY);
  private static final ZonedDateTime FIXING_DATE =
      ScheduleCalculator.getAdjustedDate(SETTLEMENT_DATE, -EURIBOR6M.getSpotLag(), CALENDAR);
  private static final ZonedDateTime ACCRUAL_START_DATE = SETTLEMENT_DATE; // pre-fixed
  private static final ZonedDateTime ACCRUAL_END_DATE =
      ScheduleCalculator.getAdjustedDate(
          ACCRUAL_START_DATE, FIXED_PAYMENT_PERIOD, BUSINESS_DAY, CALENDAR);
  private static final ZonedDateTime PAYMENT_DATE = ACCRUAL_END_DATE;
  private static final DayCount PAYMENT_DAY_COUNT = DayCounts.ACT_360;
  private static final double ACCRUAL_FACTOR =
      DayCountUtils.yearFraction(PAYMENT_DAY_COUNT, ACCRUAL_START_DATE, ACCRUAL_END_DATE);
  private static final double NOTIONAL = 10000000; // 10m
  private static final CouponCMSDefinition CMS_COUPON_RECEIVER_DEFINITION =
      CouponCMSDefinition.from(
          PAYMENT_DATE,
          ACCRUAL_START_DATE,
          ACCRUAL_END_DATE,
          ACCRUAL_FACTOR,
          NOTIONAL,
          FIXING_DATE,
          SWAP_DEFINITION,
          CMS_INDEX);
  private static final CouponCMSDefinition CMS_COUPON_PAYER_DEFINITION =
      CouponCMSDefinition.from(
          PAYMENT_DATE,
          ACCRUAL_START_DATE,
          ACCRUAL_END_DATE,
          ACCRUAL_FACTOR,
          -NOTIONAL,
          FIXING_DATE,
          SWAP_DEFINITION,
          CMS_INDEX);
  // Cap/Floor construction
  private static final double STRIKE = 0.04;
  private static final boolean IS_CAP = true;
  private static final CapFloorCMSDefinition CMS_CAP_LONG_DEFINITION =
      CapFloorCMSDefinition.from(CMS_COUPON_RECEIVER_DEFINITION, STRIKE, IS_CAP);
  private static final CapFloorCMSDefinition CMS_CAP_SHORT_DEFINITION =
      CapFloorCMSDefinition.from(CMS_COUPON_PAYER_DEFINITION, STRIKE, IS_CAP);
  private static final CapFloorCMSDefinition CMS_CAP_0_DEFINITION =
      CapFloorCMSDefinition.from(CMS_COUPON_RECEIVER_DEFINITION, 0.0, IS_CAP);
  // to derivatives
  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2010, 8, 18);

  private static final CouponCMS CMS_COUPON =
      (CouponCMS) CMS_COUPON_RECEIVER_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final CapFloorCMS CMS_CAP_0 =
      (CapFloorCMS) CMS_CAP_0_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final CapFloorCMS CMS_CAP_LONG =
      (CapFloorCMS) CMS_CAP_LONG_DEFINITION.toDerivative(REFERENCE_DATE);
  private static final CapFloorCMS CMS_CAP_SHORT =
      (CapFloorCMS) CMS_CAP_SHORT_DEFINITION.toDerivative(REFERENCE_DATE);
  // Calculators & methods
  private static final CapFloorCMSSABRReplicationMethod METHOD_STANDARD_CAP =
      CapFloorCMSSABRReplicationMethod.getDefaultInstance();
  private static final CouponCMSSABRReplicationMethod METHOD_STANDARD_CPN =
      CouponCMSSABRReplicationMethod.getInstance();
  private static final CouponCMSDiscountingMethod METHOD_DSC_CPN =
      CouponCMSDiscountingMethod.getInstance();

  private static final double CUT_OFF_STRIKE = 0.10;
  private static final double MU = 2.50;
  private static final CapFloorCMSSABRExtrapolationRightReplicationMethod METHOD_EXTRAPOLATION_CAP =
      new CapFloorCMSSABRExtrapolationRightReplicationMethod(CUT_OFF_STRIKE, MU);
  private static final CouponCMSSABRExtrapolationRightReplicationMethod METHOD_EXTRAPOLATION_CPN =
      new CouponCMSSABRExtrapolationRightReplicationMethod(CUT_OFF_STRIKE, MU);
  // Calculators
  private static final PresentValueSABRSwaptionRightExtrapolationCalculator PVSSXC =
      new PresentValueSABRSwaptionRightExtrapolationCalculator(CUT_OFF_STRIKE, MU);
  private static final PresentValueCurveSensitivitySABRSwaptionRightExtrapolationCalculator
      PVCSSSXC =
          new PresentValueCurveSensitivitySABRSwaptionRightExtrapolationCalculator(
              CUT_OFF_STRIKE, MU);
  private static final PresentValueSABRSensitivitySABRSwaptionRightExtrapolationCalculator
      PVSSSSXC =
          new PresentValueSABRSensitivitySABRSwaptionRightExtrapolationCalculator(
              CUT_OFF_STRIKE, MU);

  private static final double SHIFT = 1.0E-6;
  private static final ParameterSensitivityParameterCalculator<SABRSwaptionProviderInterface>
      PS_SS_C = new ParameterSensitivityParameterCalculator<>(PVCSSSXC);
  private static final ParameterSensitivitySABRSwaptionDiscountInterpolatedFDCalculator PS_SS_FDC =
      new ParameterSensitivitySABRSwaptionDiscountInterpolatedFDCalculator(PVSSXC, SHIFT);

  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 5.0E+3; // 0.01 currency unit for 1 bp.

  /**
   * Test the present value for a CMS coupon with pricing by replication in the SABR with
   * extrapolation framework. The present value is tested against hard-coded value and cap of strike
   * 0.
   */
  public void presentValue() {
    // CMS cap/floor with strike 0 has the same price as a CMS coupon.
    final double priceCouponStd =
        METHOD_STANDARD_CPN.presentValue(CMS_COUPON, SABR_MULTICURVES).getAmount(EUR).getAmount();
    final double rateCouponStd =
        priceCouponStd
            / (CMS_COUPON.getPaymentYearFraction()
                * CMS_COUPON.getNotional()
                * MULTICURVES.getDiscountFactor(EUR, CMS_COUPON.getPaymentTime()));
    final double priceCouponExtra =
        METHOD_EXTRAPOLATION_CPN
            .presentValue(CMS_COUPON, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    final double rateCouponExtra =
        priceCouponExtra
            / (CMS_COUPON.getPaymentYearFraction()
                * CMS_COUPON.getNotional()
                * MULTICURVES.getDiscountFactor(EUR, CMS_COUPON.getPaymentTime()));
    final double priceCouponNoAdj =
        METHOD_DSC_CPN.presentValue(CMS_COUPON, MULTICURVES).getAmount(EUR).getAmount();
    final double rateCouponNoAdj =
        priceCouponNoAdj
            / (CMS_COUPON.getPaymentYearFraction()
                * CMS_COUPON.getNotional()
                * MULTICURVES.getDiscountFactor(EUR, CMS_COUPON.getPaymentTime()));
    assertEquals(
        "Extrapolation: comparison with standard method", rateCouponStd > rateCouponExtra, true);
    assertEquals(
        "Extrapolation: comparison with no convexity adjustment",
        rateCouponExtra > rateCouponNoAdj,
        true);
    final double rateCouponExtraExpected = 0.0189864; // From previous run.
    assertEquals("Extrapolation: hard-coded value", rateCouponExtraExpected, rateCouponExtra, 1E-6);
    final double priceCap0Extra =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_0, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    assertEquals(
        "Extrapolation: CMS coupon vs Cap 0", priceCouponExtra, priceCap0Extra, TOLERANCE_PV);
  }

  /**
   * Tests the price of CMS coupon and cap/floor using replication in the SABR framework. Method v
   * Calculator.
   */
  public void presentValueMethodVsCalculator() {
    final double pvMethod =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_LONG, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    final double pvCalculator =
        CMS_CAP_LONG.accept(PVSSXC, SABR_MULTICURVES).getAmount(EUR).getAmount();
    assertEquals(
        "CMS cap/floor SABR: Present value : method vs calculator",
        pvMethod,
        pvCalculator,
        TOLERANCE_PV);
  }

  /**
   * Test the present value for a CMS cap with pricing by replication in the SABR with extrapolation
   * framework. The present value is tested against hard-coded value and a long/short parity is
   * tested.
   */
  public void presentValueReplicationCap() {
    // CMS cap/floor with strike 0 has the same price as a CMS coupon.
    final double priceCapLongStd =
        METHOD_STANDARD_CAP.presentValue(CMS_CAP_LONG, SABR_MULTICURVES).getAmount(EUR).getAmount();
    final double priceCapLongExtra =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_LONG, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    final double priceCapShortExtra =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_SHORT, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    assertEquals(
        "CMS cap by replication - Extrapolation: comparison with standard method",
        priceCapLongStd > priceCapLongExtra,
        true);
    final double priceCapExtraExpected = 30696.572; // From previous run.
    assertEquals(
        "CMS cap by replication - Extrapolation: hard-coded value",
        priceCapExtraExpected,
        priceCapLongExtra,
        TOLERANCE_PV);
    assertEquals(
        "CMS cap by replication - Extrapolation: long/short parity",
        -priceCapShortExtra,
        priceCapLongExtra,
        TOLERANCE_PV);
  }

  /**
   * Test the present value rate sensitivity for a CMS cap with pricing by replication in the SABR
   * with extrapolation framework.
   */
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsCapLongExact =
        PS_SS_C.calculateSensitivity(
            CMS_CAP_LONG, SABR_MULTICURVES, SABR_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsCapLongFD =
        PS_SS_FDC.calculateSensitivity(CMS_CAP_LONG, SABR_MULTICURVES);
    AssertSensitivityObjects.assertEquals(
        "SwaptionPhysicalFixedIborSABRMethod: presentValueCurveSensitivity ",
        pvpsCapLongExact,
        pvpsCapLongFD,
        TOLERANCE_PV_DELTA);
    final MultipleCurrencyParameterSensitivity pvpsCapShortExact =
        PS_SS_C.calculateSensitivity(
            CMS_CAP_SHORT,
            SABR_MULTICURVES,
            SABR_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsCapShortFD =
        PS_SS_FDC.calculateSensitivity(CMS_CAP_SHORT, SABR_MULTICURVES);
    AssertSensitivityObjects.assertEquals(
        "SwaptionPhysicalFixedIborSABRMethod: presentValueCurveSensitivity ",
        pvpsCapShortExact,
        pvpsCapShortFD,
        TOLERANCE_PV_DELTA);
  }

  /**
   * Test the present value rate sensitivity for a CMS cap with pricing by replication in the SABR
   * with extrapolation framework. Method v Calculator.
   */
  public void presentValueCurveSensitivityMethodVsCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsMethod =
        METHOD_EXTRAPOLATION_CAP.presentValueCurveSensitivity(CMS_CAP_LONG, SABR_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvcsCalculator =
        CMS_CAP_LONG.accept(PVCSSSXC, SABR_MULTICURVES);
    AssertSensitivityObjects.assertEquals(
        "CMS cap/floor SABR: Present value : method vs calculator",
        pvcsMethod,
        pvcsCalculator,
        TOLERANCE_PV_DELTA);
  }

  /** Tests the cap present value SABR parameters sensitivity vs finite difference. */
  public void presentValueSABRSensitivity() {
    final double pv =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_LONG, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    final PresentValueSABRSensitivityDataBundle pvsCapLong =
        METHOD_EXTRAPOLATION_CAP.presentValueSABRSensitivity(CMS_CAP_LONG, SABR_MULTICURVES);
    // SABR sensitivity vs finite difference
    final double shift = 0.0001;
    final double shiftAlpha = 0.00001;
    final double maturity =
        CMS_CAP_LONG
                .getUnderlyingSwap()
                .getFixedLeg()
                .getNthPayment(
                    CMS_CAP_LONG.getUnderlyingSwap().getFixedLeg().getNumberOfPayments() - 1)
                .getPaymentTime()
            - CMS_CAP_LONG.getSettlementTime();
    final DoublesPair expectedExpiryTenor = DoublesPair.of(CMS_CAP_LONG.getFixingTime(), maturity);
    // Alpha sensitivity vs finite difference computation
    final SABRInterestRateParameters sabrParameterAlphaBumped =
        SABRDataSets.createSABR1AlphaBumped(shiftAlpha);
    final SABRSwaptionProviderDiscount sabrBundleAlphaBumped =
        new SABRSwaptionProviderDiscount(MULTICURVES, sabrParameterAlphaBumped, EUR1YEURIBOR6M);
    final double pvLongPayerAlphaBumped =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_LONG, sabrBundleAlphaBumped)
            .getAmount(EUR)
            .getAmount();
    final double expectedAlphaSensi = (pvLongPayerAlphaBumped - pv) / shiftAlpha;
    assertEquals("Number of alpha sensitivity", pvsCapLong.getAlpha().getMap().keySet().size(), 1);
    assertEquals(
        "Alpha sensitivity expiry/tenor",
        pvsCapLong.getAlpha().getMap().keySet().contains(expectedExpiryTenor),
        true);
    assertEquals(
        "Alpha sensitivity value",
        expectedAlphaSensi,
        pvsCapLong.getAlpha().getMap().get(expectedExpiryTenor),
        TOLERANCE_PV_DELTA);
    // Rho sensitivity vs finite difference computation
    final SABRInterestRateParameters sabrParameterRhoBumped = SABRDataSets.createSABR1RhoBumped();
    final SABRSwaptionProviderDiscount sabrBundleRhoBumped =
        new SABRSwaptionProviderDiscount(MULTICURVES, sabrParameterRhoBumped, EUR1YEURIBOR6M);
    final double pvLongPayerRhoBumped =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_LONG, sabrBundleRhoBumped)
            .getAmount(EUR)
            .getAmount();
    final double expectedRhoSensi = (pvLongPayerRhoBumped - pv) / shift;
    assertEquals("Number of rho sensitivity", pvsCapLong.getRho().getMap().keySet().size(), 1);
    assertEquals(
        "Rho sensitivity expiry/tenor",
        pvsCapLong.getRho().getMap().keySet().contains(expectedExpiryTenor),
        true);
    assertEquals(
        "Rho sensitivity value",
        expectedRhoSensi,
        pvsCapLong.getRho().getMap().get(expectedExpiryTenor),
        TOLERANCE_PV_DELTA);
    // Alpha sensitivity vs finite difference computation
    final SABRInterestRateParameters sabrParameterNuBumped = SABRDataSets.createSABR1NuBumped();
    final SABRSwaptionProviderDiscount sabrBundleNuBumped =
        new SABRSwaptionProviderDiscount(MULTICURVES, sabrParameterNuBumped, EUR1YEURIBOR6M);
    final double pvLongPayerNuBumped =
        METHOD_EXTRAPOLATION_CAP
            .presentValue(CMS_CAP_LONG, sabrBundleNuBumped)
            .getAmount(EUR)
            .getAmount();
    final double expectedNuSensi = (pvLongPayerNuBumped - pv) / shift;
    assertEquals("Number of nu sensitivity", pvsCapLong.getNu().getMap().keySet().size(), 1);
    assertTrue(
        "Nu sensitivity expiry/tenor",
        pvsCapLong.getNu().getMap().keySet().contains(expectedExpiryTenor));
    assertEquals(
        "Nu sensitivity value",
        expectedNuSensi,
        pvsCapLong.getNu().getMap().get(expectedExpiryTenor),
        TOLERANCE_PV_DELTA);
  }

  /** Tests the coupon present value SABR parameters sensitivity vs finite difference. */
  public void presentValueSABRSensitivityCoupon() {
    final double pv =
        METHOD_EXTRAPOLATION_CPN
            .presentValue(CMS_COUPON, SABR_MULTICURVES)
            .getAmount(EUR)
            .getAmount();
    final PresentValueSABRSensitivityDataBundle pvsCpn =
        METHOD_EXTRAPOLATION_CPN.presentValueSABRSensitivity(CMS_COUPON, SABR_MULTICURVES);
    // SABR sensitivity vs finite difference
    final double shift = 0.0001;
    final double shiftAlpha = 0.00001;
    final double maturity =
        CMS_COUPON
                .getUnderlyingSwap()
                .getFixedLeg()
                .getNthPayment(
                    CMS_COUPON.getUnderlyingSwap().getFixedLeg().getNumberOfPayments() - 1)
                .getPaymentTime()
            - CMS_COUPON.getSettlementTime();
    final DoublesPair expectedExpiryTenor = DoublesPair.of(CMS_COUPON.getFixingTime(), maturity);
    // Alpha sensitivity vs finite difference computation
    final SABRInterestRateParameters sabrParameterAlphaBumped =
        SABRDataSets.createSABR1AlphaBumped(shiftAlpha);
    final SABRSwaptionProviderDiscount sabrBundleAlphaBumped =
        new SABRSwaptionProviderDiscount(MULTICURVES, sabrParameterAlphaBumped, EUR1YEURIBOR6M);
    final double pvLongPayerAlphaBumped =
        METHOD_EXTRAPOLATION_CPN
            .presentValue(CMS_COUPON, sabrBundleAlphaBumped)
            .getAmount(EUR)
            .getAmount();
    final double expectedAlphaSensi = (pvLongPayerAlphaBumped - pv) / shiftAlpha;
    assertEquals("Number of alpha sensitivity", pvsCpn.getAlpha().getMap().keySet().size(), 1);
    assertEquals(
        "Alpha sensitivity expiry/tenor",
        pvsCpn.getAlpha().getMap().keySet().contains(expectedExpiryTenor),
        true);
    assertEquals(
        "Alpha sensitivity value",
        expectedAlphaSensi,
        pvsCpn.getAlpha().getMap().get(expectedExpiryTenor),
        TOLERANCE_PV_DELTA);
    // Rho sensitivity vs finite difference computation
    final SABRInterestRateParameters sabrParameterRhoBumped = SABRDataSets.createSABR1RhoBumped();
    final SABRSwaptionProviderDiscount sabrBundleRhoBumped =
        new SABRSwaptionProviderDiscount(MULTICURVES, sabrParameterRhoBumped, EUR1YEURIBOR6M);
    final double pvLongPayerRhoBumped =
        METHOD_EXTRAPOLATION_CPN
            .presentValue(CMS_COUPON, sabrBundleRhoBumped)
            .getAmount(EUR)
            .getAmount();
    final double expectedRhoSensi = (pvLongPayerRhoBumped - pv) / shift;
    assertEquals("Number of rho sensitivity", pvsCpn.getRho().getMap().keySet().size(), 1);
    assertEquals(
        "Rho sensitivity expiry/tenor",
        pvsCpn.getRho().getMap().keySet().contains(expectedExpiryTenor),
        true);
    assertEquals(
        "Rho sensitivity value",
        expectedRhoSensi,
        pvsCpn.getRho().getMap().get(expectedExpiryTenor),
        TOLERANCE_PV_DELTA);
    // Nu sensitivity vs finite difference computation
    final SABRInterestRateParameters sabrParameterNuBumped = SABRDataSets.createSABR1NuBumped();
    final SABRSwaptionProviderDiscount sabrBundleNuBumped =
        new SABRSwaptionProviderDiscount(MULTICURVES, sabrParameterNuBumped, EUR1YEURIBOR6M);
    final double pvLongPayerNuBumped =
        METHOD_EXTRAPOLATION_CPN
            .presentValue(CMS_COUPON, sabrBundleNuBumped)
            .getAmount(EUR)
            .getAmount();
    final double expectedNuSensi = (pvLongPayerNuBumped - pv) / shift;
    assertEquals("Number of nu sensitivity", pvsCpn.getNu().getMap().keySet().size(), 1);
    assertTrue(
        "Nu sensitivity expiry/tenor",
        pvsCpn.getNu().getMap().keySet().contains(expectedExpiryTenor));
    assertEquals(
        "Nu sensitivity value",
        expectedNuSensi,
        pvsCpn.getNu().getMap().get(expectedExpiryTenor),
        TOLERANCE_PV_DELTA);
  }

  /** Tests the present value SABR parameters sensitivity: Method vs Calculator. */
  public void presentValueSABRSensitivityMethodVsCalculator() {
    final PresentValueSABRSensitivityDataBundle pvssMethod =
        METHOD_EXTRAPOLATION_CAP.presentValueSABRSensitivity(CMS_CAP_LONG, SABR_MULTICURVES);
    final PresentValueSABRSensitivityDataBundle pvssCalculator =
        CMS_CAP_LONG.accept(PVSSSSXC, SABR_MULTICURVES);
    assertEquals(
        "CMS cap/floor SABR: Present value SABR sensitivity: method vs calculator",
        pvssMethod,
        pvssCalculator);
  }

  /** Tests the present value strike sensitivity: Cap. */
  public void presentValueStrikeSensitivityCap() {
    final double[] strikes = new double[] {0.0001, 0.0010, 0.0050, 0.0100, 0.0200, 0.0400, 0.0500};
    final int nbStrikes = strikes.length;
    final double shift = 1.0E-5;
    final double[] errorRelative = new double[nbStrikes];
    for (int loopstrike = 0; loopstrike < nbStrikes; loopstrike++) {
      final CapFloorCMSDefinition cmsCapDefinition =
          CapFloorCMSDefinition.from(CMS_COUPON_RECEIVER_DEFINITION, strikes[loopstrike], IS_CAP);
      final CapFloorCMSDefinition cmsCapShiftUpDefinition =
          CapFloorCMSDefinition.from(
              CMS_COUPON_RECEIVER_DEFINITION, strikes[loopstrike] + shift, IS_CAP);
      final CapFloorCMSDefinition cmsCapShiftDoDefinition =
          CapFloorCMSDefinition.from(
              CMS_COUPON_RECEIVER_DEFINITION, strikes[loopstrike] - shift, IS_CAP);
      final CapFloorCMS cmsCap = (CapFloorCMS) cmsCapDefinition.toDerivative(REFERENCE_DATE);
      final CapFloorCMS cmsCapShiftUp =
          (CapFloorCMS) cmsCapShiftUpDefinition.toDerivative(REFERENCE_DATE);
      final CapFloorCMS cmsCapShiftDo =
          (CapFloorCMS) cmsCapShiftDoDefinition.toDerivative(REFERENCE_DATE);
      final double pvShiftUp =
          METHOD_EXTRAPOLATION_CAP
              .presentValue(cmsCapShiftUp, SABR_MULTICURVES)
              .getAmount(EUR)
              .getAmount();
      final double pvShiftDo =
          METHOD_EXTRAPOLATION_CAP
              .presentValue(cmsCapShiftDo, SABR_MULTICURVES)
              .getAmount(EUR)
              .getAmount();
      final double sensiExpected = (pvShiftUp - pvShiftDo) / (2 * shift);
      final double sensiComputed =
          METHOD_EXTRAPOLATION_CAP.presentValueStrikeSensitivity(cmsCap, SABR_MULTICURVES);
      errorRelative[loopstrike] = (sensiExpected - sensiComputed) / sensiExpected;
      assertEquals(
          "CMS cap/floor SABR: Present value strike sensitivity " + loopstrike,
          0,
          errorRelative[loopstrike],
          5.0E-3);
    }
  }

  /**
   * Tests to estimate the impact of mu on the CMS coupon pricing. "enabled = false" for the
   * standard testing.
   */
  public void testPriceMultiMu() {
    final double[] mu = new double[] {1.10, 1.30, 1.55, 2.25, 3.50, 6.00, 15.0};
    final int nbMu = mu.length;
    final double priceCouponStd =
        METHOD_STANDARD_CPN.presentValue(CMS_COUPON, SABR_MULTICURVES).getAmount(EUR).getAmount();
    @SuppressWarnings("unused")
    final double rateCouponStd =
        priceCouponStd
            / (CMS_COUPON.getPaymentYearFraction()
                * CMS_COUPON.getNotional()
                * MULTICURVES.getDiscountFactor(EUR, CMS_COUPON.getPaymentTime()));
    final double[] priceCouponExtra = new double[nbMu];
    final double[] rateCouponExtra = new double[nbMu];
    for (int loopmu = 0; loopmu < nbMu; loopmu++) {
      final CouponCMSSABRExtrapolationRightReplicationMethod methodExtrapolation =
          new CouponCMSSABRExtrapolationRightReplicationMethod(CUT_OFF_STRIKE, mu[loopmu]);
      priceCouponExtra[loopmu] =
          methodExtrapolation.presentValue(CMS_COUPON, SABR_MULTICURVES).getAmount(EUR).getAmount();
      rateCouponExtra[loopmu] =
          priceCouponExtra[loopmu]
              / (CMS_COUPON.getPaymentYearFraction()
                  * CMS_COUPON.getNotional()
                  * MULTICURVES.getDiscountFactor(EUR, CMS_COUPON.getPaymentTime()));
    }
    final double priceCouponNoAdj =
        METHOD_DSC_CPN.presentValue(CMS_COUPON, MULTICURVES).getAmount(EUR).getAmount();
    final double rateCouponNoAdj =
        priceCouponNoAdj
            / (CMS_COUPON.getPaymentYearFraction()
                * CMS_COUPON.getNotional()
                * MULTICURVES.getDiscountFactor(EUR, CMS_COUPON.getPaymentTime()));
    for (int loopmu = 1; loopmu < nbMu; loopmu++) {
      assertTrue(
          "Extrapolation: comparison with standard method",
          rateCouponExtra[loopmu - 1] > rateCouponExtra[loopmu]);
    }
    assertTrue(
        "Extrapolation: comparison with standard method",
        rateCouponExtra[nbMu - 1] > rateCouponNoAdj);
  }
}
public class SwaptionPhysicalFixedIborBlackMethodTest {

  private static final MulticurveProviderDiscount MULTICURVES =
      MulticurveProviderDiscountDataSets.createMulticurveEurUsd();
  private static final IborIndex EURIBOR6M =
      MulticurveProviderDiscountDataSets.getIndexesIborMulticurveEurUsd()[1];
  private static final Calendar CALENDAR = MulticurveProviderDiscountDataSets.getEURCalendar();
  private static final Currency EUR = EURIBOR6M.getCurrency();
  // Data
  private static final ZonedDateTime REFERENCE_DATE = DateUtils.getUTCDate(2012, 1, 10);
  private static final GeneratorSwapFixedIborMaster GENERATOR_SWAP_MASTER =
      GeneratorSwapFixedIborMaster.getInstance();
  private static final GeneratorSwapFixedIbor GENERATOR_EUR1YEURIBOR6M =
      GENERATOR_SWAP_MASTER.getGenerator("EUR1YEURIBOR6M", CALENDAR);

  private static final BlackFlatSwaptionParameters BLACK = BlackDataSets.createBlackSwaptionEUR6();
  private static final BlackSwaptionFlatProviderDiscount BLACK_MULTICURVES =
      new BlackSwaptionFlatProviderDiscount(MULTICURVES, BLACK);
  // Swaption
  private static final Period EXPIRY_TENOR = Period.ofMonths(26); // To be between nodes.
  private static final ZonedDateTime EXPIRY_DATE =
      ScheduleCalculator.getAdjustedDate(
          REFERENCE_DATE,
          EXPIRY_TENOR,
          GENERATOR_EUR1YEURIBOR6M.getBusinessDayConvention(),
          CALENDAR,
          GENERATOR_EUR1YEURIBOR6M.isEndOfMonth());
  private static final ZonedDateTime SETTLE_DATE =
      ScheduleCalculator.getAdjustedDate(
          EXPIRY_DATE, GENERATOR_EUR1YEURIBOR6M.getSpotLag(), CALENDAR);
  private static final int SWAP_TENOR_YEAR = 5;
  private static final Period SWAP_TENOR = Period.ofYears(SWAP_TENOR_YEAR);
  private static final double NOTIONAL = 123456789.0;
  private static final double RATE = 0.02;
  private static final SwapFixedIborDefinition SWAP_DEFINITION_REC =
      SwapFixedIborDefinition.from(
          SETTLE_DATE, SWAP_TENOR, GENERATOR_EUR1YEURIBOR6M, NOTIONAL, RATE, false);
  private static final SwaptionPhysicalFixedIborDefinition SWAPTION_DEFINITION_LONG_REC =
      SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, SWAP_DEFINITION_REC, true);
  private static final SwaptionPhysicalFixedIbor SWAPTION_LONG_REC =
      SWAPTION_DEFINITION_LONG_REC.toDerivative(REFERENCE_DATE);
  // Method - calculator
  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;
  // Testing note: Sensitivity is for a movement of 1. 1E+2 = 1 cent for a 1 bp move.

  private static final SwaptionPhysicalFixedIborBlackMethod METHOD_BLACK =
      SwaptionPhysicalFixedIborBlackMethod.getInstance();
  private static final SwapFixedCouponDiscountingMethod METHOD_SWAP =
      SwapFixedCouponDiscountingMethod.getInstance();

  private static final ParRateDiscountingCalculator PRDC =
      ParRateDiscountingCalculator.getInstance();
  private static final PresentValueDiscountingCalculator PVDC =
      PresentValueDiscountingCalculator.getInstance();

  private static final PresentValueBlackSwaptionCalculator PVBSC =
      PresentValueBlackSwaptionCalculator.getInstance();
  private static final PresentValueCurveSensitivityBlackSwaptionCalculator PVCSBSC =
      PresentValueCurveSensitivityBlackSwaptionCalculator.getInstance();
  private static final PresentValueBlackSensitivityBlackSwaptionCalculator PVBSSBSC =
      PresentValueBlackSensitivityBlackSwaptionCalculator.getInstance();

  private static final double SHIFT = 1.0E-6;
  private static final ParameterSensitivityParameterCalculator<BlackSwaptionFlatProviderInterface>
      PS_BS_C = new ParameterSensitivityParameterCalculator<>(PVCSBSC);
  private static final ParameterSensitivityBlackSwaptionDiscountInterpolatedFDCalculator PS_BS_FDC =
      new ParameterSensitivityBlackSwaptionDiscountInterpolatedFDCalculator(PVBSC, SHIFT);

  private static final BlackSwaptionSensitivityNodeCalculator BSSNC =
      new BlackSwaptionSensitivityNodeCalculator();

  @Test
  public void presentValue() {
    final MultipleCurrencyAmount pvMethod =
        METHOD_BLACK.presentValue(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final double forward = SWAPTION_LONG_REC.getUnderlyingSwap().accept(PRDC, MULTICURVES);
    final double pvbp =
        METHOD_SWAP.presentValueBasisPoint(SWAPTION_LONG_REC.getUnderlyingSwap(), MULTICURVES);
    final double volatility =
        BLACK.getVolatility(
            SWAPTION_LONG_REC.getTimeToExpiry(), SWAPTION_LONG_REC.getMaturityTime());
    final BlackPriceFunction blackFunction = new BlackPriceFunction();
    final BlackFunctionData dataBlack = new BlackFunctionData(forward, pvbp, volatility);
    final Function1D<BlackFunctionData, Double> func =
        blackFunction.getPriceFunction(SWAPTION_LONG_REC);
    final double pvExpected = func.evaluate(dataBlack);
    assertEquals(
        "Swaption Black method: present value", pvExpected, pvMethod.getAmount(EUR), TOLERANCE_PV);
  }

  @Test
  /** Tests the payer/receiver parity for swaptions present value. */
  public void presentValuePayerReceiverParity() {
    final SwapFixedIborDefinition swapDefinitionPay =
        SwapFixedIborDefinition.from(
            SETTLE_DATE, SWAP_TENOR, GENERATOR_EUR1YEURIBOR6M, NOTIONAL, RATE, true);
    final SwaptionPhysicalFixedIborDefinition swaptionDefinitionShortPayer =
        SwaptionPhysicalFixedIborDefinition.from(EXPIRY_DATE, swapDefinitionPay, false);
    final SwaptionPhysicalFixedIbor swaptionShortPayer =
        swaptionDefinitionShortPayer.toDerivative(REFERENCE_DATE);
    final InstrumentDerivative swapRec = SWAP_DEFINITION_REC.toDerivative(REFERENCE_DATE);
    final MultipleCurrencyAmount pvLR =
        METHOD_BLACK.presentValue(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final MultipleCurrencyAmount pvSP =
        METHOD_BLACK.presentValue(swaptionShortPayer, BLACK_MULTICURVES);
    final MultipleCurrencyAmount pvSwap = swapRec.accept(PVDC, MULTICURVES);
    assertEquals(
        "Swaption Black method: present value",
        pvSwap.getAmount(EUR),
        pvLR.getAmount(EUR) + pvSP.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Compare the method figures to the Calculator figures. */
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod =
        METHOD_BLACK.presentValue(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final MultipleCurrencyAmount pvCalculator = SWAPTION_LONG_REC.accept(PVBSC, BLACK_MULTICURVES);
    assertEquals(
        "Swaption Black method: present value",
        pvCalculator.getAmount(EUR),
        pvMethod.getAmount(EUR),
        TOLERANCE_PV);
  }

  @Test
  /** Tests the curve sensitivity for the explicit formula. */
  public void presentValueCurveSensitivity() {
    final MultipleCurrencyParameterSensitivity pvpsExact =
        PS_BS_C.calculateSensitivity(
            SWAPTION_LONG_REC,
            BLACK_MULTICURVES,
            BLACK_MULTICURVES.getMulticurveProvider().getAllNames());
    final MultipleCurrencyParameterSensitivity pvpsFD =
        PS_BS_FDC.calculateSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption Black method: presentValueCurveSensitivity ",
        pvpsExact,
        pvpsFD,
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Compare the method figures to the Calculator figures. */
  public void presentValueCurveSensitivityMethodVsCalculator() {
    final MultipleCurrencyMulticurveSensitivity pvcsMethod =
        METHOD_BLACK.presentValueCurveSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final MultipleCurrencyMulticurveSensitivity pvcsCalculator =
        SWAPTION_LONG_REC.accept(PVCSBSC, BLACK_MULTICURVES);
    AssertSensivityObjects.assertEquals(
        "Swaption Black method: present value", pvcsMethod, pvcsCalculator, TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests the Black volatility sensitivity (vega). */
  public void presentValueBlackSensitivity() {
    final double shift = 1.0E-6;
    final PresentValueBlackSwaptionSensitivity pvbvs =
        METHOD_BLACK.presentValueBlackSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final BlackFlatSwaptionParameters BlackP = BlackDataSets.createBlackSwaptionEUR6Shift(shift);
    final BlackSwaptionFlatProviderDiscount curvesBlackP =
        new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackP);
    final MultipleCurrencyAmount pvP = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackP);
    final BlackFlatSwaptionParameters BlackM = BlackDataSets.createBlackSwaptionEUR6Shift(-shift);
    final BlackSwaptionFlatProviderDiscount curvesBlackM =
        new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackM);
    final MultipleCurrencyAmount pvM = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackM);
    final DoublesPair point =
        new DoublesPair(SWAPTION_LONG_REC.getTimeToExpiry(), SWAPTION_LONG_REC.getMaturityTime());
    assertEquals(
        "Swaption Black method: present value volatility sensitivity",
        (pvP.getAmount(EUR) - pvM.getAmount(EUR)) / (2 * shift),
        pvbvs.getSensitivity().getMap().get(point),
        TOLERANCE_PV_DELTA);
  }

  @Test
  /** Tests the Black volatility sensitivity (vega). */
  public void presentValueBlackSensitivityMethodVsCalculator() {
    final PresentValueBlackSwaptionSensitivity pvbsMethod =
        METHOD_BLACK.presentValueBlackSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final PresentValueBlackSwaptionSensitivity pvbsCalculator =
        SWAPTION_LONG_REC.accept(PVBSSBSC, BLACK_MULTICURVES);
    assertEquals("Swaption Black method: present value", pvbsMethod, pvbsCalculator);
  }

  @Test
  /** Tests the Black volatility sensitivity (vega). */
  public void presentValueBlackNodeSensitivity() {
    final double shift = 1.0E-6;
    final PresentValueBlackSwaptionSensitivity pvbvs =
        METHOD_BLACK.presentValueBlackSensitivity(SWAPTION_LONG_REC, BLACK_MULTICURVES);
    final PresentValueBlackSwaptionSensitivity pvbns =
        BSSNC.calculateNodeSensitivities(pvbvs, BLACK);
    final double[] x =
        ((InterpolatedDoublesSurface) BLACK.getVolatilitySurface()).getXDataAsPrimitive();
    final double[] y =
        ((InterpolatedDoublesSurface) BLACK.getVolatilitySurface()).getYDataAsPrimitive();
    for (int loopindex = 0; loopindex < x.length; loopindex++) {
      final BlackFlatSwaptionParameters BlackP =
          BlackDataSets.createBlackSwaptionEUR6Shift(loopindex, shift);
      final BlackSwaptionFlatProviderDiscount curvesBlackP =
          new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackP);
      final MultipleCurrencyAmount pvP = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackP);
      final BlackFlatSwaptionParameters BlackM =
          BlackDataSets.createBlackSwaptionEUR6Shift(loopindex, -shift);
      final BlackSwaptionFlatProviderDiscount curvesBlackM =
          new BlackSwaptionFlatProviderDiscount(MULTICURVES, BlackM);
      final MultipleCurrencyAmount pvM = METHOD_BLACK.presentValue(SWAPTION_LONG_REC, curvesBlackM);
      assertEquals(
          "Swaption Black method: present value volatility sensitivity",
          (pvP.getAmount(EUR) - pvM.getAmount(EUR)) / (2 * shift),
          pvbns.getSensitivity().getMap().get(new DoublesPair(x[loopindex], y[loopindex])),
          TOLERANCE_PV_DELTA);
    }
  }
}
/** Tests the present value of Capital inflation indexed bonds. */
@Test
public class BondCapitalIndexedSecurityDiscountingMethodTest {

  private static final InflationIssuerProviderDiscount MARKET =
      MulticurveProviderDiscountDataSets.createMarket1();
  private static final IndexPrice[] PRICE_INDEXES =
      MulticurveProviderDiscountDataSets.getPriceIndexes();
  private static final IndexPrice PRICE_INDEX_UKRPI = PRICE_INDEXES[1];
  private static final IndexPrice PRICE_INDEX_USCPI = PRICE_INDEXES[2];
  private static final IndexPrice PRICE_INDEX_AUDCPI = PRICE_INDEXES[3];
  private static final String[] ISSUER_NAMES = MulticurveProviderDiscountDataSets.getIssuerNames();
  private static final String ISSUER_US_GOVT = ISSUER_NAMES[0];
  private static final String ISSUER_UK_GOVT = ISSUER_NAMES[1];
  private static final String ISSUER_AUD_GOVT = ISSUER_NAMES[3];

  private static final double SHIFT_FD = 1.0E-9;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;
  private static final double TOLERANCE_SENSI_DELTA = 1.0E-6;

  private static final ZonedDateTime PRICING_DATE = DateUtils.getUTCDate(2011, 8, 8);
  private static final BondCapitalIndexedSecurityDiscountingMethod METHOD_BOND_INFLATION =
      new BondCapitalIndexedSecurityDiscountingMethod();
  private static final CouponInflationZeroCouponMonthlyGearingDiscountingMethod
      METHOD_INFLATION_ZC_MONTHLY = new CouponInflationZeroCouponMonthlyGearingDiscountingMethod();
  private static final CouponInflationZeroCouponInterpolationGearingDiscountingMethod
      METHOD_INFLATION_ZC_INTERPOLATION =
          new CouponInflationZeroCouponInterpolationGearingDiscountingMethod();
  private static final PresentValueDiscountingInflationCalculator PVDIC =
      PresentValueDiscountingInflationCalculator.getInstance();
  private static final NetAmountInflationCalculator NADIC =
      NetAmountInflationCalculator.getInstance();
  private static final PresentValueDiscountingInflationIssuerCalculator PVDIIC =
      PresentValueDiscountingInflationIssuerCalculator.getInstance();
  private static final ParameterSensitivityInflationMulticurveDiscountInterpolatedFDCalculator
      PS_PV_FDC =
          new ParameterSensitivityInflationMulticurveDiscountInterpolatedFDCalculator(
              PVDIC, SHIFT_FD);
  private static final PresentValueCurveSensitivityDiscountingInflationCalculator PVCSDC =
      PresentValueCurveSensitivityDiscountingInflationCalculator.getInstance();
  private static final ParameterSensitivityInflationParameterCalculator<
          ParameterInflationProviderInterface>
      PSC = new ParameterSensitivityInflationParameterCalculator<>(PVCSDC);

  // Treasury Indexed Bonds CAIN 3% Index-linked Treasury Stock 2025 - AU0000XCLWP8
  private static final HolidayCalendar CALENDAR_AUD = HolidayCalendars.SAT_SUN;
  private static final BusinessDayConvention BUSINESS_DAY_AUD = BusinessDayConventions.FOLLOWING;
  private static final DayCount DAY_COUNT_CAIN = DayCounts.ACT_ACT_ISDA;
  private static final boolean IS_EOM_CAIN = false;
  private static final ZonedDateTime START_DATE_CAIN = DateUtils.getUTCDate(2009, 9, 30);
  private static final ZonedDateTime FIRST_COUPON_DATE_CAIN = DateUtils.getUTCDate(2009, 12, 20);
  private static final ZonedDateTime MATURITY_DATE_CAIN = DateUtils.getUTCDate(2025, 12, 20);
  private static final YieldConvention YIELD_CONVENTION_CAIN =
      YieldConventionFactory.INSTANCE.getYieldConvention("UK:BUMP/DMO METHOD"); // To check
  private static final int MONTH_LAG_CAIN = 6;
  private static final double INDEX_START_CAIN = 173.60; // November 2001
  private static final double NOTIONAL_CAIN = 1.00;
  private static final double REAL_RATE_CAIN = 0.03;
  private static final Period COUPON_PERIOD_CAIN = Period.ofMonths(3);
  private static final int SETTLEMENT_DAYS_CAIN = 2;
  // TODO: ex-coupon 7 days
  private static final BondCapitalIndexedSecurityDefinition<
          CouponInflationZeroCouponMonthlyGearingDefinition>
      BOND_SECURITY_CAIN_DEFINITION =
          BondCapitalIndexedSecurityDefinition.fromMonthly(
              PRICE_INDEX_AUDCPI,
              MONTH_LAG_CAIN,
              START_DATE_CAIN,
              INDEX_START_CAIN,
              FIRST_COUPON_DATE_CAIN,
              MATURITY_DATE_CAIN,
              COUPON_PERIOD_CAIN,
              NOTIONAL_CAIN,
              REAL_RATE_CAIN,
              BUSINESS_DAY_AUD,
              SETTLEMENT_DAYS_CAIN,
              CALENDAR_AUD,
              DAY_COUNT_CAIN,
              YIELD_CONVENTION_CAIN,
              IS_EOM_CAIN,
              ISSUER_AUD_GOVT);
  private static final DoubleTimeSeries<ZonedDateTime> AUD_CPI =
      MulticurveProviderDiscountDataSets.audCPIFrom2009();
  private static final BondCapitalIndexedSecurity<Coupon> BOND_SECURITY_CAIN =
      BOND_SECURITY_CAIN_DEFINITION.toDerivative(PRICING_DATE, AUD_CPI);

  /** Tests the present value computation. */
  public void presentValueCAIN() {
    final InflationProviderDiscount marketUKGovt = new InflationProviderDiscount();
    marketUKGovt.setCurve(
        BOND_SECURITY_CAIN.getCurrency(), MARKET.getCurve(BOND_SECURITY_CAIN.getIssuerEntity()));
    marketUKGovt.setCurve(PRICE_INDEX_AUDCPI, MARKET.getCurve(PRICE_INDEX_AUDCPI));
    final MultiCurrencyAmount pvNominal =
        METHOD_INFLATION_ZC_MONTHLY.presentValue(
            (CouponInflationZeroCouponMonthlyGearing)
                BOND_SECURITY_CAIN.getNominal().getNthPayment(0),
            marketUKGovt);
    MultiCurrencyAmount pvCoupon = MultiCurrencyAmount.of(BOND_SECURITY_CAIN.getCurrency(), 0.0);
    for (int loopcpn = 0;
        loopcpn < BOND_SECURITY_CAIN.getCoupon().getNumberOfPayments();
        loopcpn++) {
      pvCoupon =
          pvCoupon.plus(
              BOND_SECURITY_CAIN.getCoupon().getNthPayment(loopcpn).accept(PVDIC, marketUKGovt));
    }
    final MultiCurrencyAmount pvExpectd = pvNominal.plus(pvCoupon);
    final MultiCurrencyAmount pv = METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_CAIN, MARKET);
    assertEquals(
        "Inflation Capital Indexed bond: present value",
        pvExpectd.getAmount(BOND_SECURITY_CAIN.getCurrency()).getAmount(),
        pv.getAmount(BOND_SECURITY_CAIN.getCurrency()).getAmount(),
        1.0E-2);
  }

  /** Tests the present value Method vs Calculator. */
  public void presentValueMethodVsCalculatorCAIN() {
    final MultiCurrencyAmount pvMethod =
        METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_CAIN, MARKET);
    final MultiCurrencyAmount pvCalculator = BOND_SECURITY_CAIN.accept(PVDIIC, MARKET);
    assertEquals("Inflation Capital Indexed bond: present value", pvMethod, pvCalculator);
  }

  /** Test the present value parameter curves sensitivity. */
  public void presentValueParameterCurveSensitivityCAIN() {

    final MultipleCurrencyParameterSensitivity pvicsFD =
        PS_PV_FDC.calculateSensitivity(
            BOND_SECURITY_CAIN.getCoupon(), MARKET.getInflationProvider());
    final MultipleCurrencyParameterSensitivity pvicsExact =
        PSC.calculateSensitivity(
            BOND_SECURITY_CAIN.getCoupon(), MARKET.getInflationProvider(), MARKET.getAllNames());

    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueParameterCurveSensitivity ",
        pvicsExact,
        pvicsFD,
        TOLERANCE_SENSI_DELTA);
  }

  /** Test the present value curves sensitivity. */
  public void presentValueCurveSensitivityCAIN() {
    MulticurveProviderInterface multicurveDecorated =
        new MulticurveProviderDiscountingDecoratedIssuer(
            MARKET.getIssuerProvider(),
            BOND_SECURITY_CAIN.getCurrency(),
            BOND_SECURITY_CAIN.getIssuerEntity());
    InflationProviderInterface creditDiscounting =
        new InflationProviderDecoratedMulticurve(
            MARKET.getInflationProvider(), multicurveDecorated);
    final MultipleCurrencyInflationSensitivity sensitivityNominal =
        BOND_SECURITY_CAIN.getNominal().accept(PVCSDC, creditDiscounting);
    final MultipleCurrencyInflationSensitivity sensitivityCoupon =
        BOND_SECURITY_CAIN.getCoupon().accept(PVCSDC, creditDiscounting);
    final MultipleCurrencyInflationSensitivity pvcisCalculated =
        sensitivityNominal.plus(sensitivityCoupon);

    final MultipleCurrencyInflationSensitivity pvcisMethod =
        METHOD_BOND_INFLATION.presentValueCurveSensitivity(BOND_SECURITY_CAIN, MARKET);

    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueCurveSensitivity ",
        pvcisCalculated,
        pvcisMethod,
        TOLERANCE_PV_DELTA);
  }

  // Index-Lined Gilt 2% Index-linked Treasury Stock 2035 - GB0031790826
  private static final HolidayCalendar CALENDAR_GBP = HolidayCalendars.SAT_SUN;
  private static final BusinessDayConvention BUSINESS_DAY_GBP = BusinessDayConventions.FOLLOWING;
  private static final DayCount DAY_COUNT_GILT_1 = DayCounts.ACT_ACT_ISDA;
  private static final boolean IS_EOM_GILT_1 = false;
  private static final ZonedDateTime START_DATE_GILT_1 = DateUtils.getUTCDate(2002, 7, 11);
  private static final ZonedDateTime FIRST_COUPON_DATE_GILT_1 = DateUtils.getUTCDate(2003, 1, 26);
  private static final ZonedDateTime MATURITY_DATE_GILT_1 = DateUtils.getUTCDate(2035, 1, 26);
  private static final YieldConvention YIELD_CONVENTION_GILT_1 = SimpleYieldConvention.UK_IL_BOND;
  // YieldConventionFactory.INSTANCE.getYieldConvention("UK:BUMP/DMO METHOD"); // To check
  private static final int MONTH_LAG_GILT_1 = 8;
  private static final double INDEX_START_GILT_1 = 173.60; // November 2001
  private static final double NOTIONAL_GILT_1 = 1.00;
  private static final double REAL_RATE_GILT_1 = 0.02;
  private static final Period COUPON_PERIOD_GILT_1 = Period.ofMonths(6);
  private static final int SETTLEMENT_DAYS_GILT_1 = 2;
  // TODO: ex-coupon 7 days
  private static final BondCapitalIndexedSecurityDefinition<
          CouponInflationZeroCouponMonthlyGearingDefinition>
      BOND_SECURITY_GILT_1_DEFINITION =
          BondCapitalIndexedSecurityDefinition.fromMonthly(
              PRICE_INDEX_UKRPI,
              MONTH_LAG_GILT_1,
              START_DATE_GILT_1,
              INDEX_START_GILT_1,
              FIRST_COUPON_DATE_GILT_1,
              MATURITY_DATE_GILT_1,
              COUPON_PERIOD_GILT_1,
              NOTIONAL_GILT_1,
              REAL_RATE_GILT_1,
              BUSINESS_DAY_GBP,
              SETTLEMENT_DAYS_GILT_1,
              CALENDAR_GBP,
              DAY_COUNT_GILT_1,
              YIELD_CONVENTION_GILT_1,
              IS_EOM_GILT_1,
              ISSUER_UK_GOVT);
  private static final DoubleTimeSeries<ZonedDateTime> UK_RPI =
      MulticurveProviderDiscountDataSets.ukRpiFrom2010();
  private static final BondCapitalIndexedSecurity<Coupon> BOND_SECURITY_GILT_1 =
      BOND_SECURITY_GILT_1_DEFINITION.toDerivative(PRICING_DATE, UK_RPI);

  /** Tests the present value computation. */
  public void presentValueGilt1() {
    final InflationProviderDiscount marketUKGovt = new InflationProviderDiscount();
    marketUKGovt.setCurve(
        BOND_SECURITY_GILT_1.getCurrency(),
        MARKET.getCurve(BOND_SECURITY_GILT_1.getIssuerEntity()));
    marketUKGovt.setCurve(PRICE_INDEX_UKRPI, MARKET.getCurve(PRICE_INDEX_UKRPI));
    final MultiCurrencyAmount pvNominal =
        METHOD_INFLATION_ZC_MONTHLY.presentValue(
            (CouponInflationZeroCouponMonthlyGearing)
                BOND_SECURITY_GILT_1.getNominal().getNthPayment(0),
            marketUKGovt);
    MultiCurrencyAmount pvCoupon = MultiCurrencyAmount.of(BOND_SECURITY_GILT_1.getCurrency(), 0.0);
    for (int loopcpn = 0;
        loopcpn < BOND_SECURITY_GILT_1.getCoupon().getNumberOfPayments();
        loopcpn++) {
      pvCoupon =
          pvCoupon.plus(
              BOND_SECURITY_GILT_1.getCoupon().getNthPayment(loopcpn).accept(PVDIC, marketUKGovt));
    }
    final MultiCurrencyAmount pvExpected = pvNominal.plus(pvCoupon);
    final MultiCurrencyAmount pv = METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_GILT_1, MARKET);
    assertEquals(
        "Inflation Capital Indexed bond: present value",
        pvExpected.getAmount(BOND_SECURITY_GILT_1.getCurrency()).getAmount(),
        pv.getAmount(BOND_SECURITY_GILT_1.getCurrency()).getAmount(),
        1.0E-2);
  }

  /** Tests the present value Method vs Calculator. */
  public void presentValueMethodVsCalculator() {
    final MultiCurrencyAmount pvMethod =
        METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_GILT_1, MARKET);
    final MultiCurrencyAmount pvCalculator = BOND_SECURITY_GILT_1.accept(PVDIIC, MARKET);
    assertEquals("Inflation Capital Indexed bond: present value", pvMethod, pvCalculator);
  }

  // 2% 10-YEAR TREASURY INFLATION-PROTECTED SECURITIES (TIPS) Due January 15, 2016 - US912828ET33
  private static final HolidayCalendar CALENDAR_USD = HolidayCalendars.SAT_SUN;
  private static final BusinessDayConvention BUSINESS_DAY_USD = BusinessDayConventions.FOLLOWING;
  private static final DayCount DAY_COUNT_TIPS_1 = DayCounts.ACT_ACT_ICMA;
  private static final boolean IS_EOM_TIPS_1 = false;
  private static final ZonedDateTime START_DATE_TIPS_1 = DateUtils.getUTCDate(2006, 1, 15);
  private static final ZonedDateTime MATURITY_DATE_TIPS_1 = DateUtils.getUTCDate(2016, 1, 15);
  private static final YieldConvention YIELD_CONVENTION_TIPS_1 = SimpleYieldConvention.US_IL_REAL;
  private static final int MONTH_LAG_TIPS_1 = 3;
  private static final double INDEX_START_TIPS_1 = 198.47742; // Date:
  private static final double NOTIONAL_TIPS_1 = 100.00;
  private static final double REAL_RATE_TIPS_1 = 0.02;
  private static final Period COUPON_PERIOD_TIPS_1 = Period.ofMonths(6);
  private static final int SETTLEMENT_DAYS_TIPS_1 = 1;

  private static final BondCapitalIndexedSecurityDefinition<
          CouponInflationZeroCouponInterpolationGearingDefinition>
      BOND_SECURITY_TIPS_1_DEFINITION =
          BondCapitalIndexedSecurityDefinition.fromInterpolation(
              PRICE_INDEX_USCPI,
              MONTH_LAG_TIPS_1,
              START_DATE_TIPS_1,
              INDEX_START_TIPS_1,
              MATURITY_DATE_TIPS_1,
              COUPON_PERIOD_TIPS_1,
              NOTIONAL_TIPS_1,
              REAL_RATE_TIPS_1,
              BUSINESS_DAY_USD,
              SETTLEMENT_DAYS_TIPS_1,
              CALENDAR_USD,
              DAY_COUNT_TIPS_1,
              YIELD_CONVENTION_TIPS_1,
              IS_EOM_TIPS_1,
              ISSUER_US_GOVT);
  private static final DoubleTimeSeries<ZonedDateTime> US_CPI =
      MulticurveProviderDiscountDataSets.usCpiFrom2009();
  private static final BondCapitalIndexedSecurity<Coupon> BOND_SECURITY_TIPS_1 =
      BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(PRICING_DATE, US_CPI);

  /** Tests the present value computation. */
  public void presentValueTips1() {
    final InflationProviderDiscount marketUSGovt = new InflationProviderDiscount();
    marketUSGovt.setCurve(
        BOND_SECURITY_TIPS_1.getCurrency(),
        MARKET.getCurve(BOND_SECURITY_TIPS_1.getIssuerEntity()));
    marketUSGovt.setCurve(PRICE_INDEX_USCPI, MARKET.getCurve(PRICE_INDEX_USCPI));
    final MultiCurrencyAmount pvNominal =
        METHOD_INFLATION_ZC_INTERPOLATION.presentValue(
            (CouponInflationZeroCouponInterpolationGearing)
                BOND_SECURITY_TIPS_1.getNominal().getNthPayment(0),
            marketUSGovt);
    MultiCurrencyAmount pvCoupon = MultiCurrencyAmount.of(BOND_SECURITY_TIPS_1.getCurrency(), 0.0);
    for (int loopcpn = 0;
        loopcpn < BOND_SECURITY_TIPS_1.getCoupon().getNumberOfPayments();
        loopcpn++) {
      pvCoupon =
          pvCoupon.plus(
              BOND_SECURITY_TIPS_1.getCoupon().getNthPayment(loopcpn).accept(PVDIC, marketUSGovt));
    }
    final MultiCurrencyAmount pvExpected = pvNominal.plus(pvCoupon);
    final MultiCurrencyAmount pv = METHOD_BOND_INFLATION.presentValue(BOND_SECURITY_TIPS_1, MARKET);
    assertEquals(
        "Inflation Capital Indexed bond: present value",
        pvExpected.getAmount(BOND_SECURITY_TIPS_1.getCurrency()).getAmount(),
        pv.getAmount(BOND_SECURITY_TIPS_1.getCurrency()).getAmount(),
        1.0E-2);
  }

  /** Tests the present value computation. */
  public void presentValueFromCleanPriceRealTips1() {
    final double cleanPriceReal = 1.05;
    Currency ccy = BOND_SECURITY_TIPS_1.getCurrency();
    final MultiCurrencyAmount pv =
        METHOD_BOND_INFLATION.presentValueFromCleanRealPrice(
            BOND_SECURITY_TIPS_1, MARKET, cleanPriceReal);
    MultiCurrencyAmount pvPriceReal =
        BOND_SECURITY_TIPS_1.getSettlement().accept(PVDIIC, MARKET).multipliedBy(cleanPriceReal);
    MultiCurrencyAmount pvAccrued =
        BOND_SECURITY_TIPS_1
            .getSettlement()
            .accept(PVDIC, MARKET)
            .multipliedBy(BOND_SECURITY_TIPS_1.getAccruedInterest());
    MultiCurrencyAmount pvExpected = pvPriceReal.plus(pvAccrued);
    assertEquals(
        "Inflation Capital Indexed bond: present value from clean real price",
        pvExpected.getAmount(ccy).getAmount(),
        pv.getAmount(ccy).getAmount(),
        1.0E-6);
  }

  /** Tests the present value computation. */
  public void presentValueFromCleanPriceNominalTips1() {
    final double cleanPriceNominal = 1.05;
    Currency ccy = BOND_SECURITY_TIPS_1.getCurrency();
    final MultiCurrencyAmount pv =
        METHOD_BOND_INFLATION.presentValueFromCleanNominalPrice(
            BOND_SECURITY_TIPS_1, MARKET, cleanPriceNominal);
    MultiCurrencyAmount pvAccrued =
        BOND_SECURITY_TIPS_1
            .getSettlement()
            .accept(PVDIC, MARKET)
            .multipliedBy(BOND_SECURITY_TIPS_1.getAccruedInterest());
    double pvPriceNominal =
        cleanPriceNominal
            * MARKET.getDiscountFactor(ccy, BOND_SECURITY_TIPS_1.getSettlementTime())
            * NOTIONAL_TIPS_1;
    double pvExpected = pvPriceNominal + pvAccrued.getAmount(ccy).getAmount();
    assertEquals(
        "Inflation Capital Indexed bond: present value from clean real price",
        pvExpected,
        pv.getAmount(ccy).getAmount(),
        1.0E-6);
  }

  /** Tests the clean real price from the dirty real price. */
  public void cleanNominalPriceFromDirtyNominalPriceTips1() {
    final double dirtyNominal = 1.01;
    final double cleanReal =
        METHOD_BOND_INFLATION.cleanNominalPriceFromDirtyNominalPrice(
            BOND_SECURITY_TIPS_1, dirtyNominal);
    final double indexRatio = BOND_SECURITY_TIPS_1.getIndexRatio();
    final double cleanRealExpected =
        dirtyNominal - BOND_SECURITY_TIPS_1.getAccruedInterest() / NOTIONAL_TIPS_1 * indexRatio;
    assertEquals(
        "Inflation Capital Indexed bond: clean from dirty", cleanRealExpected, cleanReal, 1.0E-8);
  }

  /** Tests the clean real price from the dirty real price. */
  public void cleanRealFromDirtyRealTips1() {
    final double dirtyReal = 1.01;
    final double cleanReal =
        METHOD_BOND_INFLATION.cleanRealPriceFromDirtyRealPrice(BOND_SECURITY_TIPS_1, dirtyReal);
    final double cleanRealExpected =
        dirtyReal - BOND_SECURITY_TIPS_1.getAccruedInterest() / NOTIONAL_TIPS_1;
    assertEquals(
        "Inflation Capital Indexed bond: clean from dirty", cleanRealExpected, cleanReal, 1.0E-8);
  }

  /** Tests the dirty real price computation from the real yield in the "US I/L real" convention. */
  public void dirtyRealPriceFromRealYieldTips1() {
    final double[] yield = new double[] {-0.01, 0.00, 0.01, 0.02, 0.03};
    final int nbCoupon = BOND_SECURITY_TIPS_1.getCoupon().getNumberOfPayments();
    final double[] dirtyRealPrice = new double[yield.length];
    final double[] dirtyRealPriceExpected = new double[yield.length];
    for (int loopyield = 0; loopyield < yield.length; loopyield++) {
      dirtyRealPrice[loopyield] =
          METHOD_BOND_INFLATION.dirtyPriceFromRealYield(BOND_SECURITY_TIPS_1, yield[loopyield]);

      final double factorOnPeriod = 1 + yield[loopyield] / BOND_SECURITY_TIPS_1.getCouponPerYear();
      double pvAtFirstCoupon = 0;

      for (int loopcpn = 0; loopcpn < nbCoupon; loopcpn++) {
        pvAtFirstCoupon +=
            ((CouponInflationGearing) BOND_SECURITY_TIPS_1.getCoupon().getNthPayment(loopcpn))
                    .getFactor()
                / BOND_SECURITY_TIPS_1.getCouponPerYear()
                / Math.pow(factorOnPeriod, loopcpn);
      }
      pvAtFirstCoupon += 1.0 / Math.pow(factorOnPeriod, nbCoupon - 1);
      dirtyRealPriceExpected[loopyield] =
          pvAtFirstCoupon
              / (1
                  + BOND_SECURITY_TIPS_1.getAccrualFactorToNextCoupon()
                      * yield[loopyield]
                      / BOND_SECURITY_TIPS_1.getCouponPerYear());
      assertEquals(
          "Inflation Capital Indexed bond: yield " + loopyield,
          dirtyRealPriceExpected[loopyield],
          dirtyRealPrice[loopyield],
          1.0E-8);
    }
  }

  /** Tests the clean real price from the dirty real price. */
  public void yieldRealFromDirtyRealTips1() {
    final double[] yield = new double[] {-0.01, 0.00, 0.01, 0.02, 0.03};
    final double[] dirtyRealPrice = new double[yield.length];
    final double[] yieldComputed = new double[yield.length];
    for (int loopyield = 0; loopyield < yield.length; loopyield++) {
      dirtyRealPrice[loopyield] =
          METHOD_BOND_INFLATION.dirtyPriceFromRealYield(BOND_SECURITY_TIPS_1, yield[loopyield]);
      yieldComputed[loopyield] =
          METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(
              BOND_SECURITY_TIPS_1, dirtyRealPrice[loopyield]);
      assertEquals(
          "Inflation Capital Indexed bond: yield " + loopyield,
          yield[loopyield],
          yieldComputed[loopyield],
          1.0E-8);
    }
  }

  @Test(enabled = false)
  /** Tests the clean, dirty and yield vs external hard-coded values. */
  public void priceYieldExternalValues1() {
    final double m1 = 1000000; // Notional of the external figures.
    final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 16); // Spot 18-Aug-2011
    final InflationIssuerProviderDiscount market =
        MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
    final double cleanRealPrice = 1.00;
    final BondCapitalIndexedSecurity<Coupon> bond_110817 =
        BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
    final double referenceIndexExpected = 225.83129;
    final MultiCurrencyAmount netAmountSettle =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    final double referenceIndexComputed =
        netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
            * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
            / bond_110817.getSettlement().getNotional();
    assertEquals(
        "Inflation Capital Indexed bond: index",
        referenceIndexExpected,
        referenceIndexComputed,
        1.0E-5);
    final double indexRatioExpected = 1.13782;
    final MultiCurrencyAmount indexRatioCalculated =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    assertEquals(
        "Inflation Capital Indexed bond: indexRatio",
        indexRatioExpected,
        indexRatioCalculated.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount()
            / NOTIONAL_TIPS_1,
        1.0E-5);
    final double yieldExpected = 1.999644 / 100.0;
    final double dirtyRealPriceComputed =
        METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
    final double yieldComputed =
        METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
    assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
    final double accruedExpected = 2102.49;
    final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
    final double accruedReal = bond_110817.getAccruedInterest();
    assertEquals(
        "Inflation Capital Indexed bond: accrued",
        accruedRealExpected,
        accruedReal / NOTIONAL_TIPS_1,
        1.0E-8);
    final double netAmountExpected = 1139922.49; // For 1m; uses the rounding rules.
    final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
    assertEquals(
        "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
    final MultiCurrencyAmount netAmount =
        METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
    assertEquals(
        "Inflation Capital Indexed bond: net amount",
        netAmountExpected,
        netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
        2.0E+0); // The difference is due to rounding.
  }

  @Test(enabled = false)
  /** Tests the clean, dirty and yield vs external hard-coded values. */
  public void priceYieldExternalValues2() {
    final double m1 = 1000000; // Notional of the external figures.
    final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 17); // Spot 18-Aug-2011
    final InflationIssuerProviderDiscount market =
        MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
    final double cleanRealPrice = 1.13 + 0.01 / 32;
    final BondCapitalIndexedSecurity<Coupon> bond_110817 =
        BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
    final double referenceIndexExpected = 225.83129;
    final MultiCurrencyAmount netAmountSettle =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    final double referenceIndexComputed =
        netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
            * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
            / bond_110817.getSettlement().getNotional();
    assertEquals(
        "Inflation Capital Indexed bond: index",
        referenceIndexExpected,
        referenceIndexComputed,
        1.0E-5);
    final double indexRatioExpected = 1.13782;
    assertEquals(
        "Inflation Capital Indexed bond: indexRatio",
        indexRatioExpected,
        referenceIndexComputed / INDEX_START_TIPS_1,
        1.0E-5);
    final double yieldExpected = -0.892152 / 100.0;
    final double dirtyRealPriceComputed =
        METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
    final double yieldComputed =
        METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
    assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
    final double accruedExpected = 2102.49;
    final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
    final double accruedReal = bond_110817.getAccruedInterest();
    assertEquals(
        "Inflation Capital Indexed bond: accrued",
        accruedRealExpected,
        accruedReal / NOTIONAL_TIPS_1,
        1.0E-8);
    final double netAmountExpected = 1288194.66; // For 1m; uses the rounding rules.
    final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
    assertEquals(
        "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
    final MultiCurrencyAmount netAmount =
        METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
    assertEquals(
        "Inflation Capital Indexed bond: net amount",
        netAmountExpected,
        netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
        2.0E+0); // The difference is due to rounding.
  }

  @Test(enabled = false)
  /** Tests the clean, dirty and yield vs external hard-coded values. */
  public void priceYieldExternalValues3() {
    final double m1 = 1000000; // Notional of the external figures.
    final ZonedDateTime pricingDate20110817 = DateUtils.getUTCDate(2011, 8, 18); // Spot 19-Aug-2011
    final InflationIssuerProviderDiscount market =
        MulticurveProviderDiscountDataSets.createMarket1(pricingDate20110817);
    final double cleanRealPrice = 1.00;
    final BondCapitalIndexedSecurity<Coupon> bond_110817 =
        BOND_SECURITY_TIPS_1_DEFINITION.toDerivative(pricingDate20110817, US_CPI);
    final double referenceIndexExpected = 225.82348;
    final MultiCurrencyAmount netAmountSettle =
        bond_110817.getSettlement().accept(NADIC, market.getInflationProvider());
    final double referenceIndexComputed =
        netAmountSettle.getAmount(bond_110817.getCurrency()).getAmount()
            * BOND_SECURITY_TIPS_1_DEFINITION.getIndexStartValue()
            / bond_110817.getSettlement().getNotional();
    assertEquals(
        "Inflation Capital Indexed bond: index",
        referenceIndexExpected,
        referenceIndexComputed,
        1.0E-5);
    final double indexRatioExpected = 1.13778;
    final double yieldExpected = 1.999636 / 100.0;
    final double dirtyRealPriceComputed =
        METHOD_BOND_INFLATION.dirtyRealPriceFromCleanRealPrice(bond_110817, cleanRealPrice);
    final double yieldComputed =
        METHOD_BOND_INFLATION.yieldRealFromDirtyRealPrice(bond_110817, dirtyRealPriceComputed);
    assertEquals("Inflation Capital Indexed bond: yield ", yieldExpected, yieldComputed, 1.0E-8);
    final double accruedExpected = 2164.26;
    final double accruedRealExpected = accruedExpected / m1 / indexRatioExpected;
    final double accruedReal = bond_110817.getAccruedInterest();
    assertEquals(
        "Inflation Capital Indexed bond: accrued",
        accruedRealExpected,
        accruedReal / NOTIONAL_TIPS_1,
        1.0E-8);
    final double netAmountExpected = 1139944.26; // For 1m; uses the rounding rules.
    final double netAmount2 = indexRatioExpected * m1 * cleanRealPrice + accruedExpected;
    assertEquals(
        "Inflation Capital Indexed bond: net amount", netAmountExpected, netAmount2, 1.0E-2);
    final MultiCurrencyAmount netAmount =
        METHOD_BOND_INFLATION.netAmount(bond_110817, market, cleanRealPrice);
    assertEquals(
        "Inflation Capital Indexed bond: net amount",
        netAmountExpected,
        netAmount.getAmount(PRICE_INDEX_USCPI.getCurrency()).getAmount() * m1 / NOTIONAL_TIPS_1,
        2.0E+0); // The difference is due to rounding.
  }

  /** Test the present value parameter curves sensitivity. */
  public void presentValueParameterCurveSensitivity() {

    final MultipleCurrencyParameterSensitivity pvicsFD =
        PS_PV_FDC.calculateSensitivity(
            BOND_SECURITY_GILT_1.getCoupon(), MARKET.getInflationProvider());
    final MultipleCurrencyParameterSensitivity pvicsExact =
        PSC.calculateSensitivity(
            BOND_SECURITY_GILT_1.getCoupon(), MARKET.getInflationProvider(), MARKET.getAllNames());

    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueParameterCurveSensitivity ",
        pvicsExact,
        pvicsFD,
        TOLERANCE_PV_DELTA);
  }

  /** Test the present value curves sensitivity. */
  public void presentValueCurveSensitivity() {
    MulticurveProviderInterface multicurveDecorated =
        new MulticurveProviderDiscountingDecoratedIssuer(
            MARKET.getIssuerProvider(),
            BOND_SECURITY_GILT_1.getCurrency(),
            BOND_SECURITY_GILT_1.getIssuerEntity());
    InflationProviderInterface inflationDecorated =
        new InflationProviderDecoratedMulticurve(
            MARKET.getInflationProvider(), multicurveDecorated);
    final MultipleCurrencyInflationSensitivity sensitivityNominal =
        BOND_SECURITY_GILT_1.getNominal().accept(PVCSDC, inflationDecorated);
    final MultipleCurrencyInflationSensitivity sensitivityCoupon =
        BOND_SECURITY_GILT_1.getCoupon().accept(PVCSDC, inflationDecorated);
    final MultipleCurrencyInflationSensitivity pvcisCalculated =
        sensitivityNominal.plus(sensitivityCoupon);
    final MultipleCurrencyInflationSensitivity pvcisMethod =
        METHOD_BOND_INFLATION.presentValueCurveSensitivity(BOND_SECURITY_GILT_1, MARKET);
    AssertSensitivityObjects.assertEquals(
        "Bond capital indexed security: presentValueCurveSensitivity ",
        pvcisCalculated,
        pvcisMethod,
        TOLERANCE_PV_DELTA);
  }
}
/**
 * Tests the present value and its sensitivities for zero-coupon cap/floor with reference index on
 * the first of the month.
 */
public class CapFloorInflationZeroCouponMonthlyBlackSmileMethodTest {
  private static final InflationIssuerProviderDiscount MARKET =
      MulticurveProviderDiscountDataSets.createMarket1();
  private static final IndexPrice[] PRICE_INDEXES =
      MARKET.getPriceIndexes().toArray(new IndexPrice[MARKET.getPriceIndexes().size()]);
  private static final IndexPrice PRICE_INDEX_EUR = PRICE_INDEXES[0];
  private static final Calendar CALENDAR_EUR = MulticurveProviderDiscountDataSets.getEURCalendar();
  private static final BusinessDayConvention BUSINESS_DAY =
      BusinessDayConventionFactory.INSTANCE.getBusinessDayConvention("Modified Following");
  private static final ZonedDateTime START_DATE = DateUtils.getUTCDate(2008, 8, 18);
  private static final int MATURITY = 10;
  private static final Period COUPON_TENOR = Period.ofYears(MATURITY);
  private static final ZonedDateTime PAYMENT_DATE =
      ScheduleCalculator.getAdjustedDate(START_DATE, COUPON_TENOR, BUSINESS_DAY, CALENDAR_EUR);
  private static final double NOTIONAL = 98765432;
  private static final int MONTH_LAG = 3;
  private static final double INDEX_1MAY_2008 =
      108.23; // 3 m before Aug: May / 1 May index = May index: 108.23

  private static final double STRIKE = .02;
  private static final boolean IS_CAP = true;
  private static final ZonedDateTime LAST_KNOWN_FIXING_DATE = DateUtils.getUTCDate(2008, 7, 01);

  private static final double SHIFT_FD = 1.0E-7;
  private static final double TOLERANCE_PV = 1.0E-2;
  private static final double TOLERANCE_PV_DELTA = 1.0E+2;

  private static final InterpolatedDoublesSurface BLACK_SURF =
      TestsDataSetsBlack.createBlackSurfaceExpiryStrike();
  private static final BlackSmileCapInflationZeroCouponParameters BLACK_PARAM =
      new BlackSmileCapInflationZeroCouponParameters(BLACK_SURF, PRICE_INDEX_EUR);
  private static final BlackSmileCapInflationZeroCouponProviderDiscount BLACK_INFLATION =
      new BlackSmileCapInflationZeroCouponProviderDiscount(
          MARKET.getInflationProvider(), BLACK_PARAM);

  private static final ZonedDateTime PRICING_DATE = DateUtils.getUTCDate(2011, 8, 3);
  private static final CouponInflationZeroCouponMonthlyDefinition ZERO_COUPON_DEFINITION =
      CouponInflationZeroCouponMonthlyDefinition.from(
          START_DATE,
          PAYMENT_DATE,
          NOTIONAL,
          PRICE_INDEX_EUR,
          INDEX_1MAY_2008,
          MONTH_LAG,
          MONTH_LAG,
          false);
  private static final CapFloorInflationZeroCouponMonthlyDefinition ZERO_COUPON_DEFINITION_CAP =
      CapFloorInflationZeroCouponMonthlyDefinition.from(
          ZERO_COUPON_DEFINITION, LAST_KNOWN_FIXING_DATE, MATURITY, STRIKE, IS_CAP);
  private static final CapFloorInflationZeroCouponMonthly ZERO_COUPON_CAP =
      ZERO_COUPON_DEFINITION_CAP.toDerivative(PRICING_DATE, "not used");

  private static final CapFloorInflationZeroCouponMonthlyBlackSmileMethod METHOD =
      CapFloorInflationZeroCouponMonthlyBlackSmileMethod.getInstance();
  private static final PresentValueBlackSmileInflationZeroCouponCalculator PVIC =
      PresentValueBlackSmileInflationZeroCouponCalculator.getInstance();
  private static final PresentValueCurveSensitivityBlackSmileInflationZeroCouponCalculator PVCSDC =
      PresentValueCurveSensitivityBlackSmileInflationZeroCouponCalculator.getInstance();
  private static final ParameterInflationSensitivityParameterCalculator<
          BlackSmileCapInflationZeroCouponProviderInterface>
      PSC = new ParameterInflationSensitivityParameterCalculator<>(PVCSDC);
  private static final ParameterSensitivityBlackSmileZeroCouponCapDiscountInterpolatedFDCalculator
      PS_PV_FDC =
          new ParameterSensitivityBlackSmileZeroCouponCapDiscountInterpolatedFDCalculator(
              PVIC, SHIFT_FD);

  /** The Black function used in the pricing. */
  private static final BlackPriceFunction BLACK_FUNCTION = new BlackPriceFunction();

  @Test
  /** Tests the present value. */
  public void presentValueNoNotional() {
    final MultipleCurrencyAmount pv = METHOD.presentValue(ZERO_COUPON_CAP, BLACK_INFLATION);
    final double timeToMaturity =
        ZERO_COUPON_CAP.getReferenceEndTime() - ZERO_COUPON_CAP.getLastKnownFixingTime();
    final double df =
        MARKET
            .getCurve(ZERO_COUPON_CAP.getCurrency())
            .getDiscountFactor(ZERO_COUPON_CAP.getPaymentTime());
    final double finalIndex =
        MARKET.getCurve(PRICE_INDEX_EUR).getPriceIndex(ZERO_COUPON_CAP.getReferenceEndTime());
    final double forward = finalIndex / INDEX_1MAY_2008;
    final EuropeanVanillaOption option =
        new EuropeanVanillaOption(
            Math.pow(1 + ZERO_COUPON_CAP.getStrike(), ZERO_COUPON_CAP.getMaturity()),
            timeToMaturity,
            ZERO_COUPON_CAP.isCap());
    final double volatility =
        BLACK_INFLATION
            .getBlackParameters()
            .getVolatility(ZERO_COUPON_CAP.getReferenceEndTime(), ZERO_COUPON_CAP.getStrike());
    final BlackFunctionData dataBlack = new BlackFunctionData(forward, 1.0, volatility);
    final Function1D<BlackFunctionData, Double> func = BLACK_FUNCTION.getPriceFunction(option);
    final double pvExpected =
        df
            * func.evaluate(dataBlack)
            * ZERO_COUPON_CAP.getNotional()
            * ZERO_COUPON_CAP.getPaymentYearFraction();
    assertEquals(
        "Zero-coupon inflation DiscountingMethod: Present value",
        pvExpected,
        pv.getAmount(ZERO_COUPON_CAP.getCurrency()),
        TOLERANCE_PV);
  }

  @Test
  /** Tests the present value: Method vs Calculator. */
  public void presentValueMethodVsCalculator() {
    final MultipleCurrencyAmount pvMethod = METHOD.presentValue(ZERO_COUPON_CAP, BLACK_INFLATION);
    final MultipleCurrencyAmount pvCalculator = ZERO_COUPON_CAP.accept(PVIC, BLACK_INFLATION);
    assertEquals("Zero-coupon inflation DiscountingMethod: Present value", pvMethod, pvCalculator);
  }

  @Test
  /** Test the present value curves sensitivity. */
  public void presentValueCurveSensitivity() {

    final MultipleCurrencyParameterSensitivity pvicsFD =
        PS_PV_FDC.calculateSensitivity(ZERO_COUPON_CAP, BLACK_INFLATION);
    final MultipleCurrencyParameterSensitivity pvicsExact =
        PSC.calculateSensitivity(ZERO_COUPON_CAP, BLACK_INFLATION, MARKET.getAllNames());

    AssertSensivityObjects.assertEquals(
        "Zero-coupon inflation DiscountingMethod: presentValueCurveSensitivity ",
        pvicsExact,
        pvicsFD,
        TOLERANCE_PV_DELTA);
  }

  @Test
  public void presentValueMarketSensitivityMethodVsCalculator() {
    final MultipleCurrencyInflationSensitivity pvcisMethod =
        METHOD.presentValueCurveSensitivity(ZERO_COUPON_CAP, BLACK_INFLATION);
    final MultipleCurrencyInflationSensitivity pvcisCalculator =
        ZERO_COUPON_CAP.accept(PVCSDC, BLACK_INFLATION);
    AssertSensivityObjects.assertEquals(
        "Zero-coupon inflation DiscountingMethod: presentValueMarketSensitivity",
        pvcisMethod,
        pvcisCalculator,
        TOLERANCE_PV_DELTA);
  }
}