Exemplo n.º 1
0
def test_market_data_object():
    coord_val_pair = [
        {
            'coordinate': {
                'mkt_type': 'IR',
                'mkt_asset': 'USD',
                'mkt_class': 'Swap',
                'mkt_point': ('5y', ),
                'mkt_quoting_style': 'ATMRate'
            },
            'value': 0.9973194889
        },
        {
            'coordinate': {
                'mkt_type': 'IR',
                'mkt_asset': 'USD',
                'mkt_class': 'Swap',
                'mkt_point': ('40y', ),
                'mkt_quoting_style': 'ATMRate'
            },
            'value': 'redacted'
        },
    ]
    coordinates = {
        MarketDataCoordinate.from_dict(dic['coordinate']): dic['value']
        for dic in coord_val_pair
    }
    overlay_market = OverlayMarket(base_market=CloseMarket(
        market_data=coordinates))

    assert overlay_market.coordinates[0] == MarketDataCoordinate.from_dict(
        coord_val_pair[0]['coordinate'])
    assert overlay_market.redacted_coordinates[
        0] == MarketDataCoordinate.from_dict(coord_val_pair[1]['coordinate'])
Exemplo n.º 2
0
        def handle_result(result: Optional[Union[DataFrameWithInfo, ErrorValue, PricingFuture]]) -> \
                [OverlayMarket, dict]:
            if isinstance(result, ErrorValue):
                return result

            properties = MarketDataCoordinate.properties()
            is_historical = result.index.name == 'date'
            location = PricingContext.current.market_data_location

            def extract_market_data(this_result: DataFrameWithInfo):
                market_data = {}

                for _, row in this_result.iterrows():
                    coordinate_values = {p: row.get(p) for p in properties}
                    mkt_point = coordinate_values.get('mkt_point')
                    if mkt_point is not None:
                        coordinate_values['mkt_point'] = tuple(coordinate_values['mkt_point'].split(';'))

                    # return 'redacted' as coordinate value if its a redacted coordinate
                    market_data[MarketDataCoordinate.from_dict(coordinate_values)] = row['value'] if \
                        row['permissions'] == 'Granted' else 'redacted'

                return market_data

            if is_historical:
                return {date: OverlayMarket(
                    base_market=CloseMarket(date=date, location=location),
                    market_data=extract_market_data(result.loc[date]))
                    for date in set(result.index)}
            else:
                return OverlayMarket(base_market=result.risk_key.market,
                                     market_data=extract_market_data(result))
Exemplo n.º 3
0
def _value_for_date(result: Union[DataFrameWithInfo, SeriesWithInfo], date: Union[Iterable, dt.date]) -> \
        Union[DataFrameWithInfo, ErrorValue, FloatWithInfo]:
    from gs_quant.markets import CloseMarket

    raw_value = result.loc[date]
    key = result.risk_key

    risk_key = RiskKey(
        key.provider, date if isinstance(date, dt.date) else tuple(date),
        CloseMarket(date=date,
                    location=key.market.location if isinstance(
                        key.market, CloseMarket) else None), key.params,
        key.scenario, key.risk_measure)

    if isinstance(raw_value, ErrorValue):
        return raw_value
    elif isinstance(raw_value, DataFrameWithInfo):
        raw_df = raw_value.raw_value.set_index('dates')
        return DataFrameWithInfo(raw_df.reset_index(
            drop=True) if isinstance(date, dt.date) else raw_df,
                                 risk_key=risk_key,
                                 unit=result.unit,
                                 error=result.error)
    elif isinstance(raw_value, SeriesWithInfo):
        return SeriesWithInfo(raw_value.raw_value,
                              risk_key=risk_key,
                              unit=result.unit,
                              error=result.error)
    else:
        return FloatWithInfo(
            risk_key,
            raw_value,
            unit=result.unit.get(date, '') if result.unit else None,
            error=result.error)
Exemplo n.º 4
0
def test_aggregation_with_empty_measures(mocker):
    with MockCalc(mocker):
        swaptions = (IRSwaption(notional_currency='EUR',
                                termination_date='7y',
                                expiration_date='1y',
                                pay_or_receive='Receive',
                                strike='ATM+35',
                                name='EUR 1y7y'),
                     IRSwaption(notional_currency='EUR',
                                termination_date='10y',
                                expiration_date='2w',
                                pay_or_receive='Receive',
                                strike='ATM+50',
                                name='EUR 2w10y'))
        portfolio = Portfolio(swaptions)

        from_date = dt.date(2021, 11, 18)
        to_date = dt.date(2021, 11, 19)
        explain_2d = PnlExplain(CloseMarket(date=to_date))

        with PricingContext(pricing_date=from_date, visible_to_gs=True):
            portfolio.resolve()
            result_explain = portfolio.calc(explain_2d)

        total_risk = aggregate_risk(result_explain[explain_2d])['value'].sum()
        risk_swaption_1 = result_explain[0]['value'].sum()
        risk_swaption_2 = result_explain[1]['value'].sum()

        assert total_risk == risk_swaption_1 + risk_swaption_2
Exemplo n.º 5
0
        def handle_result(result: Optional[Union[DataFrameWithInfo, ErrorValue, PricingFuture]]) ->\
                [OverlayMarket, dict]:
            properties = MarketDataCoordinate.properties()
            is_historical = isinstance(PricingContext.current,
                                       HistoricalPricingContext)
            location = PricingContext.current.market_data_location

            def extract_market_data(this_result: DataFrameWithInfo):
                market_data = {}

                for _, row in result.iterrows():
                    coordinate_values = {p: row.get(p) for p in properties}
                    if 'mkt_point' in coordinate_values:
                        coordinate_values['mkt_point'] = tuple(
                            coordinate_values['mkt_point'].split(';'))
                    market_data[MarketDataCoordinate.from_dict(
                        coordinate_values)] = row['value']

                return market_data

            if is_historical:
                return {
                    date: OverlayMarket(
                        base_market=CloseMarket(date=date, location=location),
                        market_data=extract_market_data(result.loc[date]))
                    for date in set(result.index)
                }
            else:
                return OverlayMarket(base_market=result.risk_key.market,
                                     market_data=extract_market_data(result))
Exemplo n.º 6
0
def test_pricing_dates():
    # May be on weekend but doesn't matter for basic test
    future_date = dt.date.today() + dt.timedelta(2)
    yesterday = dt.date.today() - dt.timedelta(1)
    pc = PricingContext(pricing_date=future_date, market=CloseMarket(yesterday))
    assert pc is not None
    with pytest.raises(ValueError, match="pricing_date in the future"):
        PricingContext(pricing_date=future_date)
Exemplo n.º 7
0
def test_pricing_context(mocker):
    swap1 = IRSwap('Pay', '1y', 'EUR', name='EUR1y')
    future_date = business_day_offset(dt.date.today(), 10, roll='forward')
    with MockCalc(mocker):
        with RollFwd(date='10b', realise_fwd=True):
            market = swap1.market()

    with pytest.raises(ValueError):
        # cannot pass in future date into pricing context, use RollFwd instead
        with PricingContext(pricing_date=future_date):
            _ = swap1.calc(risk.Price)

        # cannot pass in market dated in the future into pricing context, use RollFwd instead
        with PricingContext(market=CloseMarket(date=future_date)):
            _ = swap1.calc(risk.Price)

        with PricingContext(market=OverlayMarket(base_market=CloseMarket(date=future_date, location='NYC'),
                                                 market_data=market.result())):
            _ = swap1.calc(risk.Price)
Exemplo n.º 8
0
 def __init__(self):
     from gs_quant.markets import CloseMarket
     super().__init__(CloseMarket())