private ViewConfig createIrsPricerConfig() {

    return configureView(
        "IRS Pricer",
        config(
            arguments(
                function(
                    MarketExposureSelector.class,
                    argument(
                        "exposureFunctions",
                        ConfigLink.resolved(InterestRateMockSources.mockExposureFunctions()))),
                function(
                    RootFinderConfiguration.class,
                    argument("rootFinderAbsoluteTolerance", 1e-10),
                    argument("rootFinderRelativeTolerance", 1e-10),
                    argument("rootFinderMaxIterations", 5000)),
                function(
                    DefaultCurrencyPairsFn.class,
                    argument("currencyPairs", ImmutableSet.of(/*no pairs*/ ))),
                function(
                    DefaultCurveNodeConverterFn.class,
                    argument("timeSeriesDuration", RetrievalPeriod.of(Period.ofYears(1)))),
                function(
                    DefaultDiscountingMulticurveBundleFn.class,
                    argument("impliedCurveNames", StringSet.of())))),
        column("Present Value", output(OutputNames.PRESENT_VALUE, InterestRateSwapSecurity.class)),
        column("PV01", output(OutputNames.PV01, InterestRateSwapSecurity.class)));
  }
  @BeforeClass
  public void setUpClass() {

    ImmutableMap<Class<?>, Object> components = generateComponents();
    VersionCorrectionProvider vcProvider = new FixedInstantVersionCorrectionProvider(Instant.now());
    ServiceContext serviceContext =
        ServiceContext.of(components).with(VersionCorrectionProvider.class, vcProvider);
    ThreadLocalServiceContext.init(serviceContext);

    ComponentMap componentMap = ComponentMap.of(components);
    MarketDataSource marketDataSource =
        InterestRateMockSources.createMarketDataSource(MARKET_DATA_DATE, true);
    TestMarketDataFactory marketDataFactory = new TestMarketDataFactory(marketDataSource);
    ConfigLink<CurrencyMatrix> currencyMatrixLink =
        ConfigLink.resolved(componentMap.getComponent(CurrencyMatrix.class));
    List<MarketDataBuilder> builders =
        MarketDataBuilders.standard(componentMap, "dataSource", currencyMatrixLink);

    MarketDataEnvironmentFactory environmentFactory =
        new MarketDataEnvironmentFactory(marketDataFactory, builders);

    _functionRunner = new FunctionRunner(environmentFactory);
    _normalIRFutureOptionFn =
        FunctionModel.build(IRFutureOptionFn.class, normalConfig(), componentMap);
    _blackIRFutureOptionFn =
        FunctionModel.build(IRFutureOptionFn.class, blackConfig(), componentMap);
  }
 private ImmutableMap<Class<?>, Object> generateComponents() {
   ImmutableMap.Builder<Class<?>, Object> builder = ImmutableMap.builder();
   for (Map.Entry<Class<?>, Object> entry :
       InterestRateMockSources.generateBaseComponents().entrySet()) {
     Class<?> key = entry.getKey();
     if (key.equals(SecuritySource.class)) {
       appendSecuritySource((SecuritySource) entry.getValue());
     }
     builder.put(key, entry.getValue());
   }
   return builder.build();
 }
  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);
  }
  private FunctionModelConfig normalConfig() {
    FunctionModelConfig config =
        config(
            arguments(
                function(
                    MarketExposureSelector.class,
                    argument(
                        "exposureFunctions",
                        ConfigLink.resolved(InterestRateMockSources.mockExposureFunctions()))),
                function(
                    RootFinderConfiguration.class,
                    argument("rootFinderAbsoluteTolerance", 1e-9),
                    argument("rootFinderRelativeTolerance", 1e-9),
                    argument("rootFinderMaxIterations", 1000)),
                function(
                    TestIRFutureOptionNormalSurfaceProviderFn.class,
                    argument("moneynessOnPrice", false)),
                function(
                    DefaultCurveNodeConverterFn.class,
                    argument("timeSeriesDuration", RetrievalPeriod.of(Period.ofYears(1))))),
            implementations(
                IRFutureOptionFn.class, DefaultIRFutureOptionFn.class,
                IRFutureOptionCalculatorFactory.class, IRFutureOptionNormalCalculatorFactory.class,
                CurveSpecificationMarketDataFn.class, DefaultCurveSpecificationMarketDataFn.class,
                FXMatrixFn.class, DefaultFXMatrixFn.class,
                CurveDefinitionFn.class, DefaultCurveDefinitionFn.class,
                CurveLabellingFn.class, CurveDefinitionCurveLabellingFn.class,
                CurveSpecificationFn.class, DefaultCurveSpecificationFn.class,
                CurveConstructionConfigurationSource.class,
                    ConfigDBCurveConstructionConfigurationSource.class,
                CurveNodeConverterFn.class, DefaultCurveNodeConverterFn.class,
                HistoricalMarketDataFn.class, DefaultHistoricalMarketDataFn.class,
                FixingsFn.class, DefaultFixingsFn.class,
                MarketDataFn.class, DefaultMarketDataFn.class,
                CurveSelector.class, MarketExposureSelector.class,
                IRFutureOptionNormalSurfaceProviderFn.class,
                    TestIRFutureOptionNormalSurfaceProviderFn.class,
                DiscountingMulticurveCombinerFn.class, CurveSelectorMulticurveBundleFn.class));

    return config;
  }
 private InterestRateFutureSecurity createIRFuture() {
   Expiry expiry =
       new Expiry(ZonedDateTime.of(LocalDate.of(2014, 6, 18), LocalTime.of(0, 0), ZoneOffset.UTC));
   String tradingExchange = "";
   String settlementExchange = "";
   Currency currency = Currency.USD;
   double unitAmount = 1000;
   ExternalId underlyingId = InterestRateMockSources.getLiborIndexId();
   String category = "";
   InterestRateFutureSecurity irFuture =
       new InterestRateFutureSecurity(
           expiry,
           tradingExchange,
           settlementExchange,
           currency,
           unitAmount,
           underlyingId,
           category);
   // Need this for time series lookup
   ExternalId irFutureId = ExternalSchemes.syntheticSecurityId("Test future");
   irFuture.setExternalIdBundle(irFutureId.toBundle());
   return irFuture;
 }
  public void testPricingMethodCanBeCaptured() {

    // Test that we can capture results when we have trades/securities involved
    AvailableOutputs availableOutputs = createAvailableOutputs();
    AvailableImplementations availableImplementations = createAvailableImplementations();

    ViewFactory viewFactory =
        EngineTestUtils.createViewFactory(
            InterestRateMockSources.generateBaseComponents(),
            availableOutputs,
            availableImplementations);

    // Run view
    View view = viewFactory.createView(createIrsPricerConfig(), InterestRateSwapSecurity.class);

    VersionCorrection versionCorrection =
        ThreadLocalServiceContext.getInstance()
            .get(VersionCorrectionProvider.class)
            .getConfigVersionCorrection();
    CycleArguments cycleArguments =
        CycleArguments.builder(InterestRateMockSources.createMarketDataEnvironment())
            .versionCorrection(versionCorrection)
            .captureInputs(true)
            .build();

    Results run = view.run(cycleArguments, ImmutableList.of(createFixedVsLibor3mSwap()));
    Result<Object> pvResult = run.get(0, 0).getResult();
    if (!pvResult.isSuccess()) {
      fail(pvResult.toString());
    }
    Result<Object> pv01Result = run.get(0, 1).getResult();
    if (!pv01Result.isSuccess()) {
      fail(pv01Result.toString());
    }

    // Capture results
    ViewResultsSerializer serializer = new ViewResultsSerializer(run);

    // Write inputs to stream
    ByteArrayOutputStream inputsBaos = new ByteArrayOutputStream(1_000_000);
    serializer.serializeViewInputs(inputsBaos);

    ByteArrayOutputStream outputsBaos = new ByteArrayOutputStream(1_000_000);
    serializer.serializeViewOutputs(outputsBaos);

    ViewResultsDeserializer inputsDeserializer =
        new ViewResultsDeserializer(new ByteArrayInputStream(inputsBaos.toByteArray()));
    ViewInputs viewInputs = inputsDeserializer.deserialize(ViewInputs.class);
    assertThat(viewInputs, is(notNullValue()));

    ViewResultsDeserializer outputsDeserializer =
        new ViewResultsDeserializer(new ByteArrayInputStream(outputsBaos.toByteArray()));
    ViewOutputs viewOutputs = outputsDeserializer.deserialize(ViewOutputs.class);
    assertThat(viewOutputs, is(notNullValue()));

    CapturedResultsLoader loader =
        new CapturedResultsLoader(viewInputs, availableOutputs, availableImplementations);
    loader.addExtraConfigData("EmptyCurrencyMatrix", ConfigItem.of(new SimpleCurrencyMatrix()));
    Results run2 = loader.runViewFromInputs();
    System.out.println(run2);

    Result<Object> pvResult2 = run2.get(0, 0).getResult();
    if (!pvResult2.isSuccess()) {
      fail(pvResult2.toString());
    }
    Result<Object> pv01Result2 = run2.get(0, 1).getResult();
    if (!pv01Result2.isSuccess()) {
      fail(pv01Result2.toString());
    }

    // Check results are same as original ones
    assertThat(pvResult2.getValue(), is(pvResult.getValue()));
    assertThat(pv01Result2.getValue(), is(pv01Result.getValue()));

    // TODO - this should work but seems to be prevented by a Fudge issue
    // assertThat(view2Outputs, is(viewOutputs));
  }
  public void testCurveViewCanBeSavedAndRead() {

    AvailableOutputs availableOutputs = createAvailableOutputs();
    AvailableImplementations availableImplementations = createAvailableImplementations();

    ImmutableMap<Class<?>, Object> components = InterestRateMockSources.generateBaseComponents();

    ViewFactory viewFactory =
        EngineTestUtils.createViewFactory(components, availableOutputs, availableImplementations);

    View view = viewFactory.createView(createCurveBundleConfig("TEST"));

    VersionCorrection versionCorrection =
        ThreadLocalServiceContext.getInstance()
            .get(VersionCorrectionProvider.class)
            .getConfigVersionCorrection();
    CycleArguments cycleArguments =
        CycleArguments.builder(InterestRateMockSources.createMarketDataEnvironment())
            .versionCorrection(versionCorrection)
            .captureInputs(true)
            .build();

    Results run = view.run(cycleArguments);
    Result<Object> result = run.getNonPortfolioResults().get("TEST").getResult();
    if (!result.isSuccess()) {
      fail(result.getFailureMessage());
    }

    // Capture results
    ViewResultsSerializer serializer = new ViewResultsSerializer(run);

    // Write inputs to stream
    ByteArrayOutputStream inputsBaos = new ByteArrayOutputStream(1_000_000);
    serializer.serializeViewInputs(inputsBaos);

    ByteArrayOutputStream outputsBaos = new ByteArrayOutputStream(1_000_000);
    serializer.serializeViewOutputs(outputsBaos);

    ViewResultsDeserializer inputsDeserializer =
        new ViewResultsDeserializer(new ByteArrayInputStream(inputsBaos.toByteArray()));
    ViewInputs viewInputs2 = inputsDeserializer.deserialize(ViewInputs.class);
    assertThat(viewInputs2, is(notNullValue()));

    ViewResultsDeserializer outputsDeserializer =
        new ViewResultsDeserializer(new ByteArrayInputStream(outputsBaos.toByteArray()));
    ViewOutputs viewOutputs = outputsDeserializer.deserialize(ViewOutputs.class);
    assertThat(viewOutputs, is(notNullValue()));

    CapturedResultsLoader loader =
        new CapturedResultsLoader(viewInputs2, availableOutputs, availableImplementations);
    loader.addExtraConfigData("EmptyCurrencyMatrix", ConfigItem.of(new SimpleCurrencyMatrix()));
    Results run2 = loader.runViewFromInputs();

    Result<Object> result2 = run2.getNonPortfolioResults().get("TEST").getResult();
    if (!result2.isSuccess()) {
      fail(result2.toString());
    }

    // Check results are same as original ones
    ViewOutputs view2Outputs =
        ViewOutputs.builder()
            .nonPortfolioResults(run2.getNonPortfolioResults())
            .columnNames(run2.getColumnNames())
            .rows(run2.getRows())
            .build();

    assertThat(result2.getValue(), is(result.getValue()));
    assertThat(view2Outputs, is(viewOutputs));
  }