@Override
 public Coupon toDerivative(final ZonedDateTime dateTime) {
   ArgumentChecker.notNull(dateTime, "date");
   final LocalDate dayConversion = dateTime.toLocalDate();
   ArgumentChecker.isTrue(
       !dayConversion.isAfter(getFixingDate().toLocalDate()),
       "Do not have any fixing data but are asking for a derivative at "
           + dateTime
           + " which is after fixing date "
           + getFixingDate());
   ArgumentChecker.isTrue(
       !dayConversion.isAfter(getPaymentDate().toLocalDate()), "date is after payment date");
   final double paymentTime = TimeCalculator.getTimeBetween(dateTime, getPaymentDate());
   final double fixingTime = TimeCalculator.getTimeBetween(dateTime, getFixingDate());
   final double fixingPeriodStartTime =
       TimeCalculator.getTimeBetween(dateTime, getFixingPeriodStartDate());
   final double fixingPeriodEndTime =
       TimeCalculator.getTimeBetween(dateTime, getFixingPeriodEndDate());
   return new CouponIbor(
       getCurrency(),
       paymentTime,
       getPaymentYearFraction(),
       getNotional(),
       fixingTime,
       getIndex(),
       fixingPeriodStartTime,
       fixingPeriodEndTime,
       getFixingPeriodAccrualFactor());
 }
 @Test
 public void testReturnsWithZeroesInSeries() {
   final int n = 20;
   final LocalDate[] times = new LocalDate[n];
   final double[] data = new double[n];
   final double[] returns = new double[n - 3];
   double random;
   for (int i = 0; i < n - 2; i++) {
     times[i] = LocalDate.ofEpochDay(i);
     random = RANDOM.nextDouble();
     data[i] = random;
     if (i > 0) {
       returns[i - 1] = Math.log(random / data[i - 1]);
     }
   }
   times[n - 2] = LocalDate.ofEpochDay(n - 2);
   data[n - 2] = 0;
   times[n - 1] = LocalDate.ofEpochDay(n - 1);
   data[n - 1] = RANDOM.nextDouble();
   final LocalDateDoubleTimeSeries priceTS = ImmutableLocalDateDoubleTimeSeries.of(times, data);
   final LocalDateDoubleTimeSeries returnTS =
       ImmutableLocalDateDoubleTimeSeries.of(Arrays.copyOfRange(times, 1, n - 2), returns);
   final TimeSeriesReturnCalculator strict =
       new ContinuouslyCompoundedTimeSeriesReturnCalculator(CalculationMode.STRICT);
   final LocalDateDoubleTimeSeries[] tsArray = new LocalDateDoubleTimeSeries[] {priceTS};
   try {
     strict.evaluate(tsArray);
     Assert.fail();
   } catch (final TimeSeriesException e) {
     // Expected
   }
   final TimeSeriesReturnCalculator lenient =
       new ContinuouslyCompoundedTimeSeriesReturnCalculator(CalculationMode.LENIENT);
   assertTrue(lenient.evaluate(tsArray).equals(returnTS));
 }
 @Test
 public void testReturnsWithDividendsAtDifferentTimes() {
   final int n = 20;
   final LocalDate[] times = new LocalDate[n];
   final double[] data = new double[n];
   final double[] returns = new double[n - 1];
   double random;
   for (int i = 0; i < n; i++) {
     times[i] = LocalDate.ofEpochDay(i);
     random = RANDOM.nextDouble();
     data[i] = random;
     if (i > 0) {
       returns[i - 1] = Math.log(random / data[i - 1]);
     }
   }
   final LocalDateDoubleTimeSeries dividendTS =
       ImmutableLocalDateDoubleTimeSeries.of(
           new LocalDate[] {LocalDate.ofEpochDay(300)}, new double[] {3});
   final LocalDateDoubleTimeSeries priceTS = ImmutableLocalDateDoubleTimeSeries.of(times, data);
   final LocalDateDoubleTimeSeries returnTS =
       ImmutableLocalDateDoubleTimeSeries.of(Arrays.copyOfRange(times, 1, n), returns);
   assertTrue(
       CALCULATOR
           .evaluate(new LocalDateDoubleTimeSeries[] {priceTS, dividendTS})
           .equals(returnTS));
 }
  /**
   * Calculate the accrued premium at the start of a trade
   *
   * @param premiumLegSchedule
   * @param stepinDate The trade effective date
   * @return accrued premium
   */
  private double calculateAccruedInterest(
      final ISDAPremiumLegSchedule premiumLegSchedule, final LocalDate stepinDate) {

    final int n = premiumLegSchedule.getNumPayments();

    // stepinDate is before first accStart or after last accEnd
    if (!stepinDate.isAfter(premiumLegSchedule.getAccStartDate(0))
        || !stepinDate.isBefore(premiumLegSchedule.getAccEndDate(n - 1))) {
      return 0.0;
    }

    int index = premiumLegSchedule.getAccStartDateIndex(stepinDate);
    if (index >= 0) {
      return 0.0; // on accrual start date
    }

    index = -(index + 1); // binary search notation
    if (index == 0) {
      throw new MathException(
          "Error in calculateAccruedInterest - check logic"); // this should never be hit
    }

    return _accuralDayCount.getDayCountFraction(
        premiumLegSchedule.getAccStartDate(index - 1), stepinDate);
  }
 @Test
 public void test() {
   for (int i = 1; i < 30; i++) {
     final LocalDate date = LocalDate.of(2013, 1, i);
     assertEquals(LocalDate.of(2013, 1, 31), ADJUSTER.adjustInto(date));
   }
 }
 @BeforeMethod
 public void setUp() {
   dates = new LocalDate[] {LocalDate.of(2012, 6, 30), LocalDate.of(2012, 7, 1)};
   values = new double[] {1.1d, 2.2d};
   ts = ImmutableLocalDateDoubleTimeSeries.of(dates, values);
   empty = ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES;
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    datePicker = (WeekDatePicker) findViewById(R.id.date_picker);

    datePicker.setDateIndicator(LocalDate.now().plusDays(1), true);
    datePicker.setLimits(LocalDate.now().minusWeeks(1), null);
  }
  @Override
  public Coupon toDerivative(
      final ZonedDateTime date,
      final DoubleTimeSeries<ZonedDateTime> priceIndexTimeSeries,
      final String... yieldCurveNames) {
    ArgumentChecker.notNull(date, "date");
    ArgumentChecker.notNull(yieldCurveNames, "yield curve names");
    ArgumentChecker.isTrue(yieldCurveNames.length > 0, "at least one curve required");
    ArgumentChecker.isTrue(!date.isAfter(getPaymentDate()), "date is after payment date");
    final double lastKnownFixingTime =
        TimeCalculator.getTimeBetween(date, getLastKnownFixingDate());
    final LocalDate dayConversion = date.toLocalDate();
    final String discountingCurveName = yieldCurveNames[0];
    final double paymentTime = TimeCalculator.getTimeBetween(date, getPaymentDate());
    final LocalDate dayFixing = getReferenceEndDate()[1].toLocalDate();
    if (dayConversion.isAfter(dayFixing)) {
      final Double fixedEndIndex1 = priceIndexTimeSeries.getValue(getReferenceEndDate()[1]);

      if (fixedEndIndex1 != null) {
        final Double fixedEndIndex0 = priceIndexTimeSeries.getValue(getReferenceEndDate()[0]);
        final Double fixedEndIndex =
            getWeight() * fixedEndIndex0 + (1 - getWeight()) * fixedEndIndex1;
        final Double fixedRate = (fixedEndIndex / getIndexStartValue() - 1.0);
        return new CouponFixed(
            getCurrency(),
            paymentTime,
            discountingCurveName,
            getPaymentYearFraction(),
            getNotional(),
            payOff(fixedRate));
      }
    }
    final double[] referenceEndTime = new double[2];
    referenceEndTime[0] = TimeCalculator.getTimeBetween(date, _referenceEndDate[0]);
    referenceEndTime[1] = TimeCalculator.getTimeBetween(date, _referenceEndDate[1]);
    final ZonedDateTime naturalPaymentDate =
        getPaymentDate().minusMonths(_monthLag - _conventionalMonthLag);
    final double naturalPaymentEndTime = TimeCalculator.getTimeBetween(date, naturalPaymentDate);
    return new CapFloorInflationZeroCouponInterpolation(
        getCurrency(),
        paymentTime,
        getPaymentYearFraction(),
        getNotional(),
        getPriceIndex(),
        lastKnownFixingTime,
        _indexStartValue,
        referenceEndTime,
        naturalPaymentEndTime,
        _maturity,
        _weight,
        _strike,
        _isCap);
  }
  private InterestRateSwapSecurity createFixedVsLibor3mSwap() {

    InterestRateSwapNotional notional = new InterestRateSwapNotional(Currency.USD, 100_000_000);
    PeriodFrequency freq6m = PeriodFrequency.of(Period.ofMonths(6));
    PeriodFrequency freq3m = PeriodFrequency.of(Period.ofMonths(3));
    Set<ExternalId> calendarUSNY =
        Sets.newHashSet(ExternalId.of(ExternalSchemes.ISDA_HOLIDAY, "USNY"));
    List<InterestRateSwapLeg> legs = new ArrayList<>();

    FixedInterestRateSwapLeg payLeg = new FixedInterestRateSwapLeg();
    payLeg.setNotional(notional);
    payLeg.setDayCountConvention(DayCounts.THIRTY_U_360);
    payLeg.setPaymentDateFrequency(freq6m);
    payLeg.setPaymentDateBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    payLeg.setPaymentDateCalendars(calendarUSNY);
    payLeg.setMaturityDateBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    payLeg.setAccrualPeriodFrequency(freq6m);
    payLeg.setAccrualPeriodBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    payLeg.setAccrualPeriodCalendars(calendarUSNY);
    payLeg.setRate(new Rate(0.0150));
    payLeg.setPayReceiveType(PayReceiveType.PAY);
    legs.add(payLeg);

    FloatingInterestRateSwapLeg receiveLeg = new FloatingInterestRateSwapLeg();
    receiveLeg.setNotional(notional);
    receiveLeg.setDayCountConvention(DayCounts.ACT_360);
    receiveLeg.setPaymentDateFrequency(freq3m);
    receiveLeg.setPaymentDateBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    receiveLeg.setPaymentDateCalendars(calendarUSNY);
    receiveLeg.setMaturityDateBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    receiveLeg.setAccrualPeriodFrequency(freq3m);
    receiveLeg.setAccrualPeriodBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    receiveLeg.setAccrualPeriodCalendars(calendarUSNY);
    receiveLeg.setResetPeriodFrequency(freq3m);
    receiveLeg.setResetPeriodBusinessDayConvention(BusinessDayConventions.MODIFIED_FOLLOWING);
    receiveLeg.setResetPeriodCalendars(calendarUSNY);
    receiveLeg.setFixingDateBusinessDayConvention(BusinessDayConventions.PRECEDING);
    receiveLeg.setFixingDateCalendars(calendarUSNY);
    receiveLeg.setFixingDateOffset(-2);
    receiveLeg.setFloatingRateType(FloatingRateType.IBOR);
    receiveLeg.setFloatingReferenceRateId(InterestRateMockSources.getLiborIndexId());
    receiveLeg.setPayReceiveType(PayReceiveType.RECEIVE);

    legs.add(receiveLeg);

    return new InterestRateSwapSecurity(
        ExternalIdBundle.of(ExternalId.of("UUID", GUIDGenerator.generate().toString())),
        "Fixed vs Libor 3m",
        LocalDate.of(2014, 9, 12), // effective date
        LocalDate.of(2021, 9, 12), // maturity date,
        legs);
  }
  /**
   * Expiry date of Brent crude Futures: The business day preceding the 15th day of the contract
   * month. See
   * http://www.cmegroup.com/trading/energy/crude-oil/brent-crude-oil-last-day_contractSpecs_futures.html#prodType=AME
   * Note: Logic to handle holidays in London is not handled currently
   *
   * @param n n'th expiry date after today
   * @param today valuation date
   * @param holidayCalendar holiday calendar
   * @return True expiry date of the option
   */
  @Override
  public LocalDate getExpiryDate(
      final int n, final LocalDate today, final Calendar holidayCalendar) {
    ArgumentChecker.isTrue(n > 0, "n must be greater than zero; have {}", n);
    ArgumentChecker.notNull(today, "today");
    ArgumentChecker.notNull(holidayCalendar, "holiday calendar");

    LocalDate expiryDate = getExpiryMonth(n, today);

    while (!holidayCalendar.isWorkingDay(expiryDate)) {
      expiryDate = expiryDate.minusDays(1);
    }
    return expiryDate;
  }
 // -------------------------------------------------------------------------
 @Override
 protected void doRun() {
   ToolContext toolContext = getToolContext();
   CommandLine commandLine = getCommandLine();
   boolean verbose = commandLine.hasOption("verbose");
   if ((commandLine.hasOption("today") && commandLine.hasOption("yesterday"))
       || (commandLine.hasOption("date") && commandLine.hasOption("today"))
       || (commandLine.hasOption("date") && commandLine.hasOption("yesterday"))) {
     System.err.println("Can only return today OR yesterday OR date!");
     System.exit(2);
   }
   String ccyStr = commandLine.getOptionValue("ccy");
   try {
     Currency ccy = Currency.of(ccyStr);
     LocalDate date = null;
     if (commandLine.hasOption("yesterday")) {
       date = LocalDate.now().minusDays(1);
     } else if (commandLine.hasOption("today")) {
       date = LocalDate.now();
     } else if (commandLine.hasOption("date")) {
       try {
         date =
             (LocalDate)
                 DateTimeFormatter.BASIC_ISO_DATE.parse(commandLine.getOptionValue("date"));
       } catch (Exception e) {
         System.err.println("Could not parse date, should be YYYYMMDD format");
         System.exit(2);
       }
     } else {
       System.err.println("Must specify either today or yesterday option");
       System.exit(2);
     }
     boolean isHoliday = toolContext.getHolidaySource().isHoliday(date, ccy);
     if (isHoliday) {
       if (verbose) {
         System.out.println("Day was a holiday");
       }
       System.exit(0);
     } else {
       if (verbose) {
         System.out.println("Day was not a holiday");
       }
       System.exit(1);
     }
   } catch (IllegalArgumentException iae) {
     System.err.println("Invalid currency code");
     System.exit(2);
   }
 }
 @Test(dataProvider = "calendars")
 public void test_badDateTimeFieldChrono(Chronology chrono) {
   LocalDate refDate = LocalDate.of(1900, 1, 1);
   ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
   for (Chronology[] clist : data_of_calendars()) {
     Chronology chrono2 = clist[0];
     ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
     TemporalField adjuster = new FixedDateTimeField(cdt2);
     if (chrono != chrono2) {
       try {
         cdt.with(adjuster, 1);
         Assert.fail(
             "DateTimeField doSet should have thrown a ClassCastException"
                 + cdt.getClass()
                 + ", can not be cast to "
                 + cdt2.getClass());
       } catch (ClassCastException cce) {
         // Expected exception; not an error
       }
     } else {
       // Same chronology,
       ChronoLocalDateTime<?> result = cdt.with(adjuster, 1);
       assertEquals(result, cdt2, "DateTimeField doSet failed to replace date");
     }
   }
 }
 /**
  * If effective date is present at the swap level, that is the value to use. If the effective date
  * is null, then there must be effective dates defined on the legs. In this case return the
  * minimum value between the two legs.
  *
  * @return effective date for the swap
  */
 public LocalDate getEffectiveDate() {
   if (_effectiveDate != null) {
     return _effectiveDate;
   } else {
     LocalDate leg1 = getPayLeg().getEffectiveDate();
     LocalDate leg2 = getReceiveLeg().getEffectiveDate();
     if (leg1 == null || leg2 == null) {
       throw new OpenGammaRuntimeException("Cannot find effective date on swap or both legs");
     }
     if (leg1.isBefore(leg2)) {
       return leg1;
     } else {
       return leg2;
     }
   }
 }
  /**
   * Computes the risky present value of a premium payment
   *
   * <p>This mimics the ISDA c code function <b>FeePaymentPVWithTimeLine<b>
   *
   * @param today
   * @param valueDate
   * @param stepinDate
   * @param accStartDate
   * @param accEndDate
   * @param payAccOnDefault
   * @return PV
   */
  private double[] calculateSinglePeriodRPV01(
      final LocalDate today,
      final LocalDate accStartDate,
      final LocalDate accEndDate,
      final LocalDate paymentDate,
      final int obsOffset,
      final ISDACompliantDateYieldCurve yieldCurve,
      final ISDACompliantDateCreditCurve hazardRateCurve) {

    final double accTime = _accuralDayCount.getDayCountFraction(accStartDate, accEndDate);
    double t = _curveDayCount.getDayCountFraction(today, paymentDate);
    double tObsOffset = _curveDayCount.getDayCountFraction(today, accEndDate.plusDays(obsOffset));

    // TODO Do we need this?
    // Compensate Java shortcoming
    if (Double.compare(t, -0.0) == 0) {
      t = 0;
    }
    if (Double.compare(tObsOffset, -0.0) == 0) {
      tObsOffset = 0;
    }

    final double survival = hazardRateCurve.getSurvivalProbability(tObsOffset);
    final double discount = yieldCurve.getDiscountFactor(t);
    return new double[] {accTime * discount * survival, accTime};
  }
 @Test
 public void testCounterparty() {
   FRASecurity security = ExposureFunctionTestHelper.getFRASecurity();
   Trade trade =
       new SimpleTrade(security, BigDecimal.ONE, COUNTERPARTY, LocalDate.now(), OffsetTime.now());
   assertEquals(COUNTERPARTY_ID, EXPOSURE_FUNCTION.getIds(trade).get(0));
 }
 @Test(dataProvider = "calendars")
 public void test_badWithAdjusterChrono(Chronology chrono) {
   LocalDate refDate = LocalDate.of(1900, 1, 1);
   ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
   for (Chronology[] clist : data_of_calendars()) {
     Chronology chrono2 = clist[0];
     ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
     TemporalAdjuster adjuster = new FixedAdjuster(cdt2);
     if (chrono != chrono2) {
       try {
         cdt.with(adjuster);
         Assert.fail(
             "WithAdjuster should have thrown a ClassCastException, "
                 + "required: "
                 + cdt
                 + ", supplied: "
                 + cdt2);
       } catch (ClassCastException cce) {
         // Expected exception; not an error
       }
     } else {
       // Same chronology,
       ChronoLocalDateTime<?> result = cdt.with(adjuster);
       assertEquals(result, cdt2, "WithAdjuster failed to replace date");
     }
   }
 }
 /**
  * If termination date is present at the swap level, that is the value to use. If the termination
  * date is null, then there must be termination dates defined on the legs. In this case return the
  * maximum value between the two legs.
  *
  * @return termination date for the swap
  */
 public LocalDate getUnadjustedMaturityDate() {
   if (_unadjustedMaturityDate != null) {
     return _unadjustedMaturityDate;
   } else {
     LocalDate leg1 = getPayLeg().getUnadjustedMaturityDate();
     LocalDate leg2 = getReceiveLeg().getUnadjustedMaturityDate();
     if (leg1 == null || leg2 == null) {
       throw new OpenGammaRuntimeException("Cannot find termination date on swap or both legs");
     }
     if (leg1.isAfter(leg2)) {
       return leg1;
     } else {
       return leg2;
     }
   }
 }
 @Test(dataProvider = "calendars")
 public void test_badPlusPeriodUnitChrono(Chronology chrono) {
   LocalDate refDate = LocalDate.of(1900, 1, 1);
   ChronoLocalDateTime cdt = chrono.date(refDate).atTime(LocalTime.NOON);
   for (Chronology[] clist : data_of_calendars()) {
     Chronology chrono2 = clist[0];
     ChronoLocalDateTime<?> cdt2 = chrono2.date(refDate).atTime(LocalTime.NOON);
     TemporalUnit adjuster = new FixedPeriodUnit(cdt2);
     if (chrono != chrono2) {
       try {
         cdt.plus(1, adjuster);
         Assert.fail(
             "PeriodUnit.doAdd plus should have thrown a ClassCastException"
                 + cdt
                 + ", can not be cast to "
                 + cdt2);
       } catch (ClassCastException cce) {
         // Expected exception; not an error
       }
     } else {
       // Same chronology,
       ChronoLocalDateTime<?> result = cdt.plus(1, adjuster);
       assertEquals(result, cdt2, "WithAdjuster failed to replace date");
     }
   }
 }
 @Test(expectedExceptions = TimeSeriesException.class)
 public void testWithBadInputs() {
   final LocalDateDoubleTimeSeries ts =
       ImmutableLocalDateDoubleTimeSeries.of(
           new LocalDate[] {LocalDate.ofEpochDay(1)}, new double[] {4});
   CALCULATOR.evaluate(new LocalDateDoubleTimeSeries[] {ts});
 }
 /**
  * {@inheritDoc} If the fixing date is strictly before the conversion date and the fixing rate is
  * not available, an exception is thrown; if the fixing rate is available a fixed coupon is
  * returned. If the fixing date is equal to the conversion date, if the fixing rate is available a
  * fixed coupon is returned, if not a coupon Ibor with spread is returned. If the fixing date is
  * strictly after the conversion date, a coupon Ibor is returned. All the comparisons are between
  * dates without time.
  */
 @Override
 public Coupon toDerivative(
     final ZonedDateTime dateTime, final DoubleTimeSeries<ZonedDateTime> indexFixingTimeSeries) {
   ArgumentChecker.notNull(dateTime, "date");
   final LocalDate dayConversion = dateTime.toLocalDate();
   ArgumentChecker.notNull(indexFixingTimeSeries, "Index fixing time series");
   ArgumentChecker.isTrue(
       !dayConversion.isAfter(getPaymentDate().toLocalDate()), "date is after payment date");
   final double paymentTime = TimeCalculator.getTimeBetween(dateTime, getPaymentDate());
   final LocalDate dayFixing = getFixingDate().toLocalDate();
   if (dayConversion.equals(
       dayFixing)) { // The fixing is on the reference date; if known the fixing is used and if
                     // not, the floating coupon is created.
     final Double fixedRate = indexFixingTimeSeries.getValue(getFixingDate());
     if (fixedRate != null) {
       return new CouponFixed(
           getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), fixedRate);
     }
   }
   if (dayConversion.isAfter(dayFixing)) { // The fixing is required
     final ZonedDateTime rezonedFixingDate =
         getFixingDate().toLocalDate().atStartOfDay(ZoneOffset.UTC);
     final Double fixedRate =
         indexFixingTimeSeries.getValue(rezonedFixingDate); // TODO: remove time from fixing date.
     if (fixedRate == null) {
       throw new OpenGammaRuntimeException(
           "Could not get fixing value for date " + getFixingDate());
     }
     return new CouponFixed(
         getCurrency(), paymentTime, getPaymentYearFraction(), getNotional(), fixedRate);
   }
   final double fixingTime = TimeCalculator.getTimeBetween(dateTime, getFixingDate());
   final double fixingPeriodStartTime =
       TimeCalculator.getTimeBetween(dateTime, getFixingPeriodStartDate());
   final double fixingPeriodEndTime =
       TimeCalculator.getTimeBetween(dateTime, getFixingPeriodEndDate());
   return new CouponIbor(
       getCurrency(),
       paymentTime,
       getPaymentYearFraction(),
       getNotional(),
       fixingTime,
       getIndex(),
       fixingPeriodStartTime,
       fixingPeriodEndTime,
       getFixingPeriodAccrualFactor());
 }
  @SuppressWarnings("deprecation")
  public void testTrade_withPremium() {
    SimpleTrade trade = new SimpleTrade();
    trade.setUniqueId(UniqueId.of("A", "B"));
    trade.setQuantity(BigDecimal.valueOf(12.34d));
    trade.setSecurityLink(new SimpleSecurityLink(ObjectId.of("E", "F")));
    trade.setCounterparty(new SimpleCounterparty(ExternalId.of("G", "H")));
    trade.setTradeDate(LocalDate.of(2011, 1, 5));
    trade.setTradeTime(OffsetTime.parse("14:30+02:00"));

    // set premium
    trade.setPremium(100.00);
    trade.setPremiumCurrency(Currency.USD);
    trade.setPremiumDate(LocalDate.of(2011, 1, 6));
    trade.setPremiumTime(OffsetTime.parse("15:30+02:00"));
    assertEncodeDecodeCycle(Trade.class, trade);
  }
 /**
  * Gets trading months (not static as depends on current date).
  *
  * @param now the date today, not null
  * @return the valid trading months, not null
  */
 private Month[] getTradingMonths(final LocalDate now) {
   // this may need improvements as the year end approaches
   Set<Month> ret = new TreeSet<>();
   ret.add(now.getMonth()); // this month
   ret.add(now.getMonth().plus(1)); // next month
   ret.add(now.getMonth().plus(2)); // next 2 months
   //  February, April, August, and October in next 23 months
   ret.add(Month.FEBRUARY);
   ret.add(Month.APRIL);
   ret.add(Month.AUGUST);
   ret.add(Month.OCTOBER);
   // June and December falling in next 72 month period
   ret.add(Month.JUNE);
   ret.add(Month.DECEMBER);
   // assuming this gives enough valid dates so dont go round to next 12 month period
   return ret.toArray(new Month[0]);
 }
  public void getHistoricalTimeSeriesByExternalIdWithMetaData() throws Exception {
    HistoricalTimeSeriesInfoSearchRequest request =
        new HistoricalTimeSeriesInfoSearchRequest(IDENTIFIERS);
    request.setValidityDate(LocalDate.now());
    request.setDataSource(BBG_DATA_SOURCE);
    request.setDataProvider(CMPL_DATA_PROVIDER);
    request.setDataField(CLOSE_DATA_FIELD);

    HistoricalTimeSeriesInfoSearchResult searchResult = new HistoricalTimeSeriesInfoSearchResult();
    HistoricalTimeSeriesInfoDocument doc = new HistoricalTimeSeriesInfoDocument();
    doc.setUniqueId(UID);

    when(_mockResolver.resolve(
            IDENTIFIERS,
            LocalDate.now(),
            BBG_DATA_SOURCE,
            CMPL_DATA_PROVIDER,
            CLOSE_DATA_FIELD,
            null))
        .thenReturn(new HistoricalTimeSeriesResolutionResult(doc.getInfo()));

    doc.getInfo().setTimeSeriesObjectId(UID.getObjectId());
    searchResult.getDocuments().add(doc);
    when(_mockMaster.search(request)).thenReturn(searchResult);

    ManageableHistoricalTimeSeries hts = new ManageableHistoricalTimeSeries();
    hts.setUniqueId(UID);
    hts.setTimeSeries(randomTimeSeries());
    when(_mockMaster.getTimeSeries(
            UID.getObjectId(),
            VersionCorrection.LATEST,
            HistoricalTimeSeriesGetFilter.ofRange(null, null)))
        .thenReturn(hts);

    HistoricalTimeSeries test =
        _tsSource.getHistoricalTimeSeries(
            IDENTIFIERS, BBG_DATA_SOURCE, CMPL_DATA_PROVIDER, CLOSE_DATA_FIELD);
    verify(_mockMaster, times(1))
        .getTimeSeries(
            UID.getObjectId(),
            VersionCorrection.LATEST,
            HistoricalTimeSeriesGetFilter.ofRange(null, null));

    assertEquals(UID, test.getUniqueId());
  }
 public static LocalDate[] getSettlementDateSchedule(
     final LocalDate[] dates,
     final Calendar calendar,
     final BusinessDayConvention businessDayConvention,
     final int settlementDays) {
   ArgumentChecker.notEmpty(dates, "dates");
   ArgumentChecker.notNull(calendar, "calendar");
   final int n = dates.length;
   final LocalDate[] result = new LocalDate[n];
   for (int i = 0; i < n; i++) {
     LocalDate date = businessDayConvention.adjustDate(calendar, dates[i].plusDays(1));
     for (int j = 0; j < settlementDays; j++) {
       date = businessDayConvention.adjustDate(calendar, date.plusDays(1));
     }
     result[i] = date;
   }
   return result;
 }
 public void testTrade() {
   SimpleTrade trade = new SimpleTrade();
   trade.setUniqueId(UniqueId.of("A", "B"));
   trade.setQuantity(BigDecimal.valueOf(12.34d));
   trade.setSecurityLink(new SimpleSecurityLink(ExternalId.of("E", "F")));
   trade.setCounterparty(new SimpleCounterparty(ExternalId.of("G", "H")));
   trade.setTradeDate(LocalDate.of(2011, 1, 5));
   trade.setTradeTime(OffsetTime.parse("14:30+02:00"));
   assertEncodeDecodeCycle(Trade.class, trade);
 }
 @Override
 /**
  * Given a LocalDate representing the valuation date and an integer representing the n'th expiry
  * after that date, returns a date in the expiry month Used in
  * BloombergFutureUtils.getExpiryCodeForSoybeanFutures()
  */
 public LocalDate getExpiryMonth(final int n, final LocalDate today) {
   ArgumentChecker.isTrue(n > 0, "n must be greater than zero");
   ArgumentChecker.notNull(today, "today");
   LocalDate expiryDate = today;
   for (int m = n; m > 0; m--) {
     expiryDate = getNextExpiryMonth(expiryDate);
   }
   if (expiryDate.getDayOfMonth() > 15) {
     expiryDate = getNextExpiryMonth(expiryDate);
   }
   // set day to first possible - used in getExpiryDate()
   return LocalDate.of(expiryDate.getYear(), expiryDate.getMonth(), 14);
 }
 private HistoricalTimeSeries getAllowedRecentPoints(
     final HistoricalTimeSeriesInfoDocument timeSeriesInfo) {
   final LocalDate from = oldestTimeSeriesAllowed();
   final HistoricalTimeSeries timeSeries =
       getToolContext()
           .getHistoricalTimeSeriesSource()
           .getHistoricalTimeSeries(
               timeSeriesInfo.getUniqueId().toLatest(), from, true, LocalDate.now(), true);
   return timeSeries;
 }
 @Override
 public List<SlackMessagePosted> fetchHistoryOfChannel(
     String channelId, LocalDate day, int numberOfMessages) {
   Map<String, String> params = new HashMap<>();
   params.put("channel", channelId);
   if (day != null) {
     ZonedDateTime start = ZonedDateTime.of(day.atStartOfDay(), ZoneId.of("UTC"));
     ZonedDateTime end =
         ZonedDateTime.of(
             day.atStartOfDay().plusDays(1).minus(1, ChronoUnit.MILLIS), ZoneId.of("UTC"));
     params.put("oldest", convertDateToSlackTimestamp(start));
     params.put("latest", convertDateToSlackTimestamp(end));
   }
   if (numberOfMessages > -1) {
     params.put("count", String.valueOf(numberOfMessages));
   } else {
     params.put("count", String.valueOf(1000));
   }
   return fetchHistoryOfChannel(params);
 }
  public void testFull() {
    SimpleTrade trade = new SimpleTrade();
    trade.setUniqueId(UniqueId.of("A", "B"));
    trade.setQuantity(BigDecimal.valueOf(12.34d));
    trade.setSecurityLink(new SimpleSecurityLink(ExternalId.of("E", "F")));
    trade.setCounterparty(new SimpleCounterparty(ExternalId.of("G", "H")));
    trade.setTradeDate(LocalDate.of(2011, 1, 5));
    trade.setTradeTime(OffsetTime.parse("14:30+02:00"));

    // set premium
    trade.setPremium(100.00);
    trade.setPremiumCurrency(Currency.USD);
    trade.setPremiumDate(LocalDate.of(2011, 1, 6));
    trade.setPremiumTime(OffsetTime.parse("15:30+02:00"));

    // set attributes
    trade.addAttribute("A", "B");
    trade.addAttribute("C", "D");
    assertEncodeDecodeCycle(Trade.class, trade);
  }
Exemple #30
0
 /**
  * Get a LocalDate field (converted from a String internally). Throws a QuandlRuntimeException if
  * it cannot find the field
  *
  * @param fieldName the name of the field
  * @return the field value, or null if the field is null
  */
 public LocalDate getLocalDate(final String fieldName) {
   try {
     if (_jsonObject.isNull(fieldName)) {
       return null;
     } else {
       return LocalDate.parse(_jsonObject.getString(fieldName), DATE_FORMATTER);
     }
   } catch (JSONException ex) {
     throw new QuandlRuntimeException("Cannot find field", ex);
   }
 }