Beispiel #1
0
    def _handle_results(cls, request: RiskRequest, results: Iterable) -> dict:
        formatted_results = {}

        pricing_key = PricingKey(
            request.pricing_and_market_data_as_of,
            request.pricing_location.value,
            request.parameters,
            request.scenario
        )

        for measure_idx, position_results in enumerate(results):
            risk_measure = request.measures[measure_idx]

            for position_idx, date_results in enumerate(position_results):
                if len(date_results) != len(pricing_key):
                    raise RuntimeError('Number of results did not match requested days')

                handler = result_handlers.get(date_results[0].get('$type'))
                position = request.positions[position_idx]

                try:
                    date_results = handler(date_results, pricing_key, position.instrument) if handler else date_results
                except Exception as e:
                    error = str(e)
                    date_results = ErrorValue(pricing_key, error)
                    _logger.error(error)

                formatted_results.setdefault(risk_measure, {})[position] = date_results

        return formatted_results
Beispiel #2
0
 def pricing_key(self) -> PricingKey:
     """A key representing information about the pricing environment"""
     return PricingKey(
         self._pricing_market_data_as_of,
         self.__market_data_location,
         self.__parameters,
         self.__scenario)
Beispiel #3
0
    def _handle_results(cls, request: RiskRequest, results: Iterable) -> dict:
        formatted_results = {}

        pricing_key = PricingKey(
            request.pricing_and_market_data_as_of,
            request.pricing_location.value,
            request.parameters,
            request.scenario
        )

        for measure_idx, position_results in enumerate(results):
            risk_measure = request.measures[measure_idx]
            formatter = Formatters.get(risk_measure) if not request.parameters.raw_results else None
            for position_idx, result in enumerate(position_results):
                position = request.positions[position_idx]

                try:
                    result = formatter(result, pricing_key, position.instrument) if formatter else result
                except Exception as e:
                    error_string = str(e)
                    result = ErrorValue(pricing_key, error_string)
                    _logger.error(error_string)

                formatted_results.setdefault(risk_measure, {})[position] = result

        return formatted_results
Beispiel #4
0
def instrument_formatter(result: List, pricing_key: PricingKey, instrument: InstrumentBase):
    # TODO Handle these correctly in the risk service
    invalid_defaults = ('-- N/A --', 'NaN')
    value_mappings = {'Payer': 'Pay', 'Rec': 'Receive', 'Receiver': 'Receive'}
    instruments_by_date = {}

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

        new_instrument = instrument.from_dict(field_values)
        new_instrument.unresolved = instrument

        if len(result) > 1 and 'date' in field_values:
            date = dt.date.fromtimestamp(field_values['date'] / 1e9) + dt.timedelta(days=1)
            as_of = next((a for a in pricing_key.pricing_market_data_as_of if date == a.pricing_date), None)

            if as_of:
                date_key = pricing_key.clone(pricing_market_data_as_of=as_of)
                new_instrument.resolution_key = date_key
                instruments_by_date[date] = new_instrument
        else:
            new_instrument.resolution_key = pricing_key
            return new_instrument

    return instruments_by_date
Beispiel #5
0
def scalar_formatter(
        result: List, pricing_key: PricingKey
) -> Optional[Union[FloatWithInfo, SeriesWithInfo]]:
    if not result:
        return None

    result = __flatten_result(result)

    if len(result) > 1 and 'date' in result[0]:
        r = [
            __float_with_info_from_result(
                r, pricing_key.for_pricing_date(r['date'])) for r in result
        ]
        return FloatWithInfo.compose(r, pricing_key)
    else:
        return __float_with_info_from_result(result[0], pricing_key)
Beispiel #6
0
def scalar_formatter(result: List, pricing_key: PricingKey, _instrument: InstrumentBase)\
        -> Optional[Union[FloatWithInfo, SeriesWithInfo]]:
    if not result:
        return None

    result = __flatten_result(result)

    if len(result) > 1 and 'date' in result[0]:
        columns = [x for x in result[0].keys() if x != 'value']
        compressed_results = pd.DataFrame(result).groupby(columns).sum().reset_index().to_dict('records')
        r = [__float_with_info_from_result(r, pricing_key.for_pricing_date(r['date'])) for r in compressed_results]
        return FloatWithInfo.compose(
            r,
            pricing_key)
    else:
        return __float_with_info_from_result(result[0], pricing_key)
Beispiel #7
0
    def _handle_results(cls, request: RiskRequest, results: Iterable) -> dict:
        formatted_results = {}

        pricing_key = PricingKey(request.pricing_and_market_data_as_of,
                                 request.pricing_location.value,
                                 request.parameters, request.scenario)

        for measure_idx, position_results in enumerate(results):
            risk_measure = request.measures[measure_idx]
            formatter = Formatters.get(risk_measure)
            for position_idx, result in enumerate(position_results):
                position = request.positions[position_idx]
                result = formatter(result,
                                   pricing_key) if formatter else result
                formatted_results.setdefault(risk_measure,
                                             {})[position] = result

        return formatted_results
Beispiel #8
0
def instrument_formatter(result: List, pricing_key: PricingKey, instrument: InstrumentBase):
    instruments_by_date = {}

    for field_values in result:
        new_instrument = instrument.from_dict(field_values)
        new_instrument.unresolved = instrument
        new_instrument.name = instrument.name

        if len(result) > 1 and 'date' in field_values:
            date = dt.date.fromtimestamp(field_values['date'] / 1e9) + dt.timedelta(days=1)
            as_of = next((a for a in pricing_key.pricing_market_data_as_of if date == a.pricing_date), None)

            if as_of:
                date_key = pricing_key.clone(pricing_market_data_as_of=as_of)
                new_instrument.resolution_key = date_key
                instruments_by_date[date] = new_instrument
        else:
            new_instrument.resolution_key = pricing_key
            return new_instrument

    return instruments_by_date