Java Code Examples for java.time.ZonedDateTime#toLocalDate()

The following examples show how to use java.time.ZonedDateTime#toLocalDate() . 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: SabrSwaptionCalibrator.java    From Strata with Apache License 2.0 6 votes vote down vote up
/**
 * Calibrate the SABR alpha parameter to an ATM normal volatility and compute the derivative of the result 
 * with respect to the input volatility.
 * 
 * @param bda  the business day adjustment for the exercise date adjustment
 * @param calibrationDateTime  the calibration date and time
 * @param dayCount  the day count for the computation of the time to exercise
 * @param periodToExpiry  the period to expiry
 * @param forward  the forward price/rate
 * @param normalVolatility  the option (call/payer) normal model implied volatility
 * @param startParameters  the starting parameters for the calibration. The alpha parameter is used as a starting
 *   point for the root-finding, the other parameters are fixed.
 * @param shiftOutput  the shift to calibrate the shifted SABR
 * @return the alpha calibrated and its derivative with respect to the volatility
 */
public Pair<Double, Double> calibrateAtmShiftedFromNormalVolatilities(
    BusinessDayAdjustment bda,
    ZonedDateTime calibrationDateTime,
    DayCount dayCount,
    Period periodToExpiry,
    double forward,
    double normalVolatility,
    DoubleArray startParameters,
    double shiftOutput) {

  LocalDate calibrationDate = calibrationDateTime.toLocalDate();
  LocalDate exerciseDate = expirationDate(bda, calibrationDate, periodToExpiry);
  double timeToExpiry = dayCount.relativeYearFraction(calibrationDate, exerciseDate);
  Pair<DoubleArray, DoubleArray> volAndDerivatives = blackVolatilitiesShiftedFromNormalVolatilities(
      forward, shiftOutput, timeToExpiry, DoubleArray.of(forward), DoubleArray.of(normalVolatility));
  DoubleArray blackVolatilitiesTransformed = volAndDerivatives.getFirst();
  Function<Double, Double> volFunction =
      (a) -> sabrVolatilityFormula.volatility(forward + shiftOutput, forward + shiftOutput, timeToExpiry, a,
          startParameters.get(1), startParameters.get(2), startParameters.get(3)) - blackVolatilitiesTransformed.get(0);
  double alphaCalibrated = ROOT_FINDER.getRoot(volFunction, startParameters.get(0));
  double dAlphadBlack = 1.0d / sabrVolatilityFormula.volatilityAdjoint(forward + shiftOutput, forward + shiftOutput,
      timeToExpiry, alphaCalibrated, startParameters.get(1), startParameters.get(2), startParameters.get(3))
      .getDerivative(2);
  return Pair.of(alphaCalibrated, dAlphadBlack * volAndDerivatives.getSecond().get(0));
}
 
Example 2
Source File: TimeMetadataProvider.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Map<String, String> retrieve() {
	final Map<String, String> map = new HashMap<>();

	final ZonedDateTime now = ZonedDateTime.now();
	final LocalTime time = now.toLocalTime();
	final LocalDate date = now.toLocalDate();
	final ZoneId zone = now.getZone();
	final ZoneOffset offset = now.getOffset();

	map.put( TIME, time.format( TIME_FORMATTER ) );
	map.put( DATE, date.format( DATE_FORMATTER ) );
	map.put( ZONE, zone.getId() );
	map.put( OFFSET, offset.getId() );

	return map;
}
 
Example 3
Source File: IslamicExpression.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMatchDateTime(ZonedDateTime dateTime) {
    IslamicDate islamic = new IslamicDate(dateTime.toLocalDate());
    int year = islamic.getYear();
    int month = islamic.getMonth();
    int day = islamic.getDay();
    int size = IslamicDate.getDaySize(year, month);
    BitSet days = getDays(size);
    LocalTime time = dateTime.toLocalTime();
    int hour = time.getHour();
    int minute = time.getMinute();
    int second = time.getSecond();
    if (seconds.get(second) && minutes.get(minute) && hours.get(hour)) {
        if (days.get(day) && months.get(month) && years.get(year - IslamicDate.MINIMUM_YEAR)) {
            return true;
        }
    }
    return false;
}
 
Example 4
Source File: LunarExpression.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isMatchDateTime(ZonedDateTime dateTime) {
    LunarDate lunar = new LunarDate(dateTime.toLocalDate());
    int year = lunar.getYear();
    boolean leap = lunar.isLeap();
    int month = lunar.getMonth();
    int day = lunar.getDay();
    int size = LunarDate.getDaySize(year, leap, month);
    BitSet days = getDays(size);
    LocalTime time = dateTime.toLocalTime();
    int hour = time.getHour();
    int minute = time.getMinute();
    int second = time.getSecond();
    if (seconds.get(second) && minutes.get(minute) && hours.get(hour)) {
        if (days.get(day) && months.get(month) && years.get(year - LunarDate.MINIMUM_YEAR)) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: SabrSwaptionCalibrator.java    From Strata with Apache License 2.0 5 votes vote down vote up
/**
 * Calibrate the SABR alpha parameter to an ATM Black volatility and compute the derivative of the result with 
 * respect to the input volatility.
 * 
 * @param bda  the business day adjustment for the exercise date adjustment
 * @param calibrationDateTime  the calibration date and time
 * @param dayCount  the day count for the computation of the time to exercise
 * @param periodToExpiry  the period to expiry
 * @param forward  the forward price/rate
 * @param blackVolatility  the option (call/payer) Black implied volatility
 * @param shiftInput  the shift used to computed the input implied shifted Black volatilities
 * @param startParameters  the starting parameters for the calibration. The alpha parameter is used as a starting
 *   point for the root-finding, the other parameters are fixed.
 * @param shiftOutput  the shift to calibrate the shifted SABR
 * @return the alpha calibrated and its derivative with respect to the volatility
 */
public Pair<Double, Double> calibrateAtmShiftedFromBlackVolatilities(
    BusinessDayAdjustment bda,
    ZonedDateTime calibrationDateTime,
    DayCount dayCount,
    Period periodToExpiry,
    double forward,
    double blackVolatility,
    double shiftInput,
    DoubleArray startParameters,
    double shiftOutput) {

  LocalDate calibrationDate = calibrationDateTime.toLocalDate();
  LocalDate exerciseDate = expirationDate(bda, calibrationDate, periodToExpiry);
  double timeToExpiry = dayCount.relativeYearFraction(calibrationDate, exerciseDate);
  Pair<DoubleArray, DoubleArray> volAndDerivatives = blackVolatilitiesShiftedFromBlackVolatilitiesShifted(
      forward, shiftOutput, timeToExpiry, DoubleArray.of(forward), DoubleArray.of(blackVolatility), shiftInput);
  DoubleArray blackVolatilitiesTransformed = volAndDerivatives.getFirst();
  Function<Double, Double> volFunction =
      (a) -> sabrVolatilityFormula.volatility(forward + shiftOutput, forward + shiftOutput, timeToExpiry, a,
          startParameters.get(1), startParameters.get(2), startParameters.get(3)) - blackVolatilitiesTransformed.get(0);
  double alphaCalibrated = ROOT_FINDER.getRoot(volFunction, startParameters.get(0));
  double dAlphadBlack = 1.0d / sabrVolatilityFormula.volatilityAdjoint(forward + shiftOutput, forward + shiftOutput,
      timeToExpiry, alphaCalibrated, startParameters.get(1), startParameters.get(2), startParameters.get(3))
      .getDerivative(2);
  return Pair.of(alphaCalibrated, dAlphadBlack * volAndDerivatives.getSecond().get(0));
}
 
Example 6
Source File: TrendController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the rule trend.This request expects asset group,ruleId and from as
 * mandatory.If API receives asset group,ruleId and from as request
 * parameters, it gives weekly based details of compliance trend from
 * mentioned date to till date for ruleId.
 *
 * @param request
 *            the request
 * @return ResponseEntity
 */

@RequestMapping(path = "/v1/trend/compliancebyrule", method = RequestMethod.POST)
public ResponseEntity<Object> getRuleTrend(@RequestBody(required = true) RuleTrendRequest request) {

    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();
    String ruleId = request.getRuleid();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    LocalDate toDate = LocalDate.now();

    if (Strings.isNullOrEmpty(assetGroup) || Strings.isNullOrEmpty(ruleId)) {
        return ResponseUtils.buildFailureResponse(new Exception("assetGroup/ruleId is Mandatory"));
    }

    try {
        Map<String, Object> ruleTrendProgressList = trendService.getTrendProgress(assetGroup, ruleId, fromDate,
                toDate, "issuecompliance");
        response.put(RESPONSE, ruleTrendProgressList);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getRuleTrend" , e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 7
Source File: TrendController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the vulnerabilities trend.This request expects asset group and from
 * as mandatory.If API receives asset group and from as request parameters,
 * it gives weekly based details of compliance trend from mentioned date to
 * till date for vulnerabilities
 *
 * @param request
 *            the request
 * @return ResponseEntity
 */

@RequestMapping(path = "/v1/trend/compliance/vulnerabilities", method = RequestMethod.POST)
public ResponseEntity<Object> getVulnTrend(@RequestBody(required = true) CompliantTrendRequest request) {

    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    LocalDate toDate = LocalDate.now();

    if (Strings.isNullOrEmpty(assetGroup)) {
        return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
    }

    try {
        Map<String, Object> ruleTrendProgressList = trendService.getTrendProgress(assetGroup, null, fromDate,
                toDate, "vulncompliance");
        response.put(RESPONSE, ruleTrendProgressList);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getVulnTrend" , e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 8
Source File: NormalIborCapletFloorletExpiryFlatVolatilities.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public double relativeTime(ZonedDateTime dateTime) {
  ArgChecker.notNull(dateTime, "dateTime");
  LocalDate valuationDate = valuationDateTime.toLocalDate();
  LocalDate date = dateTime.toLocalDate();
  return dayCount.relativeYearFraction(valuationDate, date);
}
 
Example 9
Source File: NormalSwaptionExpirySimpleMoneynessVolatilities.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public double relativeTime(ZonedDateTime dateTime) {
  ArgChecker.notNull(dateTime, "dateTime");
  LocalDate valuationDate = valuationDateTime.toLocalDate();
  LocalDate date = dateTime.toLocalDate();
  return dayCount.relativeYearFraction(valuationDate, date);
}
 
Example 10
Source File: BlackIborCapletFloorletExpiryFlatVolatilities.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public double relativeTime(ZonedDateTime dateTime) {
  ArgChecker.notNull(dateTime, "dateTime");
  LocalDate valuationDate = valuationDateTime.toLocalDate();
  LocalDate date = dateTime.toLocalDate();
  return dayCount.relativeYearFraction(valuationDate, date);
}
 
Example 11
Source File: Convert.java    From LGoodDatePicker with MIT License 5 votes vote down vote up
/**
 * setDateWithDefaultZone, Sets the date picker value from a java.util.Date using the system
 * default time zone. If either the date or the time zone are null, the date picker will be
 * cleared.
 */
public void setDateWithDefaultZone(java.util.Date javaUtilDate) {
    if (javaUtilDate == null) {
        parentDatePicker.setDate(null);
        return;
    }
    Instant instant = Instant.ofEpochMilli(javaUtilDate.getTime());
    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
    LocalDate localDate = zonedDateTime.toLocalDate();
    parentDatePicker.setDate(localDate);
}
 
Example 12
Source File: BlackFxOptionSurfaceVolatilities.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Override
public double relativeTime(ZonedDateTime dateTime) {
  ArgChecker.notNull(dateTime, "dateTime");
  LocalDate valuationDate = valuationDateTime.toLocalDate();
  LocalDate date = dateTime.toLocalDate();
  return dayCount.relativeYearFraction(valuationDate, date);
}
 
Example 13
Source File: Convert.java    From LGoodDatePicker with MIT License 5 votes vote down vote up
/**
 * setDateWithZone, Sets the date picker value from a java.util.Date using the specified time
 * zone. If either the date or the time zone are null, the date picker will be cleared.
 */
public void setDateWithZone(java.util.Date javaUtilDate, ZoneId timezone) {
    if (javaUtilDate == null || timezone == null) {
        parentDatePicker.setDate(null);
        return;
    }
    Instant instant = Instant.ofEpochMilli(javaUtilDate.getTime());
    ZonedDateTime zonedDateTime = instant.atZone(timezone);
    LocalDate localDate = zonedDateTime.toLocalDate();
    parentDatePicker.setDate(localDate);
}
 
Example 14
Source File: DateTimeConverters.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public LocalDate convert(ZonedDateTime source) {
	return source.toLocalDate();
}
 
Example 15
Source File: DateTimeConverters.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public LocalDate convert(ZonedDateTime source) {
	return source.toLocalDate();
}
 
Example 16
Source File: DirectIborCapletFloorletFlatVolatilityCalibrator.java    From Strata with Apache License 2.0 4 votes vote down vote up
@Override
public IborCapletFloorletVolatilityCalibrationResult calibrate(
    IborCapletFloorletVolatilityDefinition definition,
    ZonedDateTime calibrationDateTime,
    RawOptionData capFloorData,
    RatesProvider ratesProvider) {

  ArgChecker.isTrue(ratesProvider.getValuationDate().equals(calibrationDateTime.toLocalDate()),
      "valuationDate of ratesProvider should be coherent to calibrationDateTime");
  ArgChecker.isTrue(definition instanceof DirectIborCapletFloorletFlatVolatilityDefinition,
      "definition should be DirectIborCapletFloorletFlatVolatilityDefinition");
  DirectIborCapletFloorletFlatVolatilityDefinition directDefinition =
      (DirectIborCapletFloorletFlatVolatilityDefinition) definition;
  DoubleArray strikes = capFloorData.getStrikes();
  ArgChecker.isTrue(strikes.size() == 1, "strike size should be 1");
  // unpack cap data, create node caps
  IborIndex index = directDefinition.getIndex();
  LocalDate calibrationDate = calibrationDateTime.toLocalDate();
  LocalDate baseDate = index.getEffectiveDateOffset().adjust(calibrationDate, getReferenceData());
  LocalDate startDate = baseDate.plus(index.getTenor());
  Function<Curve, IborCapletFloorletVolatilities> volatilitiesFunction = flatVolatilitiesFunction(
      directDefinition, calibrationDateTime, capFloorData);
  CurveMetadata metadata = directDefinition.createCurveMetadata(capFloorData);
  List<Period> expiries = capFloorData.getExpiries();
  int nExpiries = expiries.size();
  List<Double> timeList = new ArrayList<>();
  List<Double> volList = new ArrayList<>();
  List<ResolvedIborCapFloorLeg> capList = new ArrayList<>();
  List<Double> priceList = new ArrayList<>();
  List<Double> errorList = new ArrayList<>();
  DoubleMatrix errorMatrix = capFloorData.getError().orElse(DoubleMatrix.filled(nExpiries, 1, 1d));
  int[] startIndex = new int[nExpiries + 1];
  for (int i = 0; i < nExpiries; ++i) {
    LocalDate endDate = baseDate.plus(expiries.get(i));
    double strike = strikes.get(0);
    double volatilityForTime = capFloorData.getData().row(i).get(0);
    double errorForTime = errorMatrix.row(i).get(0);
    reduceRawData(directDefinition, ratesProvider, strike, volatilityForTime, errorForTime, startDate,
        endDate, metadata, volatilitiesFunction, timeList, volList, capList, priceList, errorList);
    startIndex[i + 1] = volList.size();
    ArgChecker.isTrue(startIndex[i + 1] > startIndex[i], "no valid option data for {}", expiries.get(i));
  }
  // create caplet nodes and initial caplet vol curve
  ResolvedIborCapFloorLeg cap = capList.get(capList.size() - 1);
  int nCaplets = cap.getCapletFloorletPeriods().size();
  DoubleArray capletExpiries = DoubleArray.of(nCaplets, n -> directDefinition.getDayCount().relativeYearFraction(
      calibrationDate, cap.getCapletFloorletPeriods().get(n).getFixingDateTime().toLocalDate()));
  Pair<DoubleArray, DoubleArray> capletNodes;
  DoubleArray initialVols = DoubleArray.copyOf(volList);
  InterpolatedNodalCurve capVolCurve = InterpolatedNodalCurve.of(
      metadata, DoubleArray.copyOf(timeList), initialVols, CurveInterpolators.LINEAR);
  capletNodes = createCapletNodes(capVolCurve, capletExpiries);
  InterpolatedNodalCurve baseCurve = InterpolatedNodalCurve.of(
      metadata, capletNodes.getFirst(), capletNodes.getSecond(), CurveInterpolators.LINEAR);
  DoubleMatrix penaltyMatrix = directDefinition.computePenaltyMatrix(capletExpiries);
  // solve least square
  LeastSquareResults res = solver.solve(
      DoubleArray.copyOf(priceList),
      DoubleArray.copyOf(errorList),
      getPriceFunction(capList, ratesProvider, volatilitiesFunction, baseCurve),
      getJacobianFunction(capList, ratesProvider, volatilitiesFunction, baseCurve),
      capletNodes.getSecond(),
      penaltyMatrix,
      POSITIVE);
  InterpolatedNodalCurve resCurve = InterpolatedNodalCurve.of(
      metadata,
      capletNodes.getFirst(),
      res.getFitParameters(),
      directDefinition.getInterpolator(),
      directDefinition.getExtrapolatorLeft(),
      directDefinition.getExtrapolatorRight());
  IborCapletFloorletVolatilityCalibrationResult calibrationResult = IborCapletFloorletVolatilityCalibrationResult.ofLeastSquare(
      volatilitiesFunction.apply(resCurve), res.getChiSq());
  return calibrationResult;
}
 
Example 17
Source File: LunarExpression.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public ZonedDateTime getNextDateTime(ZonedDateTime dateTime) {
    LunarDate lunar = new LunarDate(dateTime.toLocalDate());
    int year = lunar.getYear();
    boolean leap = lunar.isLeap();
    int month = lunar.getMonth();
    int day = lunar.getDay();
    int size = LunarDate.getDaySize(year, leap, month);
    BitSet days = getDays(size);
    LocalTime time = dateTime.toLocalTime();
    int hour = time.getHour();
    int minute = time.getMinute();
    int second = time.getSecond();
    second = seconds.nextSetBit(second + 1);
    if (second == -1) {
        second = seconds.nextSetBit(0);
        minute++;
    }
    minute = minutes.nextSetBit(minute);
    if (minute == -1) {
        second = seconds.nextSetBit(0);
        minute = minutes.nextSetBit(0);
        hour++;
    }
    hour = hours.nextSetBit(hour);
    if (hour == -1) {
        second = seconds.nextSetBit(0);
        minute = minutes.nextSetBit(0);
        hour = hours.nextSetBit(0);
        day++;
    }
    day = days.nextSetBit(day);
    if (day == -1) {
        second = seconds.nextSetBit(0);
        minute = minutes.nextSetBit(0);
        hour = hours.nextSetBit(0);
    }
    while (day == -1) {
        // 从非闰月到是闰月
        if (!leap && month == LunarDate.getLeapMonth(year)) {
            leap = true;
        } else {
            month++;
            leap = false;
        }
        // 月份是否变化
        if (!months.get(month)) {
            month = months.nextSetBit(month);
            if (month == -1) {
                month = months.nextSetBit(1);
                year++;
            }
            year = years.nextSetBit(year - LunarDate.MINIMUM_YEAR);
            if (year == -1) {
                return null;
            }
            year += LunarDate.MINIMUM_YEAR;
            // 一定非闰月
            leap = false;
        }
        size = LunarDate.getDaySize(year, leap, month);
        days = getDays(size);
        day = days.nextSetBit(1);
    }
    if (!years.get(year - LunarDate.MINIMUM_YEAR)) {
        return null;
    }
    lunar = new LunarDate(year, leap, month, day);
    LocalDate date = lunar.getDate();
    return ZonedDateTime.of(date, LocalTime.of(hour, minute, second), dateTime.getZone());
}
 
Example 18
Source File: LunarExpression.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Override
public ZonedDateTime getPreviousDateTime(ZonedDateTime dateTime) {
    LunarDate lunar = new LunarDate(dateTime.toLocalDate());
    int year = lunar.getYear();
    boolean leap = lunar.isLeap();
    int month = lunar.getMonth();
    int day = lunar.getDay();
    int size = LunarDate.getDaySize(year, leap, month);
    BitSet days = getDays(size);
    LocalTime time = dateTime.toLocalTime();
    int hour = time.getHour();
    int minute = time.getMinute();
    int second = time.getSecond();
    second = seconds.previousSetBit(second - 1);
    if (second == -1) {
        second = seconds.previousSetBit(59);
        minute--;
    }
    minute = minutes.previousSetBit(minute);
    if (minute == -1) {
        second = seconds.previousSetBit(59);
        minute = minutes.previousSetBit(59);
        hour--;
    }
    hour = hours.previousSetBit(hour);
    if (hour == -1) {
        second = seconds.previousSetBit(59);
        minute = minutes.previousSetBit(59);
        hour = hours.previousSetBit(23);
        day--;
    }
    day = days.previousSetBit(day);
    if (day == -1) {
        second = seconds.previousSetBit(59);
        minute = minutes.previousSetBit(59);
        hour = hours.previousSetBit(23);
    }
    while (day == -1) {
        // 从是闰月到非闰月
        if (leap && month == LunarDate.getLeapMonth(year)) {
            leap = false;
        } else {
            month--;
            // 从非闰月到是闰月
            if (month == LunarDate.getLeapMonth(year)) {
                leap = true;
            }
        }
        // 月份是否变化
        if (!months.get(month)) {
            month = months.previousSetBit(month);
            if (month == -1) {
                month = months.previousSetBit(12);
                year--;
                year = years.previousSetBit(year - LunarDate.MINIMUM_YEAR);
                if (year == -1) {
                    return null;
                }
                year += LunarDate.MINIMUM_YEAR;
            }
            // 可能是闰月
            leap = month == LunarDate.getLeapMonth(year);
        }
        size = LunarDate.getDaySize(year, leap, month);
        days = getDays(size);
        day = days.previousSetBit(30);
    }
    if (!years.get(year - LunarDate.MINIMUM_YEAR)) {
        return null;
    }
    lunar = new LunarDate(year, leap, month, day);
    LocalDate date = lunar.getDate();
    return ZonedDateTime.of(date, LocalTime.of(hour, minute, second), dateTime.getZone());
}
 
Example 19
Source File: SabrIborCapletFloorletVolatilityCalibrator.java    From Strata with Apache License 2.0 4 votes vote down vote up
@Override
public IborCapletFloorletVolatilityCalibrationResult calibrate(
    IborCapletFloorletVolatilityDefinition definition,
    ZonedDateTime calibrationDateTime,
    RawOptionData capFloorData,
    RatesProvider ratesProvider) {

  ArgChecker.isTrue(ratesProvider.getValuationDate().equals(calibrationDateTime.toLocalDate()),
      "valuationDate of ratesProvider should be coherent to calibrationDateTime");
  ArgChecker.isTrue(definition instanceof SabrIborCapletFloorletVolatilityCalibrationDefinition,
      "definition should be SabrIborCapletFloorletVolatilityCalibrationDefinition");
  SabrIborCapletFloorletVolatilityCalibrationDefinition sabrDefinition =
      (SabrIborCapletFloorletVolatilityCalibrationDefinition) definition;
  // unpack cap data, create node caps
  IborIndex index = sabrDefinition.getIndex();
  LocalDate calibrationDate = calibrationDateTime.toLocalDate();
  LocalDate baseDate = index.getEffectiveDateOffset().adjust(calibrationDate, getReferenceData());
  LocalDate startDate = baseDate.plus(index.getTenor());
  Function<Surface, IborCapletFloorletVolatilities> volatilitiesFunction = volatilitiesFunction(
      sabrDefinition, calibrationDateTime, capFloorData);
  SurfaceMetadata metadata = sabrDefinition.createMetadata(capFloorData);
  List<Period> expiries = capFloorData.getExpiries();
  DoubleArray strikes = capFloorData.getStrikes();
  int nExpiries = expiries.size();
  List<Double> timeList = new ArrayList<>();
  List<Double> strikeList = new ArrayList<>();
  List<Double> volList = new ArrayList<>();
  List<ResolvedIborCapFloorLeg> capList = new ArrayList<>();
  List<Double> priceList = new ArrayList<>();
  List<Double> errorList = new ArrayList<>();
  DoubleMatrix errorMatrix = capFloorData.getError().orElse(DoubleMatrix.filled(nExpiries, strikes.size(), 1d));
  int[] startIndex = new int[nExpiries + 1];
  for (int i = 0; i < nExpiries; ++i) {
    LocalDate endDate = baseDate.plus(expiries.get(i));
    DoubleArray volatilityForTime = capFloorData.getData().row(i);
    DoubleArray errorForTime = errorMatrix.row(i);
    reduceRawData(sabrDefinition, ratesProvider, capFloorData.getStrikes(), volatilityForTime, errorForTime, startDate,
        endDate, metadata, volatilitiesFunction, timeList, strikeList, volList, capList, priceList, errorList);
    startIndex[i + 1] = volList.size();
    ArgChecker.isTrue(startIndex[i + 1] > startIndex[i], "no valid option data for {}", expiries.get(i));
  }
  // create initial caplet vol surface
  List<CurveMetadata> metadataList = sabrDefinition.createSabrParameterMetadata();
  DoubleArray initialValues = sabrDefinition.createFullInitialValues();
  List<Curve> curveList = sabrDefinition.createSabrParameterCurve(metadataList, initialValues);
  SabrParameters sabrParamsInitial = SabrParameters.of(
      curveList.get(0),
      curveList.get(1),
      curveList.get(2),
      curveList.get(3),
      sabrDefinition.getShiftCurve(),
      sabrDefinition.getSabrVolatilityFormula());
  SabrParametersIborCapletFloorletVolatilities vols = SabrParametersIborCapletFloorletVolatilities.of(
      sabrDefinition.getName(), index, calibrationDateTime, sabrParamsInitial);
  // solve least square
  UncoupledParameterTransforms transform = new UncoupledParameterTransforms(
      initialValues, sabrDefinition.createFullTransform(TRANSFORMS), new BitSet());
  Function<DoubleArray, DoubleArray> valueFunction = createPriceFunction(
      sabrDefinition, ratesProvider, vols, capList, priceList);
  Function<DoubleArray, DoubleMatrix> jacobianFunction = createJacobianFunction(
      sabrDefinition, ratesProvider, vols, capList, priceList, index.getCurrency());
  NonLinearTransformFunction transFunc = new NonLinearTransformFunction(valueFunction, jacobianFunction, transform);
  LeastSquareResults res = solver.solve(
      DoubleArray.filled(priceList.size(), 1d),
      DoubleArray.copyOf(errorList),
      transFunc.getFittingFunction(),
      transFunc.getFittingJacobian(),
      transform.transform(initialValues));
  LeastSquareResultsWithTransform resTransform = new LeastSquareResultsWithTransform(res, transform);
  vols = updateParameters(sabrDefinition, vols, resTransform.getModelParameters());

  return IborCapletFloorletVolatilityCalibrationResult.ofLeastSquare(vols, res.getChiSq());
}
 
Example 20
Source File: DateTimeConverters.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public LocalDate convert(ZonedDateTime source) {
	return source.toLocalDate();
}