/// <summary> /// Test that ScenarioArrays containing a single value are unwrapped when calling calculateAsync(). /// </summary> public virtual void unwrapScenarioResultsAsync() { ScenarioArray <string> scenarioResult = ScenarioArray.of("foo"); ScenarioResultFunction fn = new ScenarioResultFunction(TestingMeasures.PRESENT_VALUE, scenarioResult); CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL); CalculationTask task = CalculationTask.of(TARGET, fn, cell); Column column = Column.of(TestingMeasures.PRESENT_VALUE); CalculationTasks tasks = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column)); // using the direct executor means there is no need to close/shutdown the runner CalculationTaskRunner test = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); Listener listener = new Listener(); MarketData marketData = MarketData.empty(VAL_DATE); test.calculateAsync(tasks, marketData, REF_DATA, listener); CalculationResult calculationResult1 = listener.result; //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result1 = calculationResult1.getResult(); Result <object> result1 = calculationResult1.Result; // Check the result contains the string directly, not the result wrapping the string assertThat(result1).hasValue("foo"); test.calculateMultiScenarioAsync(tasks, ScenarioMarketData.of(1, marketData), REF_DATA, listener); CalculationResult calculationResult2 = listener.result; //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result2 = calculationResult2.getResult(); Result <object> result2 = calculationResult2.Result; // Check the result contains the scenario result wrapping the string assertThat(result2).hasValue(scenarioResult); }
/// <summary> /// Tests the full set of results against a golden copy. /// </summary> public virtual void testResults() { IList <Trade> trades = ImmutableList.of(createTrade1()); IList <Column> columns = ImmutableList.of(Column.of(Measures.LEG_INITIAL_NOTIONAL), Column.of(Measures.PRESENT_VALUE), Column.of(Measures.LEG_PRESENT_VALUE), Column.of(Measures.PV01_CALIBRATED_SUM), Column.of(Measures.ACCRUED_INTEREST)); ExampleMarketDataBuilder marketDataBuilder = ExampleMarketData.builder(); LocalDate valuationDate = LocalDate.of(2009, 7, 31); CalculationRules rules = CalculationRules.of(StandardComponents.calculationFunctions(), Currency.USD, marketDataBuilder.ratesLookup(valuationDate)); MarketData marketData = marketDataBuilder.buildSnapshot(valuationDate); // using the direct executor means there is no need to close/shutdown the runner CalculationTasks tasks = CalculationTasks.of(rules, trades, columns, REF_DATA); MarketDataRequirements reqs = tasks.requirements(REF_DATA); MarketData calibratedMarketData = marketDataFactory().create(reqs, MarketDataConfig.empty(), marketData, REF_DATA); CalculationTaskRunner runner = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); Results results = runner.calculate(tasks, calibratedMarketData, REF_DATA); ReportCalculationResults calculationResults = ReportCalculationResults.of(valuationDate, trades, columns, results); TradeReportTemplate reportTemplate = ExampleData.loadTradeReportTemplate("swap-report-regression-test-template"); TradeReport tradeReport = TradeReport.of(calculationResults, reportTemplate); string expectedResults = ExampleData.loadExpectedResults("swap-report"); TradeReportRegressionTestUtils.assertAsciiTableEquals(tradeReport.toAsciiTableString(), expectedResults); }
/// <summary> /// End-to-end test for curve calibration and round-tripping that uses the <seealso cref="MarketDataFactory"/> /// to calibrate a curve and calculate PVs for the instruments at the curve nodes. /// /// This tests the full pipeline of market data functions: /// - Par rates /// - Curve group (including calibration) /// - Individual curves /// - Discount factors /// </summary> public virtual void roundTripFraAndFixedFloatSwap() { // Configuration and market data for the curve --------------------------------- string fra3x6 = "fra3x6"; string fra6x9 = "fra6x9"; string swap1y = "swap1y"; string swap2y = "swap2y"; string swap3y = "swap3y"; FraCurveNode fra3x6Node = fraNode(3, fra3x6); FraCurveNode fra6x9Node = fraNode(6, fra6x9); FixedIborSwapCurveNode swap1yNode = fixedIborSwapNode(Tenor.TENOR_1Y, swap1y); FixedIborSwapCurveNode swap2yNode = fixedIborSwapNode(Tenor.TENOR_2Y, swap2y); FixedIborSwapCurveNode swap3yNode = fixedIborSwapNode(Tenor.TENOR_3Y, swap3y); IDictionary <ObservableId, double> parRateData = ImmutableMap.builder <ObservableId, double>().put(id(fra3x6), 0.0037).put(id(fra6x9), 0.0054).put(id(swap1y), 0.005).put(id(swap2y), 0.0087).put(id(swap3y), 0.012).build(); LocalDate valuationDate = date(2011, 3, 8); // Build the trades from the node instruments MarketData quotes = ImmutableMarketData.of(valuationDate, parRateData); Trade fra3x6Trade = fra3x6Node.trade(1d, quotes, REF_DATA); Trade fra6x9Trade = fra6x9Node.trade(1d, quotes, REF_DATA); Trade swap1yTrade = swap1yNode.trade(1d, quotes, REF_DATA); Trade swap2yTrade = swap2yNode.trade(1d, quotes, REF_DATA); Trade swap3yTrade = swap3yNode.trade(1d, quotes, REF_DATA); IList <Trade> trades = ImmutableList.of(fra3x6Trade, fra6x9Trade, swap1yTrade, swap2yTrade, swap3yTrade); IList <CurveNode> nodes = ImmutableList.of(fra3x6Node, fra6x9Node, swap1yNode, swap2yNode, swap3yNode); CurveGroupName groupName = CurveGroupName.of("Curve Group"); CurveName curveName = CurveName.of("FRA and Fixed-Float Swap Curve"); InterpolatedNodalCurveDefinition curveDefn = InterpolatedNodalCurveDefinition.builder().name(curveName).xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.ZERO_RATE).dayCount(DayCounts.ACT_ACT_ISDA).nodes(nodes).interpolator(CurveInterpolators.DOUBLE_QUADRATIC).extrapolatorLeft(CurveExtrapolators.FLAT).extrapolatorRight(CurveExtrapolators.FLAT).build(); RatesCurveGroupDefinition groupDefn = RatesCurveGroupDefinition.builder().name(groupName).addCurve(curveDefn, Currency.USD, IborIndices.USD_LIBOR_3M).build(); MarketDataConfig marketDataConfig = MarketDataConfig.builder().add(groupName, groupDefn).build(); // Rules for market data and calculations --------------------------------- RatesMarketDataLookup ratesLookup = RatesMarketDataLookup.of(groupDefn); CalculationRules calculationRules = CalculationRules.of(functions(), Currency.USD, ratesLookup); // Calculate the results and check the PVs for the node instruments are zero ---------------------- IList <Column> columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE)); MarketData knownMarketData = MarketData.of(date(2011, 3, 8), parRateData); // using the direct executor means there is no need to close/shutdown the runner CalculationTasks tasks = CalculationTasks.of(calculationRules, trades, columns, REF_DATA); MarketDataRequirements reqs = tasks.requirements(REF_DATA); MarketData enhancedMarketData = marketDataFactory().create(reqs, marketDataConfig, knownMarketData, REF_DATA); CalculationTaskRunner runner = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); Results results = runner.calculate(tasks, enhancedMarketData, REF_DATA); results.Cells.ForEach(this.checkPvIsZero); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeOut = 5000) public void interruptHangingResultsListener() throws InterruptedException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void interruptHangingResultsListener() { HangingFunction fn = new HangingFunction(); CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL); CalculationTask task = CalculationTask.of(TARGET, fn, cell); Column column = Column.of(TestingMeasures.PRESENT_VALUE); CalculationTasks tasks = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column)); ExecutorService executor = Executors.newSingleThreadExecutor(); try { CalculationTaskRunner test = CalculationTaskRunner.of(executor); MarketData marketData = MarketData.empty(VAL_DATE); AtomicBoolean shouldNeverComplete = new AtomicBoolean(); AtomicBoolean interrupted = new AtomicBoolean(); AtomicReference <Exception> thrown = new AtomicReference <Exception>(); ResultsListener listener = new ResultsListener(); test.calculateAsync(tasks, marketData, REF_DATA, listener); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); Thread thread = new Thread(() => { try { listener.result(); shouldNeverComplete.set(true); } catch (Exception ex) { interrupted.set(Thread.CurrentThread.Interrupted); thrown.set(ex); } latch.Signal(); }); // run the thread, wait until properly started, then interrupt, wait until properly handled thread.Start(); while (!fn.started) { } thread.Interrupt(); latch.await(); // asserts assertEquals(interrupted.get(), true); assertEquals(shouldNeverComplete.get(), false); assertEquals(thrown.get() is Exception, true); assertEquals(thrown.get().Cause is InterruptedException, true); } finally { executor.shutdownNow(); } }
//------------------------------------------------------------------------- //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(timeOut = 5000) public void interruptHangingCalculate() throws InterruptedException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void interruptHangingCalculate() { HangingFunction fn = new HangingFunction(); CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL); CalculationTask task = CalculationTask.of(TARGET, fn, cell); Column column = Column.of(TestingMeasures.PRESENT_VALUE); CalculationTasks tasks = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column)); // using the direct executor means there is no need to close/shutdown the runner CalculationTaskRunner test = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); MarketData marketData = MarketData.empty(VAL_DATE); AtomicBoolean shouldNeverThrow = new AtomicBoolean(); AtomicBoolean interrupted = new AtomicBoolean(); AtomicReference <Results> results = new AtomicReference <Results>(); System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1); Thread thread = new Thread(() => { try { Results result = test.calculate(tasks, marketData, REF_DATA); interrupted.set(Thread.CurrentThread.Interrupted); results.set(result); } catch (Exception) { shouldNeverThrow.set(true); } latch.Signal(); }); // run the thread, wait until properly started, then interrupt, wait until properly handled thread.Start(); while (!fn.started) { } thread.Interrupt(); latch.await(); // asserts assertEquals(interrupted.get(), true); assertEquals(shouldNeverThrow.get(), false); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result00 = results.get().get(0, 0); Result <object> result00 = results.get().get(0, 0); assertEquals(result00.Failure, true); assertEquals(result00.Failure.Reason, FailureReason.CALCULATION_FAILED); assertEquals(result00.Failure.Message.Contains("Runtime interrupted"), true); }
//------------------------------------------------------------------------- /// <summary> /// Tests that running an empty list of tasks completes and returns a set of results with zero rows. /// </summary> public virtual void runWithNoTasks() { Column column = Column.of(TestingMeasures.PRESENT_VALUE); CalculationTasks tasks = CalculationTasks.of(ImmutableList.of(), ImmutableList.of(column)); // using the direct executor means there is no need to close/shutdown the runner CalculationTaskRunner test = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); MarketData marketData = MarketData.empty(VAL_DATE); Results results = test.calculate(tasks, marketData, REF_DATA); assertThat(results.RowCount).isEqualTo(0); assertThat(results.ColumnCount).isEqualTo(1); assertThat(results.Columns.get(0).Measure).isEqualTo(TestingMeasures.PRESENT_VALUE); }
/// <summary> /// Test that ScenarioArrays containing multiple values are an error. /// </summary> public virtual void unwrapMultipleScenarioResults() { ScenarioArray <string> scenarioResult = ScenarioArray.of("foo", "bar"); ScenarioResultFunction fn = new ScenarioResultFunction(TestingMeasures.PAR_RATE, scenarioResult); CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PAR_RATE, NATURAL); CalculationTask task = CalculationTask.of(TARGET, fn, cell); Column column = Column.of(TestingMeasures.PAR_RATE); CalculationTasks tasks = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column)); // using the direct executor means there is no need to close/shutdown the runner CalculationTaskRunner test = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); MarketData marketData = MarketData.empty(VAL_DATE); assertThrowsIllegalArg(() => test.calculate(tasks, marketData, REF_DATA)); }
//------------------------------------------------------------------------- // Test that ScenarioArrays containing a single value are unwrapped. //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void unwrapScenarioResults() throws Exception public virtual void unwrapScenarioResults() { ScenarioArray <string> scenarioResult = ScenarioArray.of("foo"); ScenarioResultFunction fn = new ScenarioResultFunction(TestingMeasures.PRESENT_VALUE, scenarioResult); CalculationTaskCell cell = CalculationTaskCell.of(0, 0, TestingMeasures.PRESENT_VALUE, NATURAL); CalculationTask task = CalculationTask.of(TARGET, fn, cell); Column column = Column.of(TestingMeasures.PRESENT_VALUE); CalculationTasks tasks = CalculationTasks.of(ImmutableList.of(task), ImmutableList.of(column)); // using the direct executor means there is no need to close/shutdown the runner CalculationTaskRunner test = CalculationTaskRunner.of(MoreExecutors.newDirectExecutorService()); MarketData marketData = MarketData.empty(VAL_DATE); Results results1 = test.calculate(tasks, marketData, REF_DATA); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result1 = results1.get(0, 0); Result <object> result1 = results1.get(0, 0); // Check the result contains the string directly, not the result wrapping the string assertThat(result1).hasValue("foo"); Results results2 = test.calculateMultiScenario(tasks, ScenarioMarketData.of(1, marketData), REF_DATA); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result2 = results2.get(0, 0); Result <object> result2 = results2.get(0, 0); // Check the result contains the scenario result wrapping the string assertThat(result2).hasValue(scenarioResult); ResultsListener resultsListener = new ResultsListener(); test.calculateAsync(tasks, marketData, REF_DATA, resultsListener); CompletableFuture <Results> future = resultsListener.Future; // The future is guaranteed to be done because everything is running on a single thread assertThat(future.Done).True; Results results3 = future.get(); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result3 = results3.get(0, 0); Result <object> result3 = results3.get(0, 0); // Check the result contains the string directly, not the result wrapping the string assertThat(result3).hasValue("foo"); }
/// <summary> /// Creates a calculation runner capable of performing calculations, specifying the executor. /// <para> /// It is the callers responsibility to manage the life-cycle of the executor. /// /// </para> /// </summary> /// <param name="executor"> the executor to use </param> /// <returns> the calculation runner </returns> internal static DefaultCalculationRunner of(ExecutorService executor) { return(new DefaultCalculationRunner(CalculationTaskRunner.of(executor))); }