Ejemplo n.º 1
0
        private static void CreateAwakerService(StandardComponents standardComponents)
        {
            var awakeReaderService = new AwakeService();

            standardComponents.MainBus.Subscribe <StorageMessage.EventCommitted>(awakeReaderService);
            standardComponents.MainBus.Subscribe <StorageMessage.TfEofAtNonCommitRecord>(awakeReaderService);
            standardComponents.MainBus.Subscribe <AwakeServiceMessage.SubscribeAwake>(awakeReaderService);
            standardComponents.MainBus.Subscribe <AwakeServiceMessage.UnsubscribeAwake>(awakeReaderService);
        }
        // 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));
        }
Ejemplo n.º 3
0
        public virtual void test_scenarioMarketData()
        {
            ScenarioMarketData    marketDataCalibrated = StandardComponents.marketDataFactory().createMultiScenario(REQUIREMENTS, SCENARIO_CONFIG, SCENARIO_MARKET_DATA, REF_DATA, ScenarioDefinition.empty());
            Results               results = CALC_RUNNER.calculateMultiScenario(RULES, TARGETS, COLUMN, marketDataCalibrated, REF_DATA);
            CurrencyScenarioArray pvs     = results.get(0, 0, typeof(CurrencyScenarioArray)).Value;
            CurrencyAmount        pv0     = PRICER.presentValue(OPTION_TRADE.resolve(REF_DATA), EXP_RATES, EXP_VOLS).convertedTo(USD, EXP_RATES);
            CurrencyAmount        pv1     = PRICER.presentValue(OPTION_TRADE.resolve(REF_DATA), EXP_RATES_1, EXP_VOLS_1).convertedTo(USD, EXP_RATES_1);

            assertEquals(pvs.get(0), pv0);
            assertEquals(pvs.get(1), pv1);
        }
Ejemplo n.º 4
0
        public static void CreateManagerService(
            StandardComponents standardComponents,
            ProjectionsStandardComponents projectionsStandardComponents,
            IDictionary <Guid, IPublisher> queues,
            TimeSpan projectionQueryExpiry)
        {
            IQueuedHandler inputQueue   = projectionsStandardComponents.MasterInputQueue;
            InMemoryBus    outputBus    = projectionsStandardComponents.MasterOutputBus;
            var            ioDispatcher = new IODispatcher(outputBus, new PublishEnvelope(inputQueue));

            var projectionsController = new ProjectionsController(
                standardComponents.HttpForwarder,
                inputQueue,
                standardComponents.NetworkSendService);

            var forwarder = new RequestResponseQueueForwarder(
                inputQueue: projectionsStandardComponents.MasterInputQueue,
                externalRequestQueue: standardComponents.MainQueue);

            if (projectionsStandardComponents.RunProjections != ProjectionType.None)
            {
                foreach (var httpService in standardComponents.HttpServices)
                {
                    httpService.SetupController(projectionsController);
                }
            }

            var commandWriter = new MultiStreamMessageWriter(ioDispatcher);
            var projectionManagerCommandWriter  = new ProjectionManagerCommandWriter(commandWriter);
            var projectionManagerResponseReader = new ProjectionManagerResponseReader(outputBus, ioDispatcher,
                                                                                      queues.Count);

            var projectionManager = new ProjectionManager(
                inputQueue,
                outputBus,
                queues,
                new RealTimeProvider(),
                projectionsStandardComponents.RunProjections,
                ioDispatcher,
                projectionQueryExpiry);

            SubscribeMainBus(
                projectionsStandardComponents.MasterMainBus,
                projectionManager,
                projectionsStandardComponents.RunProjections,
                projectionManagerResponseReader,
                ioDispatcher,
                projectionManagerCommandWriter);


            SubscribeOutputBus(standardComponents, projectionsStandardComponents, forwarder);
        }
        // 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);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 8
0
        public void Register(StandardComponents standardComponents)
        {
            _masterMainBus    = new InMemoryBus("manager input bus");
            _masterInputQueue = new QueuedHandler(_masterMainBus, "Projections Master");
            _masterOutputBus  = new InMemoryBus("ProjectionManagerAndCoreCoordinatorOutput");

            var projectionsStandardComponents = new ProjectionsStandardComponents(
                _projectionWorkerThreadCount,
                _runProjections,
                _masterOutputBus,
                _masterInputQueue,
                _masterMainBus);

            CreateAwakerService(standardComponents);
            _coreQueues = ProjectionCoreWorkersNode.CreateCoreWorkers(standardComponents, projectionsStandardComponents);
            _queueMap   = _coreQueues.ToDictionary(v => v.Key, v => (IPublisher)v.Value);

            ProjectionManagerNode.CreateManagerService(standardComponents, projectionsStandardComponents, _queueMap);
        }
Ejemplo n.º 9
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));
        }
Ejemplo n.º 10
0
        public void Register(StandardComponents standardComponents)
        {
            _masterMainBus    = new InMemoryBus("manager input bus");
            _masterInputQueue = QueuedHandler.CreateQueuedHandler(_masterMainBus, "Projections Master");
            _masterOutputBus  = new InMemoryBus("ProjectionManagerAndCoreCoordinatorOutput");

            var projectionsStandardComponents = new ProjectionsStandardComponents(
                _projectionWorkerThreadCount,
                _runProjections,
                _masterOutputBus,
                _masterInputQueue,
                _masterMainBus, _faultOutOfOrderProjections);

            CreateAwakerService(standardComponents);
            _coreQueues = ProjectionCoreWorkersNode.CreateCoreWorkers(standardComponents, projectionsStandardComponents);
            _queueMap   = _coreQueues.ToDictionary(v => v.Key, v => (IPublisher)v.Value);

            ProjectionManagerNode.CreateManagerService(standardComponents, projectionsStandardComponents, _queueMap, _projectionsQueryExpiry);
            projectionsStandardComponents.MasterMainBus.Subscribe <CoreProjectionStatusMessage.Stopped>(this);
        }
Ejemplo n.º 11
0
        //-------------------------------------------------------------------------
        public virtual void presentValueVanillaFixedVsLibor1mSwap()
        {
            SwapLeg payLeg = fixedLeg(LocalDate.of(2014, 9, 12), LocalDate.of(2016, 9, 12), Frequency.P6M, PayReceive.PAY, NOTIONAL, 0.0125, null);

            SwapLeg receiveLeg = RateCalculationSwapLeg.builder().payReceive(RECEIVE).accrualSchedule(PeriodicSchedule.builder().startDate(LocalDate.of(2014, 9, 12)).endDate(LocalDate.of(2016, 9, 12)).frequency(Frequency.P1M).businessDayAdjustment(BDA_MF).build()).paymentSchedule(PaymentSchedule.builder().paymentFrequency(Frequency.P1M).paymentDateOffset(DaysAdjustment.NONE).build()).notionalSchedule(NOTIONAL).calculation(IborRateCalculation.builder().index(USD_LIBOR_1M).fixingDateOffset(DaysAdjustment.ofBusinessDays(-2, CalendarUSD.NYC, BDA_P)).build()).build();

            SwapTrade trade = SwapTrade.builder().info(TradeInfo.builder().tradeDate(LocalDate.of(2014, 9, 10)).build()).product(Swap.of(payLeg, receiveLeg)).build();

            CurveGroupName groupName    = CurveGroupName.of("Test");
            CurveId        idUsdDsc     = CurveId.of(groupName, StandardDataSets.GROUP1_USD_DSC.Name);
            CurveId        idUsdOn      = CurveId.of(groupName, StandardDataSets.GROUP1_USD_ON.Name);
            CurveId        idUsdL1M     = CurveId.of(groupName, StandardDataSets.GROUP1_USD_L1M.Name);
            CurveId        idUsdL3M     = CurveId.of(groupName, StandardDataSets.GROUP1_USD_L3M.Name);
            CurveId        idUsdL6M     = CurveId.of(groupName, StandardDataSets.GROUP1_USD_L6M.Name);
            MarketData     suppliedData = ImmutableMarketData.builder(VAL_DATE).addValue(idUsdDsc, StandardDataSets.GROUP1_USD_DSC).addValue(idUsdOn, StandardDataSets.GROUP1_USD_ON).addValue(idUsdL1M, StandardDataSets.GROUP1_USD_L1M).addValue(idUsdL3M, StandardDataSets.GROUP1_USD_L3M).addValue(idUsdL6M, StandardDataSets.GROUP1_USD_L6M).build();

            CalculationFunctions functions = StandardComponents.calculationFunctions();

            RatesMarketDataLookup ratesLookup = RatesMarketDataLookup.of(ImmutableMap.of(USD, idUsdDsc), ImmutableMap.of(USD_FED_FUND, idUsdOn, USD_LIBOR_1M, idUsdL1M, USD_LIBOR_3M, idUsdL3M, USD_LIBOR_6M, idUsdL6M));

            // create the calculation runner
            IList <SwapTrade> trades  = ImmutableList.of(trade);
            IList <Column>    columns = ImmutableList.of(Column.of(Measures.PRESENT_VALUE));
            CalculationRules  rules   = CalculationRules.of(functions, USD, ratesLookup);

            // calculate results using the runner
            // using the direct executor means there is no need to close/shutdown the runner
            CalculationRunner runner  = CalculationRunner.of(MoreExecutors.newDirectExecutorService());
            Results           results = runner.calculate(rules, trades, columns, suppliedData, REF_DATA);

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.opengamma.strata.collect.result.Result<?> result = results.get(0, 0);
            Result <object> result = results.get(0, 0);

            assertThat(result).Success;

            CurrencyAmount pv = (CurrencyAmount)result.Value;

            assertThat(pv.Amount).isCloseTo(-1003684.8402, offset(TOLERANCE_PV));
        }
Ejemplo n.º 12
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));
        }
Ejemplo n.º 13
0
        private static void SubscribeOutputBus(
            StandardComponents standardComponents,
            ProjectionsStandardComponents projectionsStandardComponents,
            RequestResponseQueueForwarder forwarder,
            IODispatcher ioDispatcher)
        {
            var managerOutput = projectionsStandardComponents.LeaderOutputBus;

            managerOutput.Subscribe <ClientMessage.ReadEvent>(forwarder);
            managerOutput.Subscribe <ClientMessage.ReadStreamEventsBackward>(forwarder);
            managerOutput.Subscribe <ClientMessage.ReadStreamEventsForward>(forwarder);
            managerOutput.Subscribe <ClientMessage.WriteEvents>(forwarder);
            managerOutput.Subscribe <ClientMessage.DeleteStream>(forwarder);
            managerOutput.Subscribe(Forwarder.Create <Message>(projectionsStandardComponents.LeaderInputQueue));
            managerOutput.Subscribe <ClientMessage.NotHandled>(ioDispatcher);

            managerOutput.Subscribe <TimerMessage.Schedule>(standardComponents.TimerService);
            managerOutput.Subscribe(Forwarder.Create <AwakeServiceMessage.SubscribeAwake>(standardComponents.MainQueue));
            managerOutput.Subscribe(
                Forwarder.Create <AwakeServiceMessage.UnsubscribeAwake>(standardComponents.MainQueue));
            managerOutput.Subscribe <SystemMessage.SubSystemInitialized>(forwarder);

            // self forward all
            standardComponents.MainBus.Subscribe(
                Forwarder.Create <SystemMessage.StateChangeMessage>(projectionsStandardComponents.LeaderInputQueue));
            standardComponents.MainBus.Subscribe(
                Forwarder.Create <SystemMessage.SystemCoreReady>(projectionsStandardComponents.LeaderInputQueue));
            standardComponents.MainBus.Subscribe(
                Forwarder.Create <SystemMessage.EpochWritten>(projectionsStandardComponents.LeaderInputQueue));
            standardComponents.MainBus.Subscribe(
                Forwarder.Create <ProjectionCoreServiceMessage.SubComponentStarted>(projectionsStandardComponents
                                                                                    .LeaderInputQueue));
            standardComponents.MainBus.Subscribe(
                Forwarder.Create <ProjectionCoreServiceMessage.SubComponentStopped>(projectionsStandardComponents
                                                                                    .LeaderInputQueue));
            projectionsStandardComponents.LeaderMainBus.Subscribe(new UnwrapEnvelopeHandler());
        }
Ejemplo n.º 14
0
        public virtual void test_builtData()
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<com.opengamma.strata.calc.marketdata.PerturbationMapping<?>> perturbationMapping = new java.util.ArrayList<>();
            IList <PerturbationMapping <object> > perturbationMapping = new List <PerturbationMapping <object> >();
            int nScenarios = 3;

            foreach (KeyValuePair <QuoteId, double> entry in MARKET_QUOTES.entrySet())
            {
                DoubleArray shifts = DoubleArray.of(nScenarios, n => Math.Pow(0.9, n));
                ScenarioPerturbation <double> perturb = GenericDoubleShifts.of(ShiftType.SCALED, shifts);
                perturbationMapping.Add(PerturbationMapping.of(MarketDataFilter.ofId(entry.Key), perturb));
            }
            ScenarioDefinition    scenarioDefinition   = ScenarioDefinition.ofMappings(perturbationMapping);
            ImmutableMarketData   dataWithSurface      = ImmutableMarketData.builder(VALUATION_DATE).addValueMap(MARKET_QUOTES).addValueMap(MARKET_FX_QUOTES).addValue(VOL_ID, EXP_VOLS).addValue(RatesCurveGroupId.of(CURVE_GROUP_NAME), RatesCurveGroup.ofCurves(CURVE_GROUP_DEFINITION, EXP_RATES.toImmutableRatesProvider().DiscountCurves.values())).build();
            ScenarioMarketData    marketDataCalibrated = StandardComponents.marketDataFactory().createMultiScenario(REQUIREMENTS, SCENARIO_CONFIG, dataWithSurface, REF_DATA, scenarioDefinition);
            Results               results  = CALC_RUNNER.calculateMultiScenario(RULES, TARGETS, COLUMN, marketDataCalibrated, REF_DATA);
            CurrencyScenarioArray computed = results.get(0, 0, typeof(CurrencyScenarioArray)).Value;
            CurrencyAmount        expected = PRICER.presentValue(OPTION_TRADE.resolve(REF_DATA), EXP_RATES, EXP_VOLS).convertedTo(USD, EXP_RATES);

            // dependency graph is absent, thus scenarios are not created
            assertTrue(computed.ScenarioCount == 1);
            assertEquals(computed.get(0), expected);
        }
        public static Dictionary <Guid, IQueuedHandler> CreateCoreWorkers(
            StandardComponents standardComponents,
            ProjectionsStandardComponents projectionsStandardComponents)
        {
            var coreTimeoutSchedulers =
                CreateTimeoutSchedulers(projectionsStandardComponents.ProjectionWorkerThreadCount);

            var coreQueues = new Dictionary <Guid, IQueuedHandler>();

            while (coreQueues.Count < projectionsStandardComponents.ProjectionWorkerThreadCount)
            {
                var coreInputBus = new InMemoryBus("bus");
                var coreQueue    = QueuedHandler.CreateQueuedHandler(coreInputBus,
                                                                     "Projection Core #" + coreQueues.Count,
                                                                     groupName: "Projection Core");
                var workerId       = Guid.NewGuid();
                var projectionNode = new ProjectionWorkerNode(
                    workerId,
                    standardComponents.Db,
                    coreQueue,
                    standardComponents.TimeProvider,
                    coreTimeoutSchedulers[coreQueues.Count],
                    projectionsStandardComponents.RunProjections);
                projectionNode.SetupMessaging(coreInputBus);

                var forwarder = new RequestResponseQueueForwarder(
                    inputQueue: coreQueue,
                    externalRequestQueue: standardComponents.MainQueue);
                // forwarded messages
                var coreOutput = projectionNode.CoreOutput;
                coreOutput.Subscribe <ClientMessage.ReadEvent>(forwarder);
                coreOutput.Subscribe <ClientMessage.ReadStreamEventsBackward>(forwarder);
                coreOutput.Subscribe <ClientMessage.ReadStreamEventsForward>(forwarder);
                coreOutput.Subscribe <ClientMessage.ReadAllEventsForward>(forwarder);
                coreOutput.Subscribe <ClientMessage.WriteEvents>(forwarder);
                coreOutput.Subscribe <ClientMessage.DeleteStream>(forwarder);


                if (projectionsStandardComponents.RunProjections >= ProjectionType.System)
                {
                    var slaveProjectionResponseWriter = projectionNode.SlaveProjectionResponseWriter;
                    coreOutput.Subscribe <PartitionMeasuredOutput>(slaveProjectionResponseWriter);
                    coreOutput.Subscribe <PartitionProcessingProgressOutput>(slaveProjectionResponseWriter);
                    coreOutput.Subscribe <PartitionProcessingResultOutput>(slaveProjectionResponseWriter);
                    coreOutput.Subscribe <ReaderSubscriptionManagement.SpoolStreamReading>(slaveProjectionResponseWriter);


                    coreOutput.Subscribe(
                        Forwarder.Create <AwakeServiceMessage.SubscribeAwake>(standardComponents.MainQueue));
                    coreOutput.Subscribe(
                        Forwarder.Create <AwakeServiceMessage.UnsubscribeAwake>(standardComponents.MainQueue));
                }
                coreOutput.Subscribe <TimerMessage.Schedule>(standardComponents.TimerService);


                coreOutput.Subscribe(Forwarder.Create <Message>(coreQueue)); // forward all

                coreInputBus.Subscribe(new UnwrapEnvelopeHandler());

                coreQueues.Add(workerId, coreQueue);
            }
            var queues      = coreQueues.Select(v => v.Value).Cast <IPublisher>().ToArray();
            var coordinator = new ProjectionCoreCoordinator(
                projectionsStandardComponents.RunProjections,
                coreTimeoutSchedulers,
                queues,
                projectionsStandardComponents.MasterOutputBus,
                new PublishEnvelope(projectionsStandardComponents.MasterInputQueue, crossThread: true));

            coordinator.SetupMessaging(projectionsStandardComponents.MasterMainBus);
            projectionsStandardComponents.MasterMainBus.Subscribe(
                Forwarder.CreateBalancing <FeedReaderMessage.ReadPage>(coreQueues.Values.Cast <IPublisher>().ToArray()));
            return(coreQueues);
        }
 //-------------------------------------------------------------------------
 /// <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()));
 }