public virtual void roundTripFraAndFixedFloatSwap() { CurveGroupName groupName = CurveGroupName.of("Curve Group"); InterpolatedNodalCurveDefinition curveDefn = CurveTestUtils.fraSwapCurveDefinition(); CurveName curveName = curveDefn.Name; IList <CurveNode> nodes = curveDefn.Nodes; RatesCurveGroupDefinition groupDefn = RatesCurveGroupDefinition.builder().name(groupName).addCurve(curveDefn, Currency.USD, IborIndices.USD_LIBOR_3M).build(); RatesCurveGroupMarketDataFunction function = new RatesCurveGroupMarketDataFunction(); LocalDate valuationDate = date(2011, 3, 8); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, double> inputData = com.google.common.collect.ImmutableMap.builder<com.opengamma.strata.data.MarketDataId<?>, double>().put(CurveTestUtils.key(nodes.get(0)), 0.0037).put(CurveTestUtils.key(nodes.get(1)), 0.0054).put(CurveTestUtils.key(nodes.get(2)), 0.005).put(CurveTestUtils.key(nodes.get(3)), 0.0087).put(CurveTestUtils.key(nodes.get(4)), 0.012).build(); IDictionary <MarketDataId <object>, double> inputData = ImmutableMap.builder <MarketDataId <object>, double>().put(CurveTestUtils.key(nodes[0]), 0.0037).put(CurveTestUtils.key(nodes[1]), 0.0054).put(CurveTestUtils.key(nodes[2]), 0.005).put(CurveTestUtils.key(nodes[3]), 0.0087).put(CurveTestUtils.key(nodes[4]), 0.012).build(); RatesCurveInputs curveInputs = RatesCurveInputs.of(inputData, DefaultCurveMetadata.of(curveName)); ScenarioMarketData inputMarketData = ImmutableScenarioMarketData.builder(valuationDate).addValue(RatesCurveInputsId.of(groupName, curveName, ObservableSource.NONE), curveInputs).build(); MarketDataBox <RatesCurveGroup> curveGroup = function.buildCurveGroup(groupDefn, CALIBRATOR, inputMarketData, REF_DATA, ObservableSource.NONE); Curve curve = curveGroup.SingleValue.findDiscountCurve(Currency.USD).get(); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, Object> marketDataMap = com.google.common.collect.ImmutableMap.builder<com.opengamma.strata.data.MarketDataId<?>, Object>().putAll(inputData).put(com.opengamma.strata.market.curve.CurveId.of(groupName, curveName), curve).build(); IDictionary <MarketDataId <object>, object> marketDataMap = ImmutableMap.builder <MarketDataId <object>, object>().putAll(inputData).put(CurveId.of(groupName, curveName), curve).build(); MarketData marketData = ImmutableMarketData.of(valuationDate, marketDataMap); TestMarketDataMap scenarioMarketData = new TestMarketDataMap(valuationDate, marketDataMap, ImmutableMap.of()); RatesMarketDataLookup lookup = RatesMarketDataLookup.of(groupDefn); RatesProvider ratesProvider = lookup.ratesProvider(scenarioMarketData.scenario(0)); checkFraPvIsZero((FraCurveNode)nodes[0], ratesProvider, marketData); checkFraPvIsZero((FraCurveNode)nodes[1], ratesProvider, marketData); checkSwapPvIsZero((FixedIborSwapCurveNode)nodes[2], ratesProvider, marketData); checkSwapPvIsZero((FixedIborSwapCurveNode)nodes[3], ratesProvider, marketData); checkSwapPvIsZero((FixedIborSwapCurveNode)nodes[4], ratesProvider, marketData); }
//------------------------------------------------------------------------- // calculates the Jacobian and builds the result, called once per group // this uses, but does not alter, data from previous groups private ImmutableMap <CurveName, JacobianCalibrationMatrix> updateJacobiansForGroup(ImmutableRatesProvider provider, ImmutableList <ResolvedTrade> trades, ImmutableList <CurveParameterSize> orderGroup, ImmutableList <CurveParameterSize> orderPrev, ImmutableList <CurveParameterSize> orderAll, ImmutableMap <CurveName, JacobianCalibrationMatrix> jacobians) { // sensitivity to all parameters in the stated order int totalParamsAll = orderAll.Select(e => e.ParameterCount).Sum(); DoubleMatrix res = derivatives(trades, provider, orderAll, totalParamsAll); // jacobian direct int nbTrades = trades.size(); int totalParamsGroup = orderGroup.Select(e => e.ParameterCount).Sum(); int totalParamsPrevious = totalParamsAll - totalParamsGroup; DoubleMatrix pDmCurrentMatrix = jacobianDirect(res, nbTrades, totalParamsGroup, totalParamsPrevious); // jacobian indirect: when totalParamsPrevious > 0 DoubleMatrix pDmPrevious = jacobianIndirect(res, pDmCurrentMatrix, nbTrades, totalParamsGroup, totalParamsPrevious, orderPrev, jacobians); // add to the map of jacobians, one entry for each curve in this group ImmutableMap.Builder <CurveName, JacobianCalibrationMatrix> jacobianBuilder = ImmutableMap.builder(); jacobianBuilder.putAll(jacobians); int startIndex = 0; foreach (CurveParameterSize order in orderGroup) { int paramCount = order.ParameterCount; //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java: //ORIGINAL LINE: double[][] pDmCurveArray = new double[paramCount][totalParamsAll]; double[][] pDmCurveArray = RectangularArrays.ReturnRectangularDoubleArray(paramCount, totalParamsAll); // copy data for previous groups if (totalParamsPrevious > 0) { for (int p = 0; p < paramCount; p++) { Array.Copy(pDmPrevious.rowArray(startIndex + p), 0, pDmCurveArray[p], 0, totalParamsPrevious); } } // copy data for this group for (int p = 0; p < paramCount; p++) { Array.Copy(pDmCurrentMatrix.rowArray(startIndex + p), 0, pDmCurveArray[p], totalParamsPrevious, totalParamsGroup); } // build final Jacobian matrix DoubleMatrix pDmCurveMatrix = DoubleMatrix.ofUnsafe(pDmCurveArray); jacobianBuilder.put(order.Name, JacobianCalibrationMatrix.of(orderAll, pDmCurveMatrix)); startIndex += paramCount; } return(jacobianBuilder.build()); }
//------------------------------------------------------------------------- public virtual void test_of_Map() { IDictionary <Currency, double> map = ImmutableMap.builder <Currency, double>().put(CCY1, AMT1).put(CCY3, AMT3).build(); assertMCA(MultiCurrencyAmount.of(map), CA1, CA3); }
// loads a single CSV file, filtering by date private static void parseSingle(System.Predicate <LocalDate> datePredicate, CharSource resource, IDictionary <LocalDate, ImmutableMap.Builder <QuoteId, double> > mutableMap) { try { CsvFile csv = CsvFile.of(resource, true); foreach (CsvRow row in csv.rows()) { string dateText = row.getField(DATE_FIELD); LocalDate date = LoaderUtils.parseDate(dateText); if (datePredicate(date)) { string symbologyStr = row.getField(SYMBOLOGY_FIELD); string tickerStr = row.getField(TICKER_FIELD); string fieldNameStr = row.getField(FIELD_NAME_FIELD); string valueStr = row.getField(VALUE_FIELD); double value = Convert.ToDouble(valueStr); StandardId id = StandardId.of(symbologyStr, tickerStr); FieldName fieldName = fieldNameStr.Length == 0 ? FieldName.MARKET_VALUE : FieldName.of(fieldNameStr); ImmutableMap.Builder <QuoteId, double> builderForDate = mutableMap.computeIfAbsent(date, k => ImmutableMap.builder()); builderForDate.put(QuoteId.of(id, fieldName), value); } } } catch (Exception ex) { throw new System.ArgumentException(Messages.format("Error processing resource as CSV file: {}", resource), ex); } }
//------------------------------------------------------------------------- /// <summary> /// Parses one or more CSV format quote files. /// <para> /// A predicate is specified that is used to filter the dates that are returned. /// This could match a single date, a set of dates or all dates. /// </para> /// <para> /// If the files contain a duplicate entry an exception will be thrown. /// /// </para> /// </summary> /// <param name="datePredicate"> the predicate used to select the dates </param> /// <param name="charSources"> the CSV character sources </param> /// <returns> the loaded quotes, mapped by <seealso cref="LocalDate"/> and <seealso cref="QuoteId quote ID"/> </returns> /// <exception cref="IllegalArgumentException"> if the files contain a duplicate entry </exception> public static ImmutableMap <LocalDate, ImmutableMap <QuoteId, double> > parse(System.Predicate <LocalDate> datePredicate, ICollection <CharSource> charSources) { // builder ensures keys can only be seen once IDictionary <LocalDate, ImmutableMap.Builder <QuoteId, double> > mutableMap = new Dictionary <LocalDate, ImmutableMap.Builder <QuoteId, double> >(); foreach (CharSource charSource in charSources) { parseSingle(datePredicate, charSource, mutableMap); } ImmutableMap.Builder <LocalDate, ImmutableMap <QuoteId, double> > builder = ImmutableMap.builder(); foreach (KeyValuePair <LocalDate, ImmutableMap.Builder <QuoteId, double> > entry in mutableMap.SetOfKeyValuePairs()) { builder.put(entry.Key, entry.Value.build()); } return(builder.build()); }
static FxOptionVolatilitiesMarketDataFunctionTest() { ImmutableList.Builder <FxOptionVolatilitiesNode> volNodeBuilder = ImmutableList.builder(); ImmutableMap.Builder <QuoteId, double> marketQuoteBuilder = ImmutableMap.builder(); ImmutableMap.Builder <QuoteId, MarketDataBox <double> > scenarioMarketQuoteBuilder = ImmutableMap.builder(); ImmutableList.Builder <FixedOvernightSwapCurveNode> usdNodeBuilder = ImmutableList.builder(); ImmutableList.Builder <FxSwapCurveNode> gbpNodeBuilder = ImmutableList.builder(); for (int i = 0; i < VOL_TENORS.Count; ++i) { for (int j = 0; j < STRIKES.Count; ++j) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", VOL_TENORS[i].ToString() + "_" + STRIKES[j].Label + "_" + VALUE_TYPES[j].ToString())); volNodeBuilder.add(FxOptionVolatilitiesNode.of(GBP_USD, SPOT_OFFSET, BDA, VALUE_TYPES[j], quoteId, VOL_TENORS[i], STRIKES[j])); marketQuoteBuilder.put(quoteId, VOL_QUOTES[i][j]); scenarioMarketQuoteBuilder.put(quoteId, MarketDataBox.ofScenarioValues(VOL_QUOTES[i][j], VOL_QUOTES_1[i][j])); } } for (int i = 0; i < USD_QUOTES.Count; ++i) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", USD.ToString() + "-OIS-" + USD_TENORS[i].ToString())); usdNodeBuilder.add(FixedOvernightSwapCurveNode.of(FixedOvernightSwapTemplate.of(USD_TENORS[i], FixedOvernightSwapConventions.USD_FIXED_TERM_FED_FUND_OIS), quoteId)); marketQuoteBuilder.put(quoteId, USD_QUOTES[i]); scenarioMarketQuoteBuilder.put(quoteId, MarketDataBox.ofScenarioValues(USD_QUOTES[i], USD_QUOTES_1[i])); } for (int i = 0; i < GBP_QUOTES.Count; ++i) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", GBP_USD.ToString() + "-FX-" + GBP_PERIODS[i].ToString())); gbpNodeBuilder.add(FxSwapCurveNode.of(FxSwapTemplate.of(GBP_PERIODS[i], FxSwapConventions.GBP_USD), quoteId)); marketQuoteBuilder.put(quoteId, GBP_QUOTES[i]); scenarioMarketQuoteBuilder.put(quoteId, MarketDataBox.ofScenarioValues(GBP_QUOTES[i], GBP_QUOTES_1[i])); } VOL_NODES = volNodeBuilder.build(); USD_NODES = usdNodeBuilder.build(); GBP_NODES = gbpNodeBuilder.build(); MARKET_QUOTES = marketQuoteBuilder.build(); SCENARIO_MARKET_QUOTES = scenarioMarketQuoteBuilder.build(); IList <double> expiry = VOL_TENORS.Select(t => ACT_365F.relativeYearFraction(VALUATION_DATE, BDA.adjust(SPOT_OFFSET.adjust(VALUATION_DATE, REF_DATA).plus(t), REF_DATA))).ToList(); int nSmiles = expiry.Count; double[] atm = new double[nSmiles]; //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java: //ORIGINAL LINE: double[][] rr = new double[nSmiles][2]; double[][] rr = RectangularArrays.ReturnRectangularDoubleArray(nSmiles, 2); //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java: //ORIGINAL LINE: double[][] str = new double[nSmiles][2]; double[][] str = RectangularArrays.ReturnRectangularDoubleArray(nSmiles, 2); for (int i = 0; i < nSmiles; ++i) { atm[i] = VOL_QUOTES[i][0]; rr[i][0] = VOL_QUOTES[i][1]; rr[i][1] = VOL_QUOTES[i][3]; str[i][0] = VOL_QUOTES[i][2]; str[i][1] = VOL_QUOTES[i][4]; } InterpolatedStrikeSmileDeltaTermStructure term = InterpolatedStrikeSmileDeltaTermStructure.of(DoubleArray.copyOf(expiry), DoubleArray.of(0.1, 0.25), DoubleArray.copyOf(atm), DoubleMatrix.copyOf(rr), DoubleMatrix.copyOf(str), ACT_365F, LINEAR, FLAT, FLAT, PCHIP, FLAT, FLAT); EXP_VOLS = BlackFxOptionSmileVolatilities.of(VOL_NAME, GBP_USD, VALUATION_DATE.atTime(VALUATION_TIME).atZone(ZONE), term); for (int i = 0; i < nSmiles; ++i) { atm[i] = VOL_QUOTES_1[i][0]; rr[i][0] = VOL_QUOTES_1[i][1]; rr[i][1] = VOL_QUOTES_1[i][3]; str[i][0] = VOL_QUOTES_1[i][2]; str[i][1] = VOL_QUOTES_1[i][4]; } InterpolatedStrikeSmileDeltaTermStructure term1 = InterpolatedStrikeSmileDeltaTermStructure.of(DoubleArray.copyOf(expiry), DoubleArray.of(0.1, 0.25), DoubleArray.copyOf(atm), DoubleMatrix.copyOf(rr), DoubleMatrix.copyOf(str), ACT_365F, LINEAR, FLAT, FLAT, PCHIP, FLAT, FLAT); EXP_VOLS_1 = BlackFxOptionSmileVolatilities.of(VOL_NAME, GBP_USD, VALUATION_DATE_1.atTime(VALUATION_TIME_1).atZone(ZONE), term1); ImmutableList.Builder <FxOptionVolatilitiesNode> nodeBuilder = ImmutableList.builder(); ImmutableMap.Builder <QuoteId, double> quoteBuilder = ImmutableMap.builder(); for (int i = 0; i < SURFACE_TENORS.Count; ++i) { for (int j = 0; j < SURFACE_STRIKES.Count; ++j) { QuoteId quoteId = QuoteId.of(StandardId.of("OG", GBP_USD.ToString() + "_" + SURFACE_TENORS[i].ToString() + "_" + SURFACE_STRIKES[j])); quoteBuilder.put(quoteId, SURFACE_VOL_QUOTES[i][j]); nodeBuilder.add(FxOptionVolatilitiesNode.of(GBP_USD, SPOT_OFFSET, BDA, ValueType.BLACK_VOLATILITY, quoteId, SURFACE_TENORS[i], SimpleStrike.of(SURFACE_STRIKES[j]))); } } SURFACE_NODES = nodeBuilder.build(); SURFACE_QUOTES = quoteBuilder.build(); IList <double> expiry = new List <double>(); IList <double> strike = new List <double>(); IList <double> vols = new List <double>(); for (int i = 0; i < SURFACE_TENORS.Count; ++i) { for (int j = 0; j < SURFACE_STRIKES.Count; ++j) { double yearFraction = ACT_365F.relativeYearFraction(VALUATION_DATE, BDA.adjust(SPOT_OFFSET.adjust(VALUATION_DATE, REF_DATA).plus(SURFACE_TENORS[i]), REF_DATA)); expiry.Add(yearFraction); strike.Add(SURFACE_STRIKES[j]); vols.Add(SURFACE_VOL_QUOTES[i][j]); } } SurfaceInterpolator interp = GridSurfaceInterpolator.of(LINEAR, PCHIP); InterpolatedNodalSurface surface = InterpolatedNodalSurface.ofUnsorted(Surfaces.blackVolatilityByExpiryStrike(VOL_NAME.Name, ACT_365F), DoubleArray.copyOf(expiry), DoubleArray.copyOf(strike), DoubleArray.copyOf(vols), interp); SURFACE_EXP_VOLS = BlackFxOptionSurfaceVolatilities.of(VOL_NAME, GBP_USD, VALUATION_DATE.atTime(VALUATION_TIME).atZone(ZONE), surface); }
// loads a single CSV file, filtering by date private static void parseSingle(System.Predicate <LocalDate> datePredicate, CharSource resource, IDictionary <LocalDate, ImmutableMap.Builder <FxRateId, FxRate> > mutableMap) { try { CsvFile csv = CsvFile.of(resource, true); foreach (CsvRow row in csv.rows()) { string dateText = row.getField(DATE_FIELD); LocalDate date = LoaderUtils.parseDate(dateText); if (datePredicate(date)) { string currencyPairStr = row.getField(CURRENCY_PAIR_FIELD); string valueStr = row.getField(VALUE_FIELD); CurrencyPair currencyPair = CurrencyPair.parse(currencyPairStr); double value = Convert.ToDouble(valueStr); ImmutableMap.Builder <FxRateId, FxRate> builderForDate = mutableMap.computeIfAbsent(date, k => ImmutableMap.builder()); builderForDate.put(FxRateId.of(currencyPair), FxRate.of(currencyPair, value)); } } } catch (Exception ex) { throw new System.ArgumentException(Messages.format("Error processing resource as CSV file: {}", resource), ex); } }