Java Code Examples for java.time.LocalDate#plus()

The following examples show how to use java.time.LocalDate#plus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestIsoChronoImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 2
Source File: RangeBasicTests.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "localDateRanges")
public void testRangeOfLocalDates(LocalDate start, LocalDate end, Period step, boolean parallel) {
    final Range<LocalDate> range = Range.of(start, end, step);
    final Array<LocalDate> array = range.toArray(parallel);
    final boolean ascend = start.isBefore(end);
    final int expectedLength = (int)Math.ceil(Math.abs((double)ChronoUnit.DAYS.between(start, end)) / (double)step.getDays());
    Assert.assertEquals(array.length(), expectedLength);
    Assert.assertEquals(array.typeCode(), ArrayType.LOCAL_DATE);
    Assert.assertTrue(!array.style().isSparse());
    Assert.assertEquals(range.start(), start, "The range start");
    Assert.assertEquals(range.end(), end, "The range end");
    LocalDate expected = null;
    for (int i=0; i<array.length(); ++i) {
        final LocalDate actual = array.getValue(i);
        expected = expected == null ? start : ascend ? expected.plus(step) : expected.minus(step);
        Assert.assertEquals(actual, expected, "Value matches at " + i);
        Assert.assertTrue(ascend ? actual.compareTo(start) >=0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + i);
    }
}
 
Example 3
Source File: TestIsoChronoImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 4
Source File: TestIsoChronoImpl.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 5
Source File: TestIsoChronoImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 6
Source File: RangeFilterTests.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "LocalDateRanges")
public void testRangeOfLocalDates(LocalDate start, LocalDate end, Period step, boolean parallel) {
    final boolean ascend = start.isBefore(end);
    final Range<LocalDate> range = Range.of(start, end, step, v -> v.getDayOfWeek() == DayOfWeek.MONDAY);
    final Array<LocalDate> array = range.toArray(parallel);
    final LocalDate first = array.first(v -> true).map(ArrayValue::getValue).get();
    final LocalDate last = array.last(v -> true).map(ArrayValue::getValue).get();
    Assert.assertEquals(array.typeCode(), ArrayType.LOCAL_DATE);
    Assert.assertTrue(!array.style().isSparse());
    Assert.assertEquals(range.start(), start, "The range start");
    Assert.assertEquals(range.end(), end, "The range end");
    int index = 0;
    LocalDate value = first;
    while (ascend ? value.isBefore(last) : value.isAfter(last)) {
        final LocalDate actual = array.getValue(index);
        Assert.assertEquals(actual, value, "Value matches at " + index);
        Assert.assertTrue(ascend ? actual.compareTo(start) >= 0 && actual.isBefore(end) : actual.compareTo(start) <= 0 && actual.isAfter(end), "Value in bounds at " + index);
        value = ascend ? value.plus(step) : value.minus(step);
        while (value.getDayOfWeek() == DayOfWeek.MONDAY) value = ascend ? value.plus(step) : value.minus(step);
        index++;
    }
}
 
Example 7
Source File: DiscountingSwapLegPricerTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_pvbpSensitivity_compounding_flat_ibor() {
  LocalDate tradeDate = RATES_USD.getValuationDate();
  LocalDate effectiveDate = USD_LIBOR_3M_LIBOR_6M.calculateSpotDateFromTradeDate(tradeDate, REF_DATA);
  LocalDate endDate = effectiveDate.plus(TENOR_10Y);
  double spread = 0.0015;
  RateCalculationSwapLeg leg = IborIborSwapConventions.USD_LIBOR_3M_LIBOR_6M.getSpreadLeg()
      .toLeg(effectiveDate, endDate, RECEIVE, NOTIONAL, spread);
  PointSensitivities pvbppts = PRICER_LEG.pvbpSensitivity(leg.resolve(REF_DATA), RATES_USD).build();
  CurrencyParameterSensitivities psAd = RATES_USD.parameterSensitivity(pvbppts);
  CurrencyParameterSensitivities psFd = FINITE_DIFFERENCE_CALCULATOR.sensitivity(
      RATES_USD,
      (p) -> CurrencyAmount.of(USD, PRICER_LEG.pvbp(leg.resolve(REF_DATA), p)));
  ImmutableList<CurrencyParameterSensitivity> listAd = psAd.getSensitivities();
  ImmutableList<CurrencyParameterSensitivity> listFd = psFd.getSensitivities();
  assertThat(listAd).hasSize(2); // No Libor 6M sensitivity
  assertThat(listFd).hasSize(3); // Libor 6M sensitivity equal to 0 in Finite Difference
  assertThat(psAd.equalWithTolerance(psFd, TOLERANCE_DELTA)).isTrue();
}
 
Example 8
Source File: TestIsoChronoImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 9
Source File: TestIsoChronoImpl.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_IsoChrono_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    cal.set(Calendar.YEAR, isoDate.get(YEAR));
    cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
    cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

    while (isoDate.isBefore(isoEndDate)) {
        assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
        assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
        assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

        isoDate = isoDate.plus(1, ChronoUnit.DAYS);
        cal.add(Calendar.DAY_OF_MONTH, 1);
    }
}
 
Example 10
Source File: DayCountTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_actActIcma_longInitialStub_eomFlagEom_short() {
  // nominals, 2011-08-31 (P91D) 2011-11-30 (P91D) 2012-02-29
  LocalDate start = LocalDate.of(2011, 10, 1);
  LocalDate periodEnd = LocalDate.of(2012, 2, 29);
  LocalDate end = LocalDate.of(2011, 11, 12);  // before first nominal
  ScheduleInfo info = new Info(start, periodEnd.plus(P3M), periodEnd, true, P3M);
  assertThat(ACT_ACT_ICMA.yearFraction(start, end, info)).isEqualTo((42d / (91d * 4d)));
}
 
Example 11
Source File: JFXDatePickerContent.java    From JFoenix with Apache License 2.0 5 votes vote down vote up
void updateWeekNumberDateCells() {
    if (datePicker.isShowWeekNumbers()) {
        final Locale locale = getLocale();
        LocalDate firstDayOfMonth = selectedYearMonth.get().atDay(1);
        for (int i = 0; i < 6; i++) {
            LocalDate date = firstDayOfMonth.plus(i, WEEKS);
            String weekNumber = weekNumberFormatter.withLocale(locale)
                .withDecimalStyle(DecimalStyle.of(locale))
                .format(date);
            weekNumberCells.get(i).setText(weekNumber);
        }
    }
}
 
Example 12
Source File: Java8TestPeriodDuration.java    From javase with MIT License 5 votes vote down vote up
public void testPeriod(){

     //Get the current date
     LocalDate date1 = LocalDate.now();
     System.out.println("Current date: " + date1);
	
     //add 1 month to the current date
     LocalDate date2 = date1.plus(1, ChronoUnit.MONTHS);
     System.out.println("Next month: " + date2);
     
     Period period = Period.between(date2, date1);
     System.out.println("Period: " + period);
  }
 
Example 13
Source File: SabrSwaptionCalibratorCubeNormalSimpleDataTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
@Test
public void normal_atm() {
  double beta = 0.50;
  Surface betaSurface = ConstantSurface.of("Beta", beta)
      .withMetadata(DefaultSurfaceMetadata.builder()
          .xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION)
          .zValueType(ValueType.SABR_BETA).surfaceName("Beta").build());
  double shift = 0.0300;
  Surface shiftSurface = ConstantSurface.of("Shift", shift)
      .withMetadata(DefaultSurfaceMetadata.builder()
          .xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).surfaceName("Shift").build());
  SabrParametersSwaptionVolatilities calibratedSmile = SABR_CALIBRATION.calibrateWithFixedBetaAndShift(
      DEFINITION, CALIBRATION_TIME, DATA_SIMPLE, MULTICURVE, betaSurface, shiftSurface);
  SabrParametersSwaptionVolatilities calibratedAtm =
      SABR_CALIBRATION.calibrateAlphaWithAtm(NAME_SABR, calibratedSmile, MULTICURVE, ATM_NORMAL_SIMPLE, TENORS_SIMPLE,
          EXPIRIES_SIMPLE_2, INTERPOLATOR_2D);
  int nbExp = EXPIRIES_SIMPLE_2.size();
  int nbTenor = TENORS_SIMPLE.size();
  for (int loopexpiry = 0; loopexpiry < nbExp; loopexpiry++) {
    for (int looptenor = 0; looptenor < nbTenor; looptenor++) {
      double tenor = TENORS_SIMPLE.get(looptenor).get(ChronoUnit.YEARS);
      LocalDate expiry = EUR_FIXED_1Y_EURIBOR_6M.getFloatingLeg().getStartDateBusinessDayAdjustment()
          .adjust(CALIBRATION_DATE.plus(EXPIRIES_SIMPLE_2.get(loopexpiry)), REF_DATA);
      LocalDate effectiveDate = EUR_FIXED_1Y_EURIBOR_6M.calculateSpotDateFromTradeDate(expiry, REF_DATA);
      LocalDate endDate = effectiveDate.plus(TENORS_SIMPLE.get(looptenor));
      SwapTrade swap = EUR_FIXED_1Y_EURIBOR_6M
          .toTrade(CALIBRATION_DATE, effectiveDate, endDate, BuySell.BUY, 1.0, 0.0);
      double parRate = SWAP_PRICER.parRate(swap.resolve(REF_DATA).getProduct(), MULTICURVE);
      ZonedDateTime expiryDateTime = expiry.atTime(11, 0).atZone(ZoneId.of("Europe/Berlin"));
      double time = calibratedAtm.relativeTime(expiryDateTime);
      double volBlack = calibratedAtm.volatility(expiryDateTime, tenor, parRate, parRate);
      double priceComputed = BlackFormulaRepository.price(parRate + shift, parRate + shift, time, volBlack, true);
      double priceNormal = NormalFormulaRepository.price(parRate, parRate, time,
          DATA_NORMAL_ATM_SIMPLE[looptenor + loopexpiry * nbTenor], PutCall.CALL);
      assertThat(priceComputed).isCloseTo(priceNormal, offset(TOLERANCE_PRICE_CALIBRATION_ROOT));
    }
  }
}
 
Example 14
Source File: ImmutableIborFutureConvention.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public LocalDate calculateReferenceDateFromTradeDate(
    LocalDate tradeDate,
    Period minimumPeriod,
    int sequenceNumber,
    ReferenceData refData) {

  LocalDate earliestDate = tradeDate.plus(minimumPeriod);
  LocalDate referenceDate = dateSequence.nthOrSame(earliestDate, sequenceNumber);
  return businessDayAdjustment.adjust(referenceDate, refData);
}
 
Example 15
Source File: TestRootCertificate.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testCACert()
    throws SCMSecurityException, NoSuchProviderException,
    NoSuchAlgorithmException, IOException {
  LocalDate notBefore = LocalDate.now();
  LocalDate notAfter = notBefore.plus(365, ChronoUnit.DAYS);
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "testRootCert";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  SelfSignedCertificate.Builder builder =
      SelfSignedCertificate.newBuilder()
          .setBeginDate(notBefore)
          .setEndDate(notAfter)
          .setClusterID(clusterID)
          .setScmID(scmID)
          .setSubject(subject)
          .setKey(keyPair)
          .setConfiguration(conf)
          .makeCA();

  X509CertificateHolder certificateHolder = builder.build();
  // This time we asked for a CertificateServer Certificate, make sure that
  // extension is
  // present and valid.
  Extension basicExt =
      certificateHolder.getExtension(Extension.basicConstraints);

  Assert.assertNotNull(basicExt);
  Assert.assertTrue(basicExt.isCritical());

  // Since this code assigns ONE for the root certificate, we check if the
  // serial number is the expected number.
  Assert.assertEquals(certificateHolder.getSerialNumber(), BigInteger.ONE);
}
 
Example 16
Source File: DepositIsdaCreditCurveNode.java    From Strata with Apache License 2.0 4 votes vote down vote up
@Override
public LocalDate date(LocalDate tradeDate, ReferenceData refData) {
  LocalDate startDate = spotDateOffset.adjust(tradeDate, refData);
  LocalDate endDate = startDate.plus(tenor);
  return businessDayAdjustment.adjust(endDate, refData);
}
 
Example 17
Source File: TestIsoChronoImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) {
        for (int minDays = 1; minDays <= 7; minDays++) {
            WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
            cal.setFirstDayOfWeek(Math.floorMod(firstDayOfWeek.getValue(), 7) + 1);
            cal.setMinimalDaysInFirstWeek(minDays);

            cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
            cal.set(Calendar.YEAR, isoDate.get(YEAR));
            cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
            cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

            // For every date in the range
            while (isoDate.isBefore(isoEndDate)) {
                assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
                assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
                assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

                int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1;
                int dow = isoDate.get(weekDef.dayOfWeek());
                assertEquals(jdow, dow, "Calendar DayOfWeek does not match ISO DayOfWeek");

                int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
                int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth());
                assertEquals(jweekOfMonth, isoWeekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth");

                int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
                int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear());
                assertEquals(jweekOfYear, weekOfYear,  "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear");

                int jWeekYear = cal.getWeekYear();
                int weekBasedYear = isoDate.get(weekDef.weekBasedYear());
                assertEquals(jWeekYear, weekBasedYear,  "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear");

                int jweeksInWeekyear = cal.getWeeksInWeekYear();
                int weeksInWeekBasedYear = (int)isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum();
                assertEquals(jweeksInWeekyear, weeksInWeekBasedYear, "length of weekBasedYear");

                isoDate = isoDate.plus(1, ChronoUnit.DAYS);
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }
}
 
Example 18
Source File: SabrSwaptionCalibratorCubeBlackExtremeDataTest.java    From Strata with Apache License 2.0 4 votes vote down vote up
@Test
public void log_normal_cube() {
  double beta = 0.50;
  Surface betaSurface = ConstantSurface.of("Beta", beta)
      .withMetadata(DefaultSurfaceMetadata.builder()
          .xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION)
          .zValueType(ValueType.SABR_BETA).surfaceName("Beta").build());
  double shift = 0.0300;
  Surface shiftSurface = ConstantSurface.of("Shift", shift)
      .withMetadata(DefaultSurfaceMetadata.builder()
          .xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).surfaceName("Shift").build());
  SabrParametersSwaptionVolatilities calibrated = SABR_CALIBRATION.calibrateWithFixedBetaAndShift(
      DEFINITION, CALIBRATION_TIME, DATA_SPARSE, MULTICURVE, betaSurface, shiftSurface);

  for (int looptenor = 0; looptenor < TENORS.size(); looptenor++) {
    double tenor = TENORS.get(looptenor).get(ChronoUnit.YEARS);
    for (int loopexpiry = 0; loopexpiry < EXPIRIES.size(); loopexpiry++) {
      LocalDate expiry = EUR_FIXED_1Y_EURIBOR_6M.getFloatingLeg().getStartDateBusinessDayAdjustment()
          .adjust(CALIBRATION_DATE.plus(EXPIRIES.get(loopexpiry)), REF_DATA);
      LocalDate effectiveDate = EUR_FIXED_1Y_EURIBOR_6M.calculateSpotDateFromTradeDate(expiry, REF_DATA);
      LocalDate endDate = effectiveDate.plus(TENORS.get(looptenor));
      SwapTrade swap = EUR_FIXED_1Y_EURIBOR_6M
          .toTrade(CALIBRATION_DATE, effectiveDate, endDate, BuySell.BUY, 1.0, 0.0);
      double parRate = SWAP_PRICER.parRate(swap.resolve(REF_DATA).getProduct(), MULTICURVE);
      ZonedDateTime expiryDateTime = expiry.atTime(11, 0).atZone(ZoneId.of("Europe/Berlin"));
      double time = calibrated.relativeTime(expiryDateTime);
      for (int loopmoney = 0; loopmoney < MONEYNESS.size(); loopmoney++) {
        if (!Double.isNaN(DATA_LOGNORMAL_SPARSE[looptenor][loopexpiry][loopmoney])) {
          double strike = parRate + MONEYNESS.get(loopmoney);
          double volBlack = calibrated.volatility(expiryDateTime, tenor, strike, parRate);
          double priceComputed = BlackFormulaRepository.price(parRate + shift, parRate + MONEYNESS.get(loopmoney) + shift,
              time, volBlack, true);
          double priceLogNormal = BlackFormulaRepository.price(parRate, parRate + MONEYNESS.get(loopmoney),
              time, DATA_LOGNORMAL_SPARSE[looptenor][loopexpiry][loopmoney], true);
          if (strike > 0.0025) { // Test only for strikes above 25bps
            assertThat(priceComputed).isCloseTo(priceLogNormal, offset(TOLERANCE_PRICE_CALIBRATION_LS));
          }
        }
      }
    }
  }
}
 
Example 19
Source File: TestIsoChronoImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "RangeVersusCalendar")
public void test_DayOfWeek_IsoChronology_vsCalendar(LocalDate isoStartDate, LocalDate isoEndDate) {
    GregorianCalendar cal = new GregorianCalendar();
    assertEquals(cal.getCalendarType(), "gregory", "Unexpected calendar type");
    LocalDate isoDate = IsoChronology.INSTANCE.date(isoStartDate);

    for (DayOfWeek firstDayOfWeek : DayOfWeek.values()) {
        for (int minDays = 1; minDays <= 7; minDays++) {
            WeekFields weekDef = WeekFields.of(firstDayOfWeek, minDays);
            cal.setFirstDayOfWeek(Math.floorMod(firstDayOfWeek.getValue(), 7) + 1);
            cal.setMinimalDaysInFirstWeek(minDays);

            cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
            cal.set(Calendar.YEAR, isoDate.get(YEAR));
            cal.set(Calendar.MONTH, isoDate.get(MONTH_OF_YEAR) - 1);
            cal.set(Calendar.DAY_OF_MONTH, isoDate.get(DAY_OF_MONTH));

            // For every date in the range
            while (isoDate.isBefore(isoEndDate)) {
                assertEquals(isoDate.get(DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH), "Day mismatch in " + isoDate + ";  cal: " + cal);
                assertEquals(isoDate.get(MONTH_OF_YEAR), cal.get(Calendar.MONTH) + 1, "Month mismatch in " + isoDate);
                assertEquals(isoDate.get(YEAR_OF_ERA), cal.get(Calendar.YEAR), "Year mismatch in " + isoDate);

                int jdow = Math.floorMod(cal.get(Calendar.DAY_OF_WEEK) - 2, 7) + 1;
                int dow = isoDate.get(weekDef.dayOfWeek());
                assertEquals(jdow, dow, "Calendar DayOfWeek does not match ISO DayOfWeek");

                int jweekOfMonth = cal.get(Calendar.WEEK_OF_MONTH);
                int isoWeekOfMonth = isoDate.get(weekDef.weekOfMonth());
                assertEquals(jweekOfMonth, isoWeekOfMonth, "Calendar WeekOfMonth does not match ISO WeekOfMonth");

                int jweekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
                int weekOfYear = isoDate.get(weekDef.weekOfWeekBasedYear());
                assertEquals(jweekOfYear, weekOfYear,  "GregorianCalendar WeekOfYear does not match WeekOfWeekBasedYear");

                int jWeekYear = cal.getWeekYear();
                int weekBasedYear = isoDate.get(weekDef.weekBasedYear());
                assertEquals(jWeekYear, weekBasedYear,  "GregorianCalendar getWeekYear does not match YearOfWeekBasedYear");

                int jweeksInWeekyear = cal.getWeeksInWeekYear();
                int weeksInWeekBasedYear = (int)isoDate.range(weekDef.weekOfWeekBasedYear()).getMaximum();
                assertEquals(jweeksInWeekyear, weeksInWeekBasedYear, "length of weekBasedYear");

                isoDate = isoDate.plus(1, ChronoUnit.DAYS);
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }
}
 
Example 20
Source File: CurveSensitivityUtils.java    From Strata with Apache License 2.0 4 votes vote down vote up
/**
 * Re-buckets a {@link CurrencyParameterSensitivities} to a given set of dates.
 * <p>
 * The list of dates must be sorted in chronological order. All sensitivities are re-bucketed to the same date list.
 * The re-bucketing is done by linear weighting on the number of days, i.e. the sensitivities for dates outside the 
 * extremes are fully bucketed to the extremes and for date between two re-bucketing dates, the weight on the start 
 * date is the number days between end date and the date re-bucketed divided by the number of days between the 
 * start and the end. The date of the nodes can be directly in the parameter metadata - when the metadata is of the 
 * type {@link DatedParameterMetadata} - or inferred from the sensitivity date and the tenor when the
 * metadata is of the type {@link TenorParameterMetadata}. Only those types of metadata are accepted.
 * 
 * @param sensitivities  the input sensitivities
 * @param targetDates  the list of dates for the re-bucketing
 * @param sensitivityDate  the date for which the sensitivities are valid
 * @return the sensitivity after the re-bucketing
 */
public static CurrencyParameterSensitivities linearRebucketing(
    CurrencyParameterSensitivities sensitivities,
    List<LocalDate> targetDates,
    LocalDate sensitivityDate) {

  checkSortedDates(targetDates);
  int nbBuckets = targetDates.size();
  List<ParameterMetadata> pmdTarget = targetDates.stream()
      .map(date -> LabelDateParameterMetadata.of(date, date.toString()))
      .collect(toList());
  ImmutableList<CurrencyParameterSensitivity> sensitivitiesList = sensitivities.getSensitivities();
  List<CurrencyParameterSensitivity> sensitivityTarget = new ArrayList<>();
  for (CurrencyParameterSensitivity sensitivity : sensitivitiesList) {
    double[] rebucketedSensitivityAmounts = new double[nbBuckets];
    DoubleArray sensitivityAmounts = sensitivity.getSensitivity();
    List<ParameterMetadata> parameterMetadataList = sensitivity.getParameterMetadata();
    for (int loopnode = 0; loopnode < sensitivityAmounts.size(); loopnode++) {
      ParameterMetadata nodeMetadata = parameterMetadataList.get(loopnode);
      ArgChecker.isTrue((nodeMetadata instanceof DatedParameterMetadata) ||
          (nodeMetadata instanceof TenorParameterMetadata),
          "re-bucketing requires sensitivity date or node for node {} which is of type {}",
          nodeMetadata.getLabel(), nodeMetadata.getClass().getName());
      LocalDate nodeDate;
      if (nodeMetadata instanceof DatedParameterMetadata) {
        DatedParameterMetadata datedParameterMetadata = (DatedParameterMetadata) nodeMetadata;
        nodeDate = datedParameterMetadata.getDate();
      } else {
        TenorParameterMetadata tenorParameterMetadata = (TenorParameterMetadata) nodeMetadata;
        nodeDate = sensitivityDate.plus(tenorParameterMetadata.getTenor());
      }
      rebucketingArray(targetDates, rebucketedSensitivityAmounts, sensitivityAmounts.get(loopnode), nodeDate);
    }
    CurrencyParameterSensitivity rebucketedSensitivity = CurrencyParameterSensitivity.of(
        sensitivity.getMarketDataName(),
        pmdTarget,
        sensitivity.getCurrency(),
        DoubleArray.ofUnsafe(rebucketedSensitivityAmounts));
    sensitivityTarget.add(rebucketedSensitivity);
  }
  return CurrencyParameterSensitivities.of(sensitivityTarget);
}