// 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()); }
/// <summary> /// Obtains an instance from a set of targets, columns and rules, resolving the targets. /// <para> /// The targets will typically be trades and positions. /// The columns represent the measures to calculate. /// </para> /// <para> /// The targets will be resolved if they implement <seealso cref="ResolvableCalculationTarget"/>. /// /// </para> /// </summary> /// <param name="rules"> the rules defining how the calculation is performed </param> /// <param name="targets"> the targets for which values of the measures will be calculated </param> /// <param name="columns"> the columns that will be calculated </param> /// <param name="refData"> the reference data to use to resolve the targets </param> /// <returns> the calculation tasks </returns> public static CalculationTasks of <T1>(CalculationRules rules, IList <T1> targets, IList <Column> columns, ReferenceData refData) where T1 : com.opengamma.strata.basics.CalculationTarget { // create columns that are a combination of the column overrides and the defaults // this is done once as it is the same for all targets //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: IList <Column> effectiveColumns = columns.Select(column => column.combineWithDefaults(rules.ReportingCurrency, rules.Parameters)).collect(toImmutableList()); // loop around the targets, then the columns, to build the tasks ImmutableList.Builder <CalculationTask> taskBuilder = ImmutableList.builder(); for (int rowIndex = 0; rowIndex < targets.Count; rowIndex++) { CalculationTarget target = resolveTarget(targets[rowIndex], refData); // find the applicable function, resolving the target if necessary //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: CalculationFunction<?> fn = target instanceof UnresolvableTarget ? UnresolvableTargetCalculationFunction.INSTANCE : rules.getFunctions().getFunction(target); CalculationFunction <object> fn = target is UnresolvableTarget ? UnresolvableTargetCalculationFunction.INSTANCE : rules.Functions.getFunction(target); // create the tasks IList <CalculationTask> targetTasks = createTargetTasks(target, rowIndex, fn, effectiveColumns); taskBuilder.addAll(targetTasks); } // calculation tasks holds the original user-specified columns, not the derived ones return(new CalculationTasks(taskBuilder.build(), columns)); }
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(); }
//------------------------------------------------------------------------- /// <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())); }
// 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()); }
// 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(); }
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()); }
// 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())); }
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()); }
// 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()); }
// 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()); }
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(); }
//------------------------------------------------------------------------- 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)); }
/// <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()); }
/// <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())); }
//------------------------------------------------------------------------- /// <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()); }
// 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); }
// 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> /// Returns a list created by repeating the items in the input list multiple times, with each item repeated /// in groups. /// <para> /// For example, given a list [1, 2, 3, 4], total count 12, group size 3 the result is /// [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]. /// </para> /// <para> /// This is used when creating scenarios from every possible combination of a set of perturbations. /// /// </para> /// </summary> /// <param name="inputs"> an input list whose elements are repeated in the output </param> /// <param name="totalCount"> the number of elements in the output list </param> /// <param name="groupSize"> the number of times each element should be repeated in each group </param> /// @param <T> the type of the elements </param> /// <returns> a list created by repeating the elements of the input list </returns> internal static IList <T> repeatItems <T>(IList <T> inputs, int totalCount, int groupSize) { ImmutableList.Builder <T> builder = ImmutableList.builder(); for (int i = 0; i < (totalCount / groupSize / inputs.Count); i++) { foreach (T input in inputs) { builder.addAll(Collections.nCopies(groupSize, input)); } } return(builder.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()); }
//------------------------------------------------------------------------ // 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())); }
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(); }
//------------------------------------------------------------------------- /// <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); }
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(); }
public virtual void check_pv_sensitivity() { ImmutableRatesProvider multicurve = CALIBRATOR.calibrate(GROUP_DEFINITION_PV_SENSI, MARKET_QUOTES, REF_DATA); // the trades used for calibration IDictionary <CurveName, IList <Trade> > trades = new Dictionary <CurveName, IList <Trade> >(); IDictionary <CurveName, IList <ResolvedTrade> > resolvedTrades = new Dictionary <CurveName, IList <ResolvedTrade> >(); ImmutableList <CurveDefinition> curveGroups = GROUP_DEFINITION.CurveDefinitions; ImmutableList.Builder <CurveParameterSize> builder = ImmutableList.builder(); foreach (CurveDefinition entry in curveGroups) { ImmutableList <CurveNode> nodes = entry.Nodes; IList <Trade> tradesCurve = new List <Trade>(); IList <ResolvedTrade> resolvedTradesCurve = new List <ResolvedTrade>(); foreach (CurveNode node in nodes) { tradesCurve.Add(node.trade(1d, MARKET_QUOTES, REF_DATA)); resolvedTradesCurve.Add(node.resolvedTrade(1d, MARKET_QUOTES, REF_DATA)); } trades[entry.Name] = tradesCurve; resolvedTrades[entry.Name] = resolvedTradesCurve; builder.add(entry.toCurveParameterSize()); } ImmutableList <CurveParameterSize> order = builder.build(); // order of the curves // Check CurveInfo present and sensitivity as expected IDictionary <CurveName, DoubleArray> mqsGroup = new Dictionary <CurveName, DoubleArray>(); int nodeIndex = 0; foreach (CurveParameterSize cps in order) { int nbParameters = cps.ParameterCount; double[] mqsCurve = new double[nbParameters]; for (int looptrade = 0; looptrade < nbParameters; looptrade++) { DoubleArray mqsNode = PV_MEASURES.derivative(resolvedTrades[cps.Name][looptrade], multicurve, order); mqsCurve[looptrade] = mqsNode.get(nodeIndex); nodeIndex++; } Optional <Curve> curve = multicurve.findData(cps.Name); DoubleArray pvSensitivityExpected = DoubleArray.ofUnsafe(mqsCurve); mqsGroup[cps.Name] = pvSensitivityExpected; assertTrue(curve.Present); assertTrue(curve.get().Metadata.findInfo(CurveInfoType.PV_SENSITIVITY_TO_MARKET_QUOTE).Present); DoubleArray pvSensitivityMetadata = curve.get().Metadata.findInfo(CurveInfoType.PV_SENSITIVITY_TO_MARKET_QUOTE).get(); assertTrue(pvSensitivityExpected.equalWithTolerance(pvSensitivityMetadata, 1.0E-10)); } }
//------------------------------------------------------------------------- /// <summary> /// Parses the tree from the StAX stream reader, capturing references. /// <para> /// The reader should be created using the factory returned from <seealso cref="#xmlInputFactory()"/>. /// </para> /// <para> /// This method supports capturing attribute references, such as an id/href pair. /// Wherever the parser finds an attribute with the specified name, the element is added /// to the specified map. Note that the map is mutated. /// /// </para> /// </summary> /// <param name="reader"> the StAX stream reader, positioned at or before the element to be parsed </param> /// <param name="refAttr"> the attribute name that should be parsed as a reference, null if not applicable </param> /// <param name="refs"> the mutable map of references to update, null if not applicable </param> /// <returns> the parsed element </returns> /// <exception cref="IllegalArgumentException"> if the input cannot be parsed </exception> private static XmlElement parse(XMLStreamReader reader, string refAttr, IDictionary <string, XmlElement> refs) { try { // parse start element string elementName = parseElementName(reader); ImmutableMap <string, string> attrs = parseAttributes(reader); // parse children or content ImmutableList.Builder <XmlElement> childBuilder = ImmutableList.builder(); string content = ""; int @event = reader.next(); while (@event != XMLStreamConstants.END_ELEMENT) { switch (@event) { // parse child when start element found case XMLStreamConstants.START_ELEMENT: childBuilder.add(parse(reader, refAttr, refs)); break; // append content when characters found // since XMLStreamReader has IS_COALESCING=true means there should only be one content call case XMLStreamConstants.CHARACTERS: case XMLStreamConstants.CDATA: content += reader.Text; break; default: break; } @event = reader.next(); } ImmutableList <XmlElement> children = childBuilder.build(); XmlElement parsed = children.Empty ? XmlElement.ofContent(elementName, attrs, content) : XmlElement.ofChildren(elementName, attrs, children); string @ref = attrs.get(refAttr); if (!string.ReferenceEquals(@ref, null)) { refs[@ref] = parsed; } return(parsed); } catch (XMLStreamException ex) { throw new System.ArgumentException(ex); } }