// create notional exchange events when no FxReset private static ImmutableList <SwapPaymentEvent> createStandardEvents(IList <NotionalPaymentPeriod> payPeriods, LocalDate initialExchangePaymentDate, bool initialExchange, bool intermediateExchange, bool finalExchange) { NotionalPaymentPeriod firstPeriod = payPeriods[0]; ImmutableList.Builder <SwapPaymentEvent> events = ImmutableList.builder(); if (initialExchange) { events.add(NotionalExchange.of(firstPeriod.NotionalAmount.negated(), initialExchangePaymentDate)); } if (intermediateExchange) { for (int i = 0; i < payPeriods.Count - 1; i++) { NotionalPaymentPeriod period1 = payPeriods[i]; NotionalPaymentPeriod period2 = payPeriods[i + 1]; if (period1.NotionalAmount.Amount != period2.NotionalAmount.Amount) { events.add(NotionalExchange.of(period1.NotionalAmount.minus(period2.NotionalAmount), period1.PaymentDate)); } } } if (finalExchange) { NotionalPaymentPeriod lastPeriod = payPeriods[payPeriods.Count - 1]; events.add(NotionalExchange.of(lastPeriod.NotionalAmount, lastPeriod.PaymentDate)); } return(events.build()); }
// variable fixed rate private static SwapTrade parseVariableRates(SwapTrade trade, IList <CsvRow> variableRows) { ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder(); foreach (CsvRow row in variableRows) { LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD)); row.findValue(FIXED_RATE_FIELD).map(str => LoaderUtils.parseDoublePercent(str)).ifPresent(fixedRate => stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(fixedRate)))); } ImmutableList <ValueStep> varRates = stepBuilder.build(); if (varRates.Empty) { return(trade); } // adjust the trade, inserting the variable rates ImmutableList.Builder <SwapLeg> legBuilder = ImmutableList.builder(); foreach (SwapLeg swapLeg in trade.Product.Legs) { RateCalculationSwapLeg leg = (RateCalculationSwapLeg)swapLeg; if (leg.Calculation is FixedRateCalculation) { FixedRateCalculation baseCalc = (FixedRateCalculation)leg.Calculation; FixedRateCalculation calc = baseCalc.toBuilder().rate(ValueSchedule.of(baseCalc.Rate.InitialValue, varRates)).build(); legBuilder.add(leg.toBuilder().calculation(calc).build()); } else { legBuilder.add(leg); } } return(replaceLegs(trade, legBuilder.build())); }
//------------------------------------------------------------------------- public BoundSurfaceInterpolator bind(DoubleArray xValues, DoubleArray yValues, DoubleArray zValues) { // single loop around all parameters, collecting data int size = xValues.size(); int countUniqueX = 0; double[] uniqueX = new double[size]; double[] tempY = new double[size]; double[] tempZ = new double[size]; ImmutableList.Builder <BoundCurveInterpolator> yInterpBuilder = ImmutableList.builder(); int i = 0; while (i < size) { double currentX = xValues.get(i); uniqueX[countUniqueX] = currentX; if (countUniqueX > 0 && uniqueX[countUniqueX - 1] > uniqueX[countUniqueX]) { throw new System.ArgumentException("Array of x-values must be sorted"); } int countSameX = 0; while (i < size && xValues.get(i) == currentX) { tempY[countSameX] = yValues.get(i); tempZ[countSameX] = zValues.get(i); if (countSameX > 0 && tempY[countSameX - 1] >= tempY[countSameX]) { throw new System.ArgumentException("Array of y-values must be sorted and unique within x-values"); } countSameX++; i++; } // create a curve for the same x-value if (countSameX == 1) { // when there is only one point, there is not enough data for a curve // so the value must be returned without using the configured interpolator or extrapolator yInterpBuilder.add(new ConstantCurveInterpolator(tempZ[0])); } else { // normal case, where the curve is created DoubleArray yValuesSameX = DoubleArray.ofUnsafe(Arrays.copyOf(tempY, countSameX)); DoubleArray zValuesSameX = DoubleArray.ofUnsafe(Arrays.copyOf(tempZ, countSameX)); yInterpBuilder.add(yInterpolator.bind(yValuesSameX, zValuesSameX, yExtrapolatorLeft, yExtrapolatorRight)); } countUniqueX++; } if (countUniqueX == 1) { throw new System.ArgumentException("Surface interpolator requires at least two different x-values"); } DoubleArray uniqueXArray = DoubleArray.ofUnsafe(Arrays.copyOf(uniqueX, countUniqueX)); BoundCurveInterpolator[] yInterps = yInterpBuilder.build().toArray(new BoundCurveInterpolator[0]); return(new Bound(xInterpolator, xExtrapolatorLeft, xExtrapolatorRight, size, uniqueXArray, yInterps)); }
// parses the alternate names //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unchecked") private static <R extends Named> com.google.common.collect.ImmutableList<ExtendedEnum<? extends R>> parseChildren(com.opengamma.strata.collect.io.IniFile config, Class<R> enumType) //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: private static ImmutableList<ExtendedEnum<R>> parseChildren<R>(IniFile config, Type<R> enumType) where R : Named { if (!config.contains(TYPES_SECTION)) { return ImmutableList.of(); } PropertySet section = config.section(TYPES_SECTION); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.google.common.collect.ImmutableList.Builder<ExtendedEnum<? extends R>> builder = com.google.common.collect.ImmutableList.builder(); ImmutableList.Builder<ExtendedEnum<R>> builder = ImmutableList.builder(); foreach (string key in section.keys()) { Type cls; try { cls = RenameHandler.INSTANCE.lookupType(key); } catch (Exception ex) { throw new System.ArgumentException("Unable to find extended enum class: " + key, ex); } System.Reflection.MethodInfo method; try { method = cls.GetMethod("extendedEnum"); } catch (Exception ex) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: throw new System.ArgumentException("Unable to find extendedEnum() method on class: " + cls.FullName, ex); } if (!method.ReturnType.Equals(typeof(ExtendedEnum))) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: throw new System.ArgumentException("Method extendedEnum() does not return ExtendedEnum on class: " + cls.FullName); } //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: ExtendedEnum<?> result; ExtendedEnum<object> result; try { result = typeof(ExtendedEnum).cast(method.invoke(null)); } catch (Exception ex) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: throw new System.ArgumentException("Unable to call extendedEnum() method on class: " + cls.FullName, ex); } if (!enumType.IsAssignableFrom(result.Type)) { //JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method: throw new System.ArgumentException("Method extendedEnum() returned an ExtendedEnum with an incompatible type on class: " + cls.FullName); } //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: builder.add((ExtendedEnum<? extends R>) result); builder.add((ExtendedEnum<R>) result); } return builder.build(); }
// variable notional private static SwapTrade parseVariableNotional(SwapTrade trade, IList <CsvRow> variableRows) { // parse notionals ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder(); foreach (CsvRow row in variableRows) { LocalDate date = LoaderUtils.parseDate(row.getValue(START_DATE_FIELD)); row.findValue(NOTIONAL_FIELD).map(str => LoaderUtils.parseDouble(str)).ifPresent(notional => stepBuilder.add(ValueStep.of(date, ValueAdjustment.ofReplace(notional)))); } ImmutableList <ValueStep> varNotionals = stepBuilder.build(); if (varNotionals.Empty) { return(trade); } // adjust the trade, inserting the variable notionals ImmutableList.Builder <SwapLeg> legBuilder = ImmutableList.builder(); foreach (SwapLeg swapLeg in trade.Product.Legs) { RateCalculationSwapLeg leg = (RateCalculationSwapLeg)swapLeg; NotionalSchedule notionalSchedule = leg.NotionalSchedule.toBuilder().amount(ValueSchedule.of(leg.NotionalSchedule.Amount.InitialValue, varNotionals)).build(); legBuilder.add(leg.toBuilder().notionalSchedule(notionalSchedule).build()); } return(replaceLegs(trade, legBuilder.build())); }
// creates the tasks for a single target private static IList <CalculationTask> createTargetTasks <T1>(CalculationTarget resolvedTarget, int rowIndex, CalculationFunction <T1> function, IList <Column> columns) { // create the cells and group them ListMultimap <CalculationParameters, CalculationTaskCell> grouped = ArrayListMultimap.create(); for (int colIndex = 0; colIndex < columns.Count; colIndex++) { Column column = columns[colIndex]; Measure measure = column.Measure; ReportingCurrency reportingCurrency = column.ReportingCurrency.orElse(ReportingCurrency.NATURAL); CalculationTaskCell cell = CalculationTaskCell.of(rowIndex, colIndex, measure, reportingCurrency); // group to find cells that can be shared, with same mappings and params (minus reporting currency) CalculationParameters @params = column.Parameters.filter(resolvedTarget, measure); grouped.put(@params, cell); } // build tasks ImmutableList.Builder <CalculationTask> taskBuilder = ImmutableList.builder(); foreach (CalculationParameters @params in grouped.Keys) { taskBuilder.add(CalculationTask.of(resolvedTarget, function, @params, grouped.get(@params))); } return(taskBuilder.build()); }
//------------------------------------------------------------------------- /// <summary> /// Combines two or more instances to form a single sensitivity instance. /// <para> /// The result will store information about the separate instances allowing it to be <seealso cref="#split()"/> later. /// /// </para> /// </summary> /// <param name="marketDataName"> the combined name of the market data that the sensitivity refers to </param> /// <param name="sensitivities"> the sensitivity instances to combine, two or more </param> /// <returns> the combined sensitivity object </returns> public static UnitParameterSensitivity combine <T1>(MarketDataName <T1> marketDataName, params UnitParameterSensitivity[] sensitivities) { ArgChecker.notEmpty(sensitivities, "sensitivities"); if (sensitivities.Length < 2) { throw new System.ArgumentException("At least two sensitivity instances must be specified"); } int size = Stream.of(sensitivities).mapToInt(s => s.ParameterCount).sum(); double[] combinedSensitivities = new double[size]; ImmutableList.Builder <ParameterMetadata> combinedMeta = ImmutableList.builder(); ImmutableList.Builder <ParameterSize> split = ImmutableList.builder(); int count = 0; for (int i = 0; i < sensitivities.Length; i++) { UnitParameterSensitivity sens = sensitivities[i]; Array.Copy(sens.Sensitivity.toArrayUnsafe(), 0, combinedSensitivities, count, sens.ParameterCount); combinedMeta.addAll(sens.ParameterMetadata); split.add(ParameterSize.of(sens.MarketDataName, sens.ParameterCount)); count += sens.ParameterCount; } return(new UnitParameterSensitivity(marketDataName, combinedMeta.build(), DoubleArray.ofUnsafe(combinedSensitivities), split.build())); }
static IsdaCompliantIndexCurveCalibratorTest() { ImmutableList.Builder <StandardId> legalEntityIdsbuilder = ImmutableList.builder(); ImmutableMarketDataBuilder marketDataBuilder = ImmutableMarketData.builder(VALUATION_DATE); ImmutableMarketDataBuilder marketDataPsBuilder = ImmutableMarketData.builder(VALUATION_DATE); for (int?i = 0; i.Value < INDEX_SIZE; ++i) { StandardId legalEntityId = StandardId.of("OG", "ABC" + i.ToString()); LegalEntityInformation information = DEFAULTED_NAMES.contains(i) ? LegalEntityInformation.isDefaulted(legalEntityId) : LegalEntityInformation.isNotDefaulted(legalEntityId); legalEntityIdsbuilder.add(legalEntityId); marketDataBuilder.addValue(LegalEntityInformationId.of(legalEntityId), information); marketDataPsBuilder.addValue(LegalEntityInformationId.of(legalEntityId), information); } LEGAL_ENTITIES = legalEntityIdsbuilder.build(); ImmutableList.Builder <CdsIndexIsdaCreditCurveNode> curveNodesBuilder = ImmutableList.builder(); ImmutableList.Builder <CdsIndexIsdaCreditCurveNode> curveNodesPsBuilder = ImmutableList.builder(); for (int i = 0; i < NUM_PILLARS; ++i) { QuoteId id = QuoteId.of(StandardId.of("OG", INDEX_TENORS[i].ToString())); CdsTemplate temp = TenorCdsTemplate.of(INDEX_TENORS[i], CONVENTION); curveNodesBuilder.add(CdsIndexIsdaCreditCurveNode.ofPointsUpfront(temp, id, INDEX_ID, LEGAL_ENTITIES, COUPON)); curveNodesPsBuilder.add(CdsIndexIsdaCreditCurveNode.ofParSpread(temp, id, INDEX_ID, LEGAL_ENTITIES)); marketDataBuilder.addValue(id, PUF_QUOTES[i]); marketDataPsBuilder.addValue(id, PS_QUOTES[i]); } CURVE_NODES = curveNodesBuilder.build(); MARKET_DATA = marketDataBuilder.build(); CURVE_NODES_PS = curveNodesPsBuilder.build(); MARKET_DATA_PS = marketDataPsBuilder.build(); }
public virtual void test_volatilities() { BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification @base = BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecification.builder().name(VOL_NAME).currencyPair(GBP_USD).dayCount(ACT_365F).nodes(NODES).timeInterpolator(PCHIP).strikeInterpolator(DOUBLE_QUADRATIC).build(); LocalDate date = LocalDate.of(2017, 9, 25); ZonedDateTime dateTime = date.atStartOfDay().atZone(ZoneId.of("Europe/London")); DoubleArray parameters = DoubleArray.of(0.19, 0.15, 0.13, 0.14, 0.14, 0.11, 0.09, 0.09, 0.11, 0.09, 0.07, 0.07); BlackFxOptionSurfaceVolatilities computed = @base.volatilities(dateTime, parameters, REF_DATA); DaysAdjustment expOffset = DaysAdjustment.ofBusinessDays(-2, NY_LO); double[] expiries = new double[STRIKES.Count * TENORS.Count]; double[] strikes = new double[STRIKES.Count * TENORS.Count]; ImmutableList.Builder <ParameterMetadata> paramMetadata = ImmutableList.builder(); for (int i = 0; i < TENORS.Count; ++i) { double expiry = ACT_365F.relativeYearFraction(date, expOffset.adjust(BDA.adjust(SPOT_OFFSET.adjust(date, REF_DATA).plus(TENORS[i]), REF_DATA), REF_DATA)); for (int j = 0; j < STRIKES.Count; ++j) { paramMetadata.add(FxVolatilitySurfaceYearFractionParameterMetadata.of(expiry, SimpleStrike.of(STRIKES[j]), GBP_USD)); expiries[STRIKES.Count * i + j] = expiry; strikes[STRIKES.Count * i + j] = STRIKES[j]; } } InterpolatedNodalSurface surface = InterpolatedNodalSurface.ofUnsorted(Surfaces.blackVolatilityByExpiryStrike(VOL_NAME.Name, ACT_365F).withParameterMetadata(paramMetadata.build()), DoubleArray.ofUnsafe(expiries), DoubleArray.ofUnsafe(strikes), parameters, GridSurfaceInterpolator.of(PCHIP, DOUBLE_QUADRATIC)); BlackFxOptionSurfaceVolatilities expected = BlackFxOptionSurfaceVolatilities.of(VOL_NAME, GBP_USD, dateTime, surface); assertEquals(computed, expected); }
public ImmutableList <RateAccrualPeriod> createAccrualPeriods(Schedule accrualSchedule, Schedule paymentSchedule, ReferenceData refData) { // avoid null stub definitions if there are stubs FixedRateStubCalculation initialStub = firstNonNull(this.initialStub, FixedRateStubCalculation.NONE); FixedRateStubCalculation finalStub = firstNonNull(this.finalStub, FixedRateStubCalculation.NONE); Optional <SchedulePeriod> scheduleInitialStub = accrualSchedule.InitialStub; Optional <SchedulePeriod> scheduleFinalStub = accrualSchedule.FinalStub; // resolve data by schedule DoubleArray resolvedRates = rate.resolveValues(accrualSchedule); // build accrual periods ImmutableList.Builder <RateAccrualPeriod> accrualPeriods = ImmutableList.builder(); for (int i = 0; i < accrualSchedule.size(); i++) { SchedulePeriod period = accrualSchedule.getPeriod(i); double yearFraction = period.yearFraction(dayCount, accrualSchedule); // handle stubs RateComputation rateComputation; if (scheduleInitialStub.Present && scheduleInitialStub.get() == period) { rateComputation = initialStub.createRateComputation(resolvedRates.get(i)); } else if (scheduleFinalStub.Present && scheduleFinalStub.get() == period) { rateComputation = finalStub.createRateComputation(resolvedRates.get(i)); } else { rateComputation = FixedRateComputation.of(resolvedRates.get(i)); } accrualPeriods.add(new RateAccrualPeriod(period, yearFraction, rateComputation)); } return(accrualPeriods.build()); }
// create notional exchange events when FxReset specified private static ImmutableList <SwapPaymentEvent> createFxResetEvents(IList <NotionalPaymentPeriod> payPeriods, LocalDate initialExchangeDate, bool initialExchange, bool intermediateExchange, bool finalExchange) { ImmutableList.Builder <SwapPaymentEvent> events = ImmutableList.builder(); for (int i = 0; i < payPeriods.Count; i++) { NotionalPaymentPeriod period = payPeriods[i]; LocalDate startPaymentDate = (i == 0 ? initialExchangeDate : payPeriods[i - 1].PaymentDate); bool includeStartPayment = i == 0 ? initialExchange : intermediateExchange; bool includeEndPayment = i == payPeriods.Count - 1 ? finalExchange : intermediateExchange; if (period.FxResetObservation.Present) { FxIndexObservation observation = period.FxResetObservation.get(); // notional out at start of period if (includeStartPayment) { events.add(FxResetNotionalExchange.of(period.NotionalAmount.negated(), startPaymentDate, observation)); } // notional in at end of period if (includeEndPayment) { events.add(FxResetNotionalExchange.of(period.NotionalAmount, period.PaymentDate, observation)); } } else { // handle weird swap where only some periods have FX reset // notional out at start of period if (includeStartPayment) { events.add(NotionalExchange.of(CurrencyAmount.of(period.Currency, -period.NotionalAmount.Amount), startPaymentDate)); } // notional in at end of period if (includeEndPayment) { events.add(NotionalExchange.of(CurrencyAmount.of(period.Currency, period.NotionalAmount.Amount), period.PaymentDate)); } } } return(events.build()); }
// formats a single row private ImmutableList <string> formatRow(R report, int rowIdx, ReportOutputFormat format) { ImmutableList.Builder <string> tableRow = ImmutableList.builder(); for (int colIdx = 0; colIdx < report.ColumnCount; colIdx++) { tableRow.add(formatData(report, rowIdx, colIdx, format)); } return(tableRow.build()); }
protected internal static ImmutableList <Period> createNormalEquivMaturities() { ImmutableList.Builder <Period> builder = ImmutableList.builder(); for (int i = 0; i < NUM_BLACK_MATURITIES; ++i) { builder.add(Period.ofYears(CAP_BLACK_END_TIMES[i])); } return(builder.build()); }
/// <summary> /// Applies a perturbation to each underlying. /// <para> /// The updated list of underlying instances is returned. /// /// </para> /// </summary> /// @param <R> the type of the underlying </param> /// <param name="underlyingType"> the type of the parameterized data at the specified index </param> /// <param name="perturbation"> the perturbation to apply </param> /// <returns> a parameterized data instance based on this with the specified parameter altered </returns> /// <exception cref="IndexOutOfBoundsException"> if the index is invalid </exception> public IList <R> withPerturbation <R>(Type <R> underlyingType, ParameterPerturbation perturbation) where R : ParameterizedData { ImmutableList.Builder <R> builder = ImmutableList.builder(); for (int i = 0; i < underlyings.Length; i++) { builder.add(underlyingWithPerturbation(i, underlyingType, perturbation)); } return(builder.build()); }
static IsdaHomogenousCdsIndexProductPricerTest() { ImmutableList.Builder <StandardId> builder = ImmutableList.builder(); for (int i = 0; i < 97; ++i) { builder.add(StandardId.of("OG", i.ToString())); } LEGAL_ENTITIES = builder.build(); }
// formats the ASCII table private ImmutableList <ImmutableList <string> > formatAsciiTable(R report) { ImmutableList.Builder <ImmutableList <string> > table = ImmutableList.builder(); for (int rowIdx = 0; rowIdx < report.RowCount; rowIdx++) { table.add(formatRow(report, rowIdx, ReportOutputFormat.ASCII_TABLE)); } return(table.build()); }
/// <summary> /// Obtains an instance using a function to create the entries. /// <para> /// The function is passed the scenario index and returns the value for that index. /// /// </para> /// </summary> /// @param <T> the type of the value </param> /// <param name="scenarioCount"> the number of scenarios </param> /// <param name="valueFunction"> the function used to obtain each value </param> /// <returns> an instance initialized using the function </returns> /// <exception cref="IllegalArgumentException"> is size is zero or less </exception> public static DefaultScenarioArray <T> of <T>(int scenarioCount, System.Func <int, T> valueFunction) { ArgChecker.notNegativeOrZero(scenarioCount, "scenarioCount"); ImmutableList.Builder <T> builder = ImmutableList.builder(); for (int i = 0; i < scenarioCount; i++) { builder.add(valueFunction(i)); } return(new DefaultScenarioArray <T>(builder.build())); }
// parse a single line internal static ImmutableList <string> parseLine(string line, int lineNumber, char separator) { if (line.Length == 0 || line.StartsWith("#", StringComparison.Ordinal) || line.StartsWith(";", StringComparison.Ordinal)) { return(ImmutableList.of()); } ImmutableList.Builder <string> builder = ImmutableList.builder(); int start = 0; string terminated = line + separator; int nextSeparator = terminated.IndexOf(separator, start); while (nextSeparator >= 0) { string possible = terminated.Substring(start, nextSeparator - start).Trim(); // handle convention where ="xxx" means xxx if (possible.StartsWith("=\"", StringComparison.Ordinal)) { start++; possible = possible.Substring(1); } // handle quoting where "xxx""yyy" means xxx"yyy if (possible.StartsWith("\"", StringComparison.Ordinal)) { while (true) { if (possible.Substring(1).Replace("\"\"", "").EndsWith("\"", StringComparison.Ordinal)) { possible = possible.Substring(1, (possible.Length - 1) - 1).Replace("\"\"", "\""); break; } else { nextSeparator = terminated.IndexOf(separator, nextSeparator + 1); if (nextSeparator < 0) { throw new System.ArgumentException("Mismatched quotes in CSV on line " + lineNumber); } possible = terminated.Substring(start, nextSeparator - start).Trim(); } } } builder.add(possible); start = nextSeparator + 1; nextSeparator = terminated.IndexOf(separator, start); } ImmutableList <string> fields = builder.build(); if (!hasContent(fields)) { return(ImmutableList.of()); } return(fields); }
//------------------------------------------------------------------------- /// <summary> /// Parses the FpML document extracting the trades. /// <para> /// This parses the specified FpML root element, using the map of references. /// The FpML specification uses references to link one part of the XML to another. /// For example, if one part of the XML has {@code <foo id="fooId">}, the references /// map will contain an entry mapping "fooId" to the parsed element {@code <foo>}. /// /// </para> /// </summary> /// <param name="fpmlRootEl"> the source of the FpML XML document </param> /// <param name="references"> the map of id/href to referenced element </param> /// <returns> the parsed trades </returns> /// <exception cref="RuntimeException"> if a parse error occurred </exception> public IList <Trade> parseTrades(XmlElement fpmlRootEl, IDictionary <string, XmlElement> references) { FpmlDocument document = new FpmlDocument(fpmlRootEl, references, ourPartySelector, tradeInfoParser, refData); IList <XmlElement> tradeEls = document.FpmlRoot.getChildren("trade"); ImmutableList.Builder <Trade> builder = ImmutableList.builder(); foreach (XmlElement tradeEl in tradeEls) { builder.add(parseTrade(document, tradeEl)); } return(builder.build()); }
// find the party identifiers private static IList <string> findPartyIds(XmlElement party) { ImmutableList.Builder <string> builder = ImmutableList.builder(); foreach (XmlElement child in party.getChildren("partyId")) { if (child.hasContent()) { builder.add(child.Content); } } return(builder.build()); }
//------------------------------------------------------------------------- /// <summary> /// Updates a parameter on the specified list of underlying instances. /// <para> /// The correct underlying is identified and updated, with the list returned. /// /// </para> /// </summary> /// @param <R> the type of the underlying </param> /// <param name="underlyingType"> the type of the parameterized data at the specified index </param> /// <param name="parameterIndex"> the zero-based index of the parameter to change </param> /// <param name="newValue"> the new value for the specified parameter </param> /// <returns> a parameterized data instance based on this with the specified parameter altered </returns> /// <exception cref="IndexOutOfBoundsException"> if the index is invalid </exception> public IList <R> withParameter <R>(Type <R> underlyingType, int parameterIndex, double newValue) where R : ParameterizedData { int underlyingIndex = findUnderlyingIndex(parameterIndex); ImmutableList.Builder <R> builder = ImmutableList.builder(); for (int i = 0; i < underlyings.Length; i++) { ParameterizedData underlying = underlyings[i]; if (i == underlyingIndex) { int adjustment = lookup[underlyingIndex]; ParameterizedData perturbed = underlying.withParameter(parameterIndex - adjustment, newValue); builder.add(underlyingType.cast(perturbed)); } else { builder.add(underlyingType.cast(underlying)); } } return(builder.build()); }
// parses the swap internal Swap parseSwap(FpmlDocument document, XmlElement tradeEl, TradeInfoBuilder tradeInfoBuilder) { XmlElement swapEl = tradeEl.getChild("swap"); ImmutableList <XmlElement> legEls = swapEl.getChildren("swapStream"); ImmutableList.Builder <SwapLeg> legsBuilder = ImmutableList.builder(); foreach (XmlElement legEl in legEls) { // calculation XmlElement calcPeriodAmountEl = legEl.getChild("calculationPeriodAmount"); XmlElement calcEl = calcPeriodAmountEl.findChild("calculation").orElse(XmlElement.ofChildren("calculation", ImmutableList.of())); PeriodicSchedule accrualSchedule = parseSwapAccrualSchedule(legEl, document); PaymentSchedule paymentSchedule = parseSwapPaymentSchedule(legEl, calcEl, document); // known amount or rate calculation Optional <XmlElement> knownAmountOptEl = calcPeriodAmountEl.findChild("knownAmountSchedule"); if (knownAmountOptEl.Present) { XmlElement knownAmountEl = knownAmountOptEl.get(); document.validateNotPresent(legEl, "stubCalculationPeriodAmount"); document.validateNotPresent(legEl, "resetDates"); // pay/receive and counterparty PayReceive payReceive = document.parsePayerReceiver(legEl, tradeInfoBuilder); ValueSchedule amountSchedule = parseSchedule(knownAmountEl, document); // build legsBuilder.add(KnownAmountSwapLeg.builder().payReceive(payReceive).accrualSchedule(accrualSchedule).paymentSchedule(paymentSchedule).amount(amountSchedule).currency(document.parseCurrency(knownAmountEl.getChild("currency"))).build()); } else { document.validateNotPresent(calcEl, "fxLinkedNotionalSchedule"); document.validateNotPresent(calcEl, "futureValueNotional"); // pay/receive and counterparty PayReceive payReceive = document.parsePayerReceiver(legEl, tradeInfoBuilder); NotionalSchedule notionalSchedule = parseSwapNotionalSchedule(legEl, calcEl, document); RateCalculation calculation = parseSwapCalculation(legEl, calcEl, accrualSchedule, document); // build legsBuilder.add(RateCalculationSwapLeg.builder().payReceive(payReceive).accrualSchedule(accrualSchedule).paymentSchedule(paymentSchedule).notionalSchedule(notionalSchedule).calculation(calculation).build()); } } return(Swap.of(legsBuilder.build())); }
//------------------------------------------------------------------------ // parses the CSV file format private static CsvFile parseAll(IList <string> lines, int lineIndex, char separator, ImmutableList <string> headers, ImmutableMap <string, int> searchHeaders) { ImmutableList.Builder <CsvRow> rows = ImmutableList.builder(); for (int i = lineIndex; i < lines.Count; i++) { ImmutableList <string> fields = parseLine(lines[i], i + 1, separator); if (!fields.Empty) { rows.add(new CsvRow(headers, searchHeaders, i + 1, fields)); } } return(new CsvFile(headers, searchHeaders, rows.build())); }
// Converts an FpML 'Schedule' to a {@code ValueSchedule}. private ValueSchedule parseSchedule(XmlElement scheduleEl, double initialValue, ValueStepSequence seq, FpmlDocument document) { IList <XmlElement> stepEls = scheduleEl.getChildren("step"); ImmutableList.Builder <ValueStep> stepBuilder = ImmutableList.builder(); foreach (XmlElement stepEl in stepEls) { LocalDate stepDate = document.parseDate(stepEl.getChild("stepDate")); double stepValue = document.parseDecimal(stepEl.getChild("stepValue")); stepBuilder.add(ValueStep.of(stepDate, ValueAdjustment.ofReplace(stepValue))); } return(ValueSchedule.builder().initialValue(initialValue).steps(stepBuilder.build()).stepSequence(seq).build()); }
//------------------------------------------------------------------------- /// <summary> /// Converts this schedule to a schedule where all the start and end dates are /// adjusted using the specified adjuster. /// <para> /// The result will have the same number of periods, but each start date and /// end date is replaced by the adjusted date as returned by the adjuster. /// The unadjusted start date and unadjusted end date of each period will not be changed. /// /// </para> /// </summary> /// <param name="adjuster"> the adjuster to use </param> /// <returns> the adjusted schedule </returns> public Schedule toAdjusted(DateAdjuster adjuster) { // implementation needs to return 'this' if unchanged to optimize downstream code bool adjusted = false; ImmutableList.Builder <SchedulePeriod> builder = ImmutableList.builder(); foreach (SchedulePeriod period in periods) { SchedulePeriod adjPeriod = period.toAdjusted(adjuster); builder.add(adjPeriod); adjusted |= (adjPeriod != period); } return(adjusted ? new Schedule(builder.build(), frequency, rollConvention) : this); }
StructType(Program program, StructElement element) : base(p) { super(program, new UserElementMixin(element)); this.structType = element.type(); ImmutableList.Builder <Field> fieldsBuilder = ImmutableList.builder(); for (FieldElement fieldElement : element.fields()) { fieldsBuilder.add(new Field(fieldElement)); } this.fields = fieldsBuilder.build(); }
public ImmutableList <RateAccrualPeriod> createAccrualPeriods(Schedule accrualSchedule, Schedule paymentSchedule, ReferenceData refData) { // resolve data by schedule DoubleArray resolvedGearings = firstNonNull(gearing, ALWAYS_1).resolveValues(accrualSchedule); // build accrual periods ImmutableList.Builder <RateAccrualPeriod> accrualPeriods = ImmutableList.builder(); for (int i = 0; i < accrualSchedule.size(); i++) { SchedulePeriod period = accrualSchedule.getPeriod(i); // inflation does not use a day count, so year fraction is 1d accrualPeriods.add(new RateAccrualPeriod(period, 1d, createRateComputation(period, i), resolvedGearings.get(i), 0d, NegativeRateMethod.ALLOW_NEGATIVE)); } return(accrualPeriods.build()); }
public virtual void check_equivalent_notional() { ImmutableRatesProvider multicurve = CALIBRATOR.calibrate(GROUP_DEFINITION_PV_SENSI, MARKET_QUOTES, REF_DATA); // Create notional equivalent for a basis trade ResolvedSwapTrade trade = ThreeLegBasisSwapConventions.EUR_FIXED_1Y_EURIBOR_3M_EURIBOR_6M.createTrade(VALUATION_DATE, Period.ofMonths(7), Tenor.TENOR_6Y, BuySell.SELL, 1_000_000, 0.03, REF_DATA).resolve(REF_DATA); PointSensitivities pts = PRICER_SWAP_TRADE.presentValueSensitivity(trade, multicurve); CurrencyParameterSensitivities ps = multicurve.parameterSensitivity(pts); CurrencyParameterSensitivities mqs = MQSC.sensitivity(ps, multicurve); CurrencyParameterSensitivities notionalEquivalent = NEC.notionalEquivalent(mqs, multicurve); // Check metadata are same as market quote sensitivities. foreach (CurrencyParameterSensitivity sensi in mqs.Sensitivities) { assertEquals(notionalEquivalent.getSensitivity(sensi.MarketDataName, sensi.Currency).ParameterMetadata, sensi.ParameterMetadata); } // Check sensitivity: trade sensitivity = sum(notional equivalent sensitivities) int totalNbParameters = 0; IDictionary <CurveName, IList <ResolvedTrade> > equivalentTrades = new Dictionary <CurveName, IList <ResolvedTrade> >(); ImmutableList <CurveDefinition> curveGroups = GROUP_DEFINITION.CurveDefinitions; ImmutableList.Builder <CurveParameterSize> builder = ImmutableList.builder(); foreach (CurveDefinition entry in curveGroups) { totalNbParameters += entry.ParameterCount; DoubleArray notionalCurve = notionalEquivalent.getSensitivity(entry.Name, Currency.EUR).Sensitivity; ImmutableList <CurveNode> nodes = entry.Nodes; IList <ResolvedTrade> resolvedTradesCurve = new List <ResolvedTrade>(); for (int i = 0; i < nodes.size(); i++) { resolvedTradesCurve.Add(nodes.get(i).resolvedTrade(notionalCurve.get(i), MARKET_QUOTES, REF_DATA)); } equivalentTrades[entry.Name] = resolvedTradesCurve; builder.add(entry.toCurveParameterSize()); } ImmutableList <CurveParameterSize> order = builder.build(); // order of the curves DoubleArray totalSensitivity = DoubleArray.filled(totalNbParameters); foreach (KeyValuePair <CurveName, IList <ResolvedTrade> > entry in equivalentTrades.SetOfKeyValuePairs()) { foreach (ResolvedTrade t in entry.Value) { totalSensitivity = totalSensitivity.plus(PV_MEASURES.derivative(t, multicurve, order)); } } DoubleArray instrumentSensi = PV_MEASURES.derivative(trade, multicurve, order); assertTrue(totalSensitivity.equalWithTolerance(instrumentSensi, TOLERANCE_PV_DELTA)); }
//------------------------------------------------------------------------- public ResolvedSwap resolve(ReferenceData refData) { // avoid streams as profiling showed a hotspot // most efficient to loop around legs once ImmutableList.Builder <ResolvedSwapLeg> resolvedLegs = ImmutableList.builder(); ImmutableSet.Builder <Currency> currencies = ImmutableSet.builder(); ImmutableSet.Builder <Index> indices = ImmutableSet.builder(); foreach (SwapLeg leg in legs) { ResolvedSwapLeg resolvedLeg = leg.resolve(refData); resolvedLegs.add(resolvedLeg); currencies.add(resolvedLeg.Currency); leg.collectIndices(indices); } return(new ResolvedSwap(resolvedLegs.build(), currencies.build(), indices.build())); }
static BlackFxOptionInterpolatedNodalSurfaceVolatilitiesSpecificationTest() { ImmutableList.Builder <FxOptionVolatilitiesNode> nodeBuilder = ImmutableList.builder(); ImmutableList.Builder <QuoteId> quoteIdBuilder = ImmutableList.builder(); for (int i = 0; i < TENORS.Count; ++i) { for (int j = 0; j < STRIKES.Count; ++j) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", GBP_USD.ToString() + "_" + TENORS[i].ToString() + "_" + STRIKES[j])); nodeBuilder.add(FxOptionVolatilitiesNode.of(GBP_USD, SPOT_OFFSET, BDA, ValueType.BLACK_VOLATILITY, quoteId, TENORS[i], SimpleStrike.of(STRIKES[j]))); quoteIdBuilder.add(quoteId); } } NODES = nodeBuilder.build(); QUOTE_IDS = quoteIdBuilder.build(); }