//-----------------------------------------------------------------------
        public virtual void floatingSwapLeg()
        {
            // a PeriodicSchedule generates a schedule of accrual periods
            // - interest is accrued every 6 months from 2014-02-12 to 2014-07-31
            // - accrual period dates are adjusted "modified following" using the "GBLO" holiday calendar
            // - there will be a long initial stub
            // - the regular accrual period dates will be at the end-of-month
            PeriodicSchedule accrualSchedule = PeriodicSchedule.builder().startDate(LocalDate.of(2014, 2, 12)).endDate(LocalDate.of(2016, 7, 31)).businessDayAdjustment(BusinessDayAdjustment.of(MODIFIED_FOLLOWING, HolidayCalendarIds.GBLO)).frequency(Frequency.P6M).stubConvention(StubConvention.LONG_INITIAL).rollConvention(RollConventions.EOM).build();
            // a PaymentSchedule generates a schedule of payment periods, based on the accrual schedule
            // - payments are every 6 months
            // - payments are 2 business days after the end of the period
            // - no compounding is needed as the payment schedule matches the accrual schedule
            PaymentSchedule paymentSchedule = PaymentSchedule.builder().paymentFrequency(Frequency.P6M).paymentRelativeTo(PaymentRelativeTo.PERIOD_END).paymentDateOffset(DaysAdjustment.ofBusinessDays(2, HolidayCalendarIds.GBLO)).build();
            // a NotionalSchedule generates a schedule of notional amounts, based on the payment schedule
            // - in this simple case the notional is 1 million GBP and does not change
            NotionalSchedule notionalSchedule = NotionalSchedule.of(Currency.GBP, 1_000_000);
            // a RateCalculationSwapLeg can represent a fixed or floating swap leg
            // - an IborRateCalculation is used to represent a floating Ibor rate
            // - the "Act/Act ISDA" day count is used
            // - the index is GBP LIBOR 6M
            // - fixing is 2 days before the start of the period using the "GBLO" holiday calendar
            RateCalculationSwapLeg swapLeg = RateCalculationSwapLeg.builder().payReceive(PayReceive.RECEIVE).accrualSchedule(accrualSchedule).paymentSchedule(paymentSchedule).notionalSchedule(notionalSchedule).calculation(IborRateCalculation.builder().dayCount(DayCounts.ACT_ACT_ISDA).index(IborIndices.GBP_LIBOR_6M).fixingRelativeTo(FixingRelativeTo.PERIOD_START).fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, HolidayCalendarIds.GBLO)).build()).build();
            // a ResolvedSwapLeg has all the dates of the cash flows
            // it remains valid so long as the holiday calendar does not change
            ResolvedSwapLeg resolvedLeg = swapLeg.resolve(ReferenceData.standard());

            Console.WriteLine("===== Floating =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(swapLeg));
            Console.WriteLine();
            Console.WriteLine("===== Floating resolved =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(resolvedLeg));
            Console.WriteLine();
        }
        // obtains the data and calculates the grid of results
        private static void calculate(CalculationRunner runner)
        {
            // the trades that will have measures calculated
            IList <Trade> trades = createSwapTrades();

            // the columns, specifying the measures to be calculated
            IList <Column> columns = ImmutableList.of(Column.of(Measures.LEG_INITIAL_NOTIONAL), Column.of(Measures.PRESENT_VALUE), Column.of(Measures.LEG_PRESENT_VALUE), Column.of(Measures.PV01_CALIBRATED_SUM), Column.of(Measures.PAR_RATE), Column.of(Measures.ACCRUED_INTEREST), Column.of(Measures.PV01_CALIBRATED_BUCKETED), Column.of(AdvancedMeasures.PV01_SEMI_PARALLEL_GAMMA_BUCKETED));

            // use the built-in example market data
            LocalDate valuationDate = LocalDate.of(2014, 1, 22);
            ExampleMarketDataBuilder marketDataBuilder = ExampleMarketData.builder();
            MarketData marketData = marketDataBuilder.buildSnapshot(valuationDate);

            // the complete set of rules for calculating measures
            CalculationFunctions functions = StandardComponents.calculationFunctions();
            CalculationRules     rules     = CalculationRules.of(functions, marketDataBuilder.ratesLookup(valuationDate));

            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // calculate the results
            Results results = runner.calculate(rules, trades, columns, marketData, refData);

            // use the report runner to transform the engine results into a trade report
            ReportCalculationResults calculationResults = ReportCalculationResults.of(valuationDate, trades, columns, results, functions, refData);

            TradeReportTemplate reportTemplate = ExampleData.loadTradeReportTemplate("swap-report-template");
            TradeReport         tradeReport    = TradeReport.of(calculationResults, reportTemplate);

            tradeReport.writeAsciiTable(System.out);
        }
        //-----------------------------------------------------------------------
        public virtual void fixedSwapLeg()
        {
            // a PeriodicSchedule generates a schedule of accrual periods
            // - interest is accrued every 3 months from 2014-02-12 to 2014-07-31
            // - accrual period dates are adjusted "modified following" using the "GBLO" holiday calendar
            // - there will be a long initial stub
            // - the regular accrual period dates will be at the end-of-month
            PeriodicSchedule accrualSchedule = PeriodicSchedule.builder().startDate(LocalDate.of(2014, 2, 12)).endDate(LocalDate.of(2016, 7, 31)).businessDayAdjustment(BusinessDayAdjustment.of(MODIFIED_FOLLOWING, HolidayCalendarIds.GBLO)).frequency(Frequency.P3M).stubConvention(StubConvention.LONG_INITIAL).rollConvention(RollConventions.EOM).build();
            // a PaymentSchedule generates a schedule of payment periods, based on the accrual schedule
            // - payments are every 6 months
            // - payments are 2 business days after the end of the period
            // - straight compounding is used (the payments are less frequent than the accrual, so compounding occurs)
            PaymentSchedule paymentSchedule = PaymentSchedule.builder().paymentFrequency(Frequency.P6M).paymentRelativeTo(PaymentRelativeTo.PERIOD_END).paymentDateOffset(DaysAdjustment.ofBusinessDays(2, HolidayCalendarIds.GBLO)).compoundingMethod(CompoundingMethod.STRAIGHT).build();
            // a NotionalSchedule generates a schedule of notional amounts, based on the payment schedule
            // - in this simple case the notional is 1 million GBP and does not change
            NotionalSchedule notionalSchedule = NotionalSchedule.of(Currency.GBP, 1_000_000);
            // a RateCalculationSwapLeg can represent a fixed or floating swap leg
            // - a FixedRateCalculation is used to represent a fixed rate
            // - the "Act/Act ISDA" day count is used
            // - the rate starts at 0.8% and reduces to 0.7%
            RateCalculationSwapLeg swapLeg = RateCalculationSwapLeg.builder().payReceive(PayReceive.PAY).accrualSchedule(accrualSchedule).paymentSchedule(paymentSchedule).notionalSchedule(notionalSchedule).calculation(FixedRateCalculation.builder().dayCount(DayCounts.ACT_ACT_ISDA).rate(ValueSchedule.of(0.008, ValueStep.of(LocalDate.of(2015, 1, 31), ValueAdjustment.ofReplace(0.007)))).build()).build();
            // a ResolvedSwapLeg has all the dates of the cash flows
            // it remains valid so long as the holiday calendar does not change
            ResolvedSwapLeg resolvedLeg = swapLeg.resolve(ReferenceData.standard());

            Console.WriteLine("===== Fixed =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(swapLeg));
            Console.WriteLine();
            Console.WriteLine("===== Fixed resolved =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(resolvedLeg));
            Console.WriteLine();
        }
        //-------------------------------------------------------------------------
        public virtual void test_standard()
        {
            ReferenceData test = ReferenceData.standard();

            assertEquals(test.containsValue(HolidayCalendarIds.NO_HOLIDAYS), true);
            assertEquals(test.containsValue(HolidayCalendarIds.SAT_SUN), true);
            assertEquals(test.containsValue(HolidayCalendarIds.FRI_SAT), true);
            assertEquals(test.containsValue(HolidayCalendarIds.THU_FRI), true);
            assertEquals(test.containsValue(HolidayCalendarIds.GBLO), true);
        }
        // obtains the data and calculates the grid of results
        private static void calculate(CalculationRunner runner)
        {
            // the trade that will have measures calculated
            IList <Trade> trades = ImmutableList.of(createVanillaFixedVsLibor3mSwap());

            // the columns, specifying the measures to be calculated
            IList <Column> columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE), Column.of(Measures.PV01_CALIBRATED_SUM));

            // use the built-in example market data
            ExampleMarketDataBuilder marketDataBuilder = ExampleMarketData.builder();

            // the complete set of rules for calculating measures
            LocalDate            valuationDate = LocalDate.of(2014, 1, 22);
            CalculationFunctions functions     = StandardComponents.calculationFunctions();
            CalculationRules     rules         = CalculationRules.of(functions, Currency.USD, marketDataBuilder.ratesLookup(valuationDate));

            // mappings that select which market data to apply perturbations to
            // this applies the perturbations above to all curves
            PerturbationMapping <Curve> mapping = PerturbationMapping.of(MarketDataFilter.ofIdType(typeof(CurveId)), CurveParallelShifts.absolute(0, ONE_BP));

            // create a scenario definition containing the single mapping above
            // this creates two scenarios - one for each perturbation in the mapping
            ScenarioDefinition scenarioDefinition = ScenarioDefinition.ofMappings(mapping);

            // build a market data snapshot for the valuation date
            MarketData marketData = marketDataBuilder.buildSnapshot(valuationDate);

            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // calculate the results
            MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData);
            ScenarioMarketData     scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), marketData, refData, scenarioDefinition);
            Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData);

            // TODO Replace the results processing below with a report once the reporting framework supports scenarios

            // The results are lists of currency amounts containing one value for each scenario
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.opengamma.strata.data.scenario.ScenarioArray<?> pvList = (com.opengamma.strata.data.scenario.ScenarioArray<?>) results.get(0, 0).getValue();
            ScenarioArray <object> pvList = (ScenarioArray <object>)results.get(0, 0).Value;
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.opengamma.strata.data.scenario.ScenarioArray<?> pv01List = (com.opengamma.strata.data.scenario.ScenarioArray<?>) results.get(0, 1).getValue();
            ScenarioArray <object> pv01List = (ScenarioArray <object>)results.get(0, 1).Value;

            double       pvBase       = ((CurrencyAmount)pvList.get(0)).Amount;
            double       pvShifted    = ((CurrencyAmount)pvList.get(1)).Amount;
            double       pv01Base     = ((CurrencyAmount)pv01List.get(0)).Amount;
            NumberFormat numberFormat = new DecimalFormat("###,##0.00", new DecimalFormatSymbols(Locale.ENGLISH));

            Console.WriteLine("                         PV (base) = " + numberFormat.format(pvBase));
            Console.WriteLine("             PV (1 bp curve shift) = " + numberFormat.format(pvShifted));
            Console.WriteLine("PV01 (algorithmic differentiation) = " + numberFormat.format(pv01Base));
            Console.WriteLine("          PV01 (finite difference) = " + numberFormat.format(pvShifted - pvBase));
        }
        // obtains the data and calculates the grid of results
        private static void calculate(CalculationRunner runner)
        {
            // the trades that will have measures calculated
            IList <Trade> trades = createSwapTrades();

            // the columns, specifying the measures to be calculated
            IList <Column> columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE), Column.of(Measures.PAR_RATE), Column.of(Measures.PV01_MARKET_QUOTE_BUCKETED), Column.of(Measures.PV01_CALIBRATED_BUCKETED));

            // load quotes
            ImmutableMap <QuoteId, double> quotesCcp1 = QuotesCsvLoader.load(VAL_DATE, QUOTES_RESOURCE_CCP1);
            ImmutableMap <QuoteId, double> quotesCcp2 = QuotesCsvLoader.load(VAL_DATE, QUOTES_RESOURCE_CCP2);

            // load fixings
            ImmutableMap <ObservableId, LocalDateDoubleTimeSeries> fixings = FixingSeriesCsvLoader.load(FIXINGS_RESOURCE);

            // create the market data
            MarketData marketData = ImmutableMarketData.builder(VAL_DATE).addValueMap(quotesCcp1).addValueMap(quotesCcp2).addTimeSeriesMap(fixings).build();

            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // load the curve definition
            IDictionary <CurveGroupName, RatesCurveGroupDefinition> defnsCcp1 = RatesCalibrationCsvLoader.load(GROUPS_RESOURCE_CCP1, SETTINGS_RESOURCE_CCP1, CALIBRATION_RESOURCE_CCP1);
            IDictionary <CurveGroupName, RatesCurveGroupDefinition> defnsCcp2 = RatesCalibrationCsvLoader.load(GROUPS_RESOURCE_CCP2, SETTINGS_RESOURCE_CCP2, CALIBRATION_RESOURCE_CCP2);
            RatesCurveGroupDefinition curveGroupDefinitionCcp1 = defnsCcp1[CURVE_GROUP_NAME_CCP1].filtered(VAL_DATE, refData);
            RatesCurveGroupDefinition curveGroupDefinitionCcp2 = defnsCcp2[CURVE_GROUP_NAME_CCP2].filtered(VAL_DATE, refData);

            // the configuration that defines how to create the curves when a curve group is requested
            MarketDataConfig marketDataConfig = MarketDataConfig.builder().add(CURVE_GROUP_NAME_CCP1, curveGroupDefinitionCcp1).add(CURVE_GROUP_NAME_CCP2, curveGroupDefinitionCcp2).build();

            // the complete set of rules for calculating measures
            CalculationFunctions  functions       = StandardComponents.calculationFunctions();
            RatesMarketDataLookup ratesLookupCcp1 = RatesMarketDataLookup.of(curveGroupDefinitionCcp1);
            RatesMarketDataLookup ratesLookupCcp2 = RatesMarketDataLookup.of(curveGroupDefinitionCcp2);
            // choose RatesMarketDataLookup instance based on counterparty
            TradeCounterpartyCalculationParameter perCounterparty = TradeCounterpartyCalculationParameter.of(ImmutableMap.of(CCP1_ID, ratesLookupCcp1, CCP2_ID, ratesLookupCcp2), ratesLookupCcp1);
            CalculationRules rules = CalculationRules.of(functions, perCounterparty);

            // calibrate the curves and calculate the results
            MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData);
            MarketData             calibratedMarketData = marketDataFactory().create(reqs, marketDataConfig, marketData, refData);
            Results results = runner.calculate(rules, trades, columns, calibratedMarketData, refData);

            // use the report runner to transform the engine results into a trade report
            ReportCalculationResults calculationResults = ReportCalculationResults.of(VAL_DATE, trades, columns, results, functions, refData);
            TradeReportTemplate      reportTemplate     = ExampleData.loadTradeReportTemplate("swap-report-template2");
            TradeReport tradeReport = TradeReport.of(calculationResults, reportTemplate);

            tradeReport.writeAsciiTable(System.out);
        }
Exemplo n.º 7
0
        // obtains the data and calculates the grid of results
        private static void calculate(CalculationRunner runner)
        {
            // the trades for which to calculate a P&L series
            IList <Trade> trades = ImmutableList.of(createTrade());

            // the columns, specifying the measures to be calculated
            IList <Column> columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE));

            // use the built-in example historical scenario market data
            ExampleMarketDataBuilder marketDataBuilder = ExampleMarketDataBuilder.ofResource(MARKET_DATA_RESOURCE_ROOT);

            // the complete set of rules for calculating measures
            CalculationFunctions functions = StandardComponents.calculationFunctions();
            CalculationRules     rules     = CalculationRules.of(functions, marketDataBuilder.ratesLookup(LocalDate.of(2015, 4, 23)));

            // load the historical calibrated curves from which we will build our scenarios
            // these curves are provided in the example data environment
            SortedDictionary <LocalDate, RatesCurveGroup> historicalCurves = marketDataBuilder.loadAllRatesCurves();

            // sorted list of dates for the available series of curves
            // the entries in the P&L vector we produce will correspond to these dates
            IList <LocalDate> scenarioDates = new List <LocalDate>(historicalCurves.Keys);

            // build the historical scenarios
            ScenarioDefinition historicalScenarios = buildHistoricalScenarios(historicalCurves, scenarioDates);

            // build a market data snapshot for the valuation date
            // this is the base snapshot which will be perturbed by the scenarios
            LocalDate  valuationDate = LocalDate.of(2015, 4, 23);
            MarketData marketData    = marketDataBuilder.buildSnapshot(valuationDate);

            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // calculate the results
            MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData);
            ScenarioMarketData     scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), marketData, refData, historicalScenarios);
            Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData);

            // the results contain the one measure requested (Present Value) for each scenario
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.opengamma.strata.data.scenario.ScenarioArray<?> scenarioValuations = (com.opengamma.strata.data.scenario.ScenarioArray<?>) results.get(0, 0).getValue();
            ScenarioArray <object> scenarioValuations = (ScenarioArray <object>)results.get(0, 0).Value;

            outputPnl(scenarioDates, scenarioValuations);
        }
        // obtains the data and calculates the grid of results
        private static void calculate(CalculationRunner runner)
        {
            // the trades that will have measures calculated
            IList <Trade> trades = createSwapTrades();

            // the columns, specifying the measures to be calculated
            IList <Column> columns = ImmutableList.of(Column.of(Measures.LEG_INITIAL_NOTIONAL), Column.of(Measures.PRESENT_VALUE), Column.of(Measures.LEG_PRESENT_VALUE), Column.of(Measures.PV01_CALIBRATED_SUM), Column.of(Measures.PAR_RATE), Column.of(Measures.ACCRUED_INTEREST), Column.of(Measures.PV01_CALIBRATED_BUCKETED), Column.of(AdvancedMeasures.PV01_SEMI_PARALLEL_GAMMA_BUCKETED));

            // load quotes
            ImmutableMap <QuoteId, double> quotes = QuotesCsvLoader.load(VAL_DATE, QUOTES_RESOURCE);

            // load fixings
            ImmutableMap <ObservableId, LocalDateDoubleTimeSeries> fixings = FixingSeriesCsvLoader.load(FIXINGS_RESOURCE);

            // create the market data
            MarketData marketData = MarketData.of(VAL_DATE, quotes, fixings);

            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // load the curve definition
            IDictionary <CurveGroupName, RatesCurveGroupDefinition> defns = RatesCalibrationCsvLoader.load(GROUPS_RESOURCE, SETTINGS_RESOURCE, CALIBRATION_RESOURCE);
            RatesCurveGroupDefinition curveGroupDefinition = defns[CURVE_GROUP_NAME].filtered(VAL_DATE, refData);

            // the configuration that defines how to create the curves when a curve group is requested
            MarketDataConfig marketDataConfig = MarketDataConfig.builder().add(CURVE_GROUP_NAME, curveGroupDefinition).build();

            // the complete set of rules for calculating measures
            CalculationFunctions  functions   = StandardComponents.calculationFunctions();
            RatesMarketDataLookup ratesLookup = RatesMarketDataLookup.of(curveGroupDefinition);
            CalculationRules      rules       = CalculationRules.of(functions, ratesLookup);

            // calibrate the curves and calculate the results
            MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData);
            MarketData             calibratedMarketData = marketDataFactory().create(reqs, marketDataConfig, marketData, refData);
            Results results = runner.calculate(rules, trades, columns, calibratedMarketData, refData);

            // use the report runner to transform the engine results into a trade report
            ReportCalculationResults calculationResults = ReportCalculationResults.of(VAL_DATE, trades, columns, results, functions, refData);
            TradeReportTemplate      reportTemplate     = ExampleData.loadTradeReportTemplate("swap-report-template");
            TradeReport tradeReport = TradeReport.of(calculationResults, reportTemplate);

            tradeReport.writeAsciiTable(System.out);
        }
        //-----------------------------------------------------------------------
        public virtual void vanillaFixedVsLibor3mSwap()
        {
            // we are paying a fixed rate every 3 months at 1.5% with a 100 million notional
            RateCalculationSwapLeg payLeg = RateCalculationSwapLeg.builder().payReceive(PayReceive.PAY).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 9, 12)).endDate(LocalDate.of(2021, 9, 12)).frequency(Frequency.P3M).businessDayAdjustment(BusinessDayAdjustment.of(MODIFIED_FOLLOWING, HolidayCalendarIds.USNY)).startDateBusinessDayAdjustment(BusinessDayAdjustment.NONE).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(Frequency.P3M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NotionalSchedule.builder().currency(Currency.USD).amount(ValueSchedule.of(100_000_000)).build()).calculation(FixedRateCalculation.of(0.015, DayCounts.THIRTY_U_360)).build();
            // we are receiving USD LIBOR 3M every 3 months with a 100 million notional
            RateCalculationSwapLeg receiveLeg = RateCalculationSwapLeg.builder().payReceive(PayReceive.RECEIVE).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 9, 12)).endDate(LocalDate.of(2021, 9, 12)).frequency(Frequency.P3M).businessDayAdjustment(BusinessDayAdjustment.of(MODIFIED_FOLLOWING, HolidayCalendarIds.USNY)).startDateBusinessDayAdjustment(BusinessDayAdjustment.NONE).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(Frequency.P3M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NotionalSchedule.builder().currency(Currency.USD).amount(ValueSchedule.of(100_000_000)).build()).calculation(IborRateCalculation.of(IborIndices.USD_LIBOR_3M)).build();
            // a SwapTrade combines the two legs
            SwapTrade trade = SwapTrade.builder().info(TradeInfo.builder().id(StandardId.of("OG-Trade", "1")).tradeDate(LocalDate.of(2014, 9, 10)).build()).product(Swap.of(payLeg, receiveLeg)).build();

            Console.WriteLine("===== Vanilla fixed vs Libor3m =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(trade));
            Console.WriteLine();
            Console.WriteLine("===== Vanilla fixed vs Libor3m pay leg =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(payLeg.resolve(ReferenceData.standard())));
            Console.WriteLine();
            Console.WriteLine("===== Vanilla fixed vs Libor3m receive leg =====");
            Console.WriteLine(JodaBeanSer.PRETTY.xmlWriter().write(receiveLeg.resolve(ReferenceData.standard())));
            Console.WriteLine();
        }
Exemplo n.º 10
0
        private ReportCalculationResults runCalculationRequirements(ReportRequirements requirements)
        {
            IList <Column> columns = requirements.TradeMeasureRequirements;

            ExampleMarketDataBuilder marketDataBuilder = marketDataRoot == null?ExampleMarketData.builder() : ExampleMarketDataBuilder.ofPath(marketDataRoot.toPath());

            CalculationFunctions  functions   = StandardComponents.calculationFunctions();
            RatesMarketDataLookup ratesLookup = marketDataBuilder.ratesLookup(valuationDate);
            CalculationRules      rules       = CalculationRules.of(functions, ratesLookup);

            MarketData marketData = marketDataBuilder.buildSnapshot(valuationDate);

            IList <Trade> trades;

            if (Strings.nullToEmpty(idSearch).Trim().Empty)
            {
                trades = tradeList.Trades;
            }
            else
            {
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
                trades = tradeList.Trades.Where(t => t.Info.Id.Present).Where(t => t.Info.Id.get().Value.Equals(idSearch)).collect(toImmutableList());
                if (trades.Count > 1)
                {
                    throw new System.ArgumentException(Messages.format("More than one trade found matching ID: '{}'", idSearch));
                }
            }
            if (trades.Count == 0)
            {
                throw new System.ArgumentException("No trades found. Please check the input portfolio or trade ID filter.");
            }

            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // calculate the results
            CalculationTasks       tasks = CalculationTasks.of(rules, trades, columns, refData);
            MarketDataRequirements reqs  = tasks.requirements(refData);
            MarketData             calibratedMarketData = marketDataFactory().create(reqs, MarketDataConfig.empty(), marketData, refData);
            Results results = runner.TaskRunner.calculate(tasks, calibratedMarketData, refData);

            return(ReportCalculationResults.of(valuationDate, trades, requirements.TradeMeasureRequirements, results, functions, refData));
        }
Exemplo n.º 11
0
        // calculates the PV results for the instruments used in calibration from the config
        private static Pair <IList <Trade>, Results> calculate(CalculationRunner runner)
        {
            // the reference data, such as holidays and securities
            ReferenceData refData = ReferenceData.standard();

            // load quotes
            ImmutableMap <QuoteId, double> quotes = QuotesCsvLoader.load(VAL_DATE, QUOTES_RESOURCE);

            // load time series
            IDictionary <ObservableId, LocalDateDoubleTimeSeries> fixings = FixingSeriesCsvLoader.load(FIXING_RESOURCE);

            // create the market data
            MarketData marketData = ImmutableMarketData.builder(VAL_DATE).addValueMap(quotes).addTimeSeriesMap(fixings).build();

            // load the curve definition
            IDictionary <CurveGroupName, RatesCurveGroupDefinition> defns = RatesCalibrationCsvLoader.load(GROUPS_RESOURCE, SETTINGS_RESOURCE, CALIBRATION_RESOURCE);
            RatesCurveGroupDefinition curveGroupDefinition = defns[CURVE_GROUP_NAME].filtered(VAL_DATE, refData);

            // extract the trades used for calibration
            IList <Trade> trades = curveGroupDefinition.CurveDefinitions.stream().flatMap(defn => defn.Nodes.stream()).filter(node => !(node is IborFixingDepositCurveNode)).map(node => node.trade(1d, marketData, refData)).collect(toImmutableList());

            // the columns, specifying the measures to be calculated
            IList <Column> columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE));

            // the configuration that defines how to create the curves when a curve group is requested
            MarketDataConfig marketDataConfig = MarketDataConfig.builder().add(CURVE_GROUP_NAME, curveGroupDefinition).build();

            // the complete set of rules for calculating measures
            CalculationFunctions  functions   = StandardComponents.calculationFunctions();
            RatesMarketDataLookup ratesLookup = RatesMarketDataLookup.of(curveGroupDefinition);
            CalculationRules      rules       = CalculationRules.of(functions, ratesLookup);

            // calibrate the curves and calculate the results
            MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData);
            MarketData             calibratedMarketData = marketDataFactory().create(reqs, marketDataConfig, marketData, refData);
            Results results = runner.calculate(rules, trades, columns, calibratedMarketData, refData);

            return(Pair.of(trades, results));
        }
        /// <summary>
        /// Test the behaviour when the delegate function returns no value for a measure it claims to support.
        /// This is a bug in the function, it should always return a result for all measures that are supported and
        /// were requested.
        /// </summary>
        public virtual void supportedMeasureNotReturned()
        {
            TestTarget target = new TestTarget(10);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> delegateResults = com.google.common.collect.ImmutableMap.of(CASH_FLOWS, com.opengamma.strata.collect.result.Result.success(3), PAR_RATE, com.opengamma.strata.collect.result.Result.success(5), PRESENT_VALUE, com.opengamma.strata.collect.result.Result.success(7));
            IDictionary <Measure, Result <object> > delegateResults = ImmutableMap.of(CASH_FLOWS, Result.success(3), PAR_RATE, Result.success(5), PRESENT_VALUE, Result.success(7));

            DelegateFn delegateFn = new DelegateFnAnonymousInnerClass(this, delegateResults, target);
            DerivedCalculationFunctionWrapper <TestTarget, int> wrapper = new DerivedCalculationFunctionWrapper <TestTarget, int>(new DerivedFn(), delegateFn);

            ISet <Measure> measures = ImmutableSet.of(BUCKETED_PV01);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> results = wrapper.calculate(target, measures, CalculationParameters.empty(), com.opengamma.strata.data.scenario.ScenarioMarketData.empty(), com.opengamma.strata.basics.ReferenceData.standard());
            IDictionary <Measure, Result <object> > results = wrapper.calculate(target, measures, CalculationParameters.empty(), ScenarioMarketData.empty(), ReferenceData.standard());

            assertThat(results.Keys).isEqualTo(measures);
            assertThat(results[BUCKETED_PV01]).hasFailureMessageMatching(".*did not return the expected measures.*");
        }
 /// <summary>
 /// Obtains an instance of the parser, based on the specified selector and plugins.
 /// <para>
 /// The FpML parser has a number of plugin points that can be controlled:
 /// <ul>
 /// <li>the <seealso cref="FpmlPartySelector party selector"/>
 /// <li>the <seealso cref="FpmlTradeInfoParserPlugin trade info parser"/>
 /// <li>the <seealso cref="FpmlParserPlugin trade parsers"/>
 /// <li>the <seealso cref="ReferenceData reference data"/>
 /// </ul>
 /// This method uses the <seealso cref="ReferenceData#standard() standard"/> reference data.
 ///
 /// </para>
 /// </summary>
 /// <param name="ourPartySelector">  the selector used to find "our" party within the set of parties in the FpML document </param>
 /// <param name="tradeInfoParser">  the trade info parser </param>
 /// <param name="tradeParsers">  the map of trade parsers, keyed by the FpML element name </param>
 /// <returns> the document parser </returns>
 public static FpmlDocumentParser of(FpmlPartySelector ourPartySelector, FpmlTradeInfoParserPlugin tradeInfoParser, IDictionary <string, FpmlParserPlugin> tradeParsers)
 {
     return(of(ourPartySelector, tradeInfoParser, tradeParsers, ReferenceData.standard()));
 }
        /// <summary>
        /// Test that the derived measure isn't calculated unless it is requested.
        /// </summary>
        public virtual void derivedMeasureNotRequested()
        {
            TestTarget target = new TestTarget(10);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> delegateResults = com.google.common.collect.ImmutableMap.of(CASH_FLOWS, com.opengamma.strata.collect.result.Result.success(3), PRESENT_VALUE, com.opengamma.strata.collect.result.Result.success(7));
            IDictionary <Measure, Result <object> >             delegateResults = ImmutableMap.of(CASH_FLOWS, Result.success(3), PRESENT_VALUE, Result.success(7));
            DerivedCalculationFunctionWrapper <TestTarget, int> wrapper         = new DerivedCalculationFunctionWrapper <TestTarget, int>(new DerivedFn(), new DelegateFn(delegateResults));

            ISet <Measure> measures = ImmutableSet.of(CASH_FLOWS, PRESENT_VALUE);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> results = wrapper.calculate(target, measures, CalculationParameters.empty(), com.opengamma.strata.data.scenario.ScenarioMarketData.empty(), com.opengamma.strata.basics.ReferenceData.standard());
            IDictionary <Measure, Result <object> > results = wrapper.calculate(target, measures, CalculationParameters.empty(), ScenarioMarketData.empty(), ReferenceData.standard());

            assertThat(results.Keys).isEqualTo(measures);
            assertThat(results[CASH_FLOWS]).hasValue(3);
            assertThat(results[PRESENT_VALUE]).hasValue(7);
        }
        /// <summary>
        /// Test two derived function composed together
        /// </summary>
        public virtual void calculateMeasuresNestedDerivedClasses()
        {
            TestTarget target = new TestTarget(10);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> delegateResults = com.google.common.collect.ImmutableMap.of(CASH_FLOWS, com.opengamma.strata.collect.result.Result.success(3), PAR_RATE, com.opengamma.strata.collect.result.Result.success(5), PRESENT_VALUE, com.opengamma.strata.collect.result.Result.success(7));
            IDictionary <Measure, Result <object> > delegateResults = ImmutableMap.of(CASH_FLOWS, Result.success(3), PAR_RATE, Result.success(5), PRESENT_VALUE, Result.success(7));
            DerivedFn derivedFn1 = new DerivedFn(BUCKETED_PV01);
            DerivedFn derivedFn2 = new DerivedFn(PRESENT_VALUE_MULTI_CCY);
            DerivedCalculationFunctionWrapper <TestTarget, int> wrapper = new DerivedCalculationFunctionWrapper <TestTarget, int>(derivedFn1, new DelegateFn(delegateResults));

            wrapper = new DerivedCalculationFunctionWrapper <>(derivedFn2, wrapper);

            ISet <Measure> measures = ImmutableSet.of(BUCKETED_PV01, PRESENT_VALUE_MULTI_CCY, CASH_FLOWS, PAR_RATE, PRESENT_VALUE);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> results = wrapper.calculate(target, measures, CalculationParameters.empty(), com.opengamma.strata.data.scenario.ScenarioMarketData.empty(), com.opengamma.strata.basics.ReferenceData.standard());
            IDictionary <Measure, Result <object> > results = wrapper.calculate(target, measures, CalculationParameters.empty(), ScenarioMarketData.empty(), ReferenceData.standard());

            assertThat(wrapper.supportedMeasures()).isEqualTo(measures);
            assertThat(wrapper.targetType()).isEqualTo(typeof(TestTarget));
            assertThat(results.Keys).isEqualTo(measures);
            assertThat(results[BUCKETED_PV01]).hasValue(35);
            assertThat(results[PRESENT_VALUE_MULTI_CCY]).hasValue(35);
            assertThat(results[CASH_FLOWS]).hasValue(3);
            assertThat(results[PAR_RATE]).hasValue(5);
            assertThat(results[PRESENT_VALUE]).hasValue(7);
        }
 //-------------------------------------------------------------------------
 /// <summary>
 /// Obtains an instance from the valuation date, trades, columns and results.
 /// <para>
 /// This uses standard reference data.
 ///
 /// </para>
 /// </summary>
 /// <param name="valuationDate">  the valuation date used in the calculations </param>
 /// <param name="targets">  the targets for which the results were calculated </param>
 /// <param name="columns">  the columns in the results </param>
 /// <param name="calculationResults">  the results of the calculations </param>
 /// <returns> the results </returns>
 public static ReportCalculationResults of <T1>(LocalDate valuationDate, IList <T1> targets, IList <Column> columns, Results calculationResults) where T1 : com.opengamma.strata.basics.CalculationTarget
 {
     return(of(valuationDate, targets, columns, calculationResults, StandardComponents.calculationFunctions(), ReferenceData.standard()));
 }
        /// <summary>
        /// Test the behaviour when the underlying function doesn't support the measures required by the derived function.
        /// </summary>
        public virtual void requiredMeasuresNotSupported()
        {
            TestTarget target = new TestTarget(10);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> delegateResults = com.google.common.collect.ImmutableMap.of(PAR_RATE, com.opengamma.strata.collect.result.Result.success(5), PRESENT_VALUE, com.opengamma.strata.collect.result.Result.success(7));
            IDictionary <Measure, Result <object> >             delegateResults = ImmutableMap.of(PAR_RATE, Result.success(5), PRESENT_VALUE, Result.success(7));
            DerivedCalculationFunctionWrapper <TestTarget, int> wrapper         = new DerivedCalculationFunctionWrapper <TestTarget, int>(new DerivedFn(), new DelegateFn(delegateResults));

            ISet <Measure> measures = ImmutableSet.of(BUCKETED_PV01, PAR_RATE);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.calc.Measure, com.opengamma.strata.collect.result.Result<?>> results = wrapper.calculate(target, measures, CalculationParameters.empty(), com.opengamma.strata.data.scenario.ScenarioMarketData.empty(), com.opengamma.strata.basics.ReferenceData.standard());
            IDictionary <Measure, Result <object> > results = wrapper.calculate(target, measures, CalculationParameters.empty(), ScenarioMarketData.empty(), ReferenceData.standard());

            // The derived measure isn't supported because its required measure isn't available
            assertThat(wrapper.supportedMeasures()).isEqualTo(ImmutableSet.of(PAR_RATE, PRESENT_VALUE));
            assertThat(results.Keys).isEqualTo(measures);
            assertThat(results[BUCKETED_PV01]).hasFailureMessageMatching(".*cannot calculate the required measures.*");
            assertThat(results[PAR_RATE]).hasValue(5);
        }