public virtual void test_explainPresentValue_paymentDateInPast() { SimpleRatesProvider prov = createProvider(FX_RESET_NOTIONAL_EXCHANGE_REC_USD); prov.ValuationDate = VAL_DATE.plusYears(1); DiscountingFxResetNotionalExchangePricer test = new DiscountingFxResetNotionalExchangePricer(); ExplainMapBuilder builder = ExplainMap.builder(); test.explainPresentValue(FX_RESET_NOTIONAL_EXCHANGE_REC_USD, prov, builder); ExplainMap explain = builder.build(); Currency paymentCurrency = FX_RESET_NOTIONAL_EXCHANGE_REC_USD.Currency; Currency notionalCurrency = FX_RESET_NOTIONAL_EXCHANGE_REC_USD.ReferenceCurrency; double notional = FX_RESET_NOTIONAL_EXCHANGE_REC_USD.Notional; assertEquals(explain.get(ExplainKey.ENTRY_TYPE).get(), "FxResetNotionalExchange"); assertEquals(explain.get(ExplainKey.PAYMENT_DATE).get(), FX_RESET_NOTIONAL_EXCHANGE_REC_USD.PaymentDate); assertEquals(explain.get(ExplainKey.PAYMENT_CURRENCY).get(), paymentCurrency); assertEquals(explain.get(ExplainKey.TRADE_NOTIONAL).get().Currency, notionalCurrency); assertEquals(explain.get(ExplainKey.TRADE_NOTIONAL).get().Amount, notional, TOLERANCE); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Currency, paymentCurrency); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Amount, 0d, TOLERANCE); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Currency, paymentCurrency); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Amount, 0d * DISCOUNT_FACTOR, TOLERANCE); }
/// <summary> /// Explain present value for a swap leg. /// </summary> /// <param name="leg"> the swap log </param> /// <param name="provider"> the rates provider </param> /// <returns> the explain PV map </returns> public virtual ExplainMap explainPresentValue(ResolvedSwapLeg leg, RatesProvider provider) { ExplainMapBuilder builder = ExplainMap.builder(); explainPresentValueInternal(leg, provider, builder); return(builder.build()); }
//------------------------------------------------------------------------- public virtual void test_explainPresentValue() { ExplainMap explain = LEG_PRICER.explainPresentValue(CAP_LEG, RATES_PROVIDER, VOLATILITIES); assertEquals(explain.get(ExplainKey.ENTRY_TYPE).get(), "CmsLeg"); assertEquals(explain.get(ExplainKey.PAY_RECEIVE).get().ToString(), "Receive"); assertEquals(explain.get(ExplainKey.PAYMENT_CURRENCY).get().Code, "EUR"); assertEquals(explain.get(ExplainKey.START_DATE).get(), LocalDate.of(2015, 10, 21)); assertEquals(explain.get(ExplainKey.END_DATE).get(), LocalDate.of(2020, 10, 21)); assertEquals(explain.get(ExplainKey.INDEX).get().ToString(), "EUR-EURIBOR-1100-5Y"); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Amount, 39728.51321029542); IList <ExplainMap> paymentPeriods = explain.get(ExplainKey.PAYMENT_PERIODS).get(); assertEquals(paymentPeriods.Count, 5); //Test First Period ExplainMap cmsPeriod0 = paymentPeriods[0]; assertEquals(cmsPeriod0.get(ExplainKey.ENTRY_TYPE).get(), "CmsCapletPeriod"); assertEquals(cmsPeriod0.get(ExplainKey.STRIKE_VALUE).Value, 0.0125d); assertEquals(cmsPeriod0.get(ExplainKey.NOTIONAL).get().Amount, 1000000d); assertEquals(cmsPeriod0.get(ExplainKey.PAYMENT_DATE).get(), LocalDate.of(2016, 10, 21)); assertEquals(cmsPeriod0.get(ExplainKey.DISCOUNT_FACTOR).Value, 0.9820085531995826d); assertEquals(cmsPeriod0.get(ExplainKey.START_DATE).get(), LocalDate.of(2015, 10, 21)); assertEquals(cmsPeriod0.get(ExplainKey.END_DATE).get(), LocalDate.of(2016, 10, 21)); assertEquals(cmsPeriod0.get(ExplainKey.FIXING_DATE).get(), LocalDate.of(2015, 10, 19)); assertEquals(cmsPeriod0.get(ExplainKey.ACCRUAL_YEAR_FRACTION).Value, 1.0166666666666666d); double forwardSwapRate = PRICER_SWAP.parRate(CAP_LEG.CmsPeriods.get(0).UnderlyingSwap, RATES_PROVIDER); assertEquals(cmsPeriod0.get(ExplainKey.FORWARD_RATE).Value, forwardSwapRate); CurrencyAmount pv = PERIOD_PRICER.presentValue(CAP_LEG.CmsPeriods.get(0), RATES_PROVIDER, VOLATILITIES); assertEquals(cmsPeriod0.get(ExplainKey.PRESENT_VALUE).get(), pv); }
private IList <ExplainMap> flatten(ExplainMap explainMap) { IList <ExplainMap> flattenedMap = new List <ExplainMap>(); flatten(explainMap, false, ImmutableMap.of(), Maps.newHashMap(), 0, flattenedMap); return(flattenedMap); }
public virtual void test_explainPresentValue_paymentDateInPast() { SimpleRatesProvider prov = createProvider(NOTIONAL_EXCHANGE_REC_GBP); prov.ValuationDate = VAL_DATE.plusYears(1); DiscountingNotionalExchangePricer test = DiscountingNotionalExchangePricer.DEFAULT; ExplainMapBuilder builder = ExplainMap.builder(); test.explainPresentValue(NOTIONAL_EXCHANGE_REC_GBP, prov, builder); ExplainMap explain = builder.build(); Currency currency = NOTIONAL_EXCHANGE_REC_GBP.Currency; CurrencyAmount notional = NOTIONAL_EXCHANGE_REC_GBP.PaymentAmount; assertEquals(explain.get(ExplainKey.ENTRY_TYPE).get(), "NotionalExchange"); assertEquals(explain.get(ExplainKey.PAYMENT_DATE).get(), NOTIONAL_EXCHANGE_REC_GBP.PaymentDate); assertEquals(explain.get(ExplainKey.PAYMENT_CURRENCY).get(), currency); assertEquals(explain.get(ExplainKey.TRADE_NOTIONAL).get().Currency, currency); assertEquals(explain.get(ExplainKey.TRADE_NOTIONAL).get().Amount, notional.Amount, TOLERANCE); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Amount, 0d, TOLERANCE); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Amount, 0d * DISCOUNT_FACTOR, TOLERANCE); }
public Report runReport(ReportCalculationResults calculationResults, CashFlowReportTemplate reportTemplate) { int tradeCount = calculationResults.CalculationResults.RowCount; if (tradeCount == 0) { throw new System.ArgumentException("Calculation results is empty"); } if (tradeCount > 1) { throw new System.ArgumentException(Messages.format("Unable to show cashflow report for {} trades at once. " + "Please filter the portfolio to a single trade.", tradeCount)); } int columnIdx = calculationResults.Columns.IndexOf(Column.of(Measures.EXPLAIN_PRESENT_VALUE)); if (columnIdx == -1) { throw new System.ArgumentException(Messages.format("Unable to find column for required measure '{}' in calculation results", Measures.EXPLAIN_PRESENT_VALUE)); } //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result = calculationResults.getCalculationResults().get(0, columnIdx); Result <object> result = calculationResults.CalculationResults.get(0, columnIdx); if (result.Failure) { throw new System.ArgumentException(Messages.format("Failure result found for required measure '{}': {}", Measures.EXPLAIN_PRESENT_VALUE, result.Failure.Message)); } ExplainMap explainMap = (ExplainMap)result.Value; return(runReport(explainMap, calculationResults.ValuationDate)); }
private void assertFixedNotionalPaymentEvent(ExplainMap paymentEvent, CurrencyAmount expectedNotional) { assertEquals(paymentEvent.get(ExplainKey.TRADE_NOTIONAL), expectedNotional); assertEquals(paymentEvent.get(ExplainKey.FORECAST_VALUE), expectedNotional); double firstDiscountFactor = paymentEvent.get(ExplainKey.DISCOUNT_FACTOR).Value; //Fixed notional, so PV is notional * DCF CurrencyAmount expectedPv = expectedNotional.multipliedBy(firstDiscountFactor); assertEquals(paymentEvent.get(ExplainKey.PRESENT_VALUE), expectedPv); }
//------------------------------------------------------------------------- /// <summary> /// Explains the present value of the swap product. /// <para> /// This returns explanatory information about the calculation. /// /// </para> /// </summary> /// <param name="swap"> the product </param> /// <param name="provider"> the rates provider </param> /// <returns> the explanatory information </returns> public virtual ExplainMap explainPresentValue(ResolvedSwap swap, RatesProvider provider) { ExplainMapBuilder builder = ExplainMap.builder(); builder.put(ExplainKey.ENTRY_TYPE, "Swap"); foreach (ResolvedSwapLeg leg in swap.Legs) { builder.addListEntryWithIndex(ExplainKey.LEGS, child => legPricer.explainPresentValueInternal(leg, provider, child)); } return(builder.build()); }
//------------------------------------------------------------------------- public virtual void test_explainRate_FixedRateComputation() { FixedRateComputation ro = FixedRateComputation.of(0.0123d); DispatchingRateComputationFn test = DispatchingRateComputationFn.DEFAULT; ExplainMapBuilder builder = ExplainMap.builder(); assertEquals(test.explainRate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, builder), 0.0123d, 0d); ExplainMap built = builder.build(); assertEquals(built.get(ExplainKey.FIXED_RATE), 0.0123d); assertEquals(built.get(ExplainKey.COMBINED_RATE), 0.0123d); }
public virtual void test_explainPresentValue_provider_ended() { ExplainMap explain = PRICER.explainPresentValue(PAYMENT_PAST, PROVIDER); Currency currency = PAYMENT_PAST.Currency; assertEquals(explain.get(ExplainKey.ENTRY_TYPE).get(), "Payment"); assertEquals(explain.get(ExplainKey.PAYMENT_DATE).get(), PAYMENT_PAST.Date); assertEquals(explain.get(ExplainKey.PAYMENT_CURRENCY).get(), currency); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Amount, 0, TOL); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Amount, 0, TOL); }
private Report runReport(ExplainMap explainMap, LocalDate valuationDate) { IList <ExplainMap> flatMap = flatten(explainMap); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.List<com.opengamma.strata.market.explain.ExplainKey<?>> keys = getKeys(flatMap); IList <ExplainKey <object> > keys = getKeys(flatMap); //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: IList <string> headers = keys.Select(this.mapHeader).collect(toImmutableList()); ImmutableTable <int, int, object> data = getData(flatMap, keys); return(CashFlowReport.builder().runInstant(Instant.now()).valuationDate(valuationDate).columnKeys(keys).columnHeaders(headers).data(data).build()); }
public virtual void test_rate() { LocalDate fixingDate = OBSERVATIONS[0].FixingDate; LocalDateDoubleTimeSeries timeSeries = LocalDateDoubleTimeSeries.of(fixingDate, FIXING_VALUES[0]); LocalDateDoubleTimeSeries rates = LocalDateDoubleTimeSeries.builder().put(OBSERVATIONS[1].FixingDate, FIXING_VALUES[1]).put(OBSERVATIONS[2].FixingDate, FIXING_VALUES[2]).put(OBSERVATIONS[3].FixingDate, FIXING_VALUES[3]).build(); IborIndexRates mockIbor = new TestingIborIndexRates(GBP_LIBOR_3M, fixingDate, rates, timeSeries); SimpleRatesProvider prov = new SimpleRatesProvider(fixingDate); prov.IborRates = mockIbor; IList <IborAveragedFixing> fixings = new List <IborAveragedFixing>(); double totalWeightedRate = 0.0d; double totalWeight = 0.0d; for (int i = 0; i < OBSERVATIONS.Length; i++) { IborIndexObservation obs = OBSERVATIONS[i]; IborAveragedFixing fixing = IborAveragedFixing.builder().observation(obs).weight(WEIGHTS[i]).build(); fixings.Add(fixing); totalWeightedRate += FIXING_VALUES[i] * WEIGHTS[i]; totalWeight += WEIGHTS[i]; } double rateExpected = totalWeightedRate / totalWeight; IborAveragedRateComputation ro = IborAveragedRateComputation.of(fixings); ForwardIborAveragedRateComputationFn obsFn = ForwardIborAveragedRateComputationFn.DEFAULT; double rateComputed = obsFn.rate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, prov); assertEquals(rateComputed, rateExpected, TOLERANCE_RATE); // explain ExplainMapBuilder builder = ExplainMap.builder(); assertEquals(obsFn.explainRate(ro, ACCRUAL_START_DATE, ACCRUAL_END_DATE, prov, builder), rateExpected, TOLERANCE_RATE); ExplainMap built = builder.build(); assertEquals(built.get(ExplainKey.OBSERVATIONS).Present, true); assertEquals(built.get(ExplainKey.OBSERVATIONS).get().size(), OBSERVATIONS.Length); for (int i = 0; i < 4; i++) { ExplainMap childMap = built.get(ExplainKey.OBSERVATIONS).get().get(i); assertEquals(childMap.get(ExplainKey.FIXING_DATE), (OBSERVATIONS[i].FixingDate)); assertEquals(childMap.get(ExplainKey.INDEX), GBP_LIBOR_3M); assertEquals(childMap.get(ExplainKey.INDEX_VALUE), FIXING_VALUES[i]); assertEquals(childMap.get(ExplainKey.WEIGHT), WEIGHTS[i]); assertEquals(childMap.get(ExplainKey.FROM_FIXING_SERIES), i == 0 ? true : null); } assertEquals(built.get(ExplainKey.COMBINED_RATE), rateExpected); }
//------------------------------------------------------------------------- /// <summary> /// Explains the present value of the CMS product. /// <para> /// This returns explanatory information about the calculation. /// /// </para> /// </summary> /// <param name="cms"> the CMS product </param> /// <param name="ratesProvider"> the rates provider </param> /// <param name="swaptionVolatilities"> the swaption volatilities </param> /// <returns> the explain PV map </returns> public virtual ExplainMap explainPresentValue(ResolvedCms cms, RatesProvider ratesProvider, SabrSwaptionVolatilities swaptionVolatilities) { ExplainMapBuilder builder = ExplainMap.builder(); builder.put(ExplainKey.ENTRY_TYPE, "CmsSwap"); IList <ExplainMap> legsExplain = new List <ExplainMap>(); legsExplain.Add(cmsLegPricer.explainPresentValue(cms.CmsLeg, ratesProvider, swaptionVolatilities)); if (cms.PayLeg.Present) { legsExplain.Add(payLegPricer.explainPresentValue(cms.PayLeg.get(), ratesProvider)); } builder.put(ExplainKey.LEGS, legsExplain); return(builder.build()); }
private ImmutableTable <int, int, object> getData <T1>(IList <ExplainMap> flatMap, IList <T1> keys) { ImmutableTable.Builder <int, int, object> builder = ImmutableTable.builder(); for (int rowIdx = 0; rowIdx < flatMap.Count; rowIdx++) { ExplainMap rowMap = flatMap[rowIdx]; for (int colIdx = 0; colIdx < keys.Count; colIdx++) { builder.put(rowIdx, colIdx, rowMap.get(keys[colIdx])); } } return(builder.build()); }
private int compareNestedEntries(ExplainMap m1, ExplainMap m2) { Optional <LocalDate> paymentDate1 = m1.get(ExplainKey.PAYMENT_DATE); Optional <LocalDate> paymentDate2 = m2.get(ExplainKey.PAYMENT_DATE); if (paymentDate1.Present && paymentDate1.Present) { return(paymentDate1.get().compareTo(paymentDate2.get())); } if (!paymentDate2.Present) { return(paymentDate1.Present ? 1 : 0); } return(-1); }
//------------------------------------------------------------------------- public virtual void test_explainPresentValue_provider() { CurrencyAmount fvExpected = PRICER.forecastValue(PAYMENT, PROVIDER); CurrencyAmount pvExpected = PRICER.presentValue(PAYMENT, PROVIDER); ExplainMap explain = PRICER.explainPresentValue(PAYMENT, PROVIDER); Currency currency = PAYMENT.Currency; assertEquals(explain.get(ExplainKey.ENTRY_TYPE).get(), "Payment"); assertEquals(explain.get(ExplainKey.PAYMENT_DATE).get(), PAYMENT.Date); assertEquals(explain.get(ExplainKey.PAYMENT_CURRENCY).get(), currency); assertEquals(explain.get(ExplainKey.DISCOUNT_FACTOR).Value, DF, TOL); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Amount, fvExpected.Amount, TOL); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Amount, pvExpected.Amount, TOL); }
//------------------------------------------------------------------------- public virtual void coverage() { DispatchingRateComputationFn test = new DispatchingRateComputationFn(MOCK_IBOR_EMPTY, MOCK_IBOR_INT_EMPTY, MOCK_IBOR_AVE_EMPTY, MOCK_ON_CPD_EMPTY, MOCK_ON_AVE_EMPTY, MOCK_ON_AVE_DLY_EMPTY, MOCK_INF_MON_EMPTY, MOCK_INF_INT_EMPTY, MOCK_INF_BOND_MON_EMPTY, MOCK_INF_BOND_INT_EMPTY); FixedRateComputation @fixed = FixedRateComputation.of(0.0123d); IborRateComputation ibor = IborRateComputation.of(GBP_LIBOR_3M, FIXING_DATE, REF_DATA); IborInterpolatedRateComputation iborInt = IborInterpolatedRateComputation.of(GBP_LIBOR_3M, GBP_LIBOR_6M, FIXING_DATE, REF_DATA); IborAveragedRateComputation iborAvg = IborAveragedRateComputation.of(ImmutableList.of(IborAveragedFixing.of(ibor.Observation))); OvernightCompoundedRateComputation onCpd = OvernightCompoundedRateComputation.of(USD_FED_FUND, ACCRUAL_START_DATE, ACCRUAL_END_DATE, 0, REF_DATA); OvernightAveragedRateComputation onAvg = OvernightAveragedRateComputation.of(USD_FED_FUND, ACCRUAL_START_DATE, ACCRUAL_END_DATE, 0, REF_DATA); OvernightAveragedDailyRateComputation onAvgDly = OvernightAveragedDailyRateComputation.of(USD_FED_FUND, ACCRUAL_START_DATE, ACCRUAL_END_DATE, REF_DATA); InflationMonthlyRateComputation inflationMonthly = InflationMonthlyRateComputation.of(US_CPI_U, ACCRUAL_START_MONTH, ACCRUAL_END_MONTH); InflationInterpolatedRateComputation inflationInterp = InflationInterpolatedRateComputation.of(US_CPI_U, ACCRUAL_START_MONTH, ACCRUAL_END_MONTH, 0.3); InflationEndMonthRateComputation inflationEndMonth = InflationEndMonthRateComputation.of(US_CPI_U, 234d, ACCRUAL_END_MONTH); InflationEndInterpolatedRateComputation inflationEndInterp = InflationEndInterpolatedRateComputation.of(US_CPI_U, 1234d, ACCRUAL_END_MONTH, 0.3); RateComputation mock = mock(typeof(RateComputation)); ignoreThrows(() => test.rateSensitivity(@fixed, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(ibor, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(iborInt, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(iborAvg, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(onCpd, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(onAvg, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(onAvgDly, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(inflationMonthly, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(inflationInterp, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(inflationEndMonth, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(inflationEndInterp, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ignoreThrows(() => test.rateSensitivity(mock, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV)); ExplainMapBuilder explain = ExplainMap.builder(); ignoreThrows(() => test.explainRate(@fixed, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(ibor, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(iborInt, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(iborAvg, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(onCpd, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(onAvg, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(onAvgDly, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(inflationMonthly, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(inflationInterp, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(inflationEndMonth, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(inflationEndInterp, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); ignoreThrows(() => test.explainRate(mock, ACCRUAL_START_DATE, ACCRUAL_END_DATE, MOCK_PROV, explain)); }
public virtual void test_simpleMeasures() { FraTradeCalculationFunction function = new FraTradeCalculationFunction(); ScenarioMarketData md = marketData(); RatesProvider provider = RATES_LOOKUP.marketDataView(md.scenario(0)).ratesProvider(); DiscountingFraTradePricer pricer = DiscountingFraTradePricer.DEFAULT; CurrencyAmount expectedPv = pricer.presentValue(RTRADE, provider); ExplainMap expectedExplainPv = pricer.explainPresentValue(RTRADE, provider); double expectedParRate = pricer.parRate(RTRADE, provider); double expectedParSpread = pricer.parSpread(RTRADE, provider); CashFlows expectedCashFlows = pricer.cashFlows(RTRADE, provider); MultiCurrencyAmount expectedCurrencyExposure = pricer.currencyExposure(RTRADE, provider); CurrencyAmount expectedCurrentCash = pricer.currentCash(RTRADE, provider); ISet <Measure> measures = ImmutableSet.of(Measures.PRESENT_VALUE, Measures.EXPLAIN_PRESENT_VALUE, Measures.PAR_RATE, Measures.PAR_SPREAD, Measures.CASH_FLOWS, Measures.CURRENCY_EXPOSURE, Measures.CURRENT_CASH, Measures.RESOLVED_TARGET); assertThat(function.calculate(TRADE, measures, PARAMS, md, REF_DATA)).containsEntry(Measures.PRESENT_VALUE, Result.success(CurrencyScenarioArray.of(ImmutableList.of(expectedPv)))).containsEntry(Measures.EXPLAIN_PRESENT_VALUE, Result.success(ScenarioArray.of(ImmutableList.of(expectedExplainPv)))).containsEntry(Measures.PAR_RATE, Result.success(DoubleScenarioArray.of(ImmutableList.of(expectedParRate)))).containsEntry(Measures.PAR_SPREAD, Result.success(DoubleScenarioArray.of(ImmutableList.of(expectedParSpread)))).containsEntry(Measures.CASH_FLOWS, Result.success(ScenarioArray.of(ImmutableList.of(expectedCashFlows)))).containsEntry(Measures.CURRENCY_EXPOSURE, Result.success(MultiCurrencyScenarioArray.of(ImmutableList.of(expectedCurrencyExposure)))).containsEntry(Measures.CURRENT_CASH, Result.success(CurrencyScenarioArray.of(ImmutableList.of(expectedCurrentCash)))).containsEntry(Measures.RESOLVED_TARGET, Result.success(RTRADE)); }
//------------------------------------------------------------------------- /// <summary> /// Test explain. /// </summary> public virtual void test_explainPresentValue_ISDA() { ResolvedFra fraExp = RFRA; SimpleRatesProvider prov = createProvider(fraExp); DiscountingFraProductPricer test = DiscountingFraProductPricer.DEFAULT; CurrencyAmount fvExpected = test.forecastValue(fraExp, prov); CurrencyAmount pvExpected = test.presentValue(fraExp, prov); ExplainMap explain = test.explainPresentValue(fraExp, prov); Currency currency = fraExp.Currency; int daysBetween = (int) DAYS.between(fraExp.StartDate, fraExp.EndDate); assertEquals(explain.get(ExplainKey.ENTRY_TYPE).get(), "FRA"); assertEquals(explain.get(ExplainKey.PAYMENT_DATE).get(), fraExp.PaymentDate); assertEquals(explain.get(ExplainKey.START_DATE).get(), fraExp.StartDate); assertEquals(explain.get(ExplainKey.END_DATE).get(), fraExp.EndDate); assertEquals(explain.get(ExplainKey.ACCRUAL_YEAR_FRACTION).Value, fraExp.YearFraction); assertEquals(explain.get(ExplainKey.DAYS).Value, (int?)(int) daysBetween); assertEquals(explain.get(ExplainKey.PAYMENT_CURRENCY).get(), currency); assertEquals(explain.get(ExplainKey.NOTIONAL).get().Amount, fraExp.Notional, TOLERANCE); assertEquals(explain.get(ExplainKey.TRADE_NOTIONAL).get().Amount, fraExp.Notional, TOLERANCE); assertEquals(explain.get(ExplainKey.OBSERVATIONS).get().size(), 1); ExplainMap explainObs = explain.get(ExplainKey.OBSERVATIONS).get().get(0); IborRateComputation floatingRate = (IborRateComputation) fraExp.FloatingRate; assertEquals(explainObs.get(ExplainKey.INDEX).get(), floatingRate.Index); assertEquals(explainObs.get(ExplainKey.FIXING_DATE).get(), floatingRate.FixingDate); assertEquals(explainObs.get(ExplainKey.INDEX_VALUE).Value, FORWARD_RATE, TOLERANCE); assertEquals(explainObs.get(ExplainKey.FROM_FIXING_SERIES).HasValue, false); assertEquals(explain.get(ExplainKey.DISCOUNT_FACTOR).Value, DISCOUNT_FACTOR, TOLERANCE); assertEquals(explain.get(ExplainKey.FIXED_RATE).Value, fraExp.FixedRate, TOLERANCE); assertEquals(explain.get(ExplainKey.PAY_OFF_RATE).Value, FORWARD_RATE, TOLERANCE); assertEquals(explain.get(ExplainKey.COMBINED_RATE).Value, FORWARD_RATE, TOLERANCE); assertEquals(explain.get(ExplainKey.UNIT_AMOUNT).Value, fvExpected.Amount / fraExp.Notional, TOLERANCE); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.FORECAST_VALUE).get().Amount, fvExpected.Amount, TOLERANCE); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Currency, currency); assertEquals(explain.get(ExplainKey.PRESENT_VALUE).get().Amount, pvExpected.Amount, TOLERANCE); // test via FraTrade DiscountingFraTradePricer testTrade = new DiscountingFraTradePricer(test); assertEquals(testTrade.explainPresentValue(RFRA_TRADE, prov), test.explainPresentValue(RFRA, prov)); }
//------------------------------------------------------------------------- /// <summary> /// Test for the case where publication lag=1, effective offset=0 (USD conventions) and no cutoff period. </summary> public virtual void rateFedFundNoCutOff() { OvernightIndexRates mockRates = mock(typeof(OvernightIndexRates)); when(mockRates.Index).thenReturn(USD_FED_FUND); SimpleRatesProvider simpleProv = new SimpleRatesProvider(mockRates); for (int i = 0; i < USD_OBS.Length; i++) { when(mockRates.rate(USD_OBS[i])).thenReturn(FIXING_RATES[i]); } OvernightAveragedRateComputation ro = OvernightAveragedRateComputation.of(USD_FED_FUND, START_DATE, END_DATE, 0, REF_DATA); // Accrual dates = fixing dates ForwardOvernightAveragedRateComputationFn obsFn = ForwardOvernightAveragedRateComputationFn.DEFAULT; double accrualFactorTotal = 0.0d; double accruedRate = 0.0d; int indexLast = 5; // Fixing in the observation period are from 1 to 5 (inclusive) for (int i = 1; i <= indexLast; i++) { LocalDate endDate = USD_OBS[i].MaturityDate; double af = USD_FED_FUND.DayCount.yearFraction(FIXING_DATES[i], endDate); accrualFactorTotal += af; accruedRate += FIXING_RATES[i] * af; } double rateExpected = accruedRate / accrualFactorTotal; double rateComputed = obsFn.rate(ro, DUMMY_ACCRUAL_START_DATE, DUMMY_ACCRUAL_END_DATE, simpleProv); assertEquals(rateExpected, rateComputed, TOLERANCE_RATE); // explain ExplainMapBuilder builder = ExplainMap.builder(); double explainedRate = obsFn.explainRate(ro, DUMMY_ACCRUAL_START_DATE, DUMMY_ACCRUAL_END_DATE, simpleProv, builder); assertEquals(explainedRate, rateExpected, TOLERANCE_RATE); ExplainMap built = builder.build(); assertEquals(built.get(ExplainKey.OBSERVATIONS).Present, false); assertEquals(built.get(ExplainKey.COMBINED_RATE).Value.doubleValue(), rateExpected, TOLERANCE_RATE); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unchecked") private void flatten(com.opengamma.strata.market.explain.ExplainMap explainMap, boolean parentVisible, java.util.Map<com.opengamma.strata.market.explain.ExplainKey<?>, Object> parentRow, java.util.Map<com.opengamma.strata.market.explain.ExplainKey<?>, Object> currentRow, int level, java.util.List<com.opengamma.strata.market.explain.ExplainMap> accumulator) private void flatten <T1, T2>(ExplainMap explainMap, bool parentVisible, IDictionary <T1> parentRow, IDictionary <T2> currentRow, int level, IList <ExplainMap> accumulator) { bool hasParentFlow = currentRow.ContainsKey(ExplainKey.FORECAST_VALUE); bool isFlow = explainMap.get(ExplainKey.PAYMENT_DATE).Present; bool visible = parentVisible || isFlow; //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: ISet <ExplainKey <IList <ExplainMap> > > nestedListKeys = explainMap.Map.Keys.Where(k => explainMap.get(k).get().GetType().IsAssignableFrom(typeof(System.Collections.IList))).Select(k => (ExplainKey <IList <ExplainMap> >)k).collect(toImmutableSet()); // Populate the base data //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: for (java.util.Map.Entry<com.opengamma.strata.market.explain.ExplainKey<?>, Object> entry : explainMap.getMap().entrySet()) foreach (KeyValuePair <ExplainKey <object>, object> entry in explainMap.Map.entrySet()) { //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.market.explain.ExplainKey<?> key = entry.getKey(); ExplainKey <object> key = entry.Key; if (nestedListKeys.Contains(key)) { continue; } if (key.Equals(ExplainKey.FORECAST_VALUE)) { if (hasParentFlow) { // Collapsed rows, so flow must be the same as we already have continue; } else if (isFlow) { // This is first child flow row, so flow is equal to, and replaces, calculated amount currentRow.Remove(INTERIM_AMOUNT_KEY); } } //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.market.explain.ExplainKey<?> mappedKey = mapKey(key, isFlow); ExplainKey <object> mappedKey = mapKey(key, isFlow); object mappedValue = mapValue(mappedKey, entry.Value, level); if (isFlow) { currentRow[mappedKey] = mappedValue; } else { if (!currentRow.ContainsKey(mappedKey)) { currentRow.Add(mappedKey, mappedValue); } } } // Repeat the inherited entries from the parent row if this row hasn't overridden them INHERITED_KEYS.Where(parentRow.containsKey).ForEach(inheritedKey => currentRow.putIfAbsent(inheritedKey, parentRow[inheritedKey])); if (nestedListKeys.Count > 0) { IList <ExplainMap> nestedListEntries = nestedListKeys.stream().flatMap(k => explainMap.get(k).get().stream()).sorted(this.compareNestedEntries).collect(Collectors.toList()); if (nestedListEntries.Count == 1) { // Soak it up into this row flatten(nestedListEntries[0], visible, currentRow, currentRow, level, accumulator); } else { // Add child rows foreach (ExplainMap nestedListEntry in nestedListEntries) { flatten(nestedListEntry, visible, currentRow, Maps.newHashMap(), level + 1, accumulator); } // Add parent row after child rows (parent flows are a result of the children) if (visible) { accumulator.Add(ExplainMap.of(currentRow)); } } } else { if (visible) { accumulator.Add(ExplainMap.of(currentRow)); } } }
// XCcy swap with exchange of notional and FX Reset on the USD leg public virtual void test_XCcyFixedInitialNotional() { DiscountingSwapTradePricer pricer = swapPricer(); //Create an MTM swap with initial notional override double notional = 1_000_000d; ResolvedSwapTrade fixedNotionalMtmTrade = getMtmTrade(true, true, true, notional).resolve(REF_DATA); ExplainMap explainMap = pricer.explainPresentValue(fixedNotionalMtmTrade, provider()); CurrencyAmount fixedNotional = CurrencyAmount.of(Currency.USD, notional); ExplainMap fixedNotionalMtmLeg = explainMap.get(ExplainKey.LEGS).get().get(1); IList <ExplainMap> events = fixedNotionalMtmLeg.get(ExplainKey.PAYMENT_EVENTS).get(); //First two payment events should use fixed initial notional ExplainMap firstPaymentEvent = events[0]; assertFixedNotionalPaymentEvent(firstPaymentEvent, fixedNotional.negated()); ExplainMap secondPaymentEvent = events[1]; assertFixedNotionalPaymentEvent(secondPaymentEvent, fixedNotional); //First coupon also uses fixed notional ExplainMap firstCoupon = fixedNotionalMtmLeg.get(ExplainKey.PAYMENT_PERIODS).get().get(0); assertEquals(firstCoupon.get(ExplainKey.TRADE_NOTIONAL), fixedNotional); assertEquals(firstCoupon.get(ExplainKey.NOTIONAL), fixedNotional); //Sum of all pv amounts which are impacted by overriding the first period with a fixed notional CurrencyAmount firstPaymentPv = firstPaymentEvent.get(ExplainKey.PRESENT_VALUE).get(); CurrencyAmount secondPaymentPv = secondPaymentEvent.get(ExplainKey.PRESENT_VALUE).get(); CurrencyAmount firstCouponPv = firstCoupon.get(ExplainKey.PRESENT_VALUE).get(); CurrencyAmount fixedNotionalImpactedEventsPv = firstPaymentPv.plus(secondPaymentPv).plus(firstCouponPv); //---------------------------------------------------------------------------------------------------------- //Build identical trade but with no fixed notional ResolvedSwapTrade noFixedNotionalMtmTrade = getMtmTrade(true, true, true, null).resolve(REF_DATA); ExplainMap noFixedNotionalMtmLeg = pricer.explainPresentValue(noFixedNotionalMtmTrade, provider()).get(ExplainKey.LEGS).get().get(1); //Sum the pvs for the same combination of payments and events that are impacted by fixed notional in first trade //JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter: CurrencyAmount noFixedNotionalEventsPv = noFixedNotionalMtmLeg.get(ExplainKey.PAYMENT_EVENTS).get().subList(0, 2).Select(payment => payment.get(ExplainKey.PRESENT_VALUE).get()).Aggregate(CurrencyAmount.zero(Currency.USD), CurrencyAmount::plus); CurrencyAmount noFixedNotionalCouponsPv = noFixedNotionalMtmLeg.get(ExplainKey.PAYMENT_PERIODS).get().get(0).get(ExplainKey.PRESENT_VALUE).get(); CurrencyAmount noFixedNotionalImpactedEventsPv = noFixedNotionalCouponsPv.plus(noFixedNotionalEventsPv); //---------------------------------------------------------------------------------------------------------- //PV difference of the events impacted by fixing notional CurrencyAmount paymentsPvDifference = fixedNotionalImpactedEventsPv.minus(noFixedNotionalImpactedEventsPv); //Calculate PV of the full trades MultiCurrencyAmount fixedNotionalLegPv = pricer.presentValue(fixedNotionalMtmTrade, provider()); MultiCurrencyAmount noFixedNotionalLegPv = pricer.presentValue(noFixedNotionalMtmTrade, provider()); //EUR PV should not have changed assertEquals(fixedNotionalLegPv.getAmount(Currency.EUR).Amount, noFixedNotionalLegPv.getAmount(Currency.EUR).Amount, TOLERANCE_PV); //Difference in USD PV should be equal the difference in PV of the three events impacted by the initial notional //All else should remain equal CurrencyAmount tradePvDifference = fixedNotionalLegPv.getAmount(Currency.USD).minus(noFixedNotionalLegPv.getAmount(Currency.USD)); assertEquals(tradePvDifference.Amount, paymentsPvDifference.Amount, TOLERANCE_PV); }