Exemplo n.º 1
0
  // start date before end date
  static LocalDateTime[] parse(String startDateTimeString, String endDateTimeString) {
    LocalDateTime[] dates = new LocalDateTime[2];
    String startDateString = null;
    String startTimeString = null;
    String endDateString = null;
    String endTimeString = null;

    Pattern pattern = Pattern.compile(DATE_TIME_PATTERN);

    Matcher matcher = pattern.matcher(startDateTimeString);
    matcher.find();
    startDateString = matcher.group(1);
    startTimeString = matcher.group(2);

    matcher = pattern.matcher(endDateTimeString);
    matcher.find();
    endDateString = matcher.group(1);
    endTimeString = matcher.group(2);

    if (startDateString == null) {
      startDateString = processNullStartDate(endDateString);
    }

    if (startDateString.equals("now")) {
      startTimeString = getCurrentTime();
    }

    if (endDateString == null) {
      endDateString = startDateString;
    }

    if (startTimeString == null) {
      startTimeString = processNullStartTime(startDateString);
    }

    if (endTimeString == null) {
      endTimeString = processNullEndTime(startDateString, endDateString, startTimeString);
    }

    LocalDate startDate = DateParser.parse(startDateString);
    LocalTime startTime = TimeParser.parse(startTimeString);
    LocalDateTime startDateTime = startDate.atTime(startTime);

    LocalDate endDate = DateParser.parse(endDateString);
    LocalTime endTime = TimeParser.parse(endTimeString);
    LocalDateTime endDateTime = endDate.atTime(endTime);

    if (endDateTime.isBefore(startDateTime)) {
      endDateTime.plusDays(1);
    }

    dates[0] = startDateTime;
    dates[1] = endDateTime;

    return dates;
  }
  public static void main(String[] args) {
    LocalDate today = LocalDate.now(); // Today’s date
    System.out.println("TODAY: " + today);

    /*String strDate = today.plusWeeks(1).toString(); // 2015-09-01
    String day;
    if (strDate.substring(8, 9).matches("0")) {
        day = strDate.substring(9);
        System.out.println("DAY IS: " + day);
    } else {
        day = strDate.substring(8);
        System.out.println("DAY IS: " + day);
    }*/

    int dayOfMonth = today.plusDays(4).getDayOfMonth();
    System.out.println("DAY OF MONTH: " + dayOfMonth);

    LocalDate localDate = LocalDate.of(2015, Month.valueOf("OCTOBER"), 25);
    System.out.println("LOCAL DATE: " + localDate);

    long toDays = Duration.between(localDate.atTime(0, 0), today.atTime(0, 0)).toDays();
    System.out.println("TO DAYS: " + toDays);
    Duration toDays23 = Duration.between(localDate, today);
    System.out.println("TO DAYS: " + toDays23);

    Month month = today.getMonth();
    //        localDate.
    System.out.println("Month " + month.toString());
    String displayName = month.getDisplayName(TextStyle.FULL, Locale.CANADA);
    System.out.println("DISPLAY NAME: " + displayName);

    LocalDate alonzosBirthday = LocalDate.of(1903, 6, 14);
    alonzosBirthday = LocalDate.of(1903, Month.JUNE, 14);
    // Uses the Month enumeration
    System.out.println("alonzosBirthday: " + alonzosBirthday);

    LocalDate programmersDay = LocalDate.of(2015, 1, 1).plusDays(255);
    // September 13, but in a leap year it would be September 12
    System.out.println("programmersDay: " + programmersDay);

    LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
    LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);

    System.out.println("Until christmas: " + independenceDay.until(christmas));
    System.out.println(
        "Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));

    System.out.println(LocalDate.of(2016, 1, 31).plusMonths(1));
    System.out.println(LocalDate.of(2016, 3, 31).minusMonths(1));

    DayOfWeek startOfLastMillennium = LocalDate.of(1900, 1, 1).getDayOfWeek();
    System.out.println("startOfLastMillennium: " + startOfLastMillennium);
    System.out.println(startOfLastMillennium.getValue());
    System.out.println(DayOfWeek.SATURDAY.plus(3));
  }
Exemplo n.º 3
0
  @RequestMapping(
      method = RequestMethod.GET,
      params = {"fromDate", "toDate"})
  public List<AuditEvent> getByDates(
      @RequestParam(value = "fromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
          LocalDate fromDate,
      @RequestParam(value = "toDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
          LocalDate toDate) {

    return auditEventService.findByDates(fromDate.atTime(0, 0), toDate.atTime(23, 59));
  }
Exemplo n.º 4
0
  static LocalDateTime parse(String endDateTimeString) {

    String endDateString = null;
    String endTimeString = null;

    Pattern pattern = Pattern.compile(DATE_TIME_PATTERN);
    Matcher matcher = pattern.matcher(endDateTimeString);

    matcher.find();
    endDateString = matcher.group(1);
    endTimeString = matcher.group(2);

    if (endDateString == null) {
      endDateString = "today";
    }

    if (endTimeString == null) {
      endTimeString = END_TIME_DEFAULT;
    }

    LocalDate endDate = DateParser.parse(endDateString);
    LocalTime endTime = TimeParser.parse(endTimeString);

    LocalDateTime endDateTime = endDate.atTime(endTime);

    if (endDateTime.isBefore(LocalDateTime.now())) {
      endDateTime = endDateTime.plusDays(1);
    }

    return endDateTime;
  }
Exemplo n.º 5
0
  private static void useLocalDate() {
    LocalDate date = LocalDate.of(2014, 3, 18);
    int year = date.getYear(); // 2014
    Month month = date.getMonth(); // MARCH
    int day = date.getDayOfMonth(); // 18
    DayOfWeek dow = date.getDayOfWeek(); // TUESDAY
    int len = date.lengthOfMonth(); // 31 (days in March)
    boolean leap = date.isLeapYear(); // false (not a leap year)
    System.out.println(date);

    int y = date.get(ChronoField.YEAR);
    int m = date.get(ChronoField.MONTH_OF_YEAR);
    int d = date.get(ChronoField.DAY_OF_MONTH);

    LocalTime time = LocalTime.of(13, 45, 20); // 13:45:20
    int hour = time.getHour(); // 13
    int minute = time.getMinute(); // 45
    int second = time.getSecond(); // 20
    System.out.println(time);

    LocalDateTime dt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20); // 2014-03-18T13:45
    LocalDateTime dt2 = LocalDateTime.of(date, time);
    LocalDateTime dt3 = date.atTime(13, 45, 20);
    LocalDateTime dt4 = date.atTime(time);
    LocalDateTime dt5 = time.atDate(date);
    System.out.println(dt1);

    LocalDate date1 = dt1.toLocalDate();
    System.out.println(date1);
    LocalTime time1 = dt1.toLocalTime();
    System.out.println(time1);

    Instant instant = Instant.ofEpochSecond(44 * 365 * 86400);
    Instant now = Instant.now();

    Duration d1 = Duration.between(LocalTime.of(13, 45, 10), time);
    Duration d2 = Duration.between(instant, now);
    System.out.println(d1.getSeconds());
    System.out.println(d2.getSeconds());

    Duration threeMinutes = Duration.of(3, ChronoUnit.MINUTES);
    System.out.println(threeMinutes);

    JapaneseDate japaneseDate = JapaneseDate.from(date);
    System.out.println(japaneseDate);
  }
  /**
   * Obtains an instance from the implied volatility surface and the date, time and zone for which
   * it is valid.
   *
   * @param surface the implied volatility surface
   * @param index the Ibor index for which the data is valid
   * @param valuationDate the valuation date
   * @param valuationTime the valuation time
   * @param valuationZone the valuation time zone
   * @param dayCount the day count applicable to the model
   * @return the volatilities
   */
  public static NormalIborCapletFloorletExpiryStrikeVolatilities of(
      NodalSurface surface,
      IborIndex index,
      LocalDate valuationDate,
      LocalTime valuationTime,
      ZoneId valuationZone,
      DayCount dayCount) {

    return of(surface, index, valuationDate.atTime(valuationTime).atZone(valuationZone), dayCount);
  }
Exemplo n.º 7
0
  @Test
  public void shouldPlayWithDates() {
    LocalDate d1 = LocalDate.now();
    LocalDate d2 = LocalDate.of(2014, 2, 15).plusDays(10);
    print(d1);
    print(d2);

    LocalDateTime d3 = d2.atTime(13, 23, 34, 45);
    assertThat(d3.toString(), is("2014-02-25T13:23:34.000000045"));
    LocalDateTime d4 = d3.plus(Period.of(1, 2, 3));
    assertThat(d4.toString(), is("2015-04-28T13:23:34.000000045"));
  }
/** Test {@link BlackFxVanillaOptionTradePricer}. */
@Test
public class BlackFxVanillaOptionTradePricerTest {

  private static final LocalDate VAL_DATE = RatesProviderDataSets.VAL_DATE_2014_01_22;
  private static final LocalTime VAL_TIME = LocalTime.of(13, 45);
  private static final ZoneId ZONE = ZoneId.of("Z");
  private static final ZonedDateTime VAL_DATE_TIME = VAL_DATE.atTime(VAL_TIME).atZone(ZONE);
  private static final ZonedDateTime EXPIRY = ZonedDateTime.of(2014, 5, 9, 13, 10, 0, 0, ZONE);

  private static final FxMatrix FX_MATRIX = RatesProviderFxDataSets.fxMatrix();
  private static final RatesProvider RATES_PROVIDER =
      RatesProviderFxDataSets.createProviderEURUSD(VAL_DATE);

  private static final DoubleArray TIME_TO_EXPIRY =
      DoubleArray.of(0.01, 0.252, 0.501, 1.0, 2.0, 5.0);
  private static final DoubleArray ATM = DoubleArray.of(0.175, 0.185, 0.18, 0.17, 0.16, 0.16);
  private static final DoubleArray DELTA = DoubleArray.of(0.10, 0.25);
  private static final DoubleMatrix RISK_REVERSAL =
      DoubleMatrix.ofUnsafe(
          new double[][] {
            {-0.010, -0.0050}, {-0.011, -0.0060}, {-0.012, -0.0070},
            {-0.013, -0.0080}, {-0.014, -0.0090}, {-0.014, -0.0090}
          });
  private static final DoubleMatrix STRANGLE =
      DoubleMatrix.ofUnsafe(
          new double[][] {
            {0.0300, 0.0100},
            {0.0310, 0.0110},
            {0.0320, 0.0120},
            {0.0330, 0.0130},
            {0.0340, 0.0140},
            {0.0340, 0.0140}
          });
  private static final InterpolatedStrikeSmileDeltaTermStructure SMILE_TERM =
      InterpolatedStrikeSmileDeltaTermStructure.of(
          TIME_TO_EXPIRY, DELTA, ATM, RISK_REVERSAL, STRANGLE, ACT_365F);
  private static final CurrencyPair CURRENCY_PAIR = CurrencyPair.of(EUR, USD);
  private static final BlackFxOptionSmileVolatilities VOLS =
      BlackFxOptionSmileVolatilities.of(
          FxOptionVolatilitiesName.of("Test"), CURRENCY_PAIR, VAL_DATE_TIME, SMILE_TERM);

  private static final LocalDate PAYMENT_DATE = LocalDate.of(2014, 5, 13);
  private static final double NOTIONAL = 1.0e6;
  private static final CurrencyAmount EUR_AMOUNT = CurrencyAmount.of(EUR, NOTIONAL);
  private static final CurrencyAmount USD_AMOUNT =
      CurrencyAmount.of(USD, -NOTIONAL * FX_MATRIX.fxRate(EUR, USD));
  private static final ResolvedFxSingle FX_PRODUCT =
      ResolvedFxSingle.of(EUR_AMOUNT, USD_AMOUNT, PAYMENT_DATE);
  private static final ResolvedFxVanillaOption OPTION_PRODUCT =
      ResolvedFxVanillaOption.builder()
          .longShort(SHORT)
          .expiry(EXPIRY)
          .underlying(FX_PRODUCT)
          .build();
  private static final TradeInfo TRADE_INFO = TradeInfo.builder().tradeDate(VAL_DATE).build();
  private static final LocalDate CASH_SETTLE_DATE = LocalDate.of(2014, 1, 25);
  private static final Payment PREMIUM = Payment.of(EUR, NOTIONAL * 0.027, CASH_SETTLE_DATE);
  private static final ResolvedFxVanillaOptionTrade OPTION_TRADE =
      ResolvedFxVanillaOptionTrade.builder()
          .premium(PREMIUM)
          .product(OPTION_PRODUCT)
          .info(TRADE_INFO)
          .build();

  private static final BlackFxVanillaOptionProductPricer PRICER_PRODUCT =
      BlackFxVanillaOptionProductPricer.DEFAULT;
  private static final BlackFxVanillaOptionTradePricer PRICER_TRADE =
      BlackFxVanillaOptionTradePricer.DEFAULT;
  private static final DiscountingPaymentPricer PRICER_PAYMENT = DiscountingPaymentPricer.DEFAULT;
  private static final double TOL = 1.0e-13;

  public void test_presentValue() {
    MultiCurrencyAmount pvSensiTrade =
        PRICER_TRADE.presentValue(OPTION_TRADE, RATES_PROVIDER, VOLS);
    CurrencyAmount pvSensiProduct =
        PRICER_PRODUCT.presentValue(OPTION_PRODUCT, RATES_PROVIDER, VOLS);
    CurrencyAmount pvSensiPremium = PRICER_PAYMENT.presentValue(PREMIUM, RATES_PROVIDER);
    assertEquals(pvSensiTrade, MultiCurrencyAmount.of(pvSensiProduct, pvSensiPremium));
  }

  public void test_presentValueSensitivity() {
    PointSensitivities pvSensiTrade =
        PRICER_TRADE.presentValueSensitivityRates(OPTION_TRADE, RATES_PROVIDER, VOLS);
    PointSensitivities pvSensiProduct =
        PRICER_PRODUCT.presentValueSensitivityRates(OPTION_PRODUCT, RATES_PROVIDER, VOLS);
    PointSensitivities pvSensiPremium =
        PRICER_PAYMENT.presentValueSensitivity(PREMIUM, RATES_PROVIDER).build();
    assertEquals(pvSensiTrade, pvSensiProduct.combinedWith(pvSensiPremium));
  }

  public void test_presentValueSensitivityBlackVolatility() {
    PointSensitivities pvSensiTrade =
        PRICER_TRADE.presentValueSensitivityModelParamsVolatility(
            OPTION_TRADE, RATES_PROVIDER, VOLS);
    PointSensitivities pvSensiProduct =
        PRICER_PRODUCT
            .presentValueSensitivityModelParamsVolatility(OPTION_PRODUCT, RATES_PROVIDER, VOLS)
            .build();
    assertEquals(pvSensiTrade, pvSensiProduct);
  }

  public void test_currencyExposure() {
    MultiCurrencyAmount ceComputed =
        PRICER_TRADE.currencyExposure(OPTION_TRADE, RATES_PROVIDER, VOLS);
    PointSensitivities point =
        PRICER_TRADE.presentValueSensitivityRates(OPTION_TRADE, RATES_PROVIDER, VOLS);
    MultiCurrencyAmount pv = PRICER_TRADE.presentValue(OPTION_TRADE, RATES_PROVIDER, VOLS);
    MultiCurrencyAmount ceExpected = RATES_PROVIDER.currencyExposure(point).plus(pv);
    assertEquals(ceComputed.size(), 2);
    assertEquals(
        ceComputed.getAmount(EUR).getAmount(),
        ceExpected.getAmount(EUR).getAmount(),
        TOL * NOTIONAL);
    assertEquals(
        ceComputed.getAmount(USD).getAmount(),
        ceExpected.getAmount(USD).getAmount(),
        TOL * NOTIONAL);
  }

  public void test_currentCash_zero() {
    assertEquals(
        PRICER_TRADE.currentCash(OPTION_TRADE, VAL_DATE),
        CurrencyAmount.zero(PREMIUM.getCurrency()));
  }

  public void test_currentCash_onSettle() {
    assertEquals(PRICER_TRADE.currentCash(OPTION_TRADE, CASH_SETTLE_DATE), PREMIUM.getValue());
  }
}
/** Test {@link BlackVolatilityExpiryTenorSwaptionProvider}. */
@Test
public class BlackVolatilityExpiryTenorSwaptionProviderTest {

  private static final Interpolator1D LINEAR_FLAT =
      CombinedInterpolatorExtrapolator.of(
          CurveInterpolators.LINEAR.getName(),
          CurveExtrapolators.FLAT.getName(),
          CurveExtrapolators.FLAT.getName());
  private static final GridInterpolator2D INTERPOLATOR_2D =
      new GridInterpolator2D(LINEAR_FLAT, LINEAR_FLAT);
  private static final DoubleArray TIME =
      DoubleArray.of(0.25, 0.5, 1.0, 0.25, 0.5, 1.0, 0.25, 0.5, 1.0, 0.25, 0.5, 1.0);
  private static final DoubleArray TENOR =
      DoubleArray.of(3.0, 3.0, 3.0, 5.0, 5.0, 5.0, 7.0, 7.0, 7.0, 10.0, 10.0, 10.0);
  private static final DoubleArray VOL =
      DoubleArray.of(0.14, 0.12, 0.1, 0.14, 0.13, 0.12, 0.13, 0.12, 0.11, 0.12, 0.11, 0.1);
  private static final SurfaceMetadata METADATA_WITH_PARAM;
  private static final SurfaceMetadata METADATA;

  static {
    List<SwaptionSurfaceExpiryTenorNodeMetadata> list =
        new ArrayList<SwaptionSurfaceExpiryTenorNodeMetadata>();
    int nData = TIME.size();
    for (int i = 0; i < nData; ++i) {
      SwaptionSurfaceExpiryTenorNodeMetadata parameterMetadata =
          SwaptionSurfaceExpiryTenorNodeMetadata.of(TIME.get(i), TENOR.get(i));
      list.add(parameterMetadata);
    }
    METADATA_WITH_PARAM =
        DefaultSurfaceMetadata.builder()
            .dayCount(ACT_365F)
            .parameterMetadata(list)
            .surfaceName(SurfaceName.of("GOVT1-SWAPTION-VOL"))
            .xValueType(ValueType.YEAR_FRACTION)
            .yValueType(ValueType.YEAR_FRACTION)
            .build();
    METADATA =
        DefaultSurfaceMetadata.builder()
            .dayCount(ACT_365F)
            .surfaceName(SurfaceName.of("GOVT1-SWAPTION-VOL"))
            .xValueType(ValueType.YEAR_FRACTION)
            .yValueType(ValueType.YEAR_FRACTION)
            .build();
  }

  private static final InterpolatedNodalSurface SURFACE_WITH_PARAM =
      InterpolatedNodalSurface.of(METADATA_WITH_PARAM, TIME, TENOR, VOL, INTERPOLATOR_2D);
  private static final InterpolatedNodalSurface SURFACE =
      InterpolatedNodalSurface.of(METADATA, TIME, TENOR, VOL, INTERPOLATOR_2D);
  private static final FixedIborSwapConvention CONVENTION =
      FixedIborSwapConventions.GBP_FIXED_1Y_LIBOR_3M;
  private static final LocalDate VALUATION_DATE = date(2015, 2, 17);
  private static final LocalTime VALUATION_TIME = LocalTime.of(13, 45);
  private static final ZoneId LONDON_ZONE = ZoneId.of("Europe/London");
  private static final ZonedDateTime VALUATION_DATE_TIME =
      VALUATION_DATE.atTime(VALUATION_TIME).atZone(LONDON_ZONE);
  private static final BlackVolatilityExpiryTenorSwaptionProvider PROVIDER_WITH_PARAM =
      BlackVolatilityExpiryTenorSwaptionProvider.of(
          SURFACE_WITH_PARAM, CONVENTION, ACT_365F, VALUATION_DATE, VALUATION_TIME, LONDON_ZONE);
  private static final BlackVolatilityExpiryTenorSwaptionProvider PROVIDER =
      BlackVolatilityExpiryTenorSwaptionProvider.of(
          SURFACE, CONVENTION, ACT_365F, VALUATION_DATE, VALUATION_TIME, LONDON_ZONE);

  private static final ZonedDateTime[] TEST_OPTION_EXPIRY =
      new ZonedDateTime[] {
        dateUtc(2015, 2, 17), dateUtc(2015, 5, 17), dateUtc(2015, 6, 17), dateUtc(2017, 2, 17)
      };
  private static final int NB_TEST = TEST_OPTION_EXPIRY.length;
  private static final double[] TEST_TENOR = new double[] {2.0, 6.0, 7.0, 15.0};
  private static final double[] TEST_SENSITIVITY = new double[] {1.0, 1.0, 1.0, 1.0};
  private static final double TEST_FORWARD = 0.025; // not used internally
  private static final double TEST_STRIKE = 0.03; // not used internally

  private static final double TOLERANCE_VOL = 1.0E-10;

  // -------------------------------------------------------------------------
  public void test_valuationDate() {
    assertEquals(PROVIDER_WITH_PARAM.getValuationDateTime(), VALUATION_DATE_TIME);
  }

  public void test_swapConvention() {
    assertEquals(PROVIDER_WITH_PARAM.getConvention(), CONVENTION);
  }

  public void test_tenor() {
    double test1 = PROVIDER_WITH_PARAM.tenor(VALUATION_DATE, VALUATION_DATE);
    assertEquals(test1, 0d);
    double test2 = PROVIDER_WITH_PARAM.tenor(VALUATION_DATE, date(2018, 2, 28));
    assertEquals(test2, 3d);
    double test3 = PROVIDER_WITH_PARAM.tenor(VALUATION_DATE, date(2018, 2, 10));
    assertEquals(test3, 3d);
  }

  public void test_relativeTime() {
    double test1 = PROVIDER_WITH_PARAM.relativeTime(VALUATION_DATE_TIME);
    assertEquals(test1, 0d);
    double test2 = PROVIDER_WITH_PARAM.relativeTime(date(2018, 2, 17).atStartOfDay(LONDON_ZONE));
    double test3 = PROVIDER_WITH_PARAM.relativeTime(date(2012, 2, 17).atStartOfDay(LONDON_ZONE));
    assertEquals(test2, -test3); // consistency checked
  }

  public void test_volatility() {
    for (int i = 0; i < NB_TEST; i++) {
      double expiryTime = PROVIDER_WITH_PARAM.relativeTime(TEST_OPTION_EXPIRY[i]);
      double volExpected = SURFACE_WITH_PARAM.zValue(expiryTime, TEST_TENOR[i]);
      double volComputed =
          PROVIDER_WITH_PARAM.getVolatility(
              TEST_OPTION_EXPIRY[i], TEST_TENOR[i], TEST_STRIKE, TEST_FORWARD);
      assertEquals(volComputed, volExpected, TOLERANCE_VOL);
    }
  }

  public void test_volatility_sensitivity() {
    double eps = 1.0e-6;
    int nData = TIME.size();
    for (int i = 0; i < NB_TEST; i++) {
      SwaptionSensitivity point =
          SwaptionSensitivity.of(
              CONVENTION,
              TEST_OPTION_EXPIRY[i],
              TENOR.get(i),
              TEST_STRIKE,
              TEST_FORWARD,
              GBP,
              TEST_SENSITIVITY[i]);
      SurfaceCurrencyParameterSensitivity sensi =
          PROVIDER_WITH_PARAM.surfaceCurrencyParameterSensitivity(point);
      Map<DoublesPair, Double> map = new HashMap<DoublesPair, Double>();
      for (int j = 0; j < nData; ++j) {
        DoubleArray volDataUp = VOL.subArray(0, nData).with(j, VOL.get(j) + eps);
        DoubleArray volDataDw = VOL.subArray(0, nData).with(j, VOL.get(j) - eps);
        InterpolatedNodalSurface paramUp =
            InterpolatedNodalSurface.of(
                METADATA_WITH_PARAM, TIME, TENOR, volDataUp, INTERPOLATOR_2D);
        InterpolatedNodalSurface paramDw =
            InterpolatedNodalSurface.of(
                METADATA_WITH_PARAM, TIME, TENOR, volDataDw, INTERPOLATOR_2D);
        BlackVolatilityExpiryTenorSwaptionProvider provUp =
            BlackVolatilityExpiryTenorSwaptionProvider.of(
                paramUp, CONVENTION, ACT_365F, VALUATION_DATE_TIME);
        BlackVolatilityExpiryTenorSwaptionProvider provDw =
            BlackVolatilityExpiryTenorSwaptionProvider.of(
                paramDw, CONVENTION, ACT_365F, VALUATION_DATE_TIME);
        double volUp =
            provUp.getVolatility(TEST_OPTION_EXPIRY[i], TEST_TENOR[i], TEST_STRIKE, TEST_FORWARD);
        double volDw =
            provDw.getVolatility(TEST_OPTION_EXPIRY[i], TEST_TENOR[i], TEST_STRIKE, TEST_FORWARD);
        double fd = 0.5 * (volUp - volDw) / eps;
        map.put(DoublesPair.of(TIME.get(j), TENOR.get(j)), fd);
      }
      SurfaceCurrencyParameterSensitivity sensiFromNoMetadata =
          PROVIDER.surfaceCurrencyParameterSensitivity(point);
      List<SurfaceParameterMetadata> list = sensi.getMetadata().getParameterMetadata().get();
      DoubleArray computed = sensi.getSensitivity();
      assertEquals(computed.size(), nData);
      for (int j = 0; j < list.size(); ++j) {
        SwaptionSurfaceExpiryTenorNodeMetadata metadata =
            (SwaptionSurfaceExpiryTenorNodeMetadata) list.get(i);
        double expected = map.get(DoublesPair.of(metadata.getYearFraction(), metadata.getTenor()));
        assertEquals(computed.get(i), expected, eps);
        assertTrue(
            sensiFromNoMetadata.getMetadata().getParameterMetadata().get().contains(metadata));
      }
    }
  }

  // -------------------------------------------------------------------------
  public void coverage() {
    BlackVolatilityExpiryTenorSwaptionProvider test1 =
        BlackVolatilityExpiryTenorSwaptionProvider.of(
            SURFACE_WITH_PARAM, CONVENTION, ACT_365F, VALUATION_DATE_TIME);
    coverImmutableBean(test1);
    BlackVolatilityExpiryTenorSwaptionProvider test2 =
        BlackVolatilityExpiryTenorSwaptionProvider.of(SURFACE, CONVENTION, ACT_360, VALUATION_DATE);
    coverBeanEquals(test1, test2);
  }
}
/** Test {@link BlackBondFutureOptionMarginedProductPricer}. */
@Test
public class BlackBondFutureOptionMarginedProductPricerTest {
  // product
  private static final StandardId FUTURE_SECURITY_ID = BondDataSets.FUTURE_SECURITY_ID_EUR;
  private static final BondFutureOption FUTURE_OPTION_PRODUCT =
      BondDataSets.FUTURE_OPTION_PRODUCT_EUR_116;
  // curves
  private static final LegalEntityDiscountingProvider RATE_PROVIDER =
      LegalEntityDiscountingProviderDataSets.ISSUER_REPO_ZERO_EUR;
  // vol surface
  private static final Interpolator1D LINEAR_FLAT =
      CombinedInterpolatorExtrapolator.of(
          CurveInterpolators.LINEAR, CurveExtrapolators.FLAT, CurveExtrapolators.FLAT);
  private static final GridInterpolator2D INTERPOLATOR_2D =
      new GridInterpolator2D(LINEAR_FLAT, LINEAR_FLAT);
  private static final DoubleArray TIME =
      DoubleArray.of(0.20, 0.20, 0.20, 0.20, 0.20, 0.45, 0.45, 0.45, 0.45, 0.45);
  private static final DoubleArray MONEYNESS =
      DoubleArray.of(-0.050, -0.005, 0.000, 0.005, 0.050, -0.050, -0.005, 0.000, 0.005, 0.050);
  private static final DoubleArray VOL =
      DoubleArray.of(0.50, 0.49, 0.47, 0.48, 0.51, 0.45, 0.44, 0.42, 0.43, 0.46);
  private static final SurfaceMetadata METADATA;

  static {
    List<GenericVolatilitySurfaceYearFractionMetadata> list =
        new ArrayList<GenericVolatilitySurfaceYearFractionMetadata>();
    int nData = TIME.size();
    for (int i = 0; i < nData; ++i) {
      GenericVolatilitySurfaceYearFractionMetadata parameterMetadata =
          GenericVolatilitySurfaceYearFractionMetadata.of(
              TIME.get(i), LogMoneynessStrike.of(MONEYNESS.get(i)));
      list.add(parameterMetadata);
    }
    METADATA =
        DefaultSurfaceMetadata.builder()
            .dayCount(ACT_365F)
            .parameterMetadata(list)
            .surfaceName(SurfaceName.of("GOVT1-BOND-FUT-VOL"))
            .xValueType(ValueType.YEAR_FRACTION)
            .yValueType(ValueType.STRIKE)
            .build();
  }

  private static final InterpolatedNodalSurface SURFACE =
      InterpolatedNodalSurface.of(METADATA, TIME, MONEYNESS, VOL, INTERPOLATOR_2D);
  private static final LocalDate VALUATION_DATE = RATE_PROVIDER.getValuationDate();
  private static final LocalTime VALUATION_TIME = LocalTime.of(0, 0);
  private static final ZoneId ZONE = FUTURE_OPTION_PRODUCT.getExpiryZone();
  private static final ZonedDateTime VALUATION_DATE_TIME =
      VALUATION_DATE.atTime(VALUATION_TIME).atZone(ZONE);
  private static final BlackVolatilityExpLogMoneynessBondFutureProvider VOL_PROVIDER =
      BlackVolatilityExpLogMoneynessBondFutureProvider.of(
          SURFACE, FUTURE_SECURITY_ID, ACT_365F, VALUATION_DATE_TIME);
  private static final double TOL = 1.0E-13;
  private static final double EPS = 1.0e-6;
  // pricer
  private static final DiscountingBondFutureProductPricer FUTURE_PRICER =
      DiscountingBondFutureProductPricer.DEFAULT;
  private static final BlackBondFutureOptionMarginedProductPricer OPTION_PRICER =
      new BlackBondFutureOptionMarginedProductPricer(FUTURE_PRICER);
  private static final RatesFiniteDifferenceSensitivityCalculator FD_CAL =
      new RatesFiniteDifferenceSensitivityCalculator(EPS);

  public void test_getFuturePricer() {
    assertSame(OPTION_PRICER.getFuturePricer(), FUTURE_PRICER);
  }

  public void test_price() {
    double computed = OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    double futurePrice = FUTURE_PRICER.price(FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.price(futurePrice, strike, expiryTime, vol, true);
    assertEquals(computed, expected, TOL);
  }

  public void test_price_from_future_price() {
    double futurePrice = 1.1d;
    double computed =
        OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.price(futurePrice, strike, expiryTime, vol, true);
    assertEquals(computed, expected, TOL);
  }

  public void test_price_from_generic_provider() {
    BondFutureProvider volProvider =
        BlackVolatilityExpLogMoneynessBondFutureProvider.of(
            SURFACE, FUTURE_SECURITY_ID, ACT_365F, VALUATION_DATE_TIME);
    double computed = OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, volProvider);
    double expected = OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    assertEquals(computed, expected, TOL);
  }

  // -------------------------------------------------------------------------
  public void test_delta() {
    double computed =
        OPTION_PRICER.deltaStickyStrike(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    double futurePrice = FUTURE_PRICER.price(FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.delta(futurePrice, strike, expiryTime, vol, true);
    assertEquals(computed, expected, TOL);
  }

  public void test_delta_from_future_price() {
    double futurePrice = 1.1d;
    double computed =
        OPTION_PRICER.deltaStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.delta(futurePrice, strike, expiryTime, vol, true);
    assertEquals(computed, expected, TOL);
  }

  public void test_gamma() {
    double computed =
        OPTION_PRICER.gammaStickyStrike(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    double futurePrice = FUTURE_PRICER.price(FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.gamma(futurePrice, strike, expiryTime, vol);
    assertEquals(computed, expected, TOL);
  }

  public void test_gamma_from_future_price() {
    double futurePrice = 1.1d;
    double computed =
        OPTION_PRICER.gammaStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.gamma(futurePrice, strike, expiryTime, vol);
    assertEquals(computed, expected, TOL);
  }

  public void test_theta() {
    double computed = OPTION_PRICER.theta(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    double futurePrice = FUTURE_PRICER.price(FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.driftlessTheta(futurePrice, strike, expiryTime, vol);
    assertEquals(computed, expected, TOL);
  }

  public void test_theta_from_future_price() {
    double futurePrice = 1.1d;
    double computed =
        OPTION_PRICER.theta(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double expected = BlackFormulaRepository.driftlessTheta(futurePrice, strike, expiryTime, vol);
    assertEquals(computed, expected, TOL);
  }

  // -------------------------------------------------------------------------
  public void test_priceSensitivity() {
    PointSensitivities point =
        OPTION_PRICER.priceSensitivityStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    CurveCurrencyParameterSensitivities computed = RATE_PROVIDER.curveParameterSensitivity(point);
    CurveCurrencyParameterSensitivities expected =
        FD_CAL.sensitivity(
            RATE_PROVIDER,
            (p) ->
                CurrencyAmount.of(
                    EUR, OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, (p), VOL_PROVIDER)));
    double futurePrice = FUTURE_PRICER.price(FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER);
    double strike = FUTURE_OPTION_PRODUCT.getStrikePrice();
    double expiryTime =
        ACT_365F.relativeYearFraction(VALUATION_DATE, FUTURE_OPTION_PRODUCT.getExpiryDate());
    double logMoneyness = Math.log(strike / futurePrice);
    double logMoneynessUp = Math.log(strike / (futurePrice + EPS));
    double logMoneynessDw = Math.log(strike / (futurePrice - EPS));
    double vol = SURFACE.zValue(expiryTime, logMoneyness);
    double volUp = SURFACE.zValue(expiryTime, logMoneynessUp);
    double volDw = SURFACE.zValue(expiryTime, logMoneynessDw);
    double volSensi = 0.5 * (volUp - volDw) / EPS;
    double vega = BlackFormulaRepository.vega(futurePrice, strike, expiryTime, vol);
    CurveCurrencyParameterSensitivities sensiVol =
        RATE_PROVIDER
            .curveParameterSensitivity(
                FUTURE_PRICER.priceSensitivity(
                    FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER))
            .multipliedBy(-vega * volSensi);
    expected = expected.combinedWith(sensiVol);
    assertTrue(computed.equalWithTolerance(expected, 30d * EPS));
  }

  public void test_priceSensitivity_from_future_price() {
    double futurePrice = 1.1d;
    PointSensitivities point =
        OPTION_PRICER.priceSensitivityStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    CurveCurrencyParameterSensitivities computed = RATE_PROVIDER.curveParameterSensitivity(point);
    double delta =
        OPTION_PRICER.deltaStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    CurveCurrencyParameterSensitivities expected =
        RATE_PROVIDER
            .curveParameterSensitivity(
                FUTURE_PRICER.priceSensitivity(
                    FUTURE_OPTION_PRODUCT.getUnderlying(), RATE_PROVIDER))
            .multipliedBy(delta);
    assertTrue(computed.equalWithTolerance(expected, TOL));
  }

  public void test_priceSensitivity_from_generic_provider() {
    BondFutureProvider volProvider =
        BlackVolatilityExpLogMoneynessBondFutureProvider.of(
            SURFACE, FUTURE_SECURITY_ID, ACT_365F, VALUATION_DATE_TIME);
    PointSensitivities expected =
        OPTION_PRICER.priceSensitivityStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    PointSensitivities computed =
        OPTION_PRICER.priceSensitivity(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, volProvider);
    assertEquals(computed, expected);
  }

  // -------------------------------------------------------------------------
  public void test_priceSensitivityBlackVolatility() {
    BondFutureOptionSensitivity sensi =
        OPTION_PRICER.priceSensitivityBlackVolatility(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    testPriceSensitivityBlackVolatility(
        VOL_PROVIDER.surfaceCurrencyParameterSensitivity(sensi),
        (p) -> OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, (p)));
  }

  public void test_priceSensitivityBlackVolatility_from_future_price() {
    double futurePrice = 1.1d;
    BondFutureOptionSensitivity sensi =
        OPTION_PRICER.priceSensitivityBlackVolatility(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER, futurePrice);
    testPriceSensitivityBlackVolatility(
        VOL_PROVIDER.surfaceCurrencyParameterSensitivity(sensi),
        (p) -> OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, (p), futurePrice));
  }

  private void testPriceSensitivityBlackVolatility(
      SurfaceCurrencyParameterSensitivity computed,
      Function<BlackVolatilityBondFutureProvider, Double> valueFn) {
    List<SurfaceParameterMetadata> list = computed.getMetadata().getParameterMetadata().get();
    int nVol = VOL.size();
    assertEquals(list.size(), nVol);
    for (int i = 0; i < nVol; ++i) {
      double[] volUp = Arrays.copyOf(VOL.toArray(), nVol);
      double[] volDw = Arrays.copyOf(VOL.toArray(), nVol);
      volUp[i] += EPS;
      volDw[i] -= EPS;
      InterpolatedNodalSurface sfUp =
          InterpolatedNodalSurface.of(
              METADATA, TIME, MONEYNESS, DoubleArray.copyOf(volUp), INTERPOLATOR_2D);
      InterpolatedNodalSurface sfDw =
          InterpolatedNodalSurface.of(
              METADATA, TIME, MONEYNESS, DoubleArray.copyOf(volDw), INTERPOLATOR_2D);
      BlackVolatilityExpLogMoneynessBondFutureProvider provUp =
          BlackVolatilityExpLogMoneynessBondFutureProvider.of(
              sfUp, FUTURE_SECURITY_ID, ACT_365F, VALUATION_DATE_TIME);
      BlackVolatilityExpLogMoneynessBondFutureProvider provDw =
          BlackVolatilityExpLogMoneynessBondFutureProvider.of(
              sfDw, FUTURE_SECURITY_ID, ACT_365F, VALUATION_DATE_TIME);
      double expected = 0.5 * (valueFn.apply(provUp) - valueFn.apply(provDw)) / EPS;
      int index = -1;
      for (int j = 0; j < nVol; ++j) {
        GenericVolatilitySurfaceYearFractionMetadata meta =
            (GenericVolatilitySurfaceYearFractionMetadata) list.get(j);
        if (meta.getYearFraction() == TIME.get(i)
            && meta.getStrike().getValue() == MONEYNESS.get(i)) {
          index = j;
          continue;
        }
      }
      assertEquals(computed.getSensitivity().get(index), expected, EPS);
    }
  }

  // -------------------------------------------------------------------------
  public void test_marginIndex() {
    double price = 0.12d;
    double computed = OPTION_PRICER.marginIndex(FUTURE_OPTION_PRODUCT, price);
    assertEquals(computed, price * FUTURE_OPTION_PRODUCT.getUnderlying().getNotional());
  }

  public void test_marginIndexSensitivity() {
    PointSensitivities point =
        OPTION_PRICER.priceSensitivityStickyStrike(
            FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    PointSensitivities computed =
        OPTION_PRICER.marginIndexSensitivity(FUTURE_OPTION_PRODUCT, point);
    assertEquals(computed, point.multipliedBy(FUTURE_OPTION_PRODUCT.getUnderlying().getNotional()));
  }

  // -------------------------------------------------------------------------
  public void regression_price() {
    double price = OPTION_PRICER.price(FUTURE_OPTION_PRODUCT, RATE_PROVIDER, VOL_PROVIDER);
    assertEquals(price, 0.08916005173932573, TOL); // 2.x
  }
}
/** Test {@link BlackBondFutureExpiryLogMoneynessVolatilities}. */
@Test
public class BlackBondFutureExpiryLogMoneynessVolatilitiesTest {

  private static final SurfaceInterpolator INTERPOLATOR_2D =
      GridSurfaceInterpolator.of(LINEAR, LINEAR);
  private static final DoubleArray TIME =
      DoubleArray.of(0.25, 0.25, 0.25, 0.25, 0.50, 0.50, 0.50, 0.50, 1.00, 1.00, 1.00, 1.00);
  private static final DoubleArray MONEYNESS =
      DoubleArray.of(-0.02, -0.01, 0.00, 0.01, -0.02, -0.01, 0.00, 0.01, -0.02, -0.01, 0.00, 0.01);
  private static final DoubleArray VOL =
      DoubleArray.of(
          0.01, 0.011, 0.012, 0.010, 0.011, 0.012, 0.013, 0.012, 0.012, 0.013, 0.014, 0.014);
  private static final SurfaceMetadata METADATA;

  static {
    List<GenericVolatilitySurfaceYearFractionParameterMetadata> list =
        new ArrayList<GenericVolatilitySurfaceYearFractionParameterMetadata>();
    int nData = TIME.size();
    for (int i = 0; i < nData; ++i) {
      GenericVolatilitySurfaceYearFractionParameterMetadata parameterMetadata =
          GenericVolatilitySurfaceYearFractionParameterMetadata.of(
              TIME.get(i), LogMoneynessStrike.of(MONEYNESS.get(i)));
      list.add(parameterMetadata);
    }
    METADATA =
        DefaultSurfaceMetadata.builder()
            .surfaceName(SurfaceName.of("GOVT1-BOND-FUT-VOL"))
            .xValueType(ValueType.YEAR_FRACTION)
            .yValueType(ValueType.LOG_MONEYNESS)
            .zValueType(ValueType.BLACK_VOLATILITY)
            .dayCount(ACT_365F)
            .parameterMetadata(list)
            .build();
  }

  private static final InterpolatedNodalSurface SURFACE =
      InterpolatedNodalSurface.of(METADATA, TIME, MONEYNESS, VOL, INTERPOLATOR_2D);
  private static final LocalDate VAL_DATE = date(2015, 2, 17);
  private static final LocalTime VAL_TIME = LocalTime.of(13, 45);
  private static final ZoneId LONDON_ZONE = ZoneId.of("Europe/London");
  private static final ZonedDateTime VAL_DATE_TIME = VAL_DATE.atTime(VAL_TIME).atZone(LONDON_ZONE);
  private static final BlackBondFutureExpiryLogMoneynessVolatilities VOLS =
      BlackBondFutureExpiryLogMoneynessVolatilities.of(VAL_DATE_TIME, SURFACE);

  private static final ZonedDateTime[] TEST_OPTION_EXPIRY =
      new ZonedDateTime[] {
        dateUtc(2015, 2, 17), dateUtc(2015, 5, 17), dateUtc(2015, 6, 17), dateUtc(2017, 2, 17)
      };
  private static final int NB_TEST = TEST_OPTION_EXPIRY.length;
  private static final LocalDate[] TEST_FUTURE_EXPIRY =
      new LocalDate[] {date(2015, 2, 17), date(2015, 5, 17), date(2015, 5, 17), date(2015, 5, 17)};
  private static final double[] TEST_STRIKE_PRICE = new double[] {0.985, 0.985, 0.985, 0.985};
  private static final double[] TEST_FUTURE_PRICE = new double[] {0.98, 0.985, 1.00, 1.01};
  //  private static final double[] TEST_SENSITIVITY = new double[] {9.2, 16.0, 1.8, 5.7 };
  private static final double[] TEST_SENSITIVITY = new double[] {1.0, 1.0, 1.0, 1.0};

  private static final double TOLERANCE_VOL = 1.0E-10;

  // -------------------------------------------------------------------------
  public void test_valuationDate() {
    assertEquals(VOLS.getValuationDateTime(), VAL_DATE_TIME);
  }

  public void test_volatility() {
    for (int i = 0; i < NB_TEST; i++) {
      double expiryTime = VOLS.relativeTime(TEST_OPTION_EXPIRY[i]);
      double volExpected =
          SURFACE.zValue(expiryTime, Math.log(TEST_STRIKE_PRICE[i] / TEST_FUTURE_PRICE[i]));
      double volComputed =
          VOLS.volatility(
              TEST_OPTION_EXPIRY[i],
              TEST_FUTURE_EXPIRY[i],
              TEST_STRIKE_PRICE[i],
              TEST_FUTURE_PRICE[i]);
      assertEquals(volComputed, volExpected, TOLERANCE_VOL);
    }
  }

  public void test_volatility_sensitivity() {
    double eps = 1.0e-6;
    int nData = TIME.size();
    for (int i = 0; i < NB_TEST; i++) {
      double expiry = VOLS.relativeTime(TEST_OPTION_EXPIRY[i]);
      BondFutureOptionSensitivity point =
          BondFutureOptionSensitivity.of(
              VOLS.getName(),
              expiry,
              TEST_FUTURE_EXPIRY[i],
              TEST_STRIKE_PRICE[i],
              TEST_FUTURE_PRICE[i],
              USD,
              TEST_SENSITIVITY[i]);
      CurrencyParameterSensitivity sensActual =
          VOLS.parameterSensitivity(point).getSensitivities().get(0);
      double[] computed = sensActual.getSensitivity().toArray();
      for (int j = 0; j < nData; j++) {
        DoubleArray volDataUp = VOL.with(j, VOL.get(j) + eps);
        DoubleArray volDataDw = VOL.with(j, VOL.get(j) - eps);
        InterpolatedNodalSurface paramUp =
            InterpolatedNodalSurface.of(METADATA, TIME, MONEYNESS, volDataUp, INTERPOLATOR_2D);
        InterpolatedNodalSurface paramDw =
            InterpolatedNodalSurface.of(METADATA, TIME, MONEYNESS, volDataDw, INTERPOLATOR_2D);
        BlackBondFutureExpiryLogMoneynessVolatilities provUp =
            BlackBondFutureExpiryLogMoneynessVolatilities.of(VAL_DATE_TIME, paramUp);
        BlackBondFutureExpiryLogMoneynessVolatilities provDw =
            BlackBondFutureExpiryLogMoneynessVolatilities.of(VAL_DATE_TIME, paramDw);
        double volUp =
            provUp.volatility(
                expiry, TEST_FUTURE_EXPIRY[i], TEST_STRIKE_PRICE[i], TEST_FUTURE_PRICE[i]);
        double volDw =
            provDw.volatility(
                expiry, TEST_FUTURE_EXPIRY[i], TEST_STRIKE_PRICE[i], TEST_FUTURE_PRICE[i]);
        double fd = 0.5 * (volUp - volDw) / eps;
        assertEquals(computed[j], fd, eps);
      }
    }
  }

  // -------------------------------------------------------------------------
  public void coverage() {
    BlackBondFutureExpiryLogMoneynessVolatilities test1 =
        BlackBondFutureExpiryLogMoneynessVolatilities.of(VAL_DATE_TIME, SURFACE);
    coverImmutableBean(test1);
    BlackBondFutureExpiryLogMoneynessVolatilities test2 =
        BlackBondFutureExpiryLogMoneynessVolatilities.of(
            VAL_DATE_TIME.plusDays(1), SURFACE.withParameter(0, 1d));
    coverBeanEquals(test1, test2);
  }
}
Exemplo n.º 12
0
  @FilterWith(XSRFFilter.class)
  public Result dryRun(
      Context context, @Param("startDate") String start, @Param("endDate") String end) {
    long _start = System.currentTimeMillis();
    FlashScope flash = context.getFlashScope();

    LocalDate startDate = null;
    LocalDate endDate = null;

    try {
      startDate = LocalDate.parse(start);
      endDate = LocalDate.parse(end);
    } catch (Exception ex) {
    }

    if (startDate == null || endDate == null || startDate.isAfter(endDate)) {
      flash.error("error.invalidDate");
      return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    }

    Run lastRun = baseDB.run.findLast(Module.GOOGLE, null, null);
    if (lastRun != null && lastRun.getDay().isAfter(startDate)) {
      flash.error("error.invalidDate");
      return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    }

    LocalDate date = LocalDate.from(startDate);

    GoogleSettings ggOptions = googleDB.options.get();

    int minPauseBetweenPageSec = ggOptions.getMinPauseBetweenPageSec();
    int maxPauseBetweenPageSec = ggOptions.getMaxPauseBetweenPageSec();
    ggOptions.setMinPauseBetweenPageSec(0);
    ggOptions.setMaxPauseBetweenPageSec(0);
    googleDB.options.update(ggOptions);

    try {
      while (date.isBefore(endDate)) {
        LOG.debug("dry run {}", date);
        if (!taskManager.startGoogleTask(
            new Run(Run.Mode.MANUAL, Module.GOOGLE, date.atTime(13, 37, 00)))) {
          LOG.error("can't startGoogleTask");
          flash.error("can't startGoogleTask");
          return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
        }
        taskManager.joinGoogleTask();
        date = date.plusDays(1);
      }
    } catch (Exception ex) {
      LOG.error("an error occured", ex);
      flash.error("an error occured");
      return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
    } finally {
      ggOptions.setMinPauseBetweenPageSec(minPauseBetweenPageSec);
      ggOptions.setMaxPauseBetweenPageSec(maxPauseBetweenPageSec);
      googleDB.options.update(ggOptions);
    }

    LOG.debug(
        "dry run timing : {}",
        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
    flash.success("ok");
    return Results.redirect(router.getReverseRoute(DebugController.class, "debug"));
  }
  // Calculate How many time
  public List<TestingCenterTimeSlots> generateTimeSlots(Exam exam) {
    TestingCenterInfo tci = tcr.findByTerm(tcr.getCurrentTerm().getTermId());
    int gap = tci.getGap();
    int examDuration = exam.getDuration();
    int openMinutes = (int) ChronoUnit.MINUTES.between(tci.getOpen(), tci.getClose());

    // Ensure time chunk devides 30
    int timeChuck =
        (examDuration + gap) % 30 == 0 ? examDuration : 30 * ((examDuration + gap) / 30 + 1);

    LocalTime endTime = exam.getEndDateTime().toLocalTime();
    LocalTime beginTime = exam.getStartDateTime().toLocalTime();
    LocalTime openTime = tci.getOpen();
    LocalTime closeTime = tci.getClose();
    LocalDate beginDate = exam.getStartDateTime().toLocalDate();
    LocalDate endDate = exam.getEndDateTime().toLocalDate();

    beginTime = adjustTime(beginTime); // Exam Begin Time
    endTime = adjustTime(endTime); // Exam End Time

    // Calculate Duration According to different day.
    int startDayDuration = (int) ChronoUnit.MINUTES.between(beginTime, closeTime);
    int dayLast = (int) ChronoUnit.DAYS.between(beginDate, endDate) - 1;
    int endDayDuration = (int) ChronoUnit.MINUTES.between(openTime, endTime);

    int startDayChucks = startDayDuration / timeChuck;
    int endDayChucks = endDayDuration / timeChuck;
    int regularDayChuncks = dayLast >= 0 ? (dayLast * openMinutes) / timeChuck : 0;
    int dailyChuncks = openMinutes / timeChuck;

    LocalDate dateCursor = beginDate;
    LocalTime timeCursor = beginTime;
    List<TestingCenterTimeSlots> timeSlotses = new ArrayList<>();
    if (startDayChucks > 0) {
      for (int i = 0; i < startDayChucks; i++) {
        LocalDateTime slotsBegin = dateCursor.atTime(timeCursor);
        LocalDateTime slotsEnd = dateCursor.atTime(timeCursor.plusMinutes(examDuration));

        TestingCenterTimeSlots t =
            new TestingCenterTimeSlots(
                exam.getExamId(),
                slotsBegin,
                slotsEnd,
                tci.getNumSeats(),
                tci.getNumSetAsideSeats());
        timeSlotses.add(t);

        timeCursor = timeCursor.plusMinutes(timeChuck);
      }
    }
    if (regularDayChuncks > 0) {

      for (int i = 0; i < dayLast; i++) {
        dateCursor = dateCursor.plusDays(1);
        timeCursor = adjustTime(openTime);

        for (int j = 0; j < dailyChuncks; j++) {
          LocalDateTime slotsBegin = dateCursor.atTime(timeCursor);
          LocalDateTime slotsEnd = dateCursor.atTime(timeCursor.plusMinutes(examDuration));

          TestingCenterTimeSlots t =
              new TestingCenterTimeSlots(
                  exam.getExamId(),
                  slotsBegin,
                  slotsEnd,
                  tci.getNumSeats(),
                  tci.getNumSetAsideSeats());
          timeSlotses.add(t);

          timeCursor = timeCursor.plusMinutes(timeChuck);
        }
      }
    }
    if (endDayChucks > 0) {
      dateCursor = dateCursor.plusDays(1);
      timeCursor = adjustTime(openTime);

      for (int i = 0; i < endDayChucks; i++) {
        LocalDateTime slotsBegin = dateCursor.atTime(timeCursor);
        LocalDateTime slotsEnd = dateCursor.atTime(timeCursor.plusMinutes(examDuration));

        TestingCenterTimeSlots t =
            new TestingCenterTimeSlots(
                exam.getExamId(),
                slotsBegin,
                slotsEnd,
                tci.getNumSeats(),
                tci.getNumSetAsideSeats());
        timeSlotses.add(t);

        timeCursor = timeCursor.plusMinutes(timeChuck);
      }
    }
    return timeSlotses;
  }