Exemplo n.º 1
0
def structured_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()

    values = {
        '$type': 'RiskVector',
        'asset': [0.01, 0.015],
        'points': [
            {'type': 'IR', 'asset': 'USD', 'class_': 'Swap', 'point': '1y'},
            {'type': 'IR', 'asset': 'USD', 'class_': 'Swap', 'point': '2y'}
        ]
    }
    mocker.return_value = [[[[values]]]]

    expected = risk.sort_risk(pd.DataFrame([
        {'mkt_type': 'IR', 'mkt_asset': 'USD', 'mkt_class': 'Swap', 'mkt_point': '1y', 'value': 0.01},
        {'mkt_type': 'IR', 'mkt_asset': 'USD', 'mkt_class': 'Swap', 'mkt_point': '2y', 'value': 0.015}
    ]))

    current = PricingContext.current
    result = priceable.calc(measure)
    assert result.raw_value.equals(expected)
    risk_requests = (risk.RiskRequest(
        positions=(RiskPosition(instrument=priceable, quantity=1),),
        measures=(measure,),
        pricing_and_market_data_as_of=(PricingDateAndMarketDataAsOf(pricing_date=current.pricing_date,
                                                                    market=current.market),),
        parameters=RiskRequestParameters(raw_results=True),
        wait_for_results=True),)
    mocker.assert_called_with(risk_requests)
Exemplo n.º 2
0
def structured_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()

    values = [{
        'marketDataType': 'IR',
        'assetId': 'USD',
        'pointClass': 'Swap',
        'point': '1y',
        'value': 0.01
    }, {
        'marketDataType': 'IR',
        'assetId': 'USD',
        'pointClass': 'Swap',
        'point': '2y',
        'value': 0.015
    }]
    mocker.return_value = [[values]]

    result = priceable.calc(measure)
    expected = risk.sort_risk(pd.DataFrame(values))
    assert result.equals(expected)
    risk_request = risk.RiskRequest(
        positions=(risk.RiskPosition(priceable, 1), ),
        measures=(measure, ),
        pricingLocation=PricingContext.current.market_data_location,
        pricingAndMarketDataAsOf=PricingContext.current.
        _pricing_market_data_as_of,
        waitForResults=True)
    mocker.assert_called_with(risk_request)
Exemplo n.º 3
0
        def apply_field_values(
            field_values: Union[dict, list, tuple, Future],
            priceable_inst: Priceable,
            resolution_info: dict,
            future: Optional[Future] = None
        ):
            if isinstance(field_values, str):
                raise RuntimeError(field_values)

            if isinstance(field_values, Future):
                field_values = field_values.result()

            if isinstance(field_values, (list, tuple)):
                if len(field_values) == 1:
                    field_values = field_values[0]
                else:
                    res = {}
                    for fv in field_values:
                        date = dt.date.fromtimestamp(fv['date'] / 1e9)
                        date_resolution_info = {
                            'pricing_date': date,
                            'market_data_as_of': fv['date'],
                            'market_data_location': resolution_info['market_data_location']
                        }
                        res[date] = apply_field_values(fv, priceable_inst, date_resolution_info)

                    future.set_result(res)
                    return

            field_values = {field: value_mappings.get(value, value) for field, value in field_values.items()
                            if inflection.underscore(field) in priceable_inst.properties() and value not in invalid_defaults}

            if in_place and not future:
                priceable_inst.unresolved = copy.copy(priceable_inst)
                for field, value in field_values.items():
                    setattr(priceable_inst, field, value)

                priceable_inst._resolution_info = resolution_info
            else:
                new_inst = priceable_inst._from_dict(field_values)
                new_inst.unresolved = priceable_inst
                new_inst._resolution_info = resolution_info

                if future:
                    future.set_result(new_inst)
                else:
                    return new_inst
Exemplo n.º 4
0
        def apply_field_values(field_values: Union[dict, list, tuple, Future],
                               priceable_inst: Priceable,
                               future: Optional[Future] = None):
            if isinstance(field_values, str):
                raise RuntimeError(field_values)

            if isinstance(field_values, Future):
                field_values = field_values.result()

            if isinstance(field_values, (list, tuple)):
                if len(field_values) == 1:
                    field_values = field_values[0]
                else:
                    future.set_result({
                        dt.date.fromtimestamp(fv['date'] / 1e9):
                        apply_field_values(fv, priceable_inst)
                        for fv in field_values
                    })
                    return

            field_values = {
                field: value_mappings.get(value, value)
                for field, value in field_values.items()
                if field in priceable_inst.properties()
                and value not in invalid_defaults
            }

            if in_place and not future:
                for field, value in field_values.items():
                    setattr(priceable_inst, field, value)

                priceable_inst._resolved = True
            else:
                new_inst = priceable_inst._from_dict(field_values)
                new_inst._resolved = True

                if future:
                    future.set_result(new_inst)
                else:
                    return new_inst
Exemplo n.º 5
0
def price(mocker, priceable: Priceable):
    set_session()
    mocker.return_value = [[[{'value': 0.01}]]]

    result = priceable.dollar_price()
    assert result == 0.01
    risk_request = risk.RiskRequest(
        positions=(risk.RiskPosition(priceable, 1),),
        measures=(risk.DollarPrice,),
        pricingLocation=PricingContext.current.market_data_location,
        pricingAndMarketDataAsOf=PricingContext.current._pricing_market_data_as_of,
        waitForResults=True)
    mocker.assert_called_with(risk_request)
Exemplo n.º 6
0
def scalar_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()
    mocker.return_value = [[[{'value': 0.01}]]]

    result = priceable.calc(measure)
    assert result == 0.01
    risk_request = risk.RiskRequest(
        positions=(risk.RiskPosition(priceable, 1),),
        measures=(measure,),
        pricing_location=PricingContext.current.market_data_location,
        pricing_and_market_data_as_of=PricingContext.current._pricing_market_data_as_of,
        parameters=RiskRequestParameters(),
        wait_for_results=True)
    mocker.assert_called_with(risk_request)
Exemplo n.º 7
0
def scalar_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()
    mocker.return_value = [[[[{'$type': 'Risk', 'val': 0.01}]]]]

    current = PricingContext.current
    result = priceable.calc(measure)
    assert result == 0.01
    risk_requests = (risk.RiskRequest(
        positions=(RiskPosition(instrument=priceable, quantity=1),),
        measures=(measure,),
        pricing_and_market_data_as_of=(PricingDateAndMarketDataAsOf(pricing_date=current.pricing_date,
                                                                    market=current.market),),
        parameters=RiskRequestParameters(raw_results=True),
        wait_for_results=True),)
    mocker.assert_called_with(risk_requests)
Exemplo n.º 8
0
def price(mocker, priceable: Priceable):
    set_session()
    mocker.return_value = [[[[{'$type': 'Risk', 'val': 0.01}]]]]

    result = priceable.dollar_price()
    assert result == 0.01
    risk_requests = (risk.RiskRequest(
        positions=(risk.RiskPosition(priceable, 1), ),
        measures=(risk.DollarPrice, ),
        pricing_location=PricingContext.current.market_data_location,
        pricing_and_market_data_as_of=PricingContext.current.
        _pricing_market_data_as_of,
        parameters=RiskRequestParameters(raw_results=True),
        wait_for_results=True), )
    mocker.assert_called_with(risk_requests)
Exemplo n.º 9
0
    def calc(self, priceable: Priceable,
             risk_measure: RiskMeasure) -> PricingFuture:
        futures = []
        for date in self.__date_range:
            with PricingContext(pricing_date=date,
                                market=CloseMarket(
                                    location=self.market_data_location,
                                    date=close_market_date(
                                        self.market_data_location, date)),
                                is_async=True,
                                csa_term=self.csa_term,
                                use_cache=self.use_cache,
                                visible_to_gs=self.visible_to_gs):
                futures.append(priceable.calc(risk_measure))

        return HistoricalPricingFuture(futures)
Exemplo n.º 10
0
    def calc(self, priceable: Priceable,
             risk_measure: RiskMeasure) -> PricingFuture:
        futures = []

        provider = priceable.provider()
        scenario = self._scenario
        parameters = self._parameters
        location = self.market.location

        for date in self.__date_range:
            market = CloseMarket(location=location,
                                 date=close_market_date(location, date))
            risk_key = RiskKey(provider, date, market, parameters, scenario,
                               risk_measure)
            futures.append(self._calc(priceable, risk_key))

        return HistoricalPricingFuture(futures)
Exemplo n.º 11
0
    def calc(self, priceable: Priceable, risk_measure: Union[RiskMeasure, Iterable[RiskMeasure]])\
            -> Union[list, DataFrameWithInfo, ErrorValue, FloatWithInfo, Future, MultipleRiskMeasureFuture,
                     SeriesWithInfo]:
        """
        Calculate the risk measure for the priceable instrument. Do not use directly, use via instruments

        :param priceable: The priceable (e.g. instrument)
        :param risk_measure: The measure we wish to calculate
        :return: A float, Dataframe, Series or Future (depending on is_async or whether the context is entered)

        **Examples**

        >>> from gs_quant.instrument import IRSwap
        >>> from gs_quant.risk import IRDelta
        >>>
        >>> swap = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01)
        >>> delta = swap.calc(IRDelta)
        """
        futures = {}

        with self.__active_context.__lock:
            for risk_measure in (risk_measure, ) if isinstance(
                    risk_measure, RiskMeasure) else risk_measure:
                risk_key = self.__risk_key(risk_measure, priceable.provider())
                future = self.__active_context.__pending.get(
                    (risk_key, priceable))
                cached_result = PricingCache.get(
                    risk_key, priceable) if self.use_cache else None

                if future is None:
                    future = PricingFuture(self.__active_context)
                    if cached_result is not None:
                        future.set_result(cached_result)
                    else:
                        self.__active_context.__pending[(risk_key,
                                                         priceable)] = future

                futures[risk_measure] = future

        future = MultipleRiskMeasureFuture(futures, result_future=self._result_future())\
            if len(futures) > 1 else futures[risk_measure]

        return self._return_calc_result(future)
Exemplo n.º 12
0
    def calc(self, priceable: Priceable,
             risk_measure: RiskMeasure) -> PricingFuture:
        """
        Calculate the risk measure for the priceable instrument. Do not use directly, use via instruments

        :param priceable: The priceable (e.g. instrument)
        :param risk_measure: The measure we wish to calculate
        :return: A PricingFuture whose result will be the calculation result

        **Examples**

        >>> from gs_quant.instrument import IRSwap
        >>> from gs_quant.risk import IRDelta
        >>>
        >>> swap = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01)
        >>> delta = swap.calc(IRDelta)
        """
        return self._calc(priceable,
                          self.__risk_key(risk_measure, priceable.provider()))
Exemplo n.º 13
0
    def calc(self, priceable: Priceable,
             risk_measure: RiskMeasure) -> PricingFuture:
        """
        Calculate the risk measure for the priceable instrument. Do not use directly, use via instruments

        :param priceable: The priceable (e.g. instrument)
        :param risk_measure: The measure we wish to calculate
        :return: A PricingFuture whose result will be the calculation result

        **Examples**

        >>> from gs_quant.instrument import IRSwap
        >>> from gs_quant.risk import IRDelta
        >>>
        >>> swap = IRSwap('Pay', '10y', 'USD', fixed_rate=0.01)
        >>> delta = swap.calc(IRDelta)
        """
        with self.active_context.__lock:
            risk_key = self.__risk_key(risk_measure, priceable.provider())
            future = self.active_context.__pending.get((risk_key, priceable))

            if future is None:
                future = PricingFuture()
                cached_result = PricingCache.get(
                    risk_key, priceable) if self.use_cache else None

                if cached_result is not None:
                    future.set_result(cached_result)
                else:
                    self.active_context.__pending[(risk_key,
                                                   priceable)] = future

        if not (self.is_entered or self.is_async):
            self.__calc()

        return future